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