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