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