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