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