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