more precise print for t and p scaling
[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 <sys/time.h>
17 #include <time.h>
18 #include <math.h>
19
20 #include "moldyn.h"
21 #include "report/report.h"
22
23 /* potential includes */
24 #include "potentials/harmonic_oscillator.h"
25 #include "potentials/lennard_jones.h"
26 #include "potentials/albe.h"
27 #ifdef TERSOFF_ORIG
28 #include "potentials/tersoff_orig.h"
29 #else
30 #include "potentials/tersoff.h"
31 #endif
32
33 /*
34  * the moldyn functions
35  */
36
37 int moldyn_init(t_moldyn *moldyn,int argc,char **argv) {
38
39         printf("[moldyn] init\n");
40
41         memset(moldyn,0,sizeof(t_moldyn));
42
43         moldyn->argc=argc;
44         moldyn->args=argv;
45
46         rand_init(&(moldyn->random),NULL,1);
47         moldyn->random.status|=RAND_STAT_VERBOSE;
48
49         return 0;
50 }
51
52 int moldyn_shutdown(t_moldyn *moldyn) {
53
54         printf("[moldyn] shutdown\n");
55
56         moldyn_log_shutdown(moldyn);
57         link_cell_shutdown(moldyn);
58         rand_close(&(moldyn->random));
59         free(moldyn->atom);
60
61         return 0;
62 }
63
64 int set_int_alg(t_moldyn *moldyn,u8 algo) {
65
66         printf("[moldyn] integration algorithm: ");
67
68         switch(algo) {
69                 case MOLDYN_INTEGRATE_VERLET:
70                         moldyn->integrate=velocity_verlet;
71                         printf("velocity verlet\n");
72                         break;
73                 default:
74                         printf("unknown integration algorithm: %02x\n",algo);
75                         printf("unknown\n");
76                         return -1;
77         }
78
79         return 0;
80 }
81
82 int set_cutoff(t_moldyn *moldyn,double cutoff) {
83
84         moldyn->cutoff=cutoff;
85         moldyn->cutoff_square=cutoff*cutoff;
86
87         printf("[moldyn] cutoff [A]: %f\n",moldyn->cutoff);
88
89         return 0;
90 }
91
92 int set_temperature(t_moldyn *moldyn,double t_ref) {
93
94         moldyn->t_ref=t_ref;
95
96         printf("[moldyn] temperature [K]: %f\n",moldyn->t_ref);
97
98         return 0;
99 }
100
101 int set_pressure(t_moldyn *moldyn,double p_ref) {
102
103         moldyn->p_ref=p_ref;
104
105         printf("[moldyn] pressure [bar]: %f\n",moldyn->p_ref/BAR);
106
107         return 0;
108 }
109
110 int set_p_scale(t_moldyn *moldyn,u8 ptype,double ptc) {
111
112         moldyn->pt_scale&=(~(P_SCALE_MASK));
113         moldyn->pt_scale|=ptype;
114         moldyn->p_tc=ptc;
115
116         printf("[moldyn] p scaling:\n");
117
118         printf("  p: %s",ptype?"yes":"no ");
119         if(ptype)
120                 printf(" | type: %02x | factor: %f",ptype,ptc);
121         printf("\n");
122
123         return 0;
124 }
125
126 int set_t_scale(t_moldyn *moldyn,u8 ttype,double ttc) {
127
128         moldyn->pt_scale&=(~(T_SCALE_MASK));
129         moldyn->pt_scale|=ttype;
130         moldyn->t_tc=ttc;
131
132         printf("[moldyn] t scaling:\n");
133
134         printf("  t: %s",ttype?"yes":"no ");
135         if(ttype)
136                 printf(" | type: %02x | factor: %f",ttype,ttc);
137         printf("\n");
138
139         return 0;
140 }
141
142 int set_pt_scale(t_moldyn *moldyn,u8 ptype,double ptc,u8 ttype,double ttc) {
143
144         moldyn->pt_scale=(ptype|ttype);
145         moldyn->t_tc=ttc;
146         moldyn->p_tc=ptc;
147
148         printf("[moldyn] p/t scaling:\n");
149
150         printf("  p: %s",ptype?"yes":"no ");
151         if(ptype)
152                 printf(" | type: %02x | factor: %f",ptype,ptc);
153         printf("\n");
154
155         printf("  t: %s",ttype?"yes":"no ");
156         if(ttype)
157                 printf(" | type: %02x | factor: %f",ttype,ttc);
158         printf("\n");
159
160         return 0;
161 }
162
163 int set_dim(t_moldyn *moldyn,double x,double y,double z,u8 visualize) {
164
165         moldyn->dim.x=x;
166         moldyn->dim.y=y;
167         moldyn->dim.z=z;
168
169         moldyn->volume=x*y*z;
170
171         if(visualize) {
172                 moldyn->vis.dim.x=x;
173                 moldyn->vis.dim.y=y;
174                 moldyn->vis.dim.z=z;
175         }
176
177         printf("[moldyn] dimensions in A and A^3 respectively:\n");
178         printf("  x: %f\n",moldyn->dim.x);
179         printf("  y: %f\n",moldyn->dim.y);
180         printf("  z: %f\n",moldyn->dim.z);
181         printf("  volume: %f\n",moldyn->volume);
182         printf("  visualize simulation box: %s\n",visualize?"yes":"no");
183
184         return 0;
185 }
186
187 int set_nn_dist(t_moldyn *moldyn,double dist) {
188
189         moldyn->nnd=dist;
190
191         return 0;
192 }
193
194 int set_pbc(t_moldyn *moldyn,u8 x,u8 y,u8 z) {
195
196         printf("[moldyn] periodic boundary conditions:\n");
197
198         if(x)
199                 moldyn->status|=MOLDYN_STAT_PBX;
200
201         if(y)
202                 moldyn->status|=MOLDYN_STAT_PBY;
203
204         if(z)
205                 moldyn->status|=MOLDYN_STAT_PBZ;
206
207         printf("  x: %s\n",x?"yes":"no");
208         printf("  y: %s\n",y?"yes":"no");
209         printf("  z: %s\n",z?"yes":"no");
210
211         return 0;
212 }
213
214 int set_potential(t_moldyn *moldyn,u8 type) {
215
216         switch(type) {
217                 case MOLDYN_POTENTIAL_TM:
218                         moldyn->func1b=tersoff_mult_1bp;
219                         moldyn->func3b_j1=tersoff_mult_3bp_j1;
220                         moldyn->func3b_k1=tersoff_mult_3bp_k1;
221                         moldyn->func3b_j2=tersoff_mult_3bp_j2;
222                         moldyn->func3b_k2=tersoff_mult_3bp_k2;
223                         // missing: check 2b bond func
224                         break;
225                 case MOLDYN_POTENTIAL_AM:
226                         moldyn->func3b_j1=albe_mult_3bp_j1;
227                         moldyn->func3b_k1=albe_mult_3bp_k1;
228                         moldyn->func3b_j2=albe_mult_3bp_j2;
229                         moldyn->func3b_k2=albe_mult_3bp_k2;
230                         moldyn->check_2b_bond=albe_mult_check_2b_bond;
231                         break;
232                 case MOLDYN_POTENTIAL_HO:
233                         moldyn->func2b=harmonic_oscillator;
234                         moldyn->check_2b_bond=harmonic_oscillator_check_2b_bond;
235                         break;
236                 case MOLDYN_POTENTIAL_LJ:
237                         moldyn->func2b=lennard_jones;
238                         moldyn->check_2b_bond=lennard_jones_check_2b_bond;
239                         break;
240                 default:
241                         printf("[moldyn] set potential: unknown type %02x\n",
242                                type);
243                         return -1;
244         }
245
246         return 0;
247 }
248
249 int set_avg_skip(t_moldyn *moldyn,int skip) {
250
251         printf("[moldyn] skip %d steps before starting average calc\n",skip);
252         moldyn->avg_skip=skip;
253
254         return 0;
255 }
256
257 int moldyn_set_log_dir(t_moldyn *moldyn,char *dir) {
258
259         strncpy(moldyn->vlsdir,dir,127);
260
261         return 0;
262 }
263
264 int moldyn_set_report(t_moldyn *moldyn,char *author,char *title) {
265
266         strncpy(moldyn->rauthor,author,63);
267         strncpy(moldyn->rtitle,title,63);
268
269         return 0;
270 }
271         
272 int moldyn_set_log(t_moldyn *moldyn,u8 type,int timer) {
273
274         char filename[128];
275         int ret;
276
277         printf("[moldyn] set log: ");
278
279         switch(type) {
280                 case LOG_TOTAL_ENERGY:
281                         moldyn->ewrite=timer;
282                         snprintf(filename,127,"%s/energy",moldyn->vlsdir);
283                         moldyn->efd=open(filename,
284                                          O_WRONLY|O_CREAT|O_EXCL,
285                                          S_IRUSR|S_IWUSR);
286                         if(moldyn->efd<0) {
287                                 perror("[moldyn] energy log fd open");
288                                 return moldyn->efd;
289                         }
290                         dprintf(moldyn->efd,"# total energy log file\n");
291                         printf("total energy (%d)\n",timer);
292                         break;
293                 case LOG_TOTAL_MOMENTUM:
294                         moldyn->mwrite=timer;
295                         snprintf(filename,127,"%s/momentum",moldyn->vlsdir);
296                         moldyn->mfd=open(filename,
297                                          O_WRONLY|O_CREAT|O_EXCL,
298                                          S_IRUSR|S_IWUSR);
299                         if(moldyn->mfd<0) {
300                                 perror("[moldyn] momentum log fd open");
301                                 return moldyn->mfd;
302                         }
303                         dprintf(moldyn->efd,"# total momentum log file\n");
304                         printf("total momentum (%d)\n",timer);
305                         break;
306                 case LOG_PRESSURE:
307                         moldyn->pwrite=timer;
308                         snprintf(filename,127,"%s/pressure",moldyn->vlsdir);
309                         moldyn->pfd=open(filename,
310                                          O_WRONLY|O_CREAT|O_EXCL,
311                                          S_IRUSR|S_IWUSR);
312                         if(moldyn->pfd<0) {
313                                 perror("[moldyn] pressure log file\n");
314                                 return moldyn->pfd;
315                         }
316                         dprintf(moldyn->pfd,"# pressure log file\n");
317                         printf("pressure (%d)\n",timer);
318                         break;
319                 case LOG_TEMPERATURE:
320                         moldyn->twrite=timer;
321                         snprintf(filename,127,"%s/temperature",moldyn->vlsdir);
322                         moldyn->tfd=open(filename,
323                                          O_WRONLY|O_CREAT|O_EXCL,
324                                          S_IRUSR|S_IWUSR);
325                         if(moldyn->tfd<0) {
326                                 perror("[moldyn] temperature log file\n");
327                                 return moldyn->tfd;
328                         }
329                         dprintf(moldyn->tfd,"# temperature log file\n");
330                         printf("temperature (%d)\n",timer);
331                         break;
332                 case LOG_VOLUME:
333                         moldyn->vwrite=timer;
334                         snprintf(filename,127,"%s/volume",moldyn->vlsdir);
335                         moldyn->vfd=open(filename,
336                                          O_WRONLY|O_CREAT|O_EXCL,
337                                          S_IRUSR|S_IWUSR);
338                         if(moldyn->vfd<0) {
339                                 perror("[moldyn] volume log file\n");
340                                 return moldyn->vfd;
341                         }
342                         dprintf(moldyn->vfd,"# volume log file\n");
343                         printf("volume (%d)\n",timer);
344                         break;
345                 case SAVE_STEP:
346                         moldyn->swrite=timer;
347                         printf("save file (%d)\n",timer);
348                         break;
349                 case VISUAL_STEP:
350                         moldyn->awrite=timer;
351                         ret=visual_init(moldyn,moldyn->vlsdir);
352                         if(ret<0) {
353                                 printf("[moldyn] visual init failure\n");
354                                 return ret;
355                         }
356                         printf("visual file (%d)\n",timer);
357                         break;
358                 case CREATE_REPORT:
359                         snprintf(filename,127,"%s/report.tex",moldyn->vlsdir);
360                         moldyn->rfd=open(filename,
361                                          O_WRONLY|O_CREAT|O_EXCL,
362                                          S_IRUSR|S_IWUSR);
363                         if(moldyn->rfd<0) {
364                                 perror("[moldyn] report fd open");      
365                                 return moldyn->rfd;
366                         }
367                         printf("report -> ");
368                         if(moldyn->efd) {
369                                 snprintf(filename,127,"%s/e_plot.scr",
370                                          moldyn->vlsdir);
371                                 moldyn->epfd=open(filename,
372                                                  O_WRONLY|O_CREAT|O_EXCL,
373                                                  S_IRUSR|S_IWUSR);
374                                 if(moldyn->epfd<0) {
375                                         perror("[moldyn] energy plot fd open");
376                                         return moldyn->epfd;
377                                 }
378                                 dprintf(moldyn->epfd,e_plot_script);
379                                 close(moldyn->epfd);
380                                 printf("energy ");
381                         }
382                         if(moldyn->pfd) {
383                                 snprintf(filename,127,"%s/pressure_plot.scr",
384                                          moldyn->vlsdir);
385                                 moldyn->ppfd=open(filename,
386                                                   O_WRONLY|O_CREAT|O_EXCL,
387                                                   S_IRUSR|S_IWUSR);
388                                 if(moldyn->ppfd<0) {
389                                         perror("[moldyn] p plot fd open");
390                                         return moldyn->ppfd;
391                                 }
392                                 dprintf(moldyn->ppfd,pressure_plot_script);
393                                 close(moldyn->ppfd);
394                                 printf("pressure ");
395                         }
396                         if(moldyn->tfd) {
397                                 snprintf(filename,127,"%s/temperature_plot.scr",
398                                          moldyn->vlsdir);
399                                 moldyn->tpfd=open(filename,
400                                                   O_WRONLY|O_CREAT|O_EXCL,
401                                                   S_IRUSR|S_IWUSR);
402                                 if(moldyn->tpfd<0) {
403                                         perror("[moldyn] t plot fd open");
404                                         return moldyn->tpfd;
405                                 }
406                                 dprintf(moldyn->tpfd,temperature_plot_script);
407                                 close(moldyn->tpfd);
408                                 printf("temperature ");
409                         }
410                         dprintf(moldyn->rfd,report_start,
411                                 moldyn->rauthor,moldyn->rtitle);
412                         printf("\n");
413                         break;
414                 default:
415                         printf("unknown log type: %02x\n",type);
416                         return -1;
417         }
418
419         return 0;
420 }
421
422 int moldyn_log_shutdown(t_moldyn *moldyn) {
423
424         char sc[256];
425
426         printf("[moldyn] log shutdown\n");
427         if(moldyn->efd) {
428                 close(moldyn->efd);
429                 if(moldyn->rfd) {
430                         dprintf(moldyn->rfd,report_energy);
431                         snprintf(sc,255,"cd %s && gnuplot e_plot.scr",
432                                  moldyn->vlsdir);
433                         system(sc);
434                 }
435         }
436         if(moldyn->mfd) close(moldyn->mfd);
437         if(moldyn->pfd) {
438                 close(moldyn->pfd);
439                 if(moldyn->rfd)
440                         dprintf(moldyn->rfd,report_pressure);
441                         snprintf(sc,255,"cd %s && gnuplot pressure_plot.scr",
442                                  moldyn->vlsdir);
443                         system(sc);
444         }
445         if(moldyn->tfd) {
446                 close(moldyn->tfd);
447                 if(moldyn->rfd)
448                         dprintf(moldyn->rfd,report_temperature);
449                         snprintf(sc,255,"cd %s && gnuplot temperature_plot.scr",
450                                  moldyn->vlsdir);
451                         system(sc);
452         }
453         if(moldyn->rfd) {
454                 dprintf(moldyn->rfd,report_end);
455                 close(moldyn->rfd);
456                 snprintf(sc,255,"cd %s && pdflatex report >/dev/null 2>&1",
457                          moldyn->vlsdir);
458                 system(sc);
459                 snprintf(sc,255,"cd %s && pdflatex report >/dev/null 2>&1",
460                          moldyn->vlsdir);
461                 system(sc);
462                 snprintf(sc,255,"cd %s && dvipdf report >/dev/null 2>&1",
463                          moldyn->vlsdir);
464                 system(sc);
465         }
466
467         return 0;
468 }
469
470 /*
471  * creating lattice functions
472  */
473
474 int create_lattice(t_moldyn *moldyn,u8 type,double lc,int element,double mass,
475                    u8 attr,u8 brand,int a,int b,int c,t_3dvec *origin) {
476
477         int new,count;
478         int ret;
479         t_3dvec orig;
480         void *ptr;
481         t_atom *atom;
482         char name[16];
483
484         new=a*b*c;
485         count=moldyn->count;
486
487         /* how many atoms do we expect */
488         if(type==CUBIC) new*=1;
489         if(type==FCC) new*=4;
490         if(type==DIAMOND) new*=8;
491
492         /* allocate space for atoms */
493         ptr=realloc(moldyn->atom,(count+new)*sizeof(t_atom));
494         if(!ptr) {
495                 perror("[moldyn] realloc (create lattice)");
496                 return -1;
497         }
498         moldyn->atom=ptr;
499         atom=&(moldyn->atom[count]);
500
501         /* no atoms on the boundaries (only reason: it looks better!) */
502         if(!origin) {
503                 orig.x=0.5*lc;
504                 orig.y=0.5*lc;
505                 orig.z=0.5*lc;
506         }
507         else {
508                 orig.x=origin->x;
509                 orig.y=origin->y;
510                 orig.z=origin->z;
511         }
512
513         switch(type) {
514                 case CUBIC:
515                         set_nn_dist(moldyn,lc);
516                         ret=cubic_init(a,b,c,lc,atom,&orig);
517                         strcpy(name,"cubic");
518                         break;
519                 case FCC:
520                         if(!origin)
521                                 v3_scale(&orig,&orig,0.5);
522                         set_nn_dist(moldyn,0.5*sqrt(2.0)*lc);
523                         ret=fcc_init(a,b,c,lc,atom,&orig);
524                         strcpy(name,"fcc");
525                         break;
526                 case DIAMOND:
527                         if(!origin)
528                                 v3_scale(&orig,&orig,0.25);
529                         set_nn_dist(moldyn,0.25*sqrt(3.0)*lc);
530                         ret=diamond_init(a,b,c,lc,atom,&orig);
531                         strcpy(name,"diamond");
532                         break;
533                 default:
534                         printf("unknown lattice type (%02x)\n",type);
535                         return -1;
536         }
537
538         /* debug */
539         if(ret!=new) {
540                 printf("[moldyn] creating lattice failed\n");
541                 printf("  amount of atoms\n");
542                 printf("  - expected: %d\n",new);
543                 printf("  - created: %d\n",ret);
544                 return -1;
545         }
546
547         moldyn->count+=new;
548         printf("[moldyn] created %s lattice with %d atoms\n",name,new);
549
550         for(ret=0;ret<new;ret++) {
551                 atom[ret].element=element;
552                 atom[ret].mass=mass;
553                 atom[ret].attr=attr;
554                 atom[ret].brand=brand;
555                 atom[ret].tag=count+ret;
556                 check_per_bound(moldyn,&(atom[ret].r));
557                 atom[ret].r_0=atom[ret].r;
558         }
559
560         /* update total system mass */
561         total_mass_calc(moldyn);
562
563         return ret;
564 }
565
566 int add_atom(t_moldyn *moldyn,int element,double mass,u8 brand,u8 attr,
567              t_3dvec *r,t_3dvec *v) {
568
569         t_atom *atom;
570         void *ptr;
571         int count;
572         
573         atom=moldyn->atom;
574         count=(moldyn->count)++;        // asshole style!
575
576         ptr=realloc(atom,(count+1)*sizeof(t_atom));
577         if(!ptr) {
578                 perror("[moldyn] realloc (add atom)");
579                 return -1;
580         }
581         moldyn->atom=ptr;
582
583         atom=moldyn->atom;
584
585         /* initialize new atom */
586         memset(&(atom[count]),0,sizeof(t_atom));
587         atom[count].r=*r;
588         atom[count].v=*v;
589         atom[count].element=element;
590         atom[count].mass=mass;
591         atom[count].brand=brand;
592         atom[count].tag=count;
593         atom[count].attr=attr;
594         check_per_bound(moldyn,&(atom[count].r));
595         atom[count].r_0=atom[count].r;
596
597         /* update total system mass */
598         total_mass_calc(moldyn);
599
600         return 0;
601 }
602
603 int del_atom(t_moldyn *moldyn,int tag) {
604
605         t_atom *new,*old;
606         int cnt;
607
608         old=moldyn->atom;
609
610         new=(t_atom *)malloc((moldyn->count-1)*sizeof(t_atom));
611         if(!new) {
612                 perror("[moldyn]malloc (del atom)");
613                 return -1;
614         }
615
616         for(cnt=0;cnt<tag;cnt++)
617                 new[cnt]=old[cnt];
618         
619         for(cnt=tag+1;cnt<moldyn->count;cnt++) {
620                 new[cnt-1]=old[cnt];
621                 new[cnt-1].tag=cnt-1;
622         }
623
624         moldyn->count-=1;
625         moldyn->atom=new;
626
627         free(old);
628
629         return 0;
630 }
631
632 /* cubic init */
633 int cubic_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
634
635         int count;
636         t_3dvec r;
637         int i,j,k;
638         t_3dvec o;
639
640         count=0;
641         if(origin)
642                 v3_copy(&o,origin);
643         else
644                 v3_zero(&o);
645
646         r.x=o.x;
647         for(i=0;i<a;i++) {
648                 r.y=o.y;
649                 for(j=0;j<b;j++) {
650                         r.z=o.z;
651                         for(k=0;k<c;k++) {
652                                 v3_copy(&(atom[count].r),&r);
653                                 count+=1;
654                                 r.z+=lc;
655                         }
656                         r.y+=lc;
657                 }
658                 r.x+=lc;
659         }
660
661         for(i=0;i<count;i++) {
662                 atom[i].r.x-=(a*lc)/2.0;
663                 atom[i].r.y-=(b*lc)/2.0;
664                 atom[i].r.z-=(c*lc)/2.0;
665         }
666
667         return count;
668 }
669
670 /* fcc lattice init */
671 int fcc_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
672
673         int count;
674         int i,j,k,l;
675         t_3dvec o,r,n;
676         t_3dvec basis[3];
677
678         count=0;
679         if(origin)
680                 v3_copy(&o,origin);
681         else
682                 v3_zero(&o);
683
684         /* construct the basis */
685         memset(basis,0,3*sizeof(t_3dvec));
686         basis[0].x=0.5*lc;
687         basis[0].y=0.5*lc;
688         basis[1].x=0.5*lc;
689         basis[1].z=0.5*lc;
690         basis[2].y=0.5*lc;
691         basis[2].z=0.5*lc;
692
693         /* fill up the room */
694         r.x=o.x;
695         for(i=0;i<a;i++) {
696                 r.y=o.y;
697                 for(j=0;j<b;j++) {
698                         r.z=o.z;
699                         for(k=0;k<c;k++) {
700                                 /* first atom */
701                                 v3_copy(&(atom[count].r),&r);
702                                 count+=1;
703                                 r.z+=lc;
704                                 /* the three face centered atoms */
705                                 for(l=0;l<3;l++) {
706                                         v3_add(&n,&r,&basis[l]);
707                                         v3_copy(&(atom[count].r),&n);
708                                         count+=1;
709                                 }
710                         }
711                         r.y+=lc;
712                 }
713                 r.x+=lc;
714         }
715                                 
716         /* coordinate transformation */
717         for(i=0;i<count;i++) {
718                 atom[i].r.x-=(a*lc)/2.0;
719                 atom[i].r.y-=(b*lc)/2.0;
720                 atom[i].r.z-=(c*lc)/2.0;
721         }
722
723         return count;
724 }
725
726 int diamond_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
727
728         int count;
729         t_3dvec o;
730
731         count=fcc_init(a,b,c,lc,atom,origin);
732
733         o.x=0.25*lc;
734         o.y=0.25*lc;
735         o.z=0.25*lc;
736
737         if(origin) v3_add(&o,&o,origin);
738
739         count+=fcc_init(a,b,c,lc,&atom[count],&o);
740
741         return count;
742 }
743
744 int destroy_atoms(t_moldyn *moldyn) {
745
746         if(moldyn->atom) free(moldyn->atom);
747
748         return 0;
749 }
750
751 int thermal_init(t_moldyn *moldyn,u8 equi_init) {
752
753         /*
754          * - gaussian distribution of velocities
755          * - zero total momentum
756          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
757          */
758
759         int i;
760         double v,sigma;
761         t_3dvec p_total,delta;
762         t_atom *atom;
763         t_random *random;
764
765         atom=moldyn->atom;
766         random=&(moldyn->random);
767
768         printf("[moldyn] thermal init (equi init: %s)\n",equi_init?"yes":"no");
769
770         /* gaussian distribution of velocities */
771         v3_zero(&p_total);
772         for(i=0;i<moldyn->count;i++) {
773                 sigma=sqrt(2.0*K_BOLTZMANN*moldyn->t_ref/atom[i].mass);
774                 /* x direction */
775                 v=sigma*rand_get_gauss(random);
776                 atom[i].v.x=v;
777                 p_total.x+=atom[i].mass*v;
778                 /* y direction */
779                 v=sigma*rand_get_gauss(random);
780                 atom[i].v.y=v;
781                 p_total.y+=atom[i].mass*v;
782                 /* z direction */
783                 v=sigma*rand_get_gauss(random);
784                 atom[i].v.z=v;
785                 p_total.z+=atom[i].mass*v;
786         }
787
788         /* zero total momentum */
789         v3_scale(&p_total,&p_total,1.0/moldyn->count);
790         for(i=0;i<moldyn->count;i++) {
791                 v3_scale(&delta,&p_total,1.0/atom[i].mass);
792                 v3_sub(&(atom[i].v),&(atom[i].v),&delta);
793         }
794
795         /* velocity scaling */
796         scale_velocity(moldyn,equi_init);
797
798         return 0;
799 }
800
801 double total_mass_calc(t_moldyn *moldyn) {
802
803         int i;
804
805         moldyn->mass=0.0;
806
807         for(i=0;i<moldyn->count;i++)
808                 moldyn->mass+=moldyn->atom[i].mass;
809
810         return moldyn->mass;
811 }
812
813 double temperature_calc(t_moldyn *moldyn) {
814
815         /* assume up to date kinetic energy, which is 3/2 N k_B T */
816
817         moldyn->t=(2.0*moldyn->ekin)/(3.0*K_BOLTZMANN*moldyn->count);
818
819         return moldyn->t;
820 }
821
822 double get_temperature(t_moldyn *moldyn) {
823
824         return moldyn->t;
825 }
826
827 int scale_velocity(t_moldyn *moldyn,u8 equi_init) {
828
829         int i;
830         double e,scale;
831         t_atom *atom;
832         int count;
833
834         atom=moldyn->atom;
835
836         /*
837          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
838          */
839
840         /* get kinetic energy / temperature & count involved atoms */
841         e=0.0;
842         count=0;
843         for(i=0;i<moldyn->count;i++) {
844                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB)) {
845                         e+=atom[i].mass*v3_absolute_square(&(atom[i].v));
846                         count+=1;
847                 }
848         }
849         e*=0.5;
850         if(count!=0) moldyn->t=e/(1.5*count*K_BOLTZMANN);
851         else return 0;  /* no atoms involved in scaling! */
852         
853         /* (temporary) hack for e,t = 0 */
854         if(e==0.0) {
855         moldyn->t=0.0;
856                 if(moldyn->t_ref!=0.0) {
857                         thermal_init(moldyn,equi_init);
858                         return 0;
859                 }
860                 else
861                         return 0; /* no scaling needed */
862         }
863
864
865         /* get scaling factor */
866         scale=moldyn->t_ref/moldyn->t;
867         if(equi_init&TRUE)
868                 scale*=2.0;
869         else
870                 if(moldyn->pt_scale&T_SCALE_BERENDSEN)
871                         scale=1.0+(scale-1.0)/moldyn->t_tc;
872         scale=sqrt(scale);
873
874         /* velocity scaling */
875         for(i=0;i<moldyn->count;i++) {
876                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB))
877                         v3_scale(&(atom[i].v),&(atom[i].v),scale);
878         }
879
880         return 0;
881 }
882
883 double ideal_gas_law_pressure(t_moldyn *moldyn) {
884
885         double p;
886
887         p=moldyn->count*moldyn->t*K_BOLTZMANN/moldyn->volume;
888
889         return p;
890 }
891
892 double virial_sum(t_moldyn *moldyn) {
893
894         int i;
895         t_virial *virial;
896
897         /* virial (sum over atom virials) */
898         moldyn->virial=0.0;
899         moldyn->vir.xx=0.0;
900         moldyn->vir.yy=0.0;
901         moldyn->vir.zz=0.0;
902         moldyn->vir.xy=0.0;
903         moldyn->vir.xz=0.0;
904         moldyn->vir.yz=0.0;
905         for(i=0;i<moldyn->count;i++) {
906                 virial=&(moldyn->atom[i].virial);
907                 moldyn->virial+=(virial->xx+virial->yy+virial->zz);
908                 moldyn->vir.xx+=virial->xx;
909                 moldyn->vir.yy+=virial->yy;
910                 moldyn->vir.zz+=virial->zz;
911                 moldyn->vir.xy+=virial->xy;
912                 moldyn->vir.xz+=virial->xz;
913                 moldyn->vir.yz+=virial->yz;
914         }
915
916         /* global virial (absolute coordinates) */
917         virial=&(moldyn->gvir);
918         moldyn->gv=virial->xx+virial->yy+virial->zz;
919
920         return moldyn->virial;
921 }
922
923 double pressure_calc(t_moldyn *moldyn) {
924
925         /*
926          * PV = NkT + <W>
927          * with W = 1/3 sum_i f_i r_i (- skipped!)
928          * virial = sum_i f_i r_i
929          * 
930          * => P = (2 Ekin + virial) / (3V)
931          */
932
933         /* assume up to date virial & up to date kinetic energy */
934
935         /* pressure (atom virials) */
936         moldyn->p=2.0*moldyn->ekin+moldyn->virial;
937         moldyn->p/=(3.0*moldyn->volume);
938
939         /* pressure (absolute coordinates) */
940         moldyn->gp=2.0*moldyn->ekin+moldyn->gv;
941         moldyn->gp/=(3.0*moldyn->volume);
942
943         return moldyn->p;
944 }
945
946 int average_reset(t_moldyn *moldyn) {
947
948         printf("[moldyn] average reset\n");
949
950         /* update skip value */
951         moldyn->avg_skip=moldyn->total_steps;
952
953         /* kinetic energy */
954         moldyn->k_sum=0.0;
955         moldyn->k2_sum=0.0;
956         
957         /* potential energy */
958         moldyn->v_sum=0.0;
959         moldyn->v2_sum=0.0;
960
961         /* temperature */
962         moldyn->t_sum=0.0;
963
964         /* virial */
965         moldyn->virial_sum=0.0;
966         moldyn->gv_sum=0.0;
967
968         /* pressure */
969         moldyn->p_sum=0.0;
970         moldyn->gp_sum=0.0;
971         moldyn->tp_sum=0.0;
972
973         return 0;
974 }
975
976 int average_and_fluctuation_calc(t_moldyn *moldyn) {
977
978         int denom;
979
980         if(moldyn->total_steps<moldyn->avg_skip)
981                 return 0;
982
983         denom=moldyn->total_steps+1-moldyn->avg_skip;
984
985         /* assume up to date energies, temperature, pressure etc */
986
987         /* kinetic energy */
988         moldyn->k_sum+=moldyn->ekin;
989         moldyn->k2_sum+=(moldyn->ekin*moldyn->ekin);
990         moldyn->k_avg=moldyn->k_sum/denom;
991         moldyn->k2_avg=moldyn->k2_sum/denom;
992         moldyn->dk2_avg=moldyn->k2_avg-(moldyn->k_avg*moldyn->k_avg);
993
994         /* potential energy */
995         moldyn->v_sum+=moldyn->energy;
996         moldyn->v2_sum+=(moldyn->energy*moldyn->energy);
997         moldyn->v_avg=moldyn->v_sum/denom;
998         moldyn->v2_avg=moldyn->v2_sum/denom;
999         moldyn->dv2_avg=moldyn->v2_avg-(moldyn->v_avg*moldyn->v_avg);
1000
1001         /* temperature */
1002         moldyn->t_sum+=moldyn->t;
1003         moldyn->t_avg=moldyn->t_sum/denom;
1004
1005         /* virial */
1006         moldyn->virial_sum+=moldyn->virial;
1007         moldyn->virial_avg=moldyn->virial_sum/denom;
1008         moldyn->gv_sum+=moldyn->gv;
1009         moldyn->gv_avg=moldyn->gv_sum/denom;
1010
1011         /* pressure */
1012         moldyn->p_sum+=moldyn->p;
1013         moldyn->p_avg=moldyn->p_sum/denom;
1014         moldyn->gp_sum+=moldyn->gp;
1015         moldyn->gp_avg=moldyn->gp_sum/denom;
1016         moldyn->tp_sum+=moldyn->tp;
1017         moldyn->tp_avg=moldyn->tp_sum/denom;
1018
1019         return 0;
1020 }
1021
1022 int get_heat_capacity(t_moldyn *moldyn) {
1023
1024         double temp2,ighc;
1025
1026         /* averages needed for heat capacity calc */
1027         if(moldyn->total_steps<moldyn->avg_skip)
1028                 return 0;
1029
1030         /* (temperature average)^2 */
1031         temp2=moldyn->t_avg*moldyn->t_avg;
1032         printf("[moldyn] specific heat capacity for T=%f K [J/(kg K)]\n",
1033                moldyn->t_avg);
1034
1035         /* ideal gas contribution */
1036         ighc=3.0*moldyn->count*K_BOLTZMANN/2.0;
1037         printf("  ideal gas contribution: %f\n",
1038                ighc/moldyn->mass*KILOGRAM/JOULE);
1039
1040         /* specific heat for nvt ensemble */
1041         moldyn->c_v_nvt=moldyn->dv2_avg/(K_BOLTZMANN*temp2)+ighc;
1042         moldyn->c_v_nvt/=moldyn->mass;
1043
1044         /* specific heat for nve ensemble */
1045         moldyn->c_v_nve=ighc/(1.0-(moldyn->dv2_avg/(ighc*K_BOLTZMANN*temp2)));
1046         moldyn->c_v_nve/=moldyn->mass;
1047
1048         printf("  NVE: %f\n",moldyn->c_v_nve*KILOGRAM/JOULE);
1049         printf("  NVT: %f\n",moldyn->c_v_nvt*KILOGRAM/JOULE);
1050 printf("  --> <dV2> sim: %f experimental: %f\n",moldyn->dv2_avg,1.5*moldyn->count*K_B2*moldyn->t_avg*moldyn->t_avg*(1.0-1.5*moldyn->count*K_BOLTZMANN/(700*moldyn->mass*JOULE/KILOGRAM)));
1051
1052         return 0;
1053 }
1054
1055 double thermodynamic_pressure_calc(t_moldyn *moldyn) {
1056
1057         t_3dvec dim;
1058         //t_3dvec *tp;
1059         double h,dv;
1060         double y0,y1;
1061         double su,sd;
1062         t_atom *store;
1063
1064         /*
1065          * dU = - p dV
1066          *
1067          * => p = - dU/dV
1068          *
1069          */
1070
1071         /* store atomic configuration + dimension */
1072         store=malloc(moldyn->count*sizeof(t_atom));
1073         if(store==NULL) {
1074                 printf("[moldyn] allocating store mem failed\n");
1075                 return -1;
1076         }
1077         memcpy(store,moldyn->atom,moldyn->count*sizeof(t_atom));
1078         dim=moldyn->dim;
1079
1080         /* x1, y1 */
1081         sd=0.00001;
1082         h=(1.0-sd)*(1.0-sd)*(1.0-sd);
1083         su=pow(2.0-h,ONE_THIRD)-1.0;
1084         dv=(1.0-h)*moldyn->volume;
1085
1086         /* scale up dimension and atom positions */
1087         scale_dim(moldyn,SCALE_UP,su,TRUE,TRUE,TRUE);
1088         scale_atoms(moldyn,SCALE_UP,su,TRUE,TRUE,TRUE);
1089         link_cell_shutdown(moldyn);
1090         link_cell_init(moldyn,QUIET);
1091         potential_force_calc(moldyn);
1092         y1=moldyn->energy;
1093
1094         /* restore atomic configuration + dim */
1095         memcpy(moldyn->atom,store,moldyn->count*sizeof(t_atom));
1096         moldyn->dim=dim;
1097
1098         /* scale down dimension and atom positions */
1099         scale_dim(moldyn,SCALE_DOWN,sd,TRUE,TRUE,TRUE);
1100         scale_atoms(moldyn,SCALE_DOWN,sd,TRUE,TRUE,TRUE);
1101         link_cell_shutdown(moldyn);
1102         link_cell_init(moldyn,QUIET);
1103         potential_force_calc(moldyn);
1104         y0=moldyn->energy;
1105         
1106         /* calculate pressure */
1107         moldyn->tp=-(y1-y0)/(2.0*dv);
1108
1109         /* restore atomic configuration */
1110         memcpy(moldyn->atom,store,moldyn->count*sizeof(t_atom));
1111         moldyn->dim=dim;
1112         link_cell_shutdown(moldyn);
1113         link_cell_init(moldyn,QUIET);
1114         //potential_force_calc(moldyn);
1115
1116         /* free store buffer */
1117         if(store)
1118                 free(store);
1119
1120         return moldyn->tp;
1121 }
1122
1123 double get_pressure(t_moldyn *moldyn) {
1124
1125         return moldyn->p;
1126
1127 }
1128
1129 int scale_dim(t_moldyn *moldyn,u8 dir,double scale,u8 x,u8 y,u8 z) {
1130
1131         t_3dvec *dim;
1132
1133         dim=&(moldyn->dim);
1134
1135         if(dir==SCALE_UP)
1136                 scale=1.0+scale;
1137
1138         if(dir==SCALE_DOWN)
1139                 scale=1.0-scale;
1140
1141         if(x) dim->x*=scale;
1142         if(y) dim->y*=scale;
1143         if(z) dim->z*=scale;
1144
1145         return 0;
1146 }
1147
1148 int scale_atoms(t_moldyn *moldyn,u8 dir,double scale,u8 x,u8 y,u8 z) {
1149
1150         int i;
1151         t_3dvec *r;
1152
1153         if(dir==SCALE_UP)
1154                 scale=1.0+scale;
1155
1156         if(dir==SCALE_DOWN)
1157                 scale=1.0-scale;
1158
1159         for(i=0;i<moldyn->count;i++) {
1160                 r=&(moldyn->atom[i].r);
1161                 if(x) r->x*=scale;
1162                 if(y) r->y*=scale;
1163                 if(z) r->z*=scale;
1164         }
1165
1166         return 0;
1167 }
1168
1169 int scale_volume(t_moldyn *moldyn) {
1170
1171         t_3dvec *dim,*vdim;
1172         double scale;
1173         t_linkcell *lc;
1174
1175         vdim=&(moldyn->vis.dim);
1176         dim=&(moldyn->dim);
1177         lc=&(moldyn->lc);
1178
1179         /* scaling factor */
1180         if(moldyn->pt_scale&P_SCALE_BERENDSEN) {
1181                 scale=1.0-(moldyn->p_ref-moldyn->p)*moldyn->p_tc;
1182                 scale=pow(scale,ONE_THIRD);
1183         }
1184         else {
1185                 scale=pow(moldyn->p/moldyn->p_ref,ONE_THIRD);
1186         }
1187
1188         /* scale the atoms and dimensions */
1189         scale_atoms(moldyn,SCALE_DIRECT,scale,TRUE,TRUE,TRUE);
1190         scale_dim(moldyn,SCALE_DIRECT,scale,TRUE,TRUE,TRUE);
1191
1192         /* visualize dimensions */
1193         if(vdim->x!=0) {
1194                 vdim->x=dim->x;
1195                 vdim->y=dim->y;
1196                 vdim->z=dim->z;
1197         }
1198
1199         /* recalculate scaled volume */
1200         moldyn->volume=dim->x*dim->y*dim->z;
1201
1202         /* adjust/reinit linkcell */
1203         if(((int)(dim->x/moldyn->cutoff)!=lc->nx)||
1204            ((int)(dim->y/moldyn->cutoff)!=lc->ny)||
1205            ((int)(dim->z/moldyn->cutoff)!=lc->nx)) {
1206                 link_cell_shutdown(moldyn);
1207                 link_cell_init(moldyn,QUIET);
1208         } else {
1209                 lc->x*=scale;
1210                 lc->y*=scale;
1211                 lc->z*=scale;
1212         }
1213
1214         return 0;
1215
1216 }
1217
1218 double e_kin_calc(t_moldyn *moldyn) {
1219
1220         int i;
1221         t_atom *atom;
1222
1223         atom=moldyn->atom;
1224         moldyn->ekin=0.0;
1225
1226         for(i=0;i<moldyn->count;i++) {
1227                 atom[i].ekin=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
1228                 moldyn->ekin+=atom[i].ekin;
1229         }
1230
1231         return moldyn->ekin;
1232 }
1233
1234 double get_total_energy(t_moldyn *moldyn) {
1235
1236         return(moldyn->ekin+moldyn->energy);
1237 }
1238
1239 t_3dvec get_total_p(t_moldyn *moldyn) {
1240
1241         t_3dvec p,p_total;
1242         int i;
1243         t_atom *atom;
1244
1245         atom=moldyn->atom;
1246
1247         v3_zero(&p_total);
1248         for(i=0;i<moldyn->count;i++) {
1249                 v3_scale(&p,&(atom[i].v),atom[i].mass);
1250                 v3_add(&p_total,&p_total,&p);
1251         }
1252
1253         return p_total;
1254 }
1255
1256 double estimate_time_step(t_moldyn *moldyn,double nn_dist) {
1257
1258         double tau;
1259
1260         /* nn_dist is the nearest neighbour distance */
1261
1262         tau=(0.05*nn_dist*moldyn->atom[0].mass)/sqrt(3.0*K_BOLTZMANN*moldyn->t);
1263
1264         return tau;     
1265 }
1266
1267 /*
1268  * numerical tricks
1269  */
1270
1271 /* linked list / cell method */
1272
1273 int link_cell_init(t_moldyn *moldyn,u8 vol) {
1274
1275         t_linkcell *lc;
1276         int i;
1277
1278         lc=&(moldyn->lc);
1279
1280         /* partitioning the md cell */
1281         lc->nx=moldyn->dim.x/moldyn->cutoff;
1282         lc->x=moldyn->dim.x/lc->nx;
1283         lc->ny=moldyn->dim.y/moldyn->cutoff;
1284         lc->y=moldyn->dim.y/lc->ny;
1285         lc->nz=moldyn->dim.z/moldyn->cutoff;
1286         lc->z=moldyn->dim.z/lc->nz;
1287         lc->cells=lc->nx*lc->ny*lc->nz;
1288
1289 #ifdef STATIC_LISTS
1290         lc->subcell=malloc(lc->cells*sizeof(int*));
1291 #else
1292         lc->subcell=malloc(lc->cells*sizeof(t_list));
1293 #endif
1294
1295         if(lc->subcell==NULL) {
1296                 perror("[moldyn] cell init (malloc)");
1297                 return -1;
1298         }
1299
1300         if(lc->cells<27)
1301                 printf("[moldyn] FATAL: less then 27 subcells!\n");
1302
1303         if(vol) {
1304 #ifdef STATIC_LISTS
1305                 printf("[moldyn] initializing 'static' linked cells (%d)\n",
1306                        lc->cells);
1307 #else
1308                 printf("[moldyn] initializing 'dynamic' linked cells (%d)\n",
1309                        lc->cells);
1310 #endif
1311                 printf("  x: %d x %f A\n",lc->nx,lc->x);
1312                 printf("  y: %d x %f A\n",lc->ny,lc->y);
1313                 printf("  z: %d x %f A\n",lc->nz,lc->z);
1314         }
1315
1316 #ifdef STATIC_LISTS
1317         /* list init */
1318         for(i=0;i<lc->cells;i++) {
1319                 lc->subcell[i]=malloc((MAX_ATOMS_PER_LIST+1)*sizeof(int));
1320                 if(lc->subcell[i]==NULL) {
1321                         perror("[moldyn] list init (malloc)");
1322                         return -1;
1323                 }
1324                 /*
1325                 if(i==0)
1326                         printf(" ---> %d malloc %p (%p)\n",
1327                                i,lc->subcell[0],lc->subcell);
1328                 */
1329         }
1330 #else
1331         for(i=0;i<lc->cells;i++)
1332                 list_init_f(&(lc->subcell[i]));
1333 #endif
1334
1335         /* update the list */
1336         link_cell_update(moldyn);
1337
1338         return 0;
1339 }
1340
1341 int link_cell_update(t_moldyn *moldyn) {
1342
1343         int count,i,j,k;
1344         int nx,ny;
1345         t_atom *atom;
1346         t_linkcell *lc;
1347 #ifdef STATIC_LISTS
1348         int p;
1349 #endif
1350
1351         atom=moldyn->atom;
1352         lc=&(moldyn->lc);
1353
1354         nx=lc->nx;
1355         ny=lc->ny;
1356
1357         for(i=0;i<lc->cells;i++)
1358 #ifdef STATIC_LISTS
1359                 memset(lc->subcell[i],0,(MAX_ATOMS_PER_LIST+1)*sizeof(int));
1360 #else
1361                 list_destroy_f(&(lc->subcell[i]));
1362 #endif
1363
1364         for(count=0;count<moldyn->count;count++) {
1365                 i=((atom[count].r.x+(moldyn->dim.x/2))/lc->x);
1366                 j=((atom[count].r.y+(moldyn->dim.y/2))/lc->y);
1367                 k=((atom[count].r.z+(moldyn->dim.z/2))/lc->z);
1368         
1369 #ifdef STATIC_LISTS
1370                 p=0;
1371                 while(lc->subcell[i+j*nx+k*nx*ny][p]!=0)
1372                         p++;
1373
1374                 if(p>=MAX_ATOMS_PER_LIST) {
1375                         printf("[moldyn] FATAL: amount of atoms too high!\n");
1376                         return -1;
1377                 }
1378
1379                 lc->subcell[i+j*nx+k*nx*ny][p]=count;
1380 #else
1381                 list_add_immediate_f(&(lc->subcell[i+j*nx+k*nx*ny]),
1382                                      &(atom[count]));
1383                 /*
1384                 if(j==0&&k==0)
1385                         printf(" ---> %d %d malloc %p (%p)\n",
1386                                i,count,lc->subcell[i].current,lc->subcell);
1387                 */
1388 #endif
1389         }
1390
1391         return 0;
1392 }
1393
1394 int link_cell_neighbour_index(t_moldyn *moldyn,int i,int j,int k,
1395 #ifdef STATIC_LISTS
1396                               int **cell
1397 #else
1398                               t_list *cell
1399 #endif
1400                              ) {
1401
1402         t_linkcell *lc;
1403         int a;
1404         int count1,count2;
1405         int ci,cj,ck;
1406         int nx,ny,nz;
1407         int x,y,z;
1408         u8 bx,by,bz;
1409
1410         lc=&(moldyn->lc);
1411         nx=lc->nx;
1412         ny=lc->ny;
1413         nz=lc->nz;
1414         count1=1;
1415         count2=27;
1416         a=nx*ny;
1417
1418         if(i>=nx||j>=ny||k>=nz)
1419                 printf("[moldyn] WARNING: lcni %d/%d %d/%d %d/%d\n",
1420                        i,nx,j,ny,k,nz);
1421
1422         cell[0]=lc->subcell[i+j*nx+k*a];
1423         for(ci=-1;ci<=1;ci++) {
1424                 bx=0;
1425                 x=i+ci;
1426                 if((x<0)||(x>=nx)) {
1427                         x=(x+nx)%nx;
1428                         bx=1;
1429                 }
1430                 for(cj=-1;cj<=1;cj++) {
1431                         by=0;
1432                         y=j+cj;
1433                         if((y<0)||(y>=ny)) {
1434                                 y=(y+ny)%ny;
1435                                 by=1;
1436                         }
1437                         for(ck=-1;ck<=1;ck++) {
1438                                 bz=0;
1439                                 z=k+ck;
1440                                 if((z<0)||(z>=nz)) {
1441                                         z=(z+nz)%nz;
1442                                         bz=1;
1443                                 }
1444                                 if(!(ci|cj|ck)) continue;
1445                                 if(bx|by|bz) {
1446                                         cell[--count2]=lc->subcell[x+y*nx+z*a];
1447                                 }
1448                                 else {
1449                                         cell[count1++]=lc->subcell[x+y*nx+z*a];
1450                                 }
1451                         }
1452                 }
1453         }
1454
1455         lc->dnlc=count1;
1456
1457         return count1;
1458 }
1459
1460 int link_cell_shutdown(t_moldyn *moldyn) {
1461
1462         int i;
1463         t_linkcell *lc;
1464
1465         lc=&(moldyn->lc);
1466
1467         for(i=0;i<lc->cells;i++) {
1468 #ifdef STATIC_LISTS
1469                 free(lc->subcell[i]);
1470 #else
1471                 //printf(" ---> %d free %p\n",i,lc->subcell[i].start);
1472                 list_destroy_f(&(lc->subcell[i]));
1473 #endif
1474         }
1475
1476         free(lc->subcell);
1477
1478         return 0;
1479 }
1480
1481 int moldyn_add_schedule(t_moldyn *moldyn,int runs,double tau) {
1482
1483         int count;
1484         void *ptr;
1485         t_moldyn_schedule *schedule;
1486
1487         schedule=&(moldyn->schedule);
1488         count=++(schedule->total_sched);
1489
1490         ptr=realloc(schedule->runs,count*sizeof(int));
1491         if(!ptr) {
1492                 perror("[moldyn] realloc (runs)");
1493                 return -1;
1494         }
1495         schedule->runs=ptr;
1496         schedule->runs[count-1]=runs;
1497
1498         ptr=realloc(schedule->tau,count*sizeof(double));
1499         if(!ptr) {
1500                 perror("[moldyn] realloc (tau)");
1501                 return -1;
1502         }
1503         schedule->tau=ptr;
1504         schedule->tau[count-1]=tau;
1505
1506         printf("[moldyn] schedule added:\n");
1507         printf("  number: %d | runs: %d | tau: %f\n",count-1,runs,tau);
1508                                        
1509
1510         return 0;
1511 }
1512
1513 int moldyn_set_schedule_hook(t_moldyn *moldyn,set_hook hook,void *hook_params) {
1514
1515         moldyn->schedule.hook=hook;
1516         moldyn->schedule.hook_params=hook_params;
1517         
1518         return 0;
1519 }
1520
1521 /*
1522  *
1523  * 'integration of newtons equation' - algorithms
1524  *
1525  */
1526
1527 /* start the integration */
1528
1529 int moldyn_integrate(t_moldyn *moldyn) {
1530
1531         int i;
1532         unsigned int e,m,s,v,p,t,a;
1533         t_3dvec momentum;
1534         t_moldyn_schedule *sched;
1535         t_atom *atom;
1536         int fd;
1537         char dir[128];
1538         double ds;
1539         double energy_scale;
1540         struct timeval t1,t2;
1541         //double tp;
1542
1543         sched=&(moldyn->schedule);
1544         atom=moldyn->atom;
1545
1546         /* initialize linked cell method */
1547         link_cell_init(moldyn,VERBOSE);
1548
1549         /* logging & visualization */
1550         e=moldyn->ewrite;
1551         m=moldyn->mwrite;
1552         s=moldyn->swrite;
1553         v=moldyn->vwrite;
1554         a=moldyn->awrite;
1555         p=moldyn->pwrite;
1556         t=moldyn->twrite;
1557
1558         /* sqaure of some variables */
1559         moldyn->tau_square=moldyn->tau*moldyn->tau;
1560
1561         /* get current time */
1562         gettimeofday(&t1,NULL);
1563
1564         /* calculate initial forces */
1565         potential_force_calc(moldyn);
1566 #ifdef DEBUG
1567 //return 0;
1568 #endif
1569
1570         /* some stupid checks before we actually start calculating bullshit */
1571         if(moldyn->cutoff>0.5*moldyn->dim.x)
1572                 printf("[moldyn] WARNING: cutoff > 0.5 x dim.x\n");
1573         if(moldyn->cutoff>0.5*moldyn->dim.y)
1574                 printf("[moldyn] WARNING: cutoff > 0.5 x dim.y\n");
1575         if(moldyn->cutoff>0.5*moldyn->dim.z)
1576                 printf("[moldyn] WARNING: cutoff > 0.5 x dim.z\n");
1577         ds=0.5*atom[0].f.x*moldyn->tau_square/atom[0].mass;
1578         if(ds>0.05*moldyn->nnd)
1579                 printf("[moldyn] WARNING: forces too high / tau too small!\n");
1580
1581         /* zero absolute time */
1582         moldyn->time=0.0;
1583         moldyn->total_steps=0;
1584
1585         /* debugging, ignore */
1586         moldyn->debug=0;
1587
1588         /* tell the world */
1589         printf("[moldyn] integration start, go get a coffee ...\n");
1590
1591         /* executing the schedule */
1592         sched->count=0;
1593         while(sched->count<sched->total_sched) {
1594
1595                 /* setting amount of runs and finite time step size */
1596                 moldyn->tau=sched->tau[sched->count];
1597                 moldyn->tau_square=moldyn->tau*moldyn->tau;
1598                 moldyn->time_steps=sched->runs[sched->count];
1599
1600                 /* energy scaling factor (might change!) */
1601                 energy_scale=moldyn->count*EV;
1602
1603         /* integration according to schedule */
1604
1605         for(i=0;i<moldyn->time_steps;i++) {
1606
1607                 /* integration step */
1608                 moldyn->integrate(moldyn);
1609
1610                 /* calculate kinetic energy, temperature and pressure */
1611                 e_kin_calc(moldyn);
1612                 temperature_calc(moldyn);
1613                 virial_sum(moldyn);
1614                 pressure_calc(moldyn);
1615                 /*
1616                 thermodynamic_pressure_calc(moldyn);
1617                 printf("\n\nDEBUG: numeric pressure calc: %f\n\n",
1618                        moldyn->tp/BAR);
1619                 */
1620
1621                 /* calculate fluctuations + averages */
1622                 average_and_fluctuation_calc(moldyn);
1623
1624                 /* p/t scaling */
1625                 if(moldyn->pt_scale&(T_SCALE_BERENDSEN|T_SCALE_DIRECT))
1626                         scale_velocity(moldyn,FALSE);
1627                 if(moldyn->pt_scale&(P_SCALE_BERENDSEN|P_SCALE_DIRECT))
1628                         scale_volume(moldyn);
1629
1630                 /* check for log & visualization */
1631                 if(e) {
1632                         if(!(moldyn->total_steps%e))
1633                                 dprintf(moldyn->efd,
1634                                         "%f %f %f %f\n",
1635                                         moldyn->time,moldyn->ekin/energy_scale,
1636                                         moldyn->energy/energy_scale,
1637                                         get_total_energy(moldyn)/energy_scale);
1638                 }
1639                 if(m) {
1640                         if(!(moldyn->total_steps%m)) {
1641                                 momentum=get_total_p(moldyn);
1642                                 dprintf(moldyn->mfd,
1643                                         "%f %f %f %f %f\n",moldyn->time,
1644                                         momentum.x,momentum.y,momentum.z,
1645                                         v3_norm(&momentum));
1646                         }
1647                 }
1648                 if(p) {
1649                         if(!(moldyn->total_steps%p)) {
1650                                 dprintf(moldyn->pfd,
1651                                         "%f %f %f %f %f %f %f\n",moldyn->time,
1652                                          moldyn->p/BAR,moldyn->p_avg/BAR,
1653                                          moldyn->gp/BAR,moldyn->gp_avg/BAR,
1654                                          moldyn->tp/BAR,moldyn->tp_avg/BAR);
1655                         }
1656                 }
1657                 if(t) {
1658                         if(!(moldyn->total_steps%t)) {
1659                                 dprintf(moldyn->tfd,
1660                                         "%f %f %f\n",
1661                                         moldyn->time,moldyn->t,moldyn->t_avg);
1662                         }
1663                 }
1664                 if(v) {
1665                         if(!(moldyn->total_steps%v)) {
1666                                 dprintf(moldyn->vfd,
1667                                         "%f %f\n",moldyn->time,moldyn->volume);
1668                         }
1669                 }
1670                 if(s) {
1671                         if(!(moldyn->total_steps%s)) {
1672                                 snprintf(dir,128,"%s/s-%07.f.save",
1673                                          moldyn->vlsdir,moldyn->time);
1674                                 fd=open(dir,O_WRONLY|O_TRUNC|O_CREAT,
1675                                         S_IRUSR|S_IWUSR);
1676                                 if(fd<0) perror("[moldyn] save fd open");
1677                                 else {
1678                                         write(fd,moldyn,sizeof(t_moldyn));
1679                                         write(fd,moldyn->atom,
1680                                               moldyn->count*sizeof(t_atom));
1681                                 }
1682                                 close(fd);
1683                         }       
1684                 }
1685                 if(a) {
1686                         if(!(moldyn->total_steps%a)) {
1687                                 visual_atoms(moldyn);
1688                         }
1689                 }
1690
1691                 /* display progress */
1692                 //if(!(moldyn->total_steps%10)) {
1693                         /* get current time */
1694                         gettimeofday(&t2,NULL);
1695
1696 printf("\rsched:%d, steps:%d/%d, T:%4.1f/%4.1f P:%4.1f/%4.1f V:%6.1f (%d)",
1697        sched->count,i,moldyn->total_steps,
1698        moldyn->t,moldyn->t_avg,
1699        moldyn->p/BAR,moldyn->p_avg/BAR,
1700        moldyn->volume,
1701        (int)(t2.tv_sec-t1.tv_sec));
1702
1703                         fflush(stdout);
1704
1705                         /* copy over time */
1706                         t1=t2;
1707                 //}
1708
1709                 /* increase absolute time */
1710                 moldyn->time+=moldyn->tau;
1711                 moldyn->total_steps+=1;
1712
1713         }
1714
1715                 /* check for hooks */
1716                 if(sched->hook) {
1717                         printf("\n ## schedule hook %d start ##\n",
1718                                sched->count);
1719                         sched->hook(moldyn,sched->hook_params);
1720                         printf(" ## schedule hook end ##\n");
1721                 }
1722
1723                 /* increase the schedule counter */
1724                 sched->count+=1;
1725
1726         }
1727
1728         return 0;
1729 }
1730
1731 /* velocity verlet */
1732
1733 int velocity_verlet(t_moldyn *moldyn) {
1734
1735         int i,count;
1736         double tau,tau_square,h;
1737         t_3dvec delta;
1738         t_atom *atom;
1739
1740         atom=moldyn->atom;
1741         count=moldyn->count;
1742         tau=moldyn->tau;
1743         tau_square=moldyn->tau_square;
1744
1745         for(i=0;i<count;i++) {
1746                 /* check whether fixed atom */
1747                 if(atom[i].attr&ATOM_ATTR_FP)
1748                         continue;
1749                 /* new positions */
1750                 h=0.5/atom[i].mass;
1751                 v3_scale(&delta,&(atom[i].v),tau);
1752                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
1753                 v3_scale(&delta,&(atom[i].f),h*tau_square);
1754                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
1755                 check_per_bound(moldyn,&(atom[i].r));
1756
1757                 /* velocities [actually v(t+tau/2)] */
1758                 v3_scale(&delta,&(atom[i].f),h*tau);
1759                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
1760         }
1761
1762         /* criticial check */
1763         moldyn_bc_check(moldyn);
1764
1765         /* neighbour list update */
1766         link_cell_update(moldyn);
1767
1768         /* forces depending on chosen potential */
1769         potential_force_calc(moldyn);
1770
1771         for(i=0;i<count;i++) {
1772                 /* check whether fixed atom */
1773                 if(atom[i].attr&ATOM_ATTR_FP)
1774                         continue;
1775                 /* again velocities [actually v(t+tau)] */
1776                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
1777                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
1778         }
1779
1780         return 0;
1781 }
1782
1783
1784 /*
1785  *
1786  * potentials & corresponding forces & virial routine
1787  * 
1788  */
1789
1790 /* generic potential and force calculation */
1791
1792 int potential_force_calc(t_moldyn *moldyn) {
1793
1794         int i,j,k,count;
1795         t_atom *itom,*jtom,*ktom;
1796         t_virial *virial;
1797         t_linkcell *lc;
1798 #ifdef STATIC_LISTS
1799         int *neighbour_i[27];
1800         int p,q;
1801         t_atom *atom;
1802 #else
1803         t_list neighbour_i[27];
1804         t_list neighbour_i2[27];
1805         t_list *this,*that;
1806 #endif
1807         u8 bc_ij,bc_ik;
1808         int dnlc;
1809
1810         count=moldyn->count;
1811         itom=moldyn->atom;
1812         lc=&(moldyn->lc);
1813 #ifdef STATIC_LISTS
1814         atom=moldyn->atom;
1815 #endif
1816
1817         /* reset energy */
1818         moldyn->energy=0.0;
1819
1820         /* reset global virial */
1821         memset(&(moldyn->gvir),0,sizeof(t_virial));
1822
1823         /* reset force, site energy and virial of every atom */
1824         for(i=0;i<count;i++) {
1825
1826                 /* reset force */
1827                 v3_zero(&(itom[i].f));
1828
1829                 /* reset virial */
1830                 virial=(&(itom[i].virial));
1831                 virial->xx=0.0;
1832                 virial->yy=0.0;
1833                 virial->zz=0.0;
1834                 virial->xy=0.0;
1835                 virial->xz=0.0;
1836                 virial->yz=0.0;
1837         
1838                 /* reset site energy */
1839                 itom[i].e=0.0;
1840
1841         }
1842
1843         /* get energy, force and virial of every atom */
1844
1845         /* first (and only) loop over atoms i */
1846         for(i=0;i<count;i++) {
1847
1848                 /* single particle potential/force */
1849                 if(itom[i].attr&ATOM_ATTR_1BP)
1850                         if(moldyn->func1b)
1851                                 moldyn->func1b(moldyn,&(itom[i]));
1852
1853                 if(!(itom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)))
1854                         continue;
1855
1856                 /* 2 body pair potential/force */
1857         
1858                 link_cell_neighbour_index(moldyn,
1859                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
1860                                           (itom[i].r.y+moldyn->dim.y/2)/lc->y,
1861                                           (itom[i].r.z+moldyn->dim.z/2)/lc->z,
1862                                           neighbour_i);
1863
1864                 dnlc=lc->dnlc;
1865
1866                 /* first loop over atoms j */
1867                 if(moldyn->func2b) {
1868                         for(j=0;j<27;j++) {
1869
1870                                 bc_ij=(j<dnlc)?0:1;
1871 #ifdef STATIC_LISTS
1872                                 p=0;
1873
1874                                 while(neighbour_i[j][p]!=0) {
1875
1876                                         jtom=&(atom[neighbour_i[j][p]]);
1877                                         p++;
1878
1879                                         if(jtom==&(itom[i]))
1880                                                 continue;
1881
1882                                         if((jtom->attr&ATOM_ATTR_2BP)&
1883                                            (itom[i].attr&ATOM_ATTR_2BP)) {
1884                                                 moldyn->func2b(moldyn,
1885                                                                &(itom[i]),
1886                                                                jtom,
1887                                                                bc_ij);
1888                                         }
1889                                 }
1890 #else
1891                                 this=&(neighbour_i[j]);
1892                                 list_reset_f(this);
1893
1894                                 if(this->start==NULL)
1895                                         continue;
1896
1897                                 do {
1898                                         jtom=this->current->data;
1899
1900                                         if(jtom==&(itom[i]))
1901                                                 continue;
1902
1903                                         if((jtom->attr&ATOM_ATTR_2BP)&
1904                                            (itom[i].attr&ATOM_ATTR_2BP)) {
1905                                                 moldyn->func2b(moldyn,
1906                                                                &(itom[i]),
1907                                                                jtom,
1908                                                                bc_ij);
1909                                         }
1910                                 } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
1911 #endif
1912
1913                         }
1914                 }
1915
1916                 /* 3 body potential/force */
1917
1918                 if(!(itom[i].attr&ATOM_ATTR_3BP))
1919                         continue;
1920
1921                 /* copy the neighbour lists */
1922 #ifdef STATIC_LISTS
1923                 /* no copy needed for static lists */
1924 #else
1925                 memcpy(neighbour_i2,neighbour_i,27*sizeof(t_list));
1926 #endif
1927
1928                 /* second loop over atoms j */
1929                 for(j=0;j<27;j++) {
1930
1931                         bc_ij=(j<dnlc)?0:1;
1932 #ifdef STATIC_LISTS
1933                         p=0;
1934
1935                         while(neighbour_i[j][p]!=0) {
1936
1937                                 jtom=&(atom[neighbour_i[j][p]]);
1938                                 p++;
1939 #else
1940                         this=&(neighbour_i[j]);
1941                         list_reset_f(this);
1942
1943                         if(this->start==NULL)
1944                                 continue;
1945
1946                         do {
1947
1948                                 jtom=this->current->data;
1949 #endif
1950
1951                                 if(jtom==&(itom[i]))
1952                                         continue;
1953
1954                                 if(!(jtom->attr&ATOM_ATTR_3BP))
1955                                         continue;
1956
1957                                 /* reset 3bp run */
1958                                 moldyn->run3bp=1;
1959
1960                                 if(moldyn->func3b_j1)
1961                                         moldyn->func3b_j1(moldyn,
1962                                                           &(itom[i]),
1963                                                           jtom,
1964                                                           bc_ij);
1965
1966                                 /* in first j loop, 3bp run can be skipped */
1967                                 if(!(moldyn->run3bp))
1968                                         continue;
1969                         
1970                                 /* first loop over atoms k */
1971                                 if(moldyn->func3b_k1) {
1972
1973                                 for(k=0;k<27;k++) {
1974
1975                                         bc_ik=(k<dnlc)?0:1;
1976 #ifdef STATIC_LISTS
1977                                         q=0;
1978
1979                                         while(neighbour_i[j][q]!=0) {
1980
1981                                                 ktom=&(atom[neighbour_i[k][q]]);
1982                                                 q++;
1983 #else
1984                                         that=&(neighbour_i2[k]);
1985                                         list_reset_f(that);
1986                                         
1987                                         if(that->start==NULL)
1988                                                 continue;
1989
1990                                         do {
1991                                                 ktom=that->current->data;
1992 #endif
1993
1994                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
1995                                                         continue;
1996
1997                                                 if(ktom==jtom)
1998                                                         continue;
1999
2000                                                 if(ktom==&(itom[i]))
2001                                                         continue;
2002
2003                                                 moldyn->func3b_k1(moldyn,
2004                                                                   &(itom[i]),
2005                                                                   jtom,
2006                                                                   ktom,
2007                                                                   bc_ik|bc_ij);
2008 #ifdef STATIC_LISTS
2009                                         }
2010 #else
2011                                         } while(list_next_f(that)!=\
2012                                                 L_NO_NEXT_ELEMENT);
2013 #endif
2014
2015                                 }
2016
2017                                 }
2018
2019                                 if(moldyn->func3b_j2)
2020                                         moldyn->func3b_j2(moldyn,
2021                                                           &(itom[i]),
2022                                                           jtom,
2023                                                           bc_ij);
2024
2025                                 /* second loop over atoms k */
2026                                 if(moldyn->func3b_k2) {
2027
2028                                 for(k=0;k<27;k++) {
2029
2030                                         bc_ik=(k<dnlc)?0:1;
2031 #ifdef STATIC_LISTS
2032                                         q=0;
2033
2034                                         while(neighbour_i[j][q]!=0) {
2035
2036                                                 ktom=&(atom[neighbour_i[k][q]]);
2037                                                 q++;
2038 #else
2039                                         that=&(neighbour_i2[k]);
2040                                         list_reset_f(that);
2041                                         
2042                                         if(that->start==NULL)
2043                                                 continue;
2044
2045                                         do {
2046                                                 ktom=that->current->data;
2047 #endif
2048
2049                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
2050                                                         continue;
2051
2052                                                 if(ktom==jtom)
2053                                                         continue;
2054
2055                                                 if(ktom==&(itom[i]))
2056                                                         continue;
2057
2058                                                 moldyn->func3b_k2(moldyn,
2059                                                                   &(itom[i]),
2060                                                                   jtom,
2061                                                                   ktom,
2062                                                                   bc_ik|bc_ij);
2063
2064 #ifdef STATIC_LISTS
2065                                         }
2066 #else
2067                                         } while(list_next_f(that)!=\
2068                                                 L_NO_NEXT_ELEMENT);
2069 #endif
2070
2071                                 }
2072                                 
2073                                 }
2074
2075                                 /* 2bp post function */
2076                                 if(moldyn->func3b_j3) {
2077                                         moldyn->func3b_j3(moldyn,
2078                                                           &(itom[i]),
2079                                                           jtom,bc_ij);
2080                                 }
2081 #ifdef STATIC_LISTS
2082                         }
2083 #else
2084                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2085 #endif
2086                 
2087                 }
2088                 
2089 #ifdef DEBUG
2090         //printf("\n\n");
2091 #endif
2092 #ifdef VDEBUG
2093         printf("\n\n");
2094 #endif
2095
2096         }
2097
2098 #ifdef DEBUG
2099         //printf("\nATOM 0: %f %f %f\n\n",itom->f.x,itom->f.y,itom->f.z);
2100         if(moldyn->time>DSTART&&moldyn->time<DEND) {
2101                 printf("force:\n");
2102                 printf("  x: %0.40f\n",moldyn->atom[DATOM].f.x);
2103                 printf("  y: %0.40f\n",moldyn->atom[DATOM].f.y);
2104                 printf("  z: %0.40f\n",moldyn->atom[DATOM].f.z);
2105         }
2106 #endif
2107
2108         /* some postprocessing */
2109         for(i=0;i<count;i++) {
2110                 /* calculate global virial */
2111                 moldyn->gvir.xx+=itom[i].r.x*itom[i].f.x;
2112                 moldyn->gvir.yy+=itom[i].r.y*itom[i].f.y;
2113                 moldyn->gvir.zz+=itom[i].r.z*itom[i].f.z;
2114                 moldyn->gvir.xy+=itom[i].r.y*itom[i].f.x;
2115                 moldyn->gvir.xz+=itom[i].r.z*itom[i].f.x;
2116                 moldyn->gvir.yz+=itom[i].r.z*itom[i].f.y;
2117
2118                 /* check forces regarding the given timestep */
2119                 if(v3_norm(&(itom[i].f))>\
2120                    0.1*moldyn->nnd*itom[i].mass/moldyn->tau_square)
2121                         printf("[moldyn] WARNING: pfc (high force: atom %d)\n",
2122                                i);
2123         }
2124
2125         return 0;
2126 }
2127
2128 /*
2129  * virial calculation
2130  */
2131
2132 //inline int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
2133 int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
2134
2135         a->virial.xx+=f->x*d->x;
2136         a->virial.yy+=f->y*d->y;
2137         a->virial.zz+=f->z*d->z;
2138         a->virial.xy+=f->x*d->y;
2139         a->virial.xz+=f->x*d->z;
2140         a->virial.yz+=f->y*d->z;
2141
2142         return 0;
2143 }
2144
2145 /*
2146  * periodic boundary checking
2147  */
2148
2149 //inline int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
2150 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
2151         
2152         double x,y,z;
2153         t_3dvec *dim;
2154
2155         dim=&(moldyn->dim);
2156
2157         x=dim->x/2;
2158         y=dim->y/2;
2159         z=dim->z/2;
2160
2161         if(moldyn->status&MOLDYN_STAT_PBX) {
2162                 if(a->x>=x) a->x-=dim->x;
2163                 else if(-a->x>x) a->x+=dim->x;
2164         }
2165         if(moldyn->status&MOLDYN_STAT_PBY) {
2166                 if(a->y>=y) a->y-=dim->y;
2167                 else if(-a->y>y) a->y+=dim->y;
2168         }
2169         if(moldyn->status&MOLDYN_STAT_PBZ) {
2170                 if(a->z>=z) a->z-=dim->z;
2171                 else if(-a->z>z) a->z+=dim->z;
2172         }
2173
2174         return 0;
2175 }
2176         
2177 /*
2178  * debugging / critical check functions
2179  */
2180
2181 int moldyn_bc_check(t_moldyn *moldyn) {
2182
2183         t_atom *atom;
2184         t_3dvec *dim;
2185         int i;
2186         double x;
2187         u8 byte;
2188         int j,k;
2189
2190         atom=moldyn->atom;
2191         dim=&(moldyn->dim);
2192         x=dim->x/2;
2193
2194         for(i=0;i<moldyn->count;i++) {
2195                 if(atom[i].r.x>=dim->x/2||-atom[i].r.x>dim->x/2) {
2196                         printf("FATAL: atom %d: x: %.20f (%.20f)\n",
2197                                i,atom[i].r.x,dim->x/2);
2198                         printf("diagnostic:\n");
2199                         printf("-----------\natom.r.x:\n");
2200                         for(j=0;j<8;j++) {
2201                                 memcpy(&byte,(u8 *)(&(atom[i].r.x))+j,1);
2202                                 for(k=0;k<8;k++)
2203                                         printf("%d%c",
2204                                         ((byte)&(1<<k))?1:0,
2205                                         (k==7)?'\n':'|');
2206                         }
2207                         printf("---------------\nx=dim.x/2:\n");
2208                         for(j=0;j<8;j++) {
2209                                 memcpy(&byte,(u8 *)(&x)+j,1);
2210                                 for(k=0;k<8;k++)
2211                                         printf("%d%c",
2212                                         ((byte)&(1<<k))?1:0,
2213                                         (k==7)?'\n':'|');
2214                         }
2215                         if(atom[i].r.x==x) printf("the same!\n");
2216                         else printf("different!\n");
2217                 }
2218                 if(atom[i].r.y>=dim->y/2||-atom[i].r.y>dim->y/2)
2219                         printf("FATAL: atom %d: y: %.20f (%.20f)\n",
2220                                i,atom[i].r.y,dim->y/2);
2221                 if(atom[i].r.z>=dim->z/2||-atom[i].r.z>dim->z/2)
2222                         printf("FATAL: atom %d: z: %.20f (%.20f)\n",
2223                                i,atom[i].r.z,dim->z/2);
2224         }
2225
2226         return 0;
2227 }
2228
2229 /*
2230  * restore function
2231  */
2232
2233 int moldyn_read_save_file(t_moldyn *moldyn,char *file) {
2234
2235         int fd;
2236         int cnt,size;
2237         int fsize;
2238         int corr;
2239
2240         fd=open(file,O_RDONLY);
2241         if(fd<0) {
2242                 perror("[moldyn] load save file open");
2243                 return fd;
2244         }
2245
2246         fsize=lseek(fd,0,SEEK_END);
2247         lseek(fd,0,SEEK_SET);
2248
2249         size=sizeof(t_moldyn);
2250
2251         while(size) {
2252                 cnt=read(fd,moldyn,size);
2253                 if(cnt<0) {
2254                         perror("[moldyn] load save file read (moldyn)");
2255                         return cnt;
2256                 }
2257                 size-=cnt;
2258         }
2259
2260         size=moldyn->count*sizeof(t_atom);
2261
2262         /* correcting possible atom data offset */
2263         corr=0;
2264         if(fsize!=sizeof(t_moldyn)+size) {
2265                 corr=fsize-sizeof(t_moldyn)-size;
2266                 printf("[moldyn] WARNING: lsf (illegal file size)\n");
2267                 printf("  moifying offset:\n");
2268                 printf("  - current pos: %d\n",sizeof(t_moldyn));
2269                 printf("  - atom size: %d\n",size);
2270                 printf("  - file size: %d\n",fsize);
2271                 printf("  => correction: %d\n",corr);
2272                 lseek(fd,corr,SEEK_CUR);
2273         }
2274
2275         moldyn->atom=(t_atom *)malloc(size);
2276         if(moldyn->atom==NULL) {
2277                 perror("[moldyn] load save file malloc (atoms)");
2278                 return -1;
2279         }
2280
2281         while(size) {
2282                 cnt=read(fd,moldyn->atom,size);
2283                 if(cnt<0) {
2284                         perror("[moldyn] load save file read (atoms)");
2285                         return cnt;
2286                 }
2287                 size-=cnt;
2288         }
2289
2290         // hooks etc ...
2291
2292         return 0;
2293 }
2294
2295 int moldyn_free_save_file(t_moldyn *moldyn) {
2296
2297         free(moldyn->atom);
2298
2299         return 0;
2300 }
2301
2302 int moldyn_load(t_moldyn *moldyn) {
2303
2304         // later ...
2305
2306         return 0;
2307 }
2308
2309 /*
2310  * function to find/callback all combinations of 2 body bonds
2311  */
2312
2313 int process_2b_bonds(t_moldyn *moldyn,void *data,
2314                      int (*process)(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2315                                     void *data,u8 bc)) {
2316
2317         t_linkcell *lc;
2318 #ifdef STATIC_LISTS
2319         int *neighbour[27];
2320         int p;
2321 #else
2322         t_list neighbour[27];
2323 #endif
2324         u8 bc;
2325         t_atom *itom,*jtom;
2326         int i,j;
2327         t_list *this;
2328
2329         lc=&(moldyn->lc);
2330         itom=moldyn->atom;
2331         
2332         for(i=0;i<moldyn->count;i++) {
2333                 /* neighbour indexing */
2334                 link_cell_neighbour_index(moldyn,
2335                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
2336                                           (itom[i].r.y+moldyn->dim.y/2)/lc->x,
2337                                           (itom[i].r.z+moldyn->dim.z/2)/lc->x,
2338                                           neighbour);
2339
2340                 for(j=0;j<27;j++) {
2341
2342                         bc=(j<lc->dnlc)?0:1;
2343
2344 #ifdef STATIC_LISTS
2345                         p=0;
2346
2347                         while(neighbour[j][p]!=0) {
2348
2349                                 jtom=&(moldyn->atom[neighbour[j][p]]);
2350                                 p++;
2351 #else
2352                         this=&(neighbour[j]);
2353                         list_reset_f(this);
2354
2355                         if(this->start==NULL)
2356                                 continue;
2357
2358                         do {
2359
2360                                 jtom=this->current->data;
2361 #endif
2362
2363                                 /* process bond */
2364                                 process(moldyn,&(itom[i]),jtom,data,bc);
2365
2366 #ifdef STATIC_LISTS
2367                         }
2368 #else
2369                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2370 #endif
2371                 }
2372         }
2373
2374         return 0;
2375
2376 }
2377
2378 /*
2379  * post processing functions
2380  */
2381
2382 int get_line(int fd,char *line,int max) {
2383
2384         int count,ret;
2385
2386         count=0;
2387
2388         while(1) {
2389                 if(count==max) return count;
2390                 ret=read(fd,line+count,1);
2391                 if(ret<=0) return ret;
2392                 if(line[count]=='\n') {
2393                         memset(line+count,0,max-count-1);
2394                         //line[count]='\0';
2395                         return count+1;
2396                 }
2397                 count+=1;
2398         }
2399 }
2400
2401 int pair_correlation_init(t_moldyn *moldyn,double dr) {
2402
2403         
2404         return 0;
2405 }
2406
2407 int calculate_diffusion_coefficient(t_moldyn *moldyn,double *dc) {
2408
2409         int i;
2410         t_atom *atom;
2411         t_3dvec dist;
2412         double d2;
2413         int a_cnt;
2414         int b_cnt;
2415
2416         atom=moldyn->atom;
2417         dc[0]=0;
2418         dc[1]=0;
2419         dc[2]=0;
2420         a_cnt=0;
2421         b_cnt=0;
2422
2423         for(i=0;i<moldyn->count;i++) {
2424
2425                 v3_sub(&dist,&(atom[i].r),&(atom[i].r_0));
2426                 check_per_bound(moldyn,&dist);
2427                 d2=v3_absolute_square(&dist);
2428
2429                 if(atom[i].brand) {
2430                         b_cnt+=1;
2431                         dc[1]+=d2;
2432                 }
2433                 else {
2434                         a_cnt+=1;
2435                         dc[0]+=d2;
2436                 }
2437
2438                 dc[2]+=d2;
2439         }
2440
2441         dc[0]*=(1.0/(6.0*moldyn->time*a_cnt));
2442         dc[1]*=(1.0/(6.0*moldyn->time*b_cnt));
2443         dc[2]*=(1.0/(6.0*moldyn->time*moldyn->count));
2444                 
2445         return 0;
2446 }
2447
2448 int bonding_analyze(t_moldyn *moldyn,double *cnt) {
2449
2450         return 0;
2451 }
2452
2453 int calculate_pair_correlation_process(t_moldyn *moldyn,t_atom *itom,
2454                                        t_atom *jtom,void *data,u8 bc) {
2455
2456         t_3dvec dist;
2457         double d;
2458         int s;
2459         t_pcc *pcc;
2460
2461         /* only count pairs once,
2462          * skip same atoms */
2463         if(itom->tag>=jtom->tag)
2464                 return 0;
2465
2466         /*
2467          * pair correlation calc
2468          */
2469
2470         /* get pcc data */
2471         pcc=data;
2472
2473         /* distance */
2474         v3_sub(&dist,&(jtom->r),&(itom->r));
2475         if(bc) check_per_bound(moldyn,&dist);
2476         d=v3_absolute_square(&dist);
2477
2478         /* ignore if greater cutoff */
2479         if(d>moldyn->cutoff_square)
2480                 return 0;
2481
2482         /* fill the slots */
2483         d=sqrt(d);
2484         s=(int)(d/pcc->dr);
2485
2486         /* should never happen but it does 8) -
2487          * related to -ffloat-store problem! */
2488         if(s>=pcc->o1) {
2489                 printf("[moldyn] WARNING: pcc (%d/%d)",
2490                        s,pcc->o1);
2491                 printf("\n");
2492                 s=pcc->o1-1;
2493         }
2494
2495         if(itom->brand!=jtom->brand) {
2496                 /* mixed */
2497                 pcc->stat[s]+=1;
2498         }
2499         else {
2500                 /* type a - type a bonds */
2501                 if(itom->brand==0)
2502                         pcc->stat[s+pcc->o1]+=1;
2503                 else
2504                 /* type b - type b bonds */
2505                         pcc->stat[s+pcc->o2]+=1;
2506         }
2507
2508         return 0;
2509 }
2510
2511 int calculate_pair_correlation(t_moldyn *moldyn,double dr,void *ptr) {
2512
2513         t_pcc pcc;
2514         double norm;
2515         int i;
2516
2517         pcc.dr=dr;
2518         pcc.o1=moldyn->cutoff/dr;
2519         pcc.o2=2*pcc.o1;
2520
2521         if(pcc.o1*dr<=moldyn->cutoff)
2522                 printf("[moldyn] WARNING: pcc (low #slots)\n");
2523
2524         printf("[moldyn] pair correlation calc info:\n");
2525         printf("  time: %f\n",moldyn->time);
2526         printf("  count: %d\n",moldyn->count);
2527         printf("  cutoff: %f\n",moldyn->cutoff);
2528         printf("  temperature: cur=%f avg=%f\n",moldyn->t,moldyn->t_avg);
2529
2530         if(ptr!=NULL) {
2531                 pcc.stat=(double *)ptr;
2532         }
2533         else {
2534                 pcc.stat=(double *)malloc(3*pcc.o1*sizeof(double));
2535                 if(pcc.stat==NULL) {
2536                         perror("[moldyn] pair correlation malloc");
2537                         return -1;
2538                 }
2539         }
2540
2541         memset(pcc.stat,0,3*pcc.o1*sizeof(double));
2542
2543         /* process */
2544         process_2b_bonds(moldyn,&pcc,calculate_pair_correlation_process);
2545
2546         /* normalization */
2547         for(i=1;i<pcc.o1;i++) {
2548                  // normalization: 4 pi r^2 dr
2549                  // here: not double counting pairs -> 2 pi r r dr
2550                  // ... and actually it's a constant times r^2
2551                 norm=i*i*dr*dr;
2552                 pcc.stat[i]/=norm;
2553                 pcc.stat[pcc.o1+i]/=norm;
2554                 pcc.stat[pcc.o2+i]/=norm;
2555         }
2556         /* */
2557
2558         if(ptr==NULL) {
2559                 /* todo: store/print pair correlation function */
2560                 free(pcc.stat);
2561         }
2562
2563         return 0;
2564 }
2565
2566 int bond_analyze_process(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2567                          void *data,u8 bc) {
2568
2569         t_ba *ba;
2570         t_3dvec dist;
2571         double d;
2572
2573         if(itom->tag>=jtom->tag)
2574                 return 0;
2575
2576         /* distance */
2577         v3_sub(&dist,&(jtom->r),&(itom->r));
2578         if(bc) check_per_bound(moldyn,&dist);
2579         d=v3_absolute_square(&dist);
2580
2581         /* ignore if greater or equal cutoff */
2582         if(d>moldyn->cutoff_square)
2583                 return 0;
2584
2585         /* check for potential bond */
2586         if(moldyn->check_2b_bond(moldyn,itom,jtom,bc)==FALSE)
2587                 return 0;
2588
2589         d=sqrt(d);
2590
2591         /* now count this bonding ... */
2592         ba=data;
2593
2594         /* increase total bond counter
2595          * ... double counting!
2596          */
2597         ba->tcnt+=2;
2598
2599         if(itom->brand==0)
2600                 ba->acnt[jtom->tag]+=1;
2601         else
2602                 ba->bcnt[jtom->tag]+=1;
2603         
2604         if(jtom->brand==0)
2605                 ba->acnt[itom->tag]+=1;
2606         else
2607                 ba->bcnt[itom->tag]+=1;
2608
2609         return 0;
2610 }
2611
2612 int bond_analyze(t_moldyn *moldyn,double *quality) {
2613
2614         // by now: # bonds of type 'a-4b' and 'b-4a' / # bonds total
2615
2616         int qcnt;
2617         int ccnt,cset;
2618         t_ba ba;
2619         int i;
2620         t_atom *atom;
2621
2622         ba.acnt=malloc(moldyn->count*sizeof(int));
2623         if(ba.acnt==NULL) {
2624                 perror("[moldyn] bond analyze malloc (a)");
2625                 return -1;
2626         }
2627         memset(ba.acnt,0,moldyn->count*sizeof(int));
2628
2629         ba.bcnt=malloc(moldyn->count*sizeof(int));
2630         if(ba.bcnt==NULL) {
2631                 perror("[moldyn] bond analyze malloc (b)");
2632                 return -1;
2633         }
2634         memset(ba.bcnt,0,moldyn->count*sizeof(int));
2635
2636         ba.tcnt=0;
2637         qcnt=0;
2638         ccnt=0;
2639         cset=0;
2640
2641         atom=moldyn->atom;
2642
2643         process_2b_bonds(moldyn,&ba,bond_analyze_process);
2644
2645         for(i=0;i<moldyn->count;i++) {
2646                 if(atom[i].brand==0) {
2647                         if((ba.acnt[i]==0)&(ba.bcnt[i]==4))
2648                                 qcnt+=4;
2649                 }
2650                 else {
2651                         if((ba.acnt[i]==4)&(ba.bcnt[i]==0)) {
2652                                 qcnt+=4;
2653                                 ccnt+=1;
2654                         }
2655                         cset+=1;
2656                 }
2657         }
2658
2659         printf("[moldyn] bond analyze: c_cnt=%d | set=%d\n",ccnt,cset);
2660         printf("[moldyn] bond analyze: q_cnt=%d | tot=%d\n",qcnt,ba.tcnt);
2661
2662         if(quality) {
2663                 quality[0]=1.0*ccnt/cset;
2664                 quality[1]=1.0*qcnt/ba.tcnt;
2665         }
2666         else {
2667                 printf("[moldyn] bond analyze: c_bnd_q=%f\n",1.0*qcnt/ba.tcnt);
2668                 printf("[moldyn] bond analyze:   tot_q=%f\n",1.0*qcnt/ba.tcnt);
2669         }
2670
2671         return 0;
2672 }
2673
2674 /*
2675  * visualization code
2676  */
2677
2678 int visual_init(t_moldyn *moldyn,char *filebase) {
2679
2680         strncpy(moldyn->vis.fb,filebase,128);
2681
2682         return 0;
2683 }
2684
2685 int visual_bonds_process(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2686                          void *data,u8 bc) {
2687
2688         t_vb *vb;
2689
2690         vb=data;
2691
2692         if(itom->tag>=jtom->tag)
2693                 return 0;
2694         
2695         if(moldyn->check_2b_bond(moldyn,itom,jtom,bc)==FALSE)
2696                 return 0;
2697
2698         if((itom->attr&ATOM_ATTR_VB)|(jtom->attr&ATOM_ATTR_VB))
2699                 dprintf(vb->fd,"# [B] %f %f %f %f %f %f\n",
2700                         itom->r.x,itom->r.y,itom->r.z,
2701                         jtom->r.x,jtom->r.y,jtom->r.z);
2702
2703         return 0;
2704 }
2705
2706 int visual_atoms(t_moldyn *moldyn) {
2707
2708         int i;
2709         char file[128+64];
2710         t_3dvec dim;
2711         double help;
2712         t_visual *v;
2713         t_atom *atom;
2714         t_vb vb;
2715
2716         v=&(moldyn->vis);
2717         dim.x=v->dim.x;
2718         dim.y=v->dim.y;
2719         dim.z=v->dim.z;
2720         atom=moldyn->atom;
2721
2722         help=(dim.x+dim.y);
2723
2724         sprintf(file,"%s/atomic_conf_%07.f.xyz",v->fb,moldyn->time);
2725         vb.fd=open(file,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
2726         if(vb.fd<0) {
2727                 perror("open visual save file fd");
2728                 return -1;
2729         }
2730
2731         /* write the actual data file */
2732
2733         // povray header
2734         dprintf(vb.fd,"# [P] %d %07.f <%f,%f,%f>\n",
2735                 moldyn->count,moldyn->time,help/40.0,help/40.0,-0.8*help);
2736
2737         // atomic configuration
2738         for(i=0;i<moldyn->count;i++)
2739                 // atom type, positions, color and kinetic energy
2740                 dprintf(vb.fd,"%s %f %f %f %s %f\n",pse_name[atom[i].element],
2741                                                     atom[i].r.x,
2742                                                     atom[i].r.y,
2743                                                     atom[i].r.z,
2744                                                     pse_col[atom[i].element],
2745                                                     atom[i].ekin);
2746         
2747         // bonds between atoms
2748         process_2b_bonds(moldyn,&vb,visual_bonds_process);
2749         
2750         // boundaries
2751         if(dim.x) {
2752                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2753                         -dim.x/2,-dim.y/2,-dim.z/2,
2754                         dim.x/2,-dim.y/2,-dim.z/2);
2755                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2756                         -dim.x/2,-dim.y/2,-dim.z/2,
2757                         -dim.x/2,dim.y/2,-dim.z/2);
2758                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2759                         dim.x/2,dim.y/2,-dim.z/2,
2760                         dim.x/2,-dim.y/2,-dim.z/2);
2761                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2762                         -dim.x/2,dim.y/2,-dim.z/2,
2763                         dim.x/2,dim.y/2,-dim.z/2);
2764
2765                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2766                         -dim.x/2,-dim.y/2,dim.z/2,
2767                         dim.x/2,-dim.y/2,dim.z/2);
2768                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2769                         -dim.x/2,-dim.y/2,dim.z/2,
2770                         -dim.x/2,dim.y/2,dim.z/2);
2771                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2772                         dim.x/2,dim.y/2,dim.z/2,
2773                         dim.x/2,-dim.y/2,dim.z/2);
2774                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2775                         -dim.x/2,dim.y/2,dim.z/2,
2776                         dim.x/2,dim.y/2,dim.z/2);
2777
2778                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2779                         -dim.x/2,-dim.y/2,dim.z/2,
2780                         -dim.x/2,-dim.y/2,-dim.z/2);
2781                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2782                         -dim.x/2,dim.y/2,dim.z/2,
2783                         -dim.x/2,dim.y/2,-dim.z/2);
2784                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2785                         dim.x/2,-dim.y/2,dim.z/2,
2786                         dim.x/2,-dim.y/2,-dim.z/2);
2787                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
2788                         dim.x/2,dim.y/2,dim.z/2,
2789                         dim.x/2,dim.y/2,-dim.z/2);
2790         }
2791
2792         close(vb.fd);
2793
2794         return 0;
2795 }
2796