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