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