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