foo
[physik/posic.git] / moldyn.c
1 /*
2  * moldyn.c - molecular dynamics library main file
3  *
4  * author: Frank Zirkelbach <frank.zirkelbach@physik.uni-augsburg.de>
5  *
6  */
7
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <math.h>
17
18 #include "moldyn.h"
19
20 #include "math/math.h"
21 #include "init/init.h"
22 #include "random/random.h"
23 #include "visual/visual.h"
24 #include "list/list.h"
25
26 int moldyn_usage(char **argv) {
27
28         printf("\n%s usage:\n\n",argv[0]);
29         printf("--- general options ---\n");
30         printf("-E <steps> <file> (log total energy)\n");
31         printf("-M <steps> <file> (log total momentum)\n");
32         printf("-D <steps> <file> (dump total information)\n");
33         printf("-S <steps> <filebase> (single save file)\n");
34         printf("-V <steps> <filebase> (rasmol file)\n");
35         printf("--- physics options ---\n");
36         printf("-T <temperature> [K] (%f)\n",MOLDYN_TEMP);
37         printf("-t <timestep tau> [s] (%.15f)\n",MOLDYN_TAU);
38         printf("-C <cutoff radius> [m] (%.15f)\n",MOLDYN_CUTOFF);
39         printf("-R <runs> (%d)\n",MOLDYN_RUNS);
40         printf(" -- integration algo --\n");
41         printf("  -I <number> (%d)\n",MOLDYN_INTEGRATE_DEFAULT);
42         printf("     0: velocity verlet\n");
43         printf(" -- potential --\n");
44         printf("  -P <number> <param1 param2 ...>\n");
45         printf("     0: harmonic oscillator\n");
46         printf("        param1: spring constant\n");
47         printf("        param2: equilibrium distance\n");
48         printf("     1: lennard jones\n");
49         printf("        param1: epsilon\n");
50         printf("        param2: sigma\n");
51         printf("\n");
52
53         return 0;
54 }
55
56 int moldyn_parse_argv(t_moldyn *moldyn,int argc,char **argv) {
57
58         int i;
59
60         memset(moldyn,0,sizeof(t_moldyn));
61
62         /* default values */
63         moldyn->t=MOLDYN_TEMP;
64         moldyn->tau=MOLDYN_TAU;
65         moldyn->time_steps=MOLDYN_RUNS;
66         moldyn->integrate=velocity_verlet;
67
68         /* parse argv */
69         for(i=1;i<argc;i++) {
70                 if(argv[i][0]=='-') {
71                         switch(argv[i][1]){
72                                 case 'E':
73                                         moldyn->ewrite=atoi(argv[++i]);
74                                         strncpy(moldyn->efb,argv[++i],64);
75                                         break;
76                                 case 'M':
77                                         moldyn->mwrite=atoi(argv[++i]);
78                                         strncpy(moldyn->mfb,argv[++i],64);
79                                         break;
80                                 case 'S':
81                                         moldyn->swrite=atoi(argv[++i]);
82                                         strncpy(moldyn->sfb,argv[++i],64);
83                                         break;
84                                 case 'V':
85                                         moldyn->vwrite=atoi(argv[++i]);
86                                         strncpy(moldyn->vfb,argv[++i],64);
87                                         break;
88                                 case 'T':
89                                         moldyn->t=atof(argv[++i]);
90                                         break;
91                                 case 't':
92                                         moldyn->tau=atof(argv[++i]);
93                                         break;
94                                 case 'C':
95                                         moldyn->cutoff=atof(argv[++i]);
96                                         break;
97                                 case 'R':
98                                         moldyn->time_steps=atoi(argv[++i]);
99                                         break;
100                                 case 'I':
101         /* integration algorithm */
102         switch(atoi(argv[++i])) {
103                 case MOLDYN_INTEGRATE_VERLET:
104                         moldyn->integrate=velocity_verlet;
105                         break;
106                 default:
107                         printf("unknown integration algo %s\n",argv[i]);
108                         moldyn_usage(argv);
109                         return -1;
110         }
111
112                                 case 'P':
113         /* potential + params */
114         switch(atoi(argv[++i])) {
115                 case MOLDYN_POTENTIAL_HO:
116                         hop.spring_constant=atof(argv[++i]);
117                         hop.equilibrium_distance=atof(argv[++i]);
118                         moldyn->pot_params=malloc(sizeof(t_ho_params));
119                         memcpy(moldyn->pot_params,&hop,sizeof(t_ho_params));
120                         moldyn->potential_force_function=harmonic_oscillator;
121                         break;
122                 case MOLDYN_POTENTIAL_LJ:
123                         e=atof(argv[++i]);
124                         s=atof(argv[++i]);
125                         ljp.epsilon4=4*e;
126                         ljp.sigma6=s*s*s*s*s*s;
127                         ljp.sigma12=ljp.sigma6*ljp.sigma6;
128                         moldyn->pot_params=malloc(sizeof(t_lj_params));
129                         memcpy(moldyn->pot_params,&ljp,sizeof(t_lj_params));
130                         moldyn->potential_force_function=lennard_jones;
131                         break;
132                 default:
133                         printf("unknown potential %s\n",argv[i]);
134                         moldyn_usage(argv);
135                         return -1;
136         }
137
138                                 default:
139                                         printf("unknown option %s\n",argv[i]);
140                                         moldyn_usage(argv);
141                                         return -1;
142                         }
143                 } else {
144                         moldyn_usage(argv);
145                         return -1;
146                 }
147         }
148
149         return 0;
150 }
151
152 int moldyn_log_init(t_moldyn *moldyn) {
153
154         moldyn->lvstat=0;
155         t_visual *vis;
156
157         vis=&(moldyn->vis);
158
159         if(moldyn->ewrite) {
160                 moldyn->efd=open(moldyn->efb,O_WRONLY|O_CREAT|O_TRUNC);
161                 if(moldyn->efd<0) {
162                         perror("[moldyn] efd open");
163                         return moldyn->efd;
164                 }
165                 dprintf(moldyn->efd,"# moldyn total energy logfile\n");
166                 moldyn->lvstat|=MOLDYN_LVSTAT_TOTAL_E;
167         }
168
169         if(moldyn->mwrite) {
170                 moldyn->mfd=open(moldyn->mfb,O_WRONLY|O_CREAT|O_TRUNC);
171                 if(moldyn->mfd<0) {
172                         perror("[moldyn] mfd open");
173                         return moldyn->mfd;
174                 }
175                 dprintf(moldyn->mfd,"# moldyn total momentum logfile\n");
176                 moldyn->lvstat|=MOLDYN_LVSTAT_TOTAL_M;
177         }
178
179         if(moldyn->swrite)
180                 moldyn->lvstat|=MOLDYN_LVSTAT_SAVE;
181
182         if((moldyn->vwrite)&&(vis)) {
183                 moldyn->visual=vis;
184                 visual_init(vis,moldyn->vfb);
185                 moldyn->lvstat|=MOLDYN_LVSTAT_VISUAL;
186         }
187
188         moldyn->lvstat|=MOLDYN_LVSTAT_INITIALIZED;
189
190         return 0;
191 }
192
193 int moldyn_log_shutdown(t_moldyn *moldyn) {
194
195         if(moldyn->efd) close(moldyn->efd);
196         if(moldyn->mfd) close(moldyn->efd);
197         if(moldyn->dfd) close(moldyn->efd);
198         if(moldyn->visual) visual_tini(moldyn->visual);
199
200         return 0;
201 }
202
203 int moldyn_init(t_moldyn *moldyn,int argc,char **argv) {
204
205         int ret;
206
207         ret=moldyn_parse_argv(moldyn,argc,argv);
208         if(ret<0) return ret;
209
210         ret=moldyn_log_init(moldyn);
211         if(ret<0) return ret;
212
213         rand_init(&(moldyn->random),NULL,1);
214         moldyn->random.status|=RAND_STAT_VERBOSE;
215
216         moldyn->status=0;
217
218         return 0;
219 }
220
221 int moldyn_shutdown(t_moldyn *moldyn) {
222
223         moldyn_log_shutdown(moldyn);
224         rand_close(&(moldyn->random));
225         free(moldyn->atom);
226
227         return 0;
228 }
229
230 int create_lattice(u8 type,int element,double mass,double lc,
231                    int a,int b,int c,t_atom **atom) {
232
233         int count;
234         int ret;
235         t_3dvec origin;
236
237         count=a*b*c;
238
239         if(type==FCC) count*=4;
240         if(type==DIAMOND) count*=8;
241
242         *atom=malloc(count*sizeof(t_atom));
243         if(*atom==NULL) {
244                 perror("malloc (atoms)");
245                 return -1;
246         }
247
248         v3_zero(&origin);
249
250         switch(type) {
251                 case FCC:
252                         ret=fcc_init(a,b,c,lc,*atom,&origin);
253                         break;
254                 case DIAMOND:
255                         ret=diamond_init(a,b,c,lc,*atom,&origin);
256                         break;
257                 default:
258                         printf("unknown lattice type (%02x)\n",type);
259                         return -1;
260         }
261
262         /* debug */
263         if(ret!=count) {
264                 printf("ok, there is something wrong ...\n");
265                 printf("calculated -> %d atoms\n",count);
266                 printf("created -> %d atoms\n",ret);
267                 return -1;
268         }
269
270         while(count) {
271                 (*atom)[count-1].element=element;
272                 (*atom)[count-1].mass=mass;
273                 count-=1;
274         }
275
276         return ret;
277 }
278
279 int destroy_lattice(t_atom *atom) {
280
281         if(atom) free(atom);
282
283         return 0;
284 }
285
286 int thermal_init(t_moldyn *moldyn) {
287
288         /*
289          * - gaussian distribution of velocities
290          * - zero total momentum
291          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
292          */
293
294         int i;
295         double v,sigma;
296         t_3dvec p_total,delta;
297         t_atom *atom;
298         t_random *random;
299
300         atom=moldyn->atom;
301         random=&(moldyn->random);
302
303         /* gaussian distribution of velocities */
304         v3_zero(&p_total);
305         for(i=0;i<moldyn->count;i++) {
306                 sigma=sqrt(2.0*K_BOLTZMANN*moldyn->t/atom[i].mass);
307                 /* x direction */
308                 v=sigma*rand_get_gauss(random);
309                 atom[i].v.x=v;
310                 p_total.x+=atom[i].mass*v;
311                 /* y direction */
312                 v=sigma*rand_get_gauss(random);
313                 atom[i].v.y=v;
314                 p_total.y+=atom[i].mass*v;
315                 /* z direction */
316                 v=sigma*rand_get_gauss(random);
317                 atom[i].v.z=v;
318                 p_total.z+=atom[i].mass*v;
319         }
320
321         /* zero total momentum */
322         v3_scale(&p_total,&p_total,1.0/moldyn->count);
323         for(i=0;i<moldyn->count;i++) {
324                 v3_scale(&delta,&p_total,1.0/atom[i].mass);
325                 v3_sub(&(atom[i].v),&(atom[i].v),&delta);
326         }
327
328         /* velocity scaling */
329         scale_velocity(moldyn);
330
331         return 0;
332 }
333
334 int scale_velocity(t_moldyn *moldyn) {
335
336         int i;
337         double e,c;
338         t_atom *atom;
339
340         atom=moldyn->atom;
341
342         /*
343          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
344          */
345         e=0.0;
346         for(i=0;i<moldyn->count;i++)
347                 e+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
348         c=sqrt((2.0*e)/(3.0*moldyn->count*K_BOLTZMANN*moldyn->t));
349         for(i=0;i<moldyn->count;i++)
350                 v3_scale(&(atom[i].v),&(atom[i].v),(1.0/c));
351
352         return 0;
353 }
354
355 double get_e_kin(t_atom *atom,int count) {
356
357         int i;
358         double e;
359
360         e=0.0;
361
362         for(i=0;i<count;i++) {
363                 e+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
364         }
365
366         return e;
367 }
368
369 double get_e_pot(t_moldyn *moldyn) {
370
371         return moldyn->energy;
372 }
373
374 double get_total_energy(t_moldyn *moldyn) {
375
376         double e;
377
378         e=get_e_kin(moldyn->atom,moldyn->count);
379         e+=get_e_pot(moldyn);
380
381         return e;
382 }
383
384 t_3dvec get_total_p(t_atom *atom, int count) {
385
386         t_3dvec p,p_total;
387         int i;
388
389         v3_zero(&p_total);
390         for(i=0;i<count;i++) {
391                 v3_scale(&p,&(atom[i].v),atom[i].mass);
392                 v3_add(&p_total,&p_total,&p);
393         }
394
395         return p_total;
396 }
397
398 double estimate_time_step(t_moldyn *moldyn,double nn_dist,double t) {
399
400         double tau;
401
402         tau=0.05*nn_dist/(sqrt(3.0*K_BOLTZMANN*t/moldyn->atom[0].mass));
403         tau*=1.0E-9;
404         if(tau<moldyn->tau)
405                 printf("[moldyn] warning: time step  (%f > %.15f)\n",
406                        moldyn->tau,tau);
407
408         return tau;     
409 }
410
411 /*
412  * numerical tricks
413  */
414
415 /* linked list / cell method */
416
417 int link_cell_init(t_moldyn *moldyn) {
418
419         t_linkcell *lc;
420         int i;
421
422         lc=&(moldyn->lc);
423
424         /* list log fd */
425         lc->listfd=open("/dev/null",O_WRONLY);
426
427         /* partitioning the md cell */
428         lc->nx=moldyn->dim.x/moldyn->cutoff;
429         lc->x=moldyn->dim.x/lc->nx;
430         lc->ny=moldyn->dim.y/moldyn->cutoff;
431         lc->y=moldyn->dim.y/lc->ny;
432         lc->nz=moldyn->dim.z/moldyn->cutoff;
433         lc->z=moldyn->dim.z/lc->nz;
434
435         lc->cells=lc->nx*lc->ny*lc->nz;
436         lc->subcell=malloc(lc->cells*sizeof(t_list));
437
438         printf("initializing linked cells (%d)\n",lc->cells);
439
440         for(i=0;i<lc->cells;i++)
441                 //list_init(&(lc->subcell[i]),1);
442                 list_init(&(lc->subcell[i]));
443
444         link_cell_update(moldyn);
445         
446         return 0;
447 }
448
449 int link_cell_update(t_moldyn *moldyn) {
450
451         int count,i,j,k;
452         int nx,ny,nz;
453         t_atom *atom;
454         t_linkcell *lc;
455
456         atom=moldyn->atom;
457         lc=&(moldyn->lc);
458
459         nx=lc->nx;
460         ny=lc->ny;
461         nz=lc->nz;
462
463         for(i=0;i<lc->cells;i++)
464                 list_destroy(&(moldyn->lc.subcell[i]));
465         
466         for(count=0;count<moedyn->count;count++) {
467                 i=(atom[count].r.x+(moldyn->dim.x/2))/lc->x;
468                 j=(atom[count].r.y+(moldyn->dim.y/2))/lc->y;
469                 k=(atom[count].r.z+(moldyn->dim.z/2))/lc->z;
470                 list_add_immediate_ptr(&(moldyn->lc.subcell[i+j*nx+k*nx*ny]),
471                                        &(atom[count]));
472         }
473
474         return 0;
475 }
476
477 int link_cell_neighbour_index(t_moldyn *moldyn,int i,int j,int k,t_list *cell) {
478
479         t_linkcell *lc;
480         int a;
481         int count1,count2;
482         int ci,cj,ck;
483         int nx,ny,nz;
484         int x,y,z;
485         u8 bx,by,bz;
486
487         lc=&(moldyn->lc);
488         nx=lc->nx;
489         ny=lc->ny;
490         nz=lc->nz;
491         count1=1;
492         count2=27;
493         a=nx*ny;
494
495
496         cell[0]=lc->subcell[i+j*nx+k*a];
497         for(ci=-1;ci<=1;ci++) {
498                 bx=0;
499                 x=i+ci;
500                 if((x<0)||(x>=nx)) {
501                         x=(x+nx)%nx;
502                         bx=1;
503                 }
504                 for(cj=-1;cj<=1;cj++) {
505                         by=0;
506                         y=j+cj;
507                         if((y<0)||(y>=ny)) {
508                                 y=(y+ny)%ny;
509                                 by=1;
510                         }
511                         for(ck=-1;ck<=1;ck++) {
512                                 bz=0;
513                                 z=k+ck;
514                                 if((z<0)||(z>=nz)) {
515                                         z=(z+nz)%nz;
516                                         bz=1;
517                                 }
518                                 if(!(ci|cj|ck)) continue;
519                                 if(bx|by|bz) {
520                                         cell[--count2]=lc->subcell[x+y*nx+z*a];
521                                 }
522                                 else {
523                                         cell[count1++]=lc->subcell[x+y*nx+z*a];
524                                 }
525                         }
526                 }
527         }
528
529         lc->dnlc=count2;
530         lc->countn=27;
531
532         return count2;
533 }
534
535 int link_cell_shutdown(t_moldyn *moldyn) {
536
537         int i;
538         t_linkcell *lc;
539
540         lc=&(moldyn->lc);
541
542         for(i=0;i<lc->nx*lc->ny*lc->nz;i++)
543                 list_shutdown(&(moldyn->lc.subcell[i]));
544
545         if(lc->listfd) close(lc->listfd);
546
547         return 0;
548 }
549
550 int moldyn_add_schedule(t_moldyn *moldyn,) {
551
552
553         return 0;
554 }
555
556 int moldyn_set_schedule_hook(t_moldyn *moldyn,void *hook,void *hook_params) {
557
558         
559         return 0;
560 }
561
562 /*
563  *
564  * 'integration of newtons equation' - algorithms
565  *
566  */
567
568 /* start the integration */
569
570 int moldyn_integrate(t_moldyn *moldyn) {
571
572         int i,sched;
573         unsigned int e,m,s,d,v;
574         t_3dvec p;
575
576         int fd;
577         char fb[128];
578
579         /* initialize linked cell method */
580         link_cell_init(moldyn);
581
582         /* logging & visualization */
583         e=moldyn->ewrite;
584         m=moldyn->mwrite;
585         s=moldyn->swrite;
586         d=moldyn->dwrite;
587         v=moldyn->vwrite;
588
589         if(!(moldyn->lvstat&MOLDYN_LVSTAT_INITIALIZED)) {
590                 printf("[moldyn] warning, lv system not initialized\n");
591                 return -1;
592         }
593
594         /* sqaure of some variables */
595         moldyn->tau_square=moldyn->tau*moldyn->tau;
596         moldyn->cutoff_square=moldyn->cutoff*moldyn->cutoff;
597
598         /* calculate initial forces */
599         moldyn->potential_force_function(moldyn);
600
601         for(sched=0;sched<moldyn->schedule.content_count;sched++) {
602
603                 /* setting amont of runs and finite time step size */
604                 moldyn->tau=schedule->tau[sched];
605                 moldyn->tau_square=moldyn->tau*moldyn->tau;
606                 moldyn->timesteps=schedule->runs[sched];
607
608         /* integration according to schedule */
609
610         for(i=0;i<moldyn->time_steps;i++) {
611
612                 /* integration step */
613                 moldyn->integrate(moldyn);
614
615                 /* check for log & visualization */
616                 if(e) {
617                         if(!(i%e))
618                                 dprintf(moldyn->efd,
619                                         "%.15f %.45f\n",i*moldyn->tau,
620                                         get_total_energy(moldyn));
621                 }
622                 if(m) {
623                         if(!(i%m)) {
624                                 p=get_total_p(moldyn->atom,moldyn->count);
625                                 dprintf(moldyn->mfd,
626                                         "%.15f %.45f\n",i*moldyn->tau,
627                                         v3_norm(&p));
628                         }
629                 }
630                 if(s) {
631                         if(!(i%s)) {
632                                 snprintf(fb,128,"%s-%f-%.15f.save",moldyn->sfb,
633                                          moldyn->t,i*moldyn->tau);
634                                 fd=open(fb,O_WRONLY|O_TRUNC|O_CREAT);
635                                 if(fd<0) perror("[moldyn] save fd open");
636                                 else {
637                                         write(fd,moldyn,sizeof(t_moldyn));
638                                         write(fd,moldyn->atom,
639                                               moldyn->count*sizeof(t_atom));
640                                 }
641                                 close(fd);
642                         }       
643                 }
644                 if(v) {
645                         if(!(i%v)) {
646                                 visual_atoms(moldyn->visual,i*moldyn->tau,
647                                              moldyn->atom,moldyn->count);
648                                 printf("\rsteps: %d",i);
649                                 fflush(stdout);
650                         }
651                 }
652         }
653
654                 /* check for hooks */
655                 if(schedule->hook)
656                         schedule->hook(moldyn,schedule->hook_params);
657
658         return 0;
659 }
660
661 /* velocity verlet */
662
663 int velocity_verlet(t_moldyn *moldyn) {
664
665         int i,count;
666         double tau,tau_square;
667         t_3dvec delta;
668         t_atom *atom;
669
670         atom=moldyn->atom;
671         count=moldyn->count;
672         tau=moldyn->tau;
673         tau_square=moldyn->tau_square;
674
675         for(i=0;i<count;i++) {
676                 /* new positions */
677                 v3_scale(&delta,&(atom[i].v),tau);
678                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
679                 v3_scale(&delta,&(atom[i].f),0.5*tau_square/atom[i].mass);
680                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
681                 v3_per_bound(&(atom[i].r),&(moldyn->dim));
682
683                 /* velocities */
684                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
685                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
686         }
687
688         /* neighbour list update */
689 printf("list update ...\n");
690         link_cell_update(moldyn);
691 printf("done\n");
692
693         /* forces depending on chosen potential */
694 printf("calc potential/force ...\n");
695         potential_force_calc(moldyn);
696         //moldyn->potential_force_function(moldyn);
697 printf("done\n");
698
699         for(i=0;i<count;i++) {
700                 /* again velocities */
701                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
702                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
703         }
704
705         return 0;
706 }
707
708
709 /*
710  *
711  * potentials & corresponding forces
712  * 
713  */
714
715 /* generic potential and force calculation */
716
717 int potential_force_calc(t_moldyn *moldyn) {
718
719         int i,count;
720         t_atom *atom;
721         t_linkcell *lc;
722         t_list neighbour[27];
723         t_list *this;
724         double u;
725         u8 bc,bc3;
726         int countn,dnlc;
727
728         count=moldyn->count;
729         atom=moldyn->atom;
730         lc=&(moldyn->lc);
731
732         /* reset energy */
733         moldyn->energy=0.0;
734
735         for(i=0;i<count;i++) {
736         
737                 /* reset force */
738                 v3_zero(&(atom[i].f));
739
740                 /* single particle potential/force */
741                 if(atom[i].attr&ATOM_ATTR_1BP)
742                         moldyn->pf_func1b(moldyn,&(atom[i]));
743
744                 /* 2 body pair potential/force */
745                 if(atom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)) {
746                 
747                         link_cell_neighbour_index(moldyn,
748                                 (atom[i].r.x+moldyn->dim.x/2)/lc->x,
749                                 (atom[i].r.y+moldyn->dim.y/2)/lc->y,
750                                 (atom[i].r.z+moldyn->dim.z/2)/lc->z,
751                                 neighbour);
752
753                         countn=lc->countn;
754                         dnlc=lc->dnlc;
755
756                         for(j=0;j<countn;j++) {
757
758                                 this=&(neighbour[j]);
759                                 list_reset(this);
760
761                                 if(this->start==NULL)
762                                         continue;
763
764                                 bc=(j<dnlc)?0:1;
765
766                                 do {
767                                         btom=this->current->data;
768
769                                         if(btom==&(atom[i]))
770                                                 continue;
771
772                                         if((btom->attr&ATOM_ATTR_2BP)&
773                                            (atom[i].attr&ATOM_ATTR_2BP))
774                                                 moldyn->pf_func2b(moldyn,
775                                                                   &(atom[i]),
776                                                                   btom,
777                                                                   bc);
778
779                                         /* 3 body potential/force */
780
781                                         if(!(atom[i].attr&ATOM_ATTR_3BP)||
782                                            !(btom->attr&ATOM_ATTR_3BP))
783                                                 continue;
784
785                                         link_cell_neighbour_index(moldyn,
786                                            (btom->r.x+moldyn->dim.x/2)/lc->x,
787                                            (btom->r.y+moldyn->dim.y/2)/lc->y,
788                                            (btom->r.z+moldyn->dim.z/2)/lc->z,
789                                            neighbourk);
790
791                                         for(k=0;k<lc->countn;k++) {
792
793                                                 thisk=&(neighbourk[k]);
794                                                 list_reset(thisk);
795                                         
796                                                 if(thisk->start==NULL)
797                                                         continue;
798
799                                                 bck=(k<lc->dnlc)?0:1;
800
801                                                 do {
802
803                         ktom=thisk->current->data;
804
805                         if(!(ktom->attr&ATOM_ATTR_3BP))
806                                 continue;
807
808                         if(ktom==btom)
809                                 continue;
810
811                         if(ktom==&(atom[i]))
812                                 continue;
813
814                         moldyn->pf_func3b(moldyn,&(atom[i]),btom,ktom,bck);
815
816                                                 } while(list_next(thisk)!=\
817                                                         L_NO_NEXT_ELEMENT);
818                                         
819                                 } while(list_next(this)!=L_NO_NEXT_ELEMENT);
820                         }
821                 }
822         }
823
824         return 0;
825 }
826
827 /*
828  * periodic boundayr checking
829  */
830
831 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
832         
833         double x,y,z;
834
835         x=0.5*dim->x;
836         y=0.5*dim->y;
837         z=0.5*dim->z;
838
839         if(moldyn->MOLDYN_ATTR_PBX)
840                 if(a->x>=x) a->x-=dim->x;
841                 else if(-a->x>x) a->x+=dim->x;
842         if(moldyn->MOLDYN_ATTR_PBY)
843                 if(a->y>=y) a->y-=dim->y;
844                 else if(-a->y>y) a->y+=dim->y;
845         if(moldyn->MOLDYN_ATTR_PBZ)
846                 if(a->z>=z) a->z-=dim->z;
847                 else if(-a->z>z) a->z+=dim->z;
848
849         return 0;
850 }
851         
852
853 /*
854  * example potentials
855  */
856
857 /* harmonic oscillator potential and force */
858
859 int harmonic_oscillator(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc)) {
860
861         t_ho_params *params;
862         t_3dvec force,distance;
863         double d;
864         double sc,equi_dist;
865
866         params=moldyn->pot2b_params;
867         sc=params->spring_constant;
868         equi_dist=params->equilibrium_distance;
869
870         v3_sub(&distance,&(ai->r),&(aj->r);
871         
872         v3_per_bound(&distance,&(moldyn->dim));
873         if(bc) check_per_bound(moldyn,&distance);
874         d=v3_norm(&distance);
875         if(d<=moldyn->cutoff) {
876                 /* energy is 1/2 (d-d0)^2, but we will add this twice ... */
877                 moldyn->energy+=(0.25*sc*(d-equi_dist)*(d-equi_dist));
878                 v3_scale(&force,&distance,-sc*(1.0-(equi_dist/d)));
879                 v3_add(&(ai->f),&(ai->f),&force);
880         }
881
882         return 0;
883 }
884
885 /* lennard jones potential & force for one sort of atoms */
886  
887 int lennard_jones(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
888
889         t_lj_params *params;
890         t_3dvec force,distance;
891         double d,h1,h2,u;
892         double eps,sig6,sig12;
893
894         params=moldyn->pot_params;
895         eps=params->epsilon4;
896         sig6=params->sigma6;
897         sig12=params->sigma12;
898
899         v3_sub(&distance,&(ai->r),&(aj->r));
900         if(bc) check_per_bound(moldyn,&distance);
901         d=v3_absolute_square(&distance);        /* 1/r^2 */
902         if(d<=moldyn->cutoff_square) {
903                 d=1.0/d;                        /* 1/r^2 */
904                 h2=d*d;                         /* 1/r^4 */
905                 h2*=d;                          /* 1/r^6 */
906                 h1=h2*h2;                       /* 1/r^12 */
907                 /* energy is eps*..., but we will add this twice ... */
908                 moldyn->energy+=0.5*eps*(sig12*h1-sig6*h2);
909                 h2*=d;                          /* 1/r^8 */
910                 h1*=d;                          /* 1/r^14 */
911                 h2*=6*sig6;
912                 h1*=12*sig12;
913                 d=+h1-h2;
914                 d*=eps;
915                 v3_scale(&force,&distance,d);
916                 v3_add(&(ai->f),&(aj->f),&force);
917         }
918
919         return 0;
920 }
921
922 /*
923  * tersoff potential & force for 2 sorts of atoms
924  */
925
926 /* tersoff 1 body part */
927 int tersoff_mult_1bp(t_moldyn *moldyn,t_atom *ai) {
928
929         int num;
930         t_tersoff_mult_params *params;
931         t_tersoff_exchange *exchange;
932         
933         num=ai->bnum;
934         params=moldyn->pot1b_params;
935         exchange=&(params->exchange);
936
937         /*
938          * simple: point constant parameters only depending on atom i to
939          *         their right values
940          */
941
942         exchange->beta=&(params->beta[num]);
943         exchange->n=&(params->n[num]);
944         exchange->c=&(params->c[num]);
945         exchange->d=&(params->d[num]);
946         exchange->h=&(params->h[num]);
947
948         exchange->betan=pow(*(exchange->beta),*(exchange->n));
949         exchange->c2=params->c[num]*params->c[num];
950         exchange->d2=params->d[num]*params->d[num];
951         exchange->c2d2=exchange->c2/exchange->d2;
952
953         return 0;
954 }
955         
956 /* tersoff 2 body part */
957 int tersoff_mult_2bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
958
959         t_tersoff_mult_params *params;
960         t_tersoff_exchange *exchange;
961         t_3dvec dist_ij;
962         double d_ij;
963         double A,B,R,S,lambda;
964         int num;
965
966         params=moldyn->pot_params;
967         num=ai->bnum;
968         exchange=&(params->exchange);
969
970         exchange->run3bp=0;
971         
972         /*
973          * we need: f_c, df_c, f_r, df_r
974          *
975          * therefore we need: R, S, A, lambda
976          */
977
978         v3_sub(&dist_ij,&(ai->r),&(aj->r));
979
980         if(bc) check_per_bound(moldyn,&dist_ij);
981
982         /* save for use in 3bp */ /* REALLY ?!?!?! */
983         exchange->dist_ij=dist_ij;
984
985         /* constants */
986         if(num==aj->bnum) {
987                 S=params->S[num];
988                 R=params->R[num];
989                 A=params->A[num];
990                 lambda=params->lambda[num];
991                 /* more constants depending of atoms i and j, needed in 3bp */
992                 params->exchange.B=&(params->B[num]);
993                 params->exchange.mu=params->mu[num];
994                 params->exchange.chi=1.0;
995         }
996         else {
997                 S=params->Smixed;
998                 R=params->Rmixed;
999                 A=params->Amixed;
1000                 lambda=params->lambda_m;
1001                 /* more constants depending of atoms i and j, needed in 3bp */
1002                 params->exchange.B=&(params->Bmixed);
1003                 params->exchange.mu=&(params->mu_m);
1004                 params->exchange.chi=params->chi;
1005         }
1006
1007         d_ij=v3_norm(&dist_ij);
1008
1009         /* save for use in 3bp */
1010         exchange->d_ij=d_ij;
1011
1012         if(d_ij>S)
1013                 return 0;
1014
1015         f_r=A*exp(-lamda*d_ij);
1016         df_r=-lambda*f_r/d_ij;
1017
1018         /* f_a, df_a calc + save for 3bp use */
1019         exchange->f_a=-B*exp(-mu*d_ij);
1020         exchange->df_a=-mu*exchange->f_a/d_ij;
1021
1022         if(d_ij<R) {
1023                 /* f_c = 1, df_c = 0 */
1024                 f_c=1.0;
1025                 df_c=0.0;
1026                 v3_scale(&force,&dist_ij,df_r);
1027         }
1028         else {
1029                 s_r=S-R;
1030                 arg=PI*(d_ij-R)/s_r;
1031                 f_c=0.5+0.5*cos(arg);
1032                 df_c=-0.5*sin(arg)*(PI/(s_r*d_ij));
1033                 scale=df_c*f_r+df_r*f_c;
1034                 v3_scale(&force,&dist_ij,scale);
1035         }
1036
1037         /* add forces */
1038         v3_add(&(ai->f),&(ai->f),&force);
1039         /* energy is 0.5 f_r f_c, but we will sum it up twice ... */
1040         moldyn->energy+=(0.25*f_r*f_c);
1041
1042         /* save for use in 3bp */
1043         exchange->f_c=f_c;
1044         exchange->df_c=df_c;
1045
1046         /* enable the run of 3bp function */
1047         exchange->run3bp=1;
1048
1049         return 0;
1050 }
1051
1052 /* tersoff 3 body part */
1053
1054 int tersoff_mult_3bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,t_atom *ak,u8 bc) {
1055
1056         t_tersoff_mult_params *params;
1057         t_tersoff_exchange *exchange;
1058         t_3dvec dist_ij,dist_ik,dist_jk;
1059         t_3dvec temp,force;
1060         double R,S,s_r;
1061         double d_ij,d_ik,d_jk;
1062         double f_c,df_c,b_ij,f_a,df_a;
1063         double n,c,d,h,neta,betan,betan_1;
1064         double theta,cos_theta,sin_theta;
1065         int num;
1066
1067         params=moldyn->pot_params;
1068         num=ai->bnum;
1069         exchange=params->exchange;
1070
1071         if(!(exchange->run3bp))
1072                 return 0;
1073
1074         /*
1075          * we need: f_c, d_fc, b_ij, db_ij, f_a, df_a
1076          *
1077          * we got f_c, df_c, f_a, df_a from 2bp calculation
1078          */
1079
1080         d_ij=exchange->d_ij;
1081         d_ij2=exchange->d_ij2;
1082
1083         f_a=params->exchange.f_a;
1084         df_a=params->exchange.df_a;
1085         
1086         /* d_ij is <= S, as we didn't return so far! */
1087
1088         /*
1089          * calc of b_ij (scalar) and db_ij (vector)
1090          *
1091          * - for b_ij: chi, beta, f_c_ik, w(=1), c, d, h, n, cos_theta
1092          *
1093          * - for db_ij: d_theta, sin_theta, cos_theta, f_c_ik, df_c_ik,
1094          *              w_ik,
1095          *
1096          */
1097
1098         
1099         v3_sub(&dist_ik,&(aj->i),&(ak->r));
1100         if(bc) check_per_bound(moldyn,&dist_ik);
1101         d_ik=v3_norm(&dist_ik);
1102
1103         /* constants for f_c_ik calc */
1104         if(num==ak->bnum) {
1105                 R=params->R[num];
1106                 S=params->S[num];
1107         }
1108         else {
1109                 R=params->Rmixed;
1110                 S=params->Smixed;
1111         }
1112
1113         /* calc of f_c_ik */
1114         if(d_ik>S)
1115                 return 0;
1116
1117         if(d_ik<R) {
1118                 /* f_c_ik = 1, df_c_ik = 0 */
1119                 f_c_ik=1.0;
1120                 df_c_ik=0.0;
1121         }
1122         else {
1123                 s_r=S-R;
1124                 arg=PI*(d_ik-R)/s_r;
1125                 f_c_ik=0.5+0.5*cos(arg);
1126                 df_c_ik=-0.5*sin(arg)*(PI/(s_r*d_ik));
1127         }
1128         
1129         v3_sub(&dist_jk,&(aj->r),&(ak->r));
1130         if(bc) check_per_bound(moldyn,&dist_jk);
1131         d_jk=v3_norm(&dist_jk);
1132
1133         beta=*(exchange->beta);
1134         betan=exchange->betan;
1135         n=*(exchange->n);
1136         c=*(exchange->c);
1137         d=*(exchange->d);
1138         h=*(exchange->h);
1139         c2=exchange->c2;
1140         d2=exchange->d2;
1141         c2d2=exchange->c2d2;
1142
1143         numer=d_ij2+d_ik*d_ik-d_jk*d_jk;
1144         denom=2*d_ij*d_ik;
1145         cos_theta=numer/denom;
1146         sin_theta=sqrt(1.0-(cos_theta*cos_theta));
1147         theta=arccos(cos_theta);
1148         d_theta=(-1.0/sqrt(1.0-cos_theta*cos_theta))/(denom*denom);
1149         d_theta1=2*denom-numer*2*d_ik/d_ij;
1150         d_theta2=2*denom-numer*2*d_ij/d_ik;
1151         d_theta1*=d_theta;
1152         d_theta2*=d_theta;
1153
1154         h_cos=(h-cos_theta);
1155         h_cos2=h_cos*h_cos;
1156         d2_h_cos2=d2-h_cos2;
1157
1158         /* some usefull expressions */
1159         frac1=c2/(d2-h_cos2);
1160         bracket1=1+c2d2-frac1;
1161         bracket2=f_c_ik*bracket1;
1162         bracket2_n_1=pow(bracket2,n-1.0);
1163         bracket2_n=bracket2_n_1*bracket2;
1164         bracket3=1+betan*bracket2_n;
1165         bracket3_pow_1=pow(bracket3,(-1.0/(2.0*n))-1.0);
1166         bracket3_pow=bracket3_pow_1*bracket3;
1167
1168         /* now go on with calc of b_ij and derivation of b_ij */
1169         b_ij=chi*bracket3_pow;
1170
1171         /* derivation of theta */
1172         v3_scale(&force,&dist_ij,d1_theta);
1173         v3_scale(&temp,&dist_ik,d_theta2);
1174         v3_add(&force,&force,&temp);
1175
1176         /* part 1 of derivation of b_ij */
1177         v3_scale(&force,sin_theta*2*h_cos*f_c_ik*frac1);
1178
1179         /* part 2 of derivation of b_ij */
1180         v3_scale(&temp,&dist_ik,df_c_ik*bracket1);
1181
1182         /* sum up and scale ... */
1183         v3_add(&temp,&temp,&force);
1184         scale=bracket2_n_1*n*betan*(1+betan*bracket3_pow_1)*chi*(1.0/(2.0*n));
1185         v3_scale(&temp,&temp,scale);
1186
1187         /* now construct an energy and a force out of that */
1188         v3_scale(&temp,&temp,f_a);
1189         v3_scale(&force,&dist_ij,df_a*b_ij);
1190         v3_add(&temp,&temp,&force);
1191         v3_scale(&temp,&temp,f_c);
1192         v3_scale(&force,&dist_ij,df_c*b_ij*f_a);
1193         v3_add(&force,&force,&temp);
1194
1195         /* add forces */
1196         v3_add(&(ai->f),&(ai->f),&force);
1197         /* energy is 0.5 f_r f_c, but we will sum it up twice ... */
1198         moldyn->energy+=(0.25*f_a*b_ij*f_c);
1199                                 
1200         return 0;
1201 }
1202