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