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