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