just foo
[physik/posic.git] / moldyn.c
1 /*
2  * moldyn.c - molecular dynamics library main file
3  *
4  * author: Frank Zirkelbach <frank.zirkelbach@physik.uni-augsburg.de>
5  *
6  */
7
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <math.h>
17
18 #include "moldyn.h"
19
20 int moldyn_init(t_moldyn *moldyn,int argc,char **argv) {
21
22         memset(moldyn,0,sizeof(t_moldyn));
23
24         rand_init(&(moldyn->random),NULL,1);
25         moldyn->random.status|=RAND_STAT_VERBOSE;
26
27         return 0;
28 }
29
30 int moldyn_shutdown(t_moldyn *moldyn) {
31
32         printf("[moldyn] shutdown\n");
33         moldyn_log_shutdown(moldyn);
34         link_cell_shutdown(moldyn);
35         rand_close(&(moldyn->random));
36         free(moldyn->atom);
37
38         return 0;
39 }
40
41 int set_int_alg(t_moldyn *moldyn,u8 algo) {
42
43         switch(algo) {
44                 case MOLDYN_INTEGRATE_VERLET:
45                         moldyn->integrate=velocity_verlet;
46                         break;
47                 default:
48                         printf("unknown integration algorithm: %02x\n",algo);
49                         return -1;
50         }
51
52         return 0;
53 }
54
55 int set_cutoff(t_moldyn *moldyn,double cutoff) {
56
57         moldyn->cutoff=cutoff;
58
59         return 0;
60 }
61
62 int set_temperature(t_moldyn *moldyn,double t_ref) {
63
64         moldyn->t_ref=t_ref;
65
66         return 0;
67 }
68
69 int set_pressure(t_moldyn *moldyn,double p_ref) {
70
71         moldyn->p_ref=p_ref;
72
73         return 0;
74 }
75
76 int set_pt_scale(t_moldyn *moldyn,u8 ptype,double ptc,u8 ttype,double ttc) {
77
78         moldyn->pt_scale=(ptype|ttype);
79         moldyn->t_tc=ttc;
80         moldyn->p_tc=ptc;
81
82         return 0;
83 }
84
85 int set_dim(t_moldyn *moldyn,double x,double y,double z,u8 visualize) {
86
87         moldyn->dim.x=x;
88         moldyn->dim.y=y;
89         moldyn->dim.z=z;
90
91         moldyn->volume=x*y*z;
92
93         if(visualize) {
94                 moldyn->vis.dim.x=x;
95                 moldyn->vis.dim.y=y;
96                 moldyn->vis.dim.z=z;
97         }
98
99         printf("[moldyn] dimensions in A and A^3 respectively:\n");
100         printf("  x: %f\n",moldyn->dim.x);
101         printf("  y: %f\n",moldyn->dim.y);
102         printf("  z: %f\n",moldyn->dim.z);
103         printf("  volume: %f\n",moldyn->volume);
104         printf("  visualize simulation box: %s\n",visualize?"on":"off");
105
106         return 0;
107 }
108
109 int set_nn_dist(t_moldyn *moldyn,double dist) {
110
111         moldyn->nnd=dist;
112
113         return 0;
114 }
115
116 int set_pbc(t_moldyn *moldyn,u8 x,u8 y,u8 z) {
117
118         if(x)
119                 moldyn->status|=MOLDYN_STAT_PBX;
120
121         if(y)
122                 moldyn->status|=MOLDYN_STAT_PBY;
123
124         if(z)
125                 moldyn->status|=MOLDYN_STAT_PBZ;
126
127         return 0;
128 }
129
130 int set_potential1b(t_moldyn *moldyn,pf_func1b func,void *params) {
131
132         moldyn->func1b=func;
133         moldyn->pot1b_params=params;
134
135         return 0;
136 }
137
138 int set_potential2b(t_moldyn *moldyn,pf_func2b func,void *params) {
139
140         moldyn->func2b=func;
141         moldyn->pot2b_params=params;
142
143         return 0;
144 }
145
146 int set_potential2b_post(t_moldyn *moldyn,pf_func2b_post func,void *params) {
147
148         moldyn->func2b_post=func;
149         moldyn->pot2b_params=params;
150
151         return 0;
152 }
153
154 int set_potential3b(t_moldyn *moldyn,pf_func3b func,void *params) {
155
156         moldyn->func3b=func;
157         moldyn->pot3b_params=params;
158
159         return 0;
160 }
161
162 int moldyn_set_log_dir(t_moldyn *moldyn,char *dir) {
163
164         strncpy(moldyn->vlsdir,dir,127);
165
166         return 0;
167 }
168         
169 int moldyn_set_log(t_moldyn *moldyn,u8 type,int timer) {
170
171         char filename[128];
172         int ret;
173
174         switch(type) {
175                 case LOG_TOTAL_ENERGY:
176                         moldyn->ewrite=timer;
177                         snprintf(filename,127,"%s/energy",moldyn->vlsdir);
178                         moldyn->efd=open(filename,
179                                          O_WRONLY|O_CREAT|O_EXCL,
180                                          S_IRUSR|S_IWUSR);
181                         if(moldyn->efd<0) {
182                                 perror("[moldyn] energy log fd open");
183                                 return moldyn->efd;
184                         }
185                         dprintf(moldyn->efd,"# total energy log file\n");
186                         break;
187                 case LOG_TOTAL_MOMENTUM:
188                         moldyn->mwrite=timer;
189                         snprintf(filename,127,"%s/momentum",moldyn->vlsdir);
190                         moldyn->mfd=open(filename,
191                                          O_WRONLY|O_CREAT|O_EXCL,
192                                          S_IRUSR|S_IWUSR);
193                         if(moldyn->mfd<0) {
194                                 perror("[moldyn] momentum log fd open");
195                                 return moldyn->mfd;
196                         }
197                         dprintf(moldyn->efd,"# total momentum log file\n");
198                         break;
199                 case SAVE_STEP:
200                         moldyn->swrite=timer;
201                         break;
202                 case VISUAL_STEP:
203                         moldyn->vwrite=timer;
204                         ret=visual_init(&(moldyn->vis),moldyn->vlsdir);
205                         if(ret<0) {
206                                 printf("[moldyn] visual init failure\n");
207                                 return ret;
208                         }
209                         break;
210                 default:
211                         printf("[moldyn] unknown log mechanism: %02x\n",type);
212                         return -1;
213         }
214
215         return 0;
216 }
217
218 int moldyn_log_shutdown(t_moldyn *moldyn) {
219
220         printf("[moldyn] log shutdown\n");
221         if(moldyn->efd) close(moldyn->efd);
222         if(moldyn->mfd) close(moldyn->mfd);
223         if(&(moldyn->vis)) visual_tini(&(moldyn->vis));
224
225         return 0;
226 }
227
228 /*
229  * creating lattice functions
230  */
231
232 int create_lattice(t_moldyn *moldyn,u8 type,double lc,int element,double mass,
233                    u8 attr,u8 bnum,int a,int b,int c) {
234
235         int count;
236         int ret;
237         t_3dvec origin;
238
239         count=a*b*c;
240
241         /* how many atoms do we expect */
242         if(type==FCC) count*=4;
243         if(type==DIAMOND) count*=8;
244
245         /* allocate space for atoms */
246         moldyn->atom=malloc(count*sizeof(t_atom));
247         if(moldyn->atom==NULL) {
248                 perror("malloc (atoms)");
249                 return -1;
250         }
251
252         v3_zero(&origin);
253
254         switch(type) {
255                 case FCC:
256                         ret=fcc_init(a,b,c,lc,moldyn->atom,&origin);
257                         break;
258                 case DIAMOND:
259                         ret=diamond_init(a,b,c,lc,moldyn->atom,&origin);
260                         break;
261                 default:
262                         printf("unknown lattice type (%02x)\n",type);
263                         return -1;
264         }
265
266         /* debug */
267         if(ret!=count) {
268                 printf("[moldyn] creating lattice failed\n");
269                 printf("  amount of atoms\n");
270                 printf("  - expected: %d\n",count);
271                 printf("  - created: %d\n",ret);
272                 return -1;
273         }
274
275         moldyn->count=count;
276         printf("[moldyn] created lattice with %d atoms\n",count);
277
278         while(count) {
279                 count-=1;
280                 moldyn->atom[count].element=element;
281                 moldyn->atom[count].mass=mass;
282                 moldyn->atom[count].attr=attr;
283                 moldyn->atom[count].bnum=bnum;
284                 check_per_bound(moldyn,&(moldyn->atom[count].r));
285         }
286
287         return ret;
288 }
289
290 /* fcc lattice init */
291 int fcc_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
292
293         int count;
294         int i,j;
295         t_3dvec o,r,n;
296         t_3dvec basis[3];
297         double help[3];
298         double x,y,z;
299
300         x=a*lc;
301         y=b*lc;
302         z=c*lc;
303
304         if(origin) v3_copy(&o,origin);
305         else v3_zero(&o);
306
307         /* construct the basis */
308         for(i=0;i<3;i++) {
309                 for(j=0;j<3;j++) {
310                         if(i!=j) help[j]=0.5*lc;
311                         else help[j]=.0;
312                 }
313                 v3_set(&basis[i],help);
314         }
315
316         v3_zero(&r);
317         count=0;
318         
319         /* fill up the room */
320         r.x=o.x;
321         while(r.x<x) {
322                 r.y=o.y;
323                 while(r.y<y) {
324                         r.z=o.z;
325                         while(r.z<z) {
326                                 v3_copy(&(atom[count].r),&r);
327                                 atom[count].element=1;
328                                 count+=1;
329                                 for(i=0;i<3;i++) {
330                                         v3_add(&n,&r,&basis[i]);
331                                         if((n.x<x+o.x)&&
332                                            (n.y<y+o.y)&&
333                                            (n.z<z+o.z)) {
334                                                 v3_copy(&(atom[count].r),&n);
335                                                 count+=1;
336                                         }
337                                 }
338                                 r.z+=lc;        
339                         }
340                         r.y+=lc;
341                 }
342                 r.x+=lc;
343         }
344
345         /* coordinate transformation */
346         help[0]=x/2.0;
347         help[1]=y/2.0;
348         help[2]=z/2.0;
349         v3_set(&n,help);
350         for(i=0;i<count;i++)
351                 v3_sub(&(atom[i].r),&(atom[i].r),&n);
352                 
353         return count;
354 }
355
356 int diamond_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
357
358         int count;
359         t_3dvec o;
360
361         count=fcc_init(a,b,c,lc,atom,origin);
362
363         o.x=0.25*lc;
364         o.y=0.25*lc;
365         o.z=0.25*lc;
366
367         if(origin) v3_add(&o,&o,origin);
368
369         count+=fcc_init(a,b,c,lc,&atom[count],&o);
370
371         return count;
372 }
373
374 int add_atom(t_moldyn *moldyn,int element,double mass,u8 bnum,u8 attr,
375              t_3dvec *r,t_3dvec *v) {
376
377         t_atom *atom;
378         void *ptr;
379         int count;
380         
381         atom=moldyn->atom;
382         count=++(moldyn->count);
383
384         ptr=realloc(atom,count*sizeof(t_atom));
385         if(!ptr) {
386                 perror("[moldyn] realloc (add atom)");
387                 return -1;
388         }
389         moldyn->atom=ptr;
390
391         atom=moldyn->atom;
392         atom[count-1].r=*r;
393         atom[count-1].v=*v;
394         atom[count-1].element=element;
395         atom[count-1].mass=mass;
396         atom[count-1].bnum=bnum;
397         atom[count-1].attr=attr;
398
399         return 0;
400 }
401
402 int destroy_atoms(t_moldyn *moldyn) {
403
404         if(moldyn->atom) free(moldyn->atom);
405
406         return 0;
407 }
408
409 int thermal_init(t_moldyn *moldyn,u8 equi_init) {
410
411         /*
412          * - gaussian distribution of velocities
413          * - zero total momentum
414          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
415          */
416
417         int i;
418         double v,sigma;
419         t_3dvec p_total,delta;
420         t_atom *atom;
421         t_random *random;
422
423         atom=moldyn->atom;
424         random=&(moldyn->random);
425
426         /* gaussian distribution of velocities */
427         v3_zero(&p_total);
428         for(i=0;i<moldyn->count;i++) {
429                 sigma=sqrt(2.0*K_BOLTZMANN*moldyn->t_ref/atom[i].mass);
430                 /* x direction */
431                 v=sigma*rand_get_gauss(random);
432                 atom[i].v.x=v;
433                 p_total.x+=atom[i].mass*v;
434                 /* y direction */
435                 v=sigma*rand_get_gauss(random);
436                 atom[i].v.y=v;
437                 p_total.y+=atom[i].mass*v;
438                 /* z direction */
439                 v=sigma*rand_get_gauss(random);
440                 atom[i].v.z=v;
441                 p_total.z+=atom[i].mass*v;
442         }
443
444         /* zero total momentum */
445         v3_scale(&p_total,&p_total,1.0/moldyn->count);
446         for(i=0;i<moldyn->count;i++) {
447                 v3_scale(&delta,&p_total,1.0/atom[i].mass);
448                 v3_sub(&(atom[i].v),&(atom[i].v),&delta);
449         }
450
451         /* velocity scaling */
452         scale_velocity(moldyn,equi_init);
453
454         return 0;
455 }
456
457 int scale_velocity(t_moldyn *moldyn,u8 equi_init) {
458
459         int i;
460         double e,scale;
461         t_atom *atom;
462         int count;
463
464         atom=moldyn->atom;
465
466         /*
467          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
468          */
469
470         /* get kinetic energy / temperature & count involved atoms */
471         e=0.0;
472         count=0;
473         for(i=0;i<moldyn->count;i++) {
474                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB)) {
475                         e+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
476                         count+=1;
477                 }
478         }
479         if(count!=0) moldyn->t=e/(1.5*count*K_BOLTZMANN);
480         else return 0;  /* no atoms involved in scaling! */
481         
482         /* (temporary) hack for e,t = 0 */
483         if(e==0.0) {
484         moldyn->t=0.0;
485                 if(moldyn->t_ref!=0.0) {
486                         thermal_init(moldyn,equi_init);
487                         return 0;
488                 }
489                 else
490                         return 0; /* no scaling needed */
491         }
492
493
494         /* get scaling factor */
495         scale=moldyn->t_ref/moldyn->t;
496         if(equi_init&TRUE)
497                 scale*=2.0;
498         else
499                 if(moldyn->pt_scale&T_SCALE_BERENDSEN)
500                         scale=1.0+(scale-1.0)/moldyn->t_tc;
501         scale=sqrt(scale);
502
503         /* velocity scaling */
504         for(i=0;i<moldyn->count;i++) {
505                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB))
506                         v3_scale(&(atom[i].v),&(atom[i].v),scale);
507         }
508
509         return 0;
510 }
511
512 int scale_volume(t_moldyn *moldyn) {
513
514         t_atom *atom;
515         t_3dvec *dim,*vdim;
516         double virial,scale;
517         t_linkcell *lc;
518         int i;
519
520         atom=moldyn->atom;
521         dim=&(moldyn->dim);
522         vdim=&(moldyn->vis.dim);
523         lc=&(moldyn->lc);
524
525         for(i=0;i<moldyn->count;i++)
526                 virial+=v3_norm(&(atom[i].virial));
527
528 printf("%f\n",virial);
529         /* get pressure from virial */
530         moldyn->p=moldyn->count*K_BOLTZMANN*moldyn->t-ONE_THIRD*virial;
531         moldyn->p/=moldyn->volume;
532 printf("%f\n",moldyn->p/(ATM));
533
534         /* scale factor */
535         if(moldyn->pt_scale&P_SCALE_BERENDSEN)
536                 scale=3*sqrt(1-(moldyn->p_ref-moldyn->p)/moldyn->p_tc);
537         else 
538                 /* should actually never be used */
539                 scale=pow(moldyn->p/moldyn->p_ref,1.0/3.0);
540
541 printf("scale = %f\n",scale);
542         /* actual scaling */
543         dim->x*=scale;
544         dim->y*=scale;
545         dim->z*=scale;
546         if(vdim->x) vdim->x=dim->x;
547         if(vdim->y) vdim->y=dim->y;
548         if(vdim->z) vdim->z=dim->z;
549         moldyn->volume*=(scale*scale*scale);
550
551         /* check whether we need a new linkcell init */
552         if((dim->x/moldyn->cutoff!=lc->nx)||
553            (dim->y/moldyn->cutoff!=lc->ny)||
554            (dim->z/moldyn->cutoff!=lc->nx)) {
555                 link_cell_shutdown(moldyn);
556                 link_cell_init(moldyn);
557         }
558
559         return 0;
560
561 }
562
563 double get_e_kin(t_moldyn *moldyn) {
564
565         int i;
566         t_atom *atom;
567
568         atom=moldyn->atom;
569         moldyn->ekin=0.0;
570
571         for(i=0;i<moldyn->count;i++)
572                 moldyn->ekin+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
573
574         return moldyn->ekin;
575 }
576
577 double get_e_pot(t_moldyn *moldyn) {
578
579         return moldyn->energy;
580 }
581
582 double update_e_kin(t_moldyn *moldyn) {
583
584         return(get_e_kin(moldyn));
585 }
586
587 double get_total_energy(t_moldyn *moldyn) {
588
589         return(moldyn->ekin+moldyn->energy);
590 }
591
592 t_3dvec get_total_p(t_moldyn *moldyn) {
593
594         t_3dvec p,p_total;
595         int i;
596         t_atom *atom;
597
598         atom=moldyn->atom;
599
600         v3_zero(&p_total);
601         for(i=0;i<moldyn->count;i++) {
602                 v3_scale(&p,&(atom[i].v),atom[i].mass);
603                 v3_add(&p_total,&p_total,&p);
604         }
605
606         return p_total;
607 }
608
609 double estimate_time_step(t_moldyn *moldyn,double nn_dist) {
610
611         double tau;
612
613         /* nn_dist is the nearest neighbour distance */
614
615         tau=(0.05*nn_dist*moldyn->atom[0].mass)/sqrt(3.0*K_BOLTZMANN*moldyn->t);
616
617         return tau;     
618 }
619
620 /*
621  * numerical tricks
622  */
623
624 /* linked list / cell method */
625
626 int link_cell_init(t_moldyn *moldyn) {
627
628         t_linkcell *lc;
629         int i;
630
631         lc=&(moldyn->lc);
632
633         /* partitioning the md cell */
634         lc->nx=moldyn->dim.x/moldyn->cutoff;
635         lc->x=moldyn->dim.x/lc->nx;
636         lc->ny=moldyn->dim.y/moldyn->cutoff;
637         lc->y=moldyn->dim.y/lc->ny;
638         lc->nz=moldyn->dim.z/moldyn->cutoff;
639         lc->z=moldyn->dim.z/lc->nz;
640
641         lc->cells=lc->nx*lc->ny*lc->nz;
642         lc->subcell=malloc(lc->cells*sizeof(t_list));
643
644         printf("[moldyn] initializing linked cells (%d)\n",lc->cells);
645
646         for(i=0;i<lc->cells;i++)
647                 list_init_f(&(lc->subcell[i]));
648
649         link_cell_update(moldyn);
650         
651         return 0;
652 }
653
654 int link_cell_update(t_moldyn *moldyn) {
655
656         int count,i,j,k;
657         int nx,ny;
658         t_atom *atom;
659         t_linkcell *lc;
660         double x,y,z;
661
662         atom=moldyn->atom;
663         lc=&(moldyn->lc);
664
665         nx=lc->nx;
666         ny=lc->ny;
667
668         x=moldyn->dim.x/2;
669         y=moldyn->dim.y/2;
670         z=moldyn->dim.z/2;
671
672         for(i=0;i<lc->cells;i++)
673                 list_destroy_f(&(lc->subcell[i]));
674         
675         for(count=0;count<moldyn->count;count++) {
676                 i=((atom[count].r.x+(moldyn->dim.x/2))/lc->x);
677                 j=((atom[count].r.y+(moldyn->dim.y/2))/lc->y);
678                 k=((atom[count].r.z+(moldyn->dim.z/2))/lc->z);
679                 list_add_immediate_f(&(moldyn->lc.subcell[i+j*nx+k*nx*ny]),
680                                      &(atom[count]));
681         }
682
683         return 0;
684 }
685
686 int link_cell_neighbour_index(t_moldyn *moldyn,int i,int j,int k,t_list *cell) {
687
688         t_linkcell *lc;
689         int a;
690         int count1,count2;
691         int ci,cj,ck;
692         int nx,ny,nz;
693         int x,y,z;
694         u8 bx,by,bz;
695
696         lc=&(moldyn->lc);
697         nx=lc->nx;
698         ny=lc->ny;
699         nz=lc->nz;
700         count1=1;
701         count2=27;
702         a=nx*ny;
703
704         cell[0]=lc->subcell[i+j*nx+k*a];
705         for(ci=-1;ci<=1;ci++) {
706                 bx=0;
707                 x=i+ci;
708                 if((x<0)||(x>=nx)) {
709                         x=(x+nx)%nx;
710                         bx=1;
711                 }
712                 for(cj=-1;cj<=1;cj++) {
713                         by=0;
714                         y=j+cj;
715                         if((y<0)||(y>=ny)) {
716                                 y=(y+ny)%ny;
717                                 by=1;
718                         }
719                         for(ck=-1;ck<=1;ck++) {
720                                 bz=0;
721                                 z=k+ck;
722                                 if((z<0)||(z>=nz)) {
723                                         z=(z+nz)%nz;
724                                         bz=1;
725                                 }
726                                 if(!(ci|cj|ck)) continue;
727                                 if(bx|by|bz) {
728                                         cell[--count2]=lc->subcell[x+y*nx+z*a];
729                                 }
730                                 else {
731                                         cell[count1++]=lc->subcell[x+y*nx+z*a];
732                                 }
733                         }
734                 }
735         }
736
737         lc->dnlc=count1;
738
739         return count1;
740 }
741
742 int link_cell_shutdown(t_moldyn *moldyn) {
743
744         int i;
745         t_linkcell *lc;
746
747         lc=&(moldyn->lc);
748
749         for(i=0;i<lc->nx*lc->ny*lc->nz;i++)
750                 list_destroy_f(&(moldyn->lc.subcell[i]));
751
752         free(lc->subcell);
753
754         return 0;
755 }
756
757 int moldyn_add_schedule(t_moldyn *moldyn,int runs,double tau) {
758
759         int count;
760         void *ptr;
761         t_moldyn_schedule *schedule;
762
763         schedule=&(moldyn->schedule);
764         count=++(schedule->content_count);
765
766         ptr=realloc(moldyn->schedule.runs,count*sizeof(int));
767         if(!ptr) {
768                 perror("[moldyn] realloc (runs)");
769                 return -1;
770         }
771         moldyn->schedule.runs=ptr;
772         moldyn->schedule.runs[count-1]=runs;
773
774         ptr=realloc(schedule->tau,count*sizeof(double));
775         if(!ptr) {
776                 perror("[moldyn] realloc (tau)");
777                 return -1;
778         }
779         moldyn->schedule.tau=ptr;
780         moldyn->schedule.tau[count-1]=tau;
781
782         return 0;
783 }
784
785 int moldyn_set_schedule_hook(t_moldyn *moldyn,void *hook,void *hook_params) {
786
787         moldyn->schedule.hook=hook;
788         moldyn->schedule.hook_params=hook_params;
789         
790         return 0;
791 }
792
793 /*
794  *
795  * 'integration of newtons equation' - algorithms
796  *
797  */
798
799 /* start the integration */
800
801 int moldyn_integrate(t_moldyn *moldyn) {
802
803         int i,sched;
804         unsigned int e,m,s,v;
805         t_3dvec p;
806         t_moldyn_schedule *schedule;
807         t_atom *atom;
808         int fd;
809         char dir[128];
810         double ds;
811
812         schedule=&(moldyn->schedule);
813         atom=moldyn->atom;
814
815         /* initialize linked cell method */
816         link_cell_init(moldyn);
817
818         /* logging & visualization */
819         e=moldyn->ewrite;
820         m=moldyn->mwrite;
821         s=moldyn->swrite;
822         v=moldyn->vwrite;
823
824         /* sqaure of some variables */
825         moldyn->tau_square=moldyn->tau*moldyn->tau;
826         moldyn->cutoff_square=moldyn->cutoff*moldyn->cutoff;
827
828         /* calculate initial forces */
829         potential_force_calc(moldyn);
830
831         /* some stupid checks before we actually start calculating bullshit */
832         if(moldyn->cutoff>0.5*moldyn->dim.x)
833                 printf("[moldyn] warning: cutoff > 0.5 x dim.x\n");
834         if(moldyn->cutoff>0.5*moldyn->dim.y)
835                 printf("[moldyn] warning: cutoff > 0.5 x dim.y\n");
836         if(moldyn->cutoff>0.5*moldyn->dim.z)
837                 printf("[moldyn] warning: cutoff > 0.5 x dim.z\n");
838         ds=0.5*atom[0].f.x*moldyn->tau_square/atom[0].mass;
839         if(ds>0.05*moldyn->nnd)
840                 printf("[moldyn] warning: forces too high / tau too small!\n");
841
842         /* zero absolute time */
843         moldyn->time=0.0;
844
845         /* debugging, ignore */
846         moldyn->debug=0;
847
848         /* executing the schedule */
849         for(sched=0;sched<moldyn->schedule.content_count;sched++) {
850
851                 /* setting amount of runs and finite time step size */
852                 moldyn->tau=schedule->tau[sched];
853                 moldyn->tau_square=moldyn->tau*moldyn->tau;
854                 moldyn->time_steps=schedule->runs[sched];
855
856         /* integration according to schedule */
857
858         for(i=0;i<moldyn->time_steps;i++) {
859
860                 /* integration step */
861                 moldyn->integrate(moldyn);
862
863                 /* p/t scaling */
864                 if(moldyn->pt_scale&(T_SCALE_BERENDSEN|T_SCALE_DIRECT))
865                         scale_velocity(moldyn,FALSE);
866                 if(moldyn->pt_scale&(P_SCALE_BERENDSEN|P_SCALE_DIRECT))
867                         scale_volume(moldyn);
868
869                 /* check for log & visualization */
870                 if(e) {
871                         if(!(i%e))
872                                 dprintf(moldyn->efd,
873                                         "%f %f %f %f\n",
874                                         moldyn->time,update_e_kin(moldyn),
875                                         moldyn->energy,
876                                         get_total_energy(moldyn));
877                 }
878                 if(m) {
879                         if(!(i%m)) {
880                                 p=get_total_p(moldyn);
881                                 dprintf(moldyn->mfd,
882                                         "%f %f\n",moldyn->time,v3_norm(&p));
883                         }
884                 }
885                 if(s) {
886                         if(!(i%s)) {
887                                 snprintf(dir,128,"%s/s-%07.f.save",
888                                          moldyn->vlsdir,moldyn->time);
889                                 fd=open(dir,O_WRONLY|O_TRUNC|O_CREAT);
890                                 if(fd<0) perror("[moldyn] save fd open");
891                                 else {
892                                         write(fd,moldyn,sizeof(t_moldyn));
893                                         write(fd,moldyn->atom,
894                                               moldyn->count*sizeof(t_atom));
895                                 }
896                                 close(fd);
897                         }       
898                 }
899                 if(v) {
900                         if(!(i%v)) {
901                                 visual_atoms(&(moldyn->vis),moldyn->time,
902                                              moldyn->atom,moldyn->count);
903                                 printf("\rsched: %d, steps: %d, debug: %d",
904                                        sched,i,moldyn->debug);
905                                 fflush(stdout);
906                         }
907                 }
908
909                 /* increase absolute time */
910                 moldyn->time+=moldyn->tau;
911
912         }
913
914                 /* check for hooks */
915                 if(schedule->hook)
916                         schedule->hook(moldyn,schedule->hook_params);
917
918                 /* get a new info line */
919                 printf("\n");
920
921         }
922
923         return 0;
924 }
925
926 /* velocity verlet */
927
928 int velocity_verlet(t_moldyn *moldyn) {
929
930         int i,count;
931         double tau,tau_square;
932         t_3dvec delta;
933         t_atom *atom;
934
935         atom=moldyn->atom;
936         count=moldyn->count;
937         tau=moldyn->tau;
938         tau_square=moldyn->tau_square;
939
940         for(i=0;i<count;i++) {
941                 /* new positions */
942                 v3_scale(&delta,&(atom[i].v),tau);
943                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
944                 v3_scale(&delta,&(atom[i].f),0.5*tau_square/atom[i].mass);
945                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
946                 check_per_bound(moldyn,&(atom[i].r));
947
948                 /* velocities */
949                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
950                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
951         }
952
953         /* neighbour list update */
954         link_cell_update(moldyn);
955
956         /* forces depending on chosen potential */
957         potential_force_calc(moldyn);
958
959         for(i=0;i<count;i++) {
960                 /* again velocities */
961                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
962                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
963         }
964
965         return 0;
966 }
967
968
969 /*
970  *
971  * potentials & corresponding forces
972  * 
973  */
974
975 /* generic potential and force calculation */
976
977 int potential_force_calc(t_moldyn *moldyn) {
978
979         int i,j,k,count;
980         t_atom *itom,*jtom,*ktom;
981         t_linkcell *lc;
982         t_list neighbour_i[27];
983         t_list neighbour_i2[27];
984         t_list *this,*that;
985         u8 bc_ij,bc_ik;
986         int dnlc;
987
988         count=moldyn->count;
989         itom=moldyn->atom;
990         lc=&(moldyn->lc);
991
992         /* reset energy */
993         moldyn->energy=0.0;
994         
995         /* get energy and force of every atom */
996         for(i=0;i<count;i++) {
997
998                 /* reset force */
999                 v3_zero(&(itom[i].f));
1000
1001                 /* reset viral of atom i */
1002                 v3_zero(&(itom[i].virial));
1003
1004                 /* reset site energy */
1005                 itom[i].e=0.0;
1006
1007                 /* single particle potential/force */
1008                 if(itom[i].attr&ATOM_ATTR_1BP)
1009                         moldyn->func1b(moldyn,&(itom[i]));
1010
1011                 if(!(itom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)))
1012                         continue;
1013
1014                 /* 2 body pair potential/force */
1015         
1016                 link_cell_neighbour_index(moldyn,
1017                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
1018                                           (itom[i].r.y+moldyn->dim.y/2)/lc->y,
1019                                           (itom[i].r.z+moldyn->dim.z/2)/lc->z,
1020                                           neighbour_i);
1021
1022                 dnlc=lc->dnlc;
1023
1024                 for(j=0;j<27;j++) {
1025
1026                         this=&(neighbour_i[j]);
1027                         list_reset_f(this);
1028
1029                         if(this->start==NULL)
1030                                 continue;
1031
1032                         bc_ij=(j<dnlc)?0:1;
1033
1034                         do {
1035                                 jtom=this->current->data;
1036
1037                                 if(jtom==&(itom[i]))
1038                                         continue;
1039
1040                                 if((jtom->attr&ATOM_ATTR_2BP)&
1041                                    (itom[i].attr&ATOM_ATTR_2BP)) {
1042                                         moldyn->func2b(moldyn,
1043                                                        &(itom[i]),
1044                                                        jtom,
1045                                                        bc_ij);
1046                                 }
1047
1048                                 /* 3 body potential/force */
1049
1050                                 if(!(itom[i].attr&ATOM_ATTR_3BP)||
1051                                    !(jtom->attr&ATOM_ATTR_3BP))
1052                                         continue;
1053
1054                                 /* copy the neighbour lists */
1055                                 memcpy(neighbour_i2,neighbour_i,
1056                                        27*sizeof(t_list));
1057
1058                                 /* get neighbours of i */
1059                                 for(k=0;k<27;k++) {
1060
1061                                         that=&(neighbour_i2[k]);
1062                                         list_reset_f(that);
1063                                         
1064                                         if(that->start==NULL)
1065                                                 continue;
1066
1067                                         bc_ik=(k<dnlc)?0:1;
1068
1069                                         do {
1070
1071                                                 ktom=that->current->data;
1072
1073                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
1074                                                         continue;
1075
1076                                                 if(ktom==jtom)
1077                                                         continue;
1078
1079                                                 if(ktom==&(itom[i]))
1080                                                         continue;
1081
1082                                                 moldyn->func3b(moldyn,
1083                                                                &(itom[i]),
1084                                                                jtom,
1085                                                                ktom,
1086                                                                bc_ik|bc_ij);
1087
1088                                         } while(list_next_f(that)!=\
1089                                                 L_NO_NEXT_ELEMENT);
1090
1091                                 }
1092
1093                                 /* 2bp post function */
1094                                 if(moldyn->func2b_post) {
1095                                         moldyn->func2b_post(moldyn,
1096                                                             &(itom[i]),
1097                                                             jtom,bc_ij);
1098                                 }
1099                                         
1100                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
1101                 
1102                 }
1103
1104         }
1105
1106         return 0;
1107 }
1108
1109 /*
1110  * periodic boundayr checking
1111  */
1112
1113 inline int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
1114         
1115         double x,y,z;
1116         t_3dvec *dim;
1117
1118         dim=&(moldyn->dim);
1119
1120         x=dim->x/2;
1121         y=dim->y/2;
1122         z=dim->z/2;
1123
1124         if(moldyn->status&MOLDYN_STAT_PBX) {
1125                 if(a->x>=x) a->x-=dim->x;
1126                 else if(-a->x>x) a->x+=dim->x;
1127         }
1128         if(moldyn->status&MOLDYN_STAT_PBY) {
1129                 if(a->y>=y) a->y-=dim->y;
1130                 else if(-a->y>y) a->y+=dim->y;
1131         }
1132         if(moldyn->status&MOLDYN_STAT_PBZ) {
1133                 if(a->z>=z) a->z-=dim->z;
1134                 else if(-a->z>z) a->z+=dim->z;
1135         }
1136
1137         return 0;
1138 }
1139         
1140
1141 /*
1142  * example potentials
1143  */
1144
1145 /* harmonic oscillator potential and force */
1146
1147 int harmonic_oscillator(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1148
1149         t_ho_params *params;
1150         t_3dvec force,distance;
1151         double d;
1152         double sc,equi_dist;
1153
1154         params=moldyn->pot2b_params;
1155         sc=params->spring_constant;
1156         equi_dist=params->equilibrium_distance;
1157
1158         v3_sub(&distance,&(aj->r),&(ai->r));
1159         
1160         if(bc) check_per_bound(moldyn,&distance);
1161         d=v3_norm(&distance);
1162         if(d<=moldyn->cutoff) {
1163                 /* energy is 1/2 (d-d0)^2, but we will add this twice ... */
1164                 moldyn->energy+=(0.25*sc*(d-equi_dist)*(d-equi_dist));
1165                 /* f = -grad E; grad r_ij = -1 1/r_ij distance */
1166                 v3_scale(&force,&distance,sc*(1.0-(equi_dist/d)));
1167                 v3_add(&(ai->f),&(ai->f),&force);
1168         }
1169
1170         return 0;
1171 }
1172
1173 /* lennard jones potential & force for one sort of atoms */
1174  
1175 int lennard_jones(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1176
1177         t_lj_params *params;
1178         t_3dvec force,distance;
1179         double d,h1,h2;
1180         double eps,sig6,sig12;
1181
1182         params=moldyn->pot2b_params;
1183         eps=params->epsilon4;
1184         sig6=params->sigma6;
1185         sig12=params->sigma12;
1186
1187         v3_sub(&distance,&(aj->r),&(ai->r));
1188         if(bc) check_per_bound(moldyn,&distance);
1189         d=v3_absolute_square(&distance);        /* 1/r^2 */
1190         if(d<=moldyn->cutoff_square) {
1191                 d=1.0/d;                        /* 1/r^2 */
1192                 h2=d*d;                         /* 1/r^4 */
1193                 h2*=d;                          /* 1/r^6 */
1194                 h1=h2*h2;                       /* 1/r^12 */
1195                 /* energy is eps*..., but we will add this twice ... */
1196                 moldyn->energy+=0.5*eps*(sig12*h1-sig6*h2);
1197                 h2*=d;                          /* 1/r^8 */
1198                 h1*=d;                          /* 1/r^14 */
1199                 h2*=6*sig6;
1200                 h1*=12*sig12;
1201                 d=+h1-h2;
1202                 d*=eps;
1203                 v3_scale(&force,&distance,-1.0*d); /* f = - grad E */
1204                 v3_add(&(ai->f),&(ai->f),&force);
1205         }
1206
1207         return 0;
1208 }
1209
1210 /*
1211  * tersoff potential & force for 2 sorts of atoms
1212  */
1213
1214 /* create mixed terms from parameters and set them */
1215 int tersoff_mult_complete_params(t_tersoff_mult_params *p) {
1216
1217         printf("[moldyn] tersoff parameter completion\n");
1218         p->Smixed=sqrt(p->S[0]*p->S[1]);
1219         p->Rmixed=sqrt(p->R[0]*p->R[1]);
1220         p->Amixed=sqrt(p->A[0]*p->A[1]);
1221         p->Bmixed=sqrt(p->B[0]*p->B[1]);
1222         p->lambda_m=0.5*(p->lambda[0]+p->lambda[1]);
1223         p->mu_m=0.5*(p->mu[0]+p->mu[1]);
1224
1225         printf("[moldyn] tersoff mult parameter info:\n");
1226         printf("  S (A)  | %f | %f | %f\n",p->S[0],p->S[1],p->Smixed);
1227         printf("  R (A)  | %f | %f | %f\n",p->R[0],p->R[1],p->Rmixed);
1228         printf("  A (eV) | %f | %f | %f\n",p->A[0]/EV,p->A[1]/EV,p->Amixed/EV);
1229         printf("  B (eV) | %f | %f | %f\n",p->B[0]/EV,p->B[1]/EV,p->Bmixed/EV);
1230         printf("  lambda | %f | %f | %f\n",p->lambda[0],p->lambda[1],
1231                                           p->lambda_m);
1232         printf("  mu     | %f | %f | %f\n",p->mu[0],p->mu[1],p->mu_m);
1233         printf("  beta   | %.10f | %.10f\n",p->beta[0],p->beta[1]);
1234         printf("  n      | %f | %f\n",p->n[0],p->n[1]);
1235         printf("  c      | %f | %f\n",p->c[0],p->c[1]);
1236         printf("  d      | %f | %f\n",p->d[0],p->d[1]);
1237         printf("  h      | %f | %f\n",p->h[0],p->h[1]);
1238         printf("  chi    | %f \n",p->chi);
1239
1240         return 0;
1241 }
1242
1243 /* tersoff 1 body part */
1244 int tersoff_mult_1bp(t_moldyn *moldyn,t_atom *ai) {
1245
1246         int num;
1247         t_tersoff_mult_params *params;
1248         t_tersoff_exchange *exchange;
1249         
1250         num=ai->bnum;
1251         params=moldyn->pot1b_params;
1252         exchange=&(params->exchange);
1253
1254         /*
1255          * simple: point constant parameters only depending on atom i to
1256          *         their right values
1257          */
1258
1259         exchange->beta_i=&(params->beta[num]);
1260         exchange->n_i=&(params->n[num]);
1261         exchange->c_i=&(params->c[num]);
1262         exchange->d_i=&(params->d[num]);
1263         exchange->h_i=&(params->h[num]);
1264
1265         exchange->betaini=pow(*(exchange->beta_i),*(exchange->n_i));
1266         exchange->ci2=params->c[num]*params->c[num];
1267         exchange->di2=params->d[num]*params->d[num];
1268         exchange->ci2di2=exchange->ci2/exchange->di2;
1269
1270         return 0;
1271 }
1272         
1273 /* tersoff 2 body part */
1274 int tersoff_mult_2bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1275
1276         t_tersoff_mult_params *params;
1277         t_tersoff_exchange *exchange;
1278         t_3dvec dist_ij,force;
1279         double d_ij;
1280         double A,B,R,S,lambda,mu;
1281         double f_r,df_r;
1282         double f_c,df_c;
1283         int num;
1284         double s_r;
1285         double arg;
1286
1287         params=moldyn->pot2b_params;
1288         num=aj->bnum;
1289         exchange=&(params->exchange);
1290
1291         /* clear 3bp and 2bp post run */
1292         exchange->run3bp=0;
1293         exchange->run2bp_post=0;
1294
1295         /* reset S > r > R mark */
1296         exchange->d_ij_between_rs=0;
1297         
1298         /*
1299          * calc of 2bp contribution of V_ij and dV_ij/ji
1300          *
1301          * for Vij and dV_ij we need:
1302          * - f_c_ij, df_c_ij
1303          * - f_r_ij, df_r_ij
1304          *
1305          * for dV_ji we need:
1306          * - f_c_ji = f_c_ij, df_c_ji = df_c_ij
1307          * - f_r_ji = f_r_ij; df_r_ji = df_r_ij
1308          *
1309          */
1310
1311         /* dist_ij, d_ij */
1312         v3_sub(&dist_ij,&(aj->r),&(ai->r));
1313         if(bc) check_per_bound(moldyn,&dist_ij);
1314         d_ij=v3_norm(&dist_ij);
1315
1316         /* save for use in 3bp */
1317         exchange->d_ij=d_ij;
1318         exchange->dist_ij=dist_ij;
1319
1320         /* constants */
1321         if(num==ai->bnum) {
1322                 S=params->S[num];
1323                 R=params->R[num];
1324                 A=params->A[num];
1325                 B=params->B[num];
1326                 lambda=params->lambda[num];
1327                 mu=params->mu[num];
1328                 exchange->chi=1.0;
1329         }
1330         else {
1331                 S=params->Smixed;
1332                 R=params->Rmixed;
1333                 A=params->Amixed;
1334                 B=params->Bmixed;
1335                 lambda=params->lambda_m;
1336                 mu=params->mu_m;
1337                 params->exchange.chi=params->chi;
1338         }
1339
1340         /* if d_ij > S => no force & potential energy contribution */
1341         if(d_ij>S)
1342                 return 0;
1343
1344         /* more constants */
1345         exchange->beta_j=&(params->beta[num]);
1346         exchange->n_j=&(params->n[num]);
1347         exchange->c_j=&(params->c[num]);
1348         exchange->d_j=&(params->d[num]);
1349         exchange->h_j=&(params->h[num]);
1350         if(num==ai->bnum) {
1351                 exchange->betajnj=exchange->betaini;
1352                 exchange->cj2=exchange->ci2;
1353                 exchange->dj2=exchange->di2;
1354                 exchange->cj2dj2=exchange->ci2di2;
1355         }
1356         else {
1357                 exchange->betajnj=pow(*(exchange->beta_j),*(exchange->n_j));
1358                 exchange->cj2=params->c[num]*params->c[num];
1359                 exchange->dj2=params->d[num]*params->d[num];
1360                 exchange->cj2dj2=exchange->cj2/exchange->dj2;
1361         }
1362
1363         /* f_r_ij = f_r_ji, df_r_ij = df_r_ji */
1364         f_r=A*exp(-lambda*d_ij);
1365         df_r=lambda*f_r/d_ij;
1366
1367         /* f_a, df_a calc (again, same for ij and ji) | save for later use! */
1368         exchange->f_a=-B*exp(-mu*d_ij);
1369         exchange->df_a=mu*exchange->f_a/d_ij;
1370
1371         /* f_c, df_c calc (again, same for ij and ji) */
1372         if(d_ij<R) {
1373                 /* f_c = 1, df_c = 0 */
1374                 f_c=1.0;
1375                 df_c=0.0;
1376                 /* two body contribution (ij, ji) */
1377                 v3_scale(&force,&dist_ij,-df_r);
1378         }
1379         else {
1380                 s_r=S-R;
1381                 arg=M_PI*(d_ij-R)/s_r;
1382                 f_c=0.5+0.5*cos(arg);
1383                 //df_c=-0.5*sin(arg)*(M_PI/(s_r*d_ij)); /* MARK! */
1384                 df_c=0.5*sin(arg)*(M_PI/(s_r*d_ij));
1385                 /* two body contribution (ij, ji) */
1386                 v3_scale(&force,&dist_ij,-df_c*f_r-df_r*f_c);
1387                 /* tell 3bp that S > r > R */
1388                 exchange->d_ij_between_rs=1;
1389         }
1390
1391         /* add forces of 2bp (ij, ji) contribution
1392          * dVij = dVji and we sum up both: no 1/2) */
1393         v3_add(&(ai->f),&(ai->f),&force);
1394
1395         /* energy 2bp contribution (ij, ji) is 0.5 f_r f_c ... */
1396         moldyn->energy+=(0.5*f_r*f_c);
1397
1398         /* save for use in 3bp */
1399         exchange->f_c=f_c;
1400         exchange->df_c=df_c;
1401
1402         /* enable the run of 3bp function and 2bp post processing */
1403         exchange->run3bp=1;
1404         exchange->run2bp_post=1;
1405
1406         /* reset 3bp sums */
1407         exchange->zeta_ij=0.0;
1408         exchange->zeta_ji=0.0;
1409         v3_zero(&(exchange->dzeta_ij));
1410         v3_zero(&(exchange->dzeta_ji));
1411
1412         return 0;
1413 }
1414
1415 /* tersoff 2 body post part */
1416
1417 int tersoff_mult_post_2bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1418
1419         /*
1420          * here we have to allow for the 3bp sums
1421          *
1422          * that is:
1423          * - zeta_ij, dzeta_ij
1424          * - zeta_ji, dzeta_ji
1425          *
1426          * to compute the 3bp contribution to:
1427          * - Vij, dVij
1428          * - dVji
1429          *
1430          */
1431
1432         t_tersoff_mult_params *params;
1433         t_tersoff_exchange *exchange;
1434
1435         t_3dvec force,temp;
1436         t_3dvec *dist_ij;
1437         double b,db,tmp;
1438         double f_c,df_c,f_a,df_a;
1439         double chi,ni,betaini,nj,betajnj;
1440         double zeta;
1441
1442         params=moldyn->pot2b_params;
1443         exchange=&(params->exchange);
1444
1445         /* we do not run if f_c_ij was detected to be 0! */
1446         if(!(exchange->run2bp_post))
1447                 return 0;
1448
1449         f_c=exchange->f_c;
1450         df_c=exchange->df_c;
1451         f_a=exchange->f_a;
1452         df_a=exchange->df_a;
1453         betaini=exchange->betaini;
1454         betajnj=exchange->betajnj;
1455         ni=*(exchange->n_i);
1456         nj=*(exchange->n_j);
1457         chi=exchange->chi;
1458         dist_ij=&(exchange->dist_ij);
1459         
1460         /* Vij and dVij */
1461         zeta=exchange->zeta_ij;
1462         if(zeta==0.0) {
1463                 moldyn->debug++;                /* just for debugging ... */
1464                 db=0.0;
1465                 b=chi;
1466                 v3_scale(&force,dist_ij,df_a*b*f_c);
1467         }
1468         else {
1469                 tmp=betaini*pow(zeta,ni-1.0);           /* beta^n * zeta^n-1 */
1470                 b=(1+zeta*tmp);                         /* 1 + beta^n zeta^n */
1471                 db=chi*pow(b,-1.0/(2*ni)-1);            /* x(...)^(-1/2n - 1) */
1472                 b=db*b;                                 /* b_ij */
1473                 db*=-0.5*tmp;                           /* db_ij */
1474                 v3_scale(&force,&(exchange->dzeta_ij),f_a*db);
1475                 v3_scale(&temp,dist_ij,df_a*b);
1476                 v3_add(&force,&force,&temp);
1477                 v3_scale(&force,&force,f_c);
1478         }
1479         v3_scale(&temp,dist_ij,df_c*b*f_a);
1480         v3_add(&force,&force,&temp);
1481         v3_scale(&force,&force,-0.5);
1482
1483         /* add force */
1484         v3_add(&(ai->f),&(ai->f),&force);
1485
1486         /* add energy of 3bp sum */
1487         moldyn->energy+=(0.5*f_c*b*f_a);
1488
1489         /* dVji */
1490         zeta=exchange->zeta_ji;
1491         if(zeta==0.0) {
1492                 moldyn->debug++;
1493                 b=chi;
1494                 v3_scale(&force,dist_ij,df_a*b*f_c);
1495         }
1496         else {
1497                 tmp=betajnj*pow(zeta,nj-1.0);           /* beta^n * zeta^n-1 */
1498                 b=(1+zeta*tmp);                         /* 1 + beta^n zeta^n */
1499                 db=chi*pow(b,-1.0/(2*nj)-1);            /* x(...)^(-1/2n - 1) */
1500                 b=db*b;                                 /* b_ij */
1501                 db*=-0.5*tmp;                           /* db_ij */
1502                 v3_scale(&force,&(exchange->dzeta_ji),f_a*db);
1503                 v3_scale(&temp,dist_ij,df_a*b);
1504                 v3_add(&force,&force,&temp);
1505                 v3_scale(&force,&force,f_c);
1506         }
1507         v3_scale(&temp,dist_ij,df_c*b*f_a);
1508         v3_add(&force,&force,&temp);
1509         v3_scale(&force,&force,-0.5);
1510
1511         /* add force */
1512         v3_add(&(ai->f),&(ai->f),&force);
1513
1514         return 0;
1515 }
1516
1517 /* tersoff 3 body part */
1518
1519 int tersoff_mult_3bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,t_atom *ak,u8 bc) {
1520
1521         t_tersoff_mult_params *params;
1522         t_tersoff_exchange *exchange;
1523         t_3dvec dist_ij,dist_ik,dist_jk;
1524         t_3dvec temp1,temp2;
1525         t_3dvec *dzeta;
1526         double R,S,s_r;
1527         double B,mu;
1528         double d_ij,d_ik,d_jk;
1529         double rr,dd;
1530         double f_c,df_c;
1531         double f_c_ik,df_c_ik,arg;
1532         double f_c_jk;
1533         double n,c,d,h;
1534         double c2,d2,c2d2;
1535         double cos_theta,d_costheta1,d_costheta2;
1536         double h_cos,d2_h_cos2;
1537         double frac,g,zeta,chi;
1538         double tmp;
1539         int num;
1540
1541         params=moldyn->pot3b_params;
1542         exchange=&(params->exchange);
1543
1544         if(!(exchange->run3bp))
1545                 return 0;
1546
1547         /*
1548          * calc of 3bp contribution of V_ij and dV_ij/ji/jk &
1549          * 2bp contribution of dV_jk
1550          *
1551          * for Vij and dV_ij we still need:
1552          * - b_ij, db_ij (zeta_ij)
1553          *   - f_c_ik, df_c_ik, constants_i, cos_theta_ijk, d_costheta_ijk
1554          *
1555          * for dV_ji we still need:
1556          * - b_ji, db_ji (zeta_ji)
1557          *   - f_c_jk, d_c_jk, constants_j, cos_theta_jik, d_costheta_jik
1558          *
1559          * for dV_jk we need:
1560          * - f_c_jk
1561          * - f_a_jk
1562          * - db_jk (zeta_jk)
1563          *   - f_c_ji, df_c_ji, constants_j, cos_theta_jki, d_costheta_jki
1564          *
1565          */
1566
1567         /*
1568          * get exchange data 
1569          */
1570
1571         /* dist_ij, d_ij - this is < S_ij ! */
1572         dist_ij=exchange->dist_ij;
1573         d_ij=exchange->d_ij;
1574
1575         /* f_c_ij, df_c_ij (same for ji) */
1576         f_c=exchange->f_c;
1577         df_c=exchange->df_c;
1578
1579         /*
1580          * calculate unknown values now ...
1581          */
1582
1583         /* V_ij and dV_ij stuff (in b_ij there is f_c_ik) */
1584
1585         /* dist_ik, d_ik */
1586         v3_sub(&dist_ik,&(ak->r),&(ai->r));
1587         if(bc) check_per_bound(moldyn,&dist_ik);
1588         d_ik=v3_norm(&dist_ik);
1589
1590         /* ik constants */
1591         num=ai->bnum;
1592         if(num==ak->bnum) {
1593                 R=params->R[num];
1594                 S=params->S[num];
1595         }
1596         else {
1597                 R=params->Rmixed;
1598                 S=params->Smixed;
1599         }
1600
1601         /* zeta_ij/dzeta_ij contribution only for d_ik < S */
1602         if(d_ik<S) {
1603
1604                 /* get constants_i from exchange data */
1605                 n=*(exchange->n_i);
1606                 c=*(exchange->c_i);
1607                 d=*(exchange->d_i);
1608                 h=*(exchange->h_i);
1609                 c2=exchange->ci2;
1610                 d2=exchange->di2;
1611                 c2d2=exchange->ci2di2;
1612
1613                 /* cosine of theta_ijk by scalaproduct */
1614                 rr=v3_scalar_product(&dist_ij,&dist_ik);
1615                 dd=d_ij*d_ik;
1616                 cos_theta=rr/dd;
1617
1618                 /* d_costheta */
1619                 tmp=1.0/dd;
1620                 d_costheta1=cos_theta/(d_ij*d_ij)-tmp;
1621                 d_costheta2=cos_theta/(d_ik*d_ik)-tmp;
1622
1623                 /* some usefull values */
1624                 h_cos=(h-cos_theta);
1625                 d2_h_cos2=d2+(h_cos*h_cos);
1626                 frac=c2/(d2_h_cos2);
1627
1628                 /* g(cos_theta) */
1629                 g=1.0+c2d2-frac;
1630
1631                 /* d_costheta_ij and dg(cos_theta) - needed in any case! */
1632                 v3_scale(&temp1,&dist_ij,d_costheta1);
1633                 v3_scale(&temp2,&dist_ik,d_costheta2);
1634                 v3_add(&temp1,&temp1,&temp2);
1635                 v3_scale(&temp1,&temp1,-2.0*frac*h_cos/d2_h_cos2); /* dg */
1636
1637                 /* f_c_ik & df_c_ik + {d,}zeta contribution */
1638                 dzeta=&(exchange->dzeta_ij);
1639                 if(d_ik<R) {
1640                         /* {d,}f_c_ik */
1641                         // => f_c_ik=1.0;
1642                         // => df_c_ik=0.0; of course we do not set this!
1643
1644                         /* zeta_ij */
1645                         exchange->zeta_ij+=g;
1646
1647                         /* dzeta_ij */
1648                         v3_add(dzeta,dzeta,&temp1);
1649                 }
1650                 else {
1651                         /* {d,}f_c_ik */
1652                         s_r=S-R;
1653                         arg=M_PI*(d_ik-R)/s_r;
1654                         f_c_ik=0.5+0.5*cos(arg);
1655                         //df_c_ik=-0.5*sin(arg)*(M_PI/(s_r*d_ik)); /* MARK */
1656                         df_c_ik=0.5*sin(arg)*(M_PI/(s_r*d_ik));
1657
1658                         /* zeta_ij */
1659                         exchange->zeta_ij+=f_c_ik*g;
1660
1661                         /* dzeta_ij */
1662                         v3_scale(&temp1,&temp1,f_c_ik);
1663                         v3_scale(&temp2,&dist_ik,g*df_c_ik);
1664                         v3_add(&temp1,&temp1,&temp2);
1665                         v3_add(dzeta,dzeta,&temp1);
1666                 }
1667         }
1668
1669         /* dV_ji stuff (in b_ji there is f_c_jk) + dV_jk stuff! */
1670
1671         /* dist_jk, d_jk */
1672         v3_sub(&dist_jk,&(ak->r),&(aj->r));
1673         if(bc) check_per_bound(moldyn,&dist_jk);
1674         d_jk=v3_norm(&dist_jk);
1675
1676         /* jk constants */
1677         num=aj->bnum;
1678         if(num==ak->bnum) {
1679                 R=params->R[num];
1680                 S=params->S[num];
1681                 B=params->B[num];
1682                 mu=params->mu[num];
1683                 chi=1.0;
1684         }
1685         else {
1686                 R=params->Rmixed;
1687                 S=params->Smixed;
1688                 B=params->Bmixed;
1689                 mu=params->mu_m;
1690                 chi=params->chi;
1691         }
1692
1693         /* zeta_ji/dzeta_ji contribution only for d_jk < S_jk */
1694         if(d_jk<S) {
1695
1696                 /* constants_j from exchange data */
1697                 n=*(exchange->n_j);
1698                 c=*(exchange->c_j);
1699                 d=*(exchange->d_j);
1700                 h=*(exchange->h_j);
1701                 c2=exchange->cj2;
1702                 d2=exchange->dj2;
1703                 c2d2=exchange->cj2dj2;
1704
1705                 /* cosine of theta_jik by scalaproduct */
1706                 rr=-v3_scalar_product(&dist_ij,&dist_jk); /* -1, as ij -> ji */
1707                 dd=d_ij*d_jk;
1708                 cos_theta=rr/dd;
1709
1710                 /* d_costheta */
1711                 d_costheta1=1.0/dd;
1712                 d_costheta2=cos_theta/(d_ij*d_ij);
1713
1714                 /* some usefull values */
1715                 h_cos=(h-cos_theta);
1716                 d2_h_cos2=d2+(h_cos*h_cos);
1717                 frac=c2/(d2_h_cos2);
1718
1719                 /* g(cos_theta) */
1720                 g=1.0+c2d2-frac;
1721
1722                 /* d_costheta_ij and dg(cos_theta) - needed in any case! */
1723                 v3_scale(&temp1,&dist_jk,d_costheta1);
1724                 v3_scale(&temp2,&dist_ij,-d_costheta2); /* ji -> ij => -1 */
1725                 v3_add(&temp1,&temp1,&temp2);
1726                 v3_scale(&temp1,&temp1,-2.0*frac*h_cos/d2_h_cos2); /* dg */
1727
1728                 /* store dg in temp2 and use it for dVjk later */
1729                 v3_copy(&temp2,&temp1);
1730
1731                 /* f_c_jk + {d,}zeta contribution (df_c_jk = 0) */
1732                 dzeta=&(exchange->dzeta_ji);
1733                 if(d_jk<R) {
1734                         /* f_c_jk */
1735                         f_c_jk=1.0;
1736
1737                         /* zeta_ji */
1738                         exchange->zeta_ji+=g;
1739
1740                         /* dzeta_ji */
1741                         v3_add(dzeta,dzeta,&temp1);
1742                 }
1743                 else {
1744                         /* f_c_jk */
1745                         s_r=S-R;
1746                         arg=M_PI*(d_jk-R)/s_r;
1747                         f_c_jk=0.5+0.5*cos(arg);
1748
1749                         /* zeta_ji */
1750                         exchange->zeta_ji+=f_c_jk*g;
1751
1752                         /* dzeta_ji */
1753                         v3_scale(&temp1,&temp1,f_c_jk);
1754                         v3_add(dzeta,dzeta,&temp1);
1755                 }
1756
1757                 /* dV_jk stuff | add force contribution on atom i immediately */
1758                 if(exchange->d_ij_between_rs) {
1759                         zeta=f_c*g;
1760                         v3_scale(&temp1,&temp2,f_c);
1761                         v3_scale(&temp2,&dist_ij,df_c*g);
1762                         v3_add(&temp2,&temp2,&temp1); /* -> dzeta_jk in temp2 */
1763                 }
1764                 else {
1765                         zeta=g;
1766                         // dzeta_jk is simply dg, which is stored in temp2
1767                 }
1768                 /* betajnj * zeta_jk ^ nj-1 */
1769                 tmp=exchange->betajnj*pow(zeta,(n-1.0));
1770                 tmp=-chi/2.0*pow((1+tmp*zeta),(-1.0/(2.0*n)-1))*tmp;
1771                 v3_scale(&temp2,&temp2,tmp*B*exp(-mu*d_jk)*f_c_jk*0.5);
1772                 v3_add(&(ai->f),&(ai->f),&temp2); /* -1 skipped in f_a calc ^ */
1773                                                   /* scaled with 0.5 ^ */
1774
1775         }
1776
1777         return 0;
1778 }
1779
1780
1781 /*
1782  * debugging / critical check functions
1783  */
1784
1785 int moldyn_bc_check(t_moldyn *moldyn) {
1786
1787         t_atom *atom;
1788         t_3dvec *dim;
1789         int i;
1790 double x;
1791 u8 byte;
1792 int j,k;
1793
1794         atom=moldyn->atom;
1795         dim=&(moldyn->dim);
1796 x=dim->x/2;
1797
1798         for(i=0;i<moldyn->count;i++) {
1799                 if(atom[i].r.x>=dim->x/2||-atom[i].r.x>dim->x/2) {
1800                         printf("FATAL: atom %d: x: %.20f (%.20f)\n",
1801                                i,atom[i].r.x,dim->x/2);
1802                         printf("diagnostic:\n");
1803                         printf("-----------\natom.r.x:\n");
1804                         for(j=0;j<8;j++) {
1805                                 memcpy(&byte,(u8 *)(&(atom[i].r.x))+j,1);
1806                                 for(k=0;k<8;k++)
1807                                         printf("%d%c",
1808                                         ((byte)&(1<<k))?1:0,
1809                                         (k==7)?'\n':'|');
1810                         }
1811                         printf("---------------\nx=dim.x/2:\n");
1812                         for(j=0;j<8;j++) {
1813                                 memcpy(&byte,(u8 *)(&x)+j,1);
1814                                 for(k=0;k<8;k++)
1815                                         printf("%d%c",
1816                                         ((byte)&(1<<k))?1:0,
1817                                         (k==7)?'\n':'|');
1818                         }
1819                         if(atom[i].r.x==x) printf("the same!\n");
1820                         else printf("different!\n");
1821                 }
1822                 if(atom[i].r.y>=dim->y/2||-atom[i].r.y>dim->y/2)
1823                         printf("FATAL: atom %d: y: %.20f (%.20f)\n",
1824                                i,atom[i].r.y,dim->y/2);
1825                 if(atom[i].r.z>=dim->z/2||-atom[i].r.z>dim->z/2)
1826                         printf("FATAL: atom %d: z: %.20f (%.20f)\n",
1827                                i,atom[i].r.z,dim->z/2);
1828         }
1829
1830         return 0;
1831 }