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