pthread imp started for orig albe (more easier in the 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 #ifdef PTHREADS
1955         int ret;
1956         pthread_t kthread[27];
1957         t_kdata kdata[27];
1958 #endif
1959
1960         count=moldyn->count;
1961         itom=moldyn->atom;
1962         lc=&(moldyn->lc);
1963 #ifdef STATIC_LISTS
1964         atom=moldyn->atom;
1965 #endif
1966
1967 #ifdef PTHREADS
1968         memset(kdata,0,27*sizeof(t_kdata));
1969 #endif
1970
1971         /* reset energy */
1972         moldyn->energy=0.0;
1973
1974         /* reset global virial */
1975         memset(&(moldyn->gvir),0,sizeof(t_virial));
1976
1977         /* reset force, site energy and virial of every atom */
1978 #ifdef PARALLEL
1979         i=omp_get_thread_num();
1980         #pragma omp parallel for private(virial)
1981 #endif
1982         for(i=0;i<count;i++) {
1983
1984                 /* reset force */
1985                 v3_zero(&(itom[i].f));
1986
1987                 /* reset virial */
1988                 virial=(&(itom[i].virial));
1989                 virial->xx=0.0;
1990                 virial->yy=0.0;
1991                 virial->zz=0.0;
1992                 virial->xy=0.0;
1993                 virial->xz=0.0;
1994                 virial->yz=0.0;
1995         
1996                 /* reset site energy */
1997                 itom[i].e=0.0;
1998
1999         }
2000
2001         /* get energy, force and virial of every atom */
2002
2003         /* first (and only) loop over atoms i */
2004         for(i=0;i<count;i++) {
2005
2006                 /* single particle potential/force */
2007                 if(itom[i].attr&ATOM_ATTR_1BP)
2008                         if(moldyn->func1b)
2009                                 moldyn->func1b(moldyn,&(itom[i]));
2010
2011                 if(!(itom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)))
2012                         continue;
2013
2014                 /* 2 body pair potential/force */
2015         
2016                 link_cell_neighbour_index(moldyn,
2017                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
2018                                           (itom[i].r.y+moldyn->dim.y/2)/lc->y,
2019                                           (itom[i].r.z+moldyn->dim.z/2)/lc->z,
2020                                           neighbour_i);
2021
2022                 dnlc=lc->dnlc;
2023
2024                 /* first loop over atoms j */
2025                 if(moldyn->func2b) {
2026                         for(j=0;j<27;j++) {
2027
2028                                 bc_ij=(j<dnlc)?0:1;
2029 #ifdef STATIC_LISTS
2030                                 p=0;
2031
2032                                 while(neighbour_i[j][p]!=-1) {
2033
2034                                         jtom=&(atom[neighbour_i[j][p]]);
2035                                         p++;
2036 #elif LOWMEM_LISTS
2037                                 p=neighbour_i[j];
2038
2039                                 while(p!=-1) {
2040
2041                                         jtom=&(itom[p]);
2042                                         p=lc->subcell->list[p];
2043 #else
2044                                 this=&(neighbour_i[j]);
2045                                 list_reset_f(this);
2046
2047                                 if(this->start==NULL)
2048                                         continue;
2049
2050                                 do {
2051                                         jtom=this->current->data;
2052 #endif
2053
2054                                         if(jtom==&(itom[i]))
2055                                                 continue;
2056
2057                                         if((jtom->attr&ATOM_ATTR_2BP)&
2058                                            (itom[i].attr&ATOM_ATTR_2BP)) {
2059                                                 moldyn->func2b(moldyn,
2060                                                                &(itom[i]),
2061                                                                jtom,
2062                                                                bc_ij);
2063                                         }
2064 #ifdef STATIC_LISTS
2065                                 }
2066 #elif LOWMEM_LISTS
2067                                 }
2068 #else
2069                                 } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2070 #endif
2071
2072                         }
2073                 }
2074
2075                 /* 3 body potential/force */
2076
2077                 if(!(itom[i].attr&ATOM_ATTR_3BP))
2078                         continue;
2079
2080                 /* copy the neighbour lists */
2081 #ifdef STATIC_LISTS
2082                 /* no copy needed for static lists */
2083 #elif LOWMEM_LISTS
2084                 /* no copy needed for lowmem lists */
2085 #else
2086                 memcpy(neighbour_i2,neighbour_i,27*sizeof(t_list));
2087 #endif
2088
2089                 /* second loop over atoms j */
2090                 for(j=0;j<27;j++) {
2091
2092                         bc_ij=(j<dnlc)?0:1;
2093 #ifdef STATIC_LISTS
2094                         p=0;
2095
2096                         while(neighbour_i[j][p]!=-1) {
2097
2098                                 jtom=&(atom[neighbour_i[j][p]]);
2099                                 p++;
2100 #elif LOWMEM_LISTS
2101                                 p=neighbour_i[j];
2102
2103                                 while(p!=-1) {
2104
2105                                         jtom=&(itom[p]);
2106                                         p=lc->subcell->list[p];
2107 #else
2108                         this=&(neighbour_i[j]);
2109                         list_reset_f(this);
2110
2111                         if(this->start==NULL)
2112                                 continue;
2113
2114                         do {
2115
2116                                 jtom=this->current->data;
2117 #endif
2118
2119                                 if(jtom==&(itom[i]))
2120                                         continue;
2121
2122                                 if(!(jtom->attr&ATOM_ATTR_3BP))
2123                                         continue;
2124
2125                                 /* reset 3bp run */
2126                                 moldyn->run3bp=1;
2127
2128                                 if(moldyn->func3b_j1)
2129                                         moldyn->func3b_j1(moldyn,
2130                                                           &(itom[i]),
2131                                                           jtom,
2132                                                           bc_ij);
2133
2134                                 /* in first j loop, 3bp run can be skipped */
2135                                 if(!(moldyn->run3bp))
2136                                         continue;
2137                         
2138                                 /* first loop over atoms k */
2139 #ifndef PTHREADS
2140                                 if(moldyn->func3b_k1) {
2141 #endif
2142
2143                                 for(k=0;k<27;k++) {
2144
2145                                         bc_ik=(k<dnlc)?0:1;
2146 #ifdef STATIC_LISTS
2147                                         q=0;
2148
2149                                         while(neighbour_i[k][q]!=-1) {
2150
2151                                                 ktom=&(atom[neighbour_i[k][q]]);
2152                                                 q++;
2153 #elif LOWMEM_LISTS
2154                                         q=neighbour_i[k];
2155
2156                                         while(q!=-1) {
2157
2158                                                 ktom=&(itom[q]);
2159                                                 q=lc->subcell->list[q];
2160 #else
2161                                         that=&(neighbour_i2[k]);
2162                                         list_reset_f(that);
2163                                         
2164                                         if(that->start==NULL)
2165                                                 continue;
2166
2167                                         do {
2168                                                 ktom=that->current->data;
2169 #endif
2170
2171                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
2172                                                         continue;
2173
2174                                                 if(ktom==jtom)
2175                                                         continue;
2176
2177                                                 if(ktom==&(itom[i]))
2178                                                         continue;
2179
2180 #ifdef PTHREADS
2181                                                 kdata[k].moldyn=moldyn;
2182                                                 kdata[k].ai=&(itom[i]);
2183                                                 kdata[k].aj=jtom;
2184                                                 kdata[k].ak=ktom;
2185                                                 kdata[k].bc=bc_ik;
2186         ret=pthread_create(&(kthread[k]),NULL,moldyn->func3b_k1,&(kdata[k]));
2187         if(ret) {
2188                 perror("[moldyn] create k1 thread");
2189                 return ret;
2190         }
2191 #else
2192                                                 moldyn->func3b_k1(moldyn,
2193                                                                   &(itom[i]),
2194                                                                   jtom,
2195                                                                   ktom,
2196                                                                   bc_ik|bc_ij);
2197 #endif
2198
2199 #ifdef STATIC_LISTS
2200                                         }
2201 #elif LOWMEM_LISTS
2202                                         }
2203 #else
2204                                         } while(list_next_f(that)!=\
2205                                                 L_NO_NEXT_ELEMENT);
2206 #endif
2207
2208                                 }
2209
2210 #ifndef PTHREADS
2211                                 }
2212 #endif
2213
2214                                 if(moldyn->func3b_j2)
2215                                         moldyn->func3b_j2(moldyn,
2216                                                           &(itom[i]),
2217                                                           jtom,
2218                                                           bc_ij);
2219
2220                                 /* second loop over atoms k */
2221                                 if(moldyn->func3b_k2) {
2222
2223                                 for(k=0;k<27;k++) {
2224
2225                                         bc_ik=(k<dnlc)?0:1;
2226 #ifdef STATIC_LISTS
2227                                         q=0;
2228
2229                                         while(neighbour_i[k][q]!=-1) {
2230
2231                                                 ktom=&(atom[neighbour_i[k][q]]);
2232                                                 q++;
2233 #elif LOWMEM_LISTS
2234                                         q=neighbour_i[k];
2235
2236                                         while(q!=-1) {
2237
2238                                                 ktom=&(itom[q]);
2239                                                 q=lc->subcell->list[q];
2240 #else
2241                                         that=&(neighbour_i2[k]);
2242                                         list_reset_f(that);
2243                                         
2244                                         if(that->start==NULL)
2245                                                 continue;
2246
2247                                         do {
2248                                                 ktom=that->current->data;
2249 #endif
2250
2251                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
2252                                                         continue;
2253
2254                                                 if(ktom==jtom)
2255                                                         continue;
2256
2257                                                 if(ktom==&(itom[i]))
2258                                                         continue;
2259
2260                                                 moldyn->func3b_k2(moldyn,
2261                                                                   &(itom[i]),
2262                                                                   jtom,
2263                                                                   ktom,
2264                                                                   bc_ik|bc_ij);
2265
2266 #ifdef STATIC_LISTS
2267                                         }
2268 #elif LOWMEM_LISTS
2269                                         }
2270 #else
2271                                         } while(list_next_f(that)!=\
2272                                                 L_NO_NEXT_ELEMENT);
2273 #endif
2274
2275                                 }
2276                                 
2277                                 }
2278
2279                                 /* 2bp post function */
2280                                 if(moldyn->func3b_j3) {
2281                                         moldyn->func3b_j3(moldyn,
2282                                                           &(itom[i]),
2283                                                           jtom,bc_ij);
2284                                 }
2285 #ifdef STATIC_LISTS
2286                         }
2287 #elif LOWMEM_LISTS
2288                         }
2289 #else
2290                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2291 #endif
2292                 
2293                 }
2294                 
2295 #ifdef DEBUG
2296         //printf("\n\n");
2297 #endif
2298 #ifdef VDEBUG
2299         printf("\n\n");
2300 #endif
2301
2302         }
2303
2304 #ifdef DEBUG
2305         //printf("\nATOM 0: %f %f %f\n\n",itom->f.x,itom->f.y,itom->f.z);
2306         if(moldyn->time>DSTART&&moldyn->time<DEND) {
2307                 printf("force:\n");
2308                 printf("  x: %0.40f\n",moldyn->atom[DATOM].f.x);
2309                 printf("  y: %0.40f\n",moldyn->atom[DATOM].f.y);
2310                 printf("  z: %0.40f\n",moldyn->atom[DATOM].f.z);
2311         }
2312 #endif
2313
2314         /* some postprocessing */
2315 #ifdef PARALLEL
2316         #pragma omp parallel for
2317 #endif
2318         for(i=0;i<count;i++) {
2319                 /* calculate global virial */
2320                 moldyn->gvir.xx+=itom[i].r.x*itom[i].f.x;
2321                 moldyn->gvir.yy+=itom[i].r.y*itom[i].f.y;
2322                 moldyn->gvir.zz+=itom[i].r.z*itom[i].f.z;
2323                 moldyn->gvir.xy+=itom[i].r.y*itom[i].f.x;
2324                 moldyn->gvir.xz+=itom[i].r.z*itom[i].f.x;
2325                 moldyn->gvir.yz+=itom[i].r.z*itom[i].f.y;
2326
2327                 /* check forces regarding the given timestep */
2328                 if(v3_norm(&(itom[i].f))>\
2329                    0.1*moldyn->nnd*itom[i].mass/moldyn->tau_square)
2330                         printf("[moldyn] WARNING: pfc (high force: atom %d)\n",
2331                                i);
2332         }
2333
2334         return 0;
2335 }
2336
2337 /*
2338  * virial calculation
2339  */
2340
2341 //inline int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
2342 int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
2343
2344         a->virial.xx+=f->x*d->x;
2345         a->virial.yy+=f->y*d->y;
2346         a->virial.zz+=f->z*d->z;
2347         a->virial.xy+=f->x*d->y;
2348         a->virial.xz+=f->x*d->z;
2349         a->virial.yz+=f->y*d->z;
2350
2351         return 0;
2352 }
2353
2354 /*
2355  * periodic boundary checking
2356  */
2357
2358 //inline int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
2359 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
2360         
2361         double x,y,z;
2362         t_3dvec *dim;
2363
2364         dim=&(moldyn->dim);
2365
2366         x=dim->x/2;
2367         y=dim->y/2;
2368         z=dim->z/2;
2369
2370         if(moldyn->status&MOLDYN_STAT_PBX) {
2371                 if(a->x>=x) a->x-=dim->x;
2372                 else if(-a->x>x) a->x+=dim->x;
2373         }
2374         if(moldyn->status&MOLDYN_STAT_PBY) {
2375                 if(a->y>=y) a->y-=dim->y;
2376                 else if(-a->y>y) a->y+=dim->y;
2377         }
2378         if(moldyn->status&MOLDYN_STAT_PBZ) {
2379                 if(a->z>=z) a->z-=dim->z;
2380                 else if(-a->z>z) a->z+=dim->z;
2381         }
2382
2383         return 0;
2384 }
2385         
2386 /*
2387  * debugging / critical check functions
2388  */
2389
2390 int moldyn_bc_check(t_moldyn *moldyn) {
2391
2392         t_atom *atom;
2393         t_3dvec *dim;
2394         int i;
2395         double x;
2396         u8 byte;
2397         int j,k;
2398
2399         atom=moldyn->atom;
2400         dim=&(moldyn->dim);
2401         x=dim->x/2;
2402
2403         for(i=0;i<moldyn->count;i++) {
2404                 if(atom[i].r.x>=dim->x/2||-atom[i].r.x>dim->x/2) {
2405                         printf("FATAL: atom %d: x: %.20f (%.20f)\n",
2406                                i,atom[i].r.x,dim->x/2);
2407                         printf("diagnostic:\n");
2408                         printf("-----------\natom.r.x:\n");
2409                         for(j=0;j<8;j++) {
2410                                 memcpy(&byte,(u8 *)(&(atom[i].r.x))+j,1);
2411                                 for(k=0;k<8;k++)
2412                                         printf("%d%c",
2413                                         ((byte)&(1<<k))?1:0,
2414                                         (k==7)?'\n':'|');
2415                         }
2416                         printf("---------------\nx=dim.x/2:\n");
2417                         for(j=0;j<8;j++) {
2418                                 memcpy(&byte,(u8 *)(&x)+j,1);
2419                                 for(k=0;k<8;k++)
2420                                         printf("%d%c",
2421                                         ((byte)&(1<<k))?1:0,
2422                                         (k==7)?'\n':'|');
2423                         }
2424                         if(atom[i].r.x==x) printf("the same!\n");
2425                         else printf("different!\n");
2426                 }
2427                 if(atom[i].r.y>=dim->y/2||-atom[i].r.y>dim->y/2)
2428                         printf("FATAL: atom %d: y: %.20f (%.20f)\n",
2429                                i,atom[i].r.y,dim->y/2);
2430                 if(atom[i].r.z>=dim->z/2||-atom[i].r.z>dim->z/2)
2431                         printf("FATAL: atom %d: z: %.20f (%.20f)\n",
2432                                i,atom[i].r.z,dim->z/2);
2433         }
2434
2435         return 0;
2436 }
2437
2438 /*
2439  * restore function
2440  */
2441
2442 int moldyn_read_save_file(t_moldyn *moldyn,char *file) {
2443
2444         int fd;
2445         int cnt,size;
2446         int fsize;
2447         int corr;
2448
2449         fd=open(file,O_RDONLY);
2450         if(fd<0) {
2451                 perror("[moldyn] load save file open");
2452                 return fd;
2453         }
2454
2455         fsize=lseek(fd,0,SEEK_END);
2456         lseek(fd,0,SEEK_SET);
2457
2458         size=sizeof(t_moldyn);
2459
2460         while(size) {
2461                 cnt=read(fd,moldyn,size);
2462                 if(cnt<0) {
2463                         perror("[moldyn] load save file read (moldyn)");
2464                         return cnt;
2465                 }
2466                 size-=cnt;
2467         }
2468
2469         size=moldyn->count*sizeof(t_atom);
2470
2471         /* correcting possible atom data offset */
2472         corr=0;
2473         if(fsize!=sizeof(t_moldyn)+size) {
2474                 corr=fsize-sizeof(t_moldyn)-size;
2475                 printf("[moldyn] WARNING: lsf (illegal file size)\n");
2476                 printf("  moifying offset:\n");
2477                 printf("  - current pos: %d\n",sizeof(t_moldyn));
2478                 printf("  - atom size: %d\n",size);
2479                 printf("  - file size: %d\n",fsize);
2480                 printf("  => correction: %d\n",corr);
2481                 lseek(fd,corr,SEEK_CUR);
2482         }
2483
2484         moldyn->atom=(t_atom *)malloc(size);
2485         if(moldyn->atom==NULL) {
2486                 perror("[moldyn] load save file malloc (atoms)");
2487                 return -1;
2488         }
2489
2490         while(size) {
2491                 cnt=read(fd,moldyn->atom,size);
2492                 if(cnt<0) {
2493                         perror("[moldyn] load save file read (atoms)");
2494                         return cnt;
2495                 }
2496                 size-=cnt;
2497         }
2498
2499         // hooks etc ...
2500
2501         return 0;
2502 }
2503
2504 int moldyn_free_save_file(t_moldyn *moldyn) {
2505
2506         free(moldyn->atom);
2507
2508         return 0;
2509 }
2510
2511 int moldyn_load(t_moldyn *moldyn) {
2512
2513         // later ...
2514
2515         return 0;
2516 }
2517
2518 /*
2519  * function to find/callback all combinations of 2 body bonds
2520  */
2521
2522 int process_2b_bonds(t_moldyn *moldyn,void *data,
2523                      int (*process)(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2524                                     void *data,u8 bc)) {
2525
2526         t_linkcell *lc;
2527 #ifdef STATIC_LISTS
2528         int *neighbour[27];
2529         int p;
2530 #elif LOWMEM_LISTS
2531         int neighbour[27];
2532         int p;
2533 #else
2534         t_list neighbour[27];
2535         t_list *this;
2536 #endif
2537         u8 bc;
2538         t_atom *itom,*jtom;
2539         int i,j;
2540
2541         lc=&(moldyn->lc);
2542         itom=moldyn->atom;
2543         
2544         for(i=0;i<moldyn->count;i++) {
2545                 /* neighbour indexing */
2546                 link_cell_neighbour_index(moldyn,
2547                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
2548                                           (itom[i].r.y+moldyn->dim.y/2)/lc->x,
2549                                           (itom[i].r.z+moldyn->dim.z/2)/lc->x,
2550                                           neighbour);
2551
2552                 for(j=0;j<27;j++) {
2553
2554                         bc=(j<lc->dnlc)?0:1;
2555
2556 #ifdef STATIC_LISTS
2557                         p=0;
2558
2559                         while(neighbour[j][p]!=-1) {
2560
2561                                 jtom=&(moldyn->atom[neighbour[j][p]]);
2562                                 p++;
2563 #elif LOWMEM_LISTS
2564                         p=neighbour[j];
2565
2566                         while(p!=-1) {
2567
2568                                 jtom=&(itom[p]);
2569                                 p=lc->subcell->list[p];
2570 #else
2571                         this=&(neighbour[j]);
2572                         list_reset_f(this);
2573
2574                         if(this->start==NULL)
2575                                 continue;
2576
2577                         do {
2578
2579                                 jtom=this->current->data;
2580 #endif
2581
2582                                 /* process bond */
2583                                 process(moldyn,&(itom[i]),jtom,data,bc);
2584
2585 #ifdef STATIC_LISTS
2586                         }
2587 #elif LOWMEM_LISTS
2588                         }
2589 #else
2590                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2591 #endif
2592                 }
2593         }
2594
2595         return 0;
2596
2597 }
2598
2599 /*
2600  * function to find neighboured atoms
2601  */
2602
2603 int process_neighbours(t_moldyn *moldyn,void *data,t_atom *atom,
2604                        int (*process)(t_moldyn *moldyn,t_atom *atom,t_atom *natom,
2605                                       void *data,u8 bc)) {
2606
2607         t_linkcell *lc;
2608 #ifdef STATIC_LISTS
2609         int *neighbour[27];
2610         int p;
2611 #elif LOWMEM_LISTS
2612         int neighbour[27];
2613         int p;
2614 #else
2615         t_list neighbour[27];
2616         t_list *this;
2617 #endif
2618         u8 bc;
2619         t_atom *natom;
2620         int j;
2621
2622         lc=&(moldyn->lc);
2623         
2624         /* neighbour indexing */
2625         link_cell_neighbour_index(moldyn,
2626                                   (atom->r.x+moldyn->dim.x/2)/lc->x,
2627                                   (atom->r.y+moldyn->dim.y/2)/lc->x,
2628                                   (atom->r.z+moldyn->dim.z/2)/lc->x,
2629                                   neighbour);
2630
2631         for(j=0;j<27;j++) {
2632
2633                 bc=(j<lc->dnlc)?0:1;
2634
2635 #ifdef STATIC_LISTS
2636                 p=0;
2637
2638                 while(neighbour[j][p]!=-1) {
2639
2640                         natom=&(moldyn->atom[neighbour[j][p]]);
2641                         p++;
2642 #elif LOWMEM_LISTS
2643                 p=neighbour[j];
2644
2645                 while(p!=-1) {
2646
2647                         natom=&(moldyn->atom[p]);
2648                         p=lc->subcell->list[p];
2649 #else
2650                 this=&(neighbour[j]);
2651                 list_reset_f(this);
2652
2653                 if(this->start==NULL)
2654                         continue;
2655
2656                 do {
2657
2658                         natom=this->current->data;
2659 #endif
2660
2661                         /* process bond */
2662                         process(moldyn,atom,natom,data,bc);
2663
2664 #ifdef STATIC_LISTS
2665                 }
2666 #elif LOWMEM_LISTS
2667                 }
2668 #else
2669                 } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2670 #endif
2671         }
2672
2673         return 0;
2674
2675 }
2676
2677 /*
2678  * post processing functions
2679  */
2680
2681 int get_line(int fd,char *line,int max) {
2682
2683         int count,ret;
2684
2685         count=0;
2686
2687         while(1) {
2688                 if(count==max) return count;
2689                 ret=read(fd,line+count,1);
2690                 if(ret<=0) return ret;
2691                 if(line[count]=='\n') {
2692                         memset(line+count,0,max-count-1);
2693                         //line[count]='\0';
2694                         return count+1;
2695                 }
2696                 count+=1;
2697         }
2698 }
2699
2700 int pair_correlation_init(t_moldyn *moldyn,double dr) {
2701
2702         
2703         return 0;
2704 }
2705
2706 int calculate_diffusion_coefficient(t_moldyn *moldyn,double *dc) {
2707
2708         int i;
2709         t_atom *atom;
2710         t_3dvec dist;
2711         double d2;
2712         int a_cnt;
2713         int b_cnt;
2714
2715         atom=moldyn->atom;
2716         dc[0]=0;
2717         dc[1]=0;
2718         dc[2]=0;
2719         a_cnt=0;
2720         b_cnt=0;
2721
2722         for(i=0;i<moldyn->count;i++) {
2723
2724                 v3_sub(&dist,&(atom[i].r),&(atom[i].r_0));
2725                 check_per_bound(moldyn,&dist);
2726                 d2=v3_absolute_square(&dist);
2727
2728                 if(atom[i].brand) {
2729                         b_cnt+=1;
2730                         dc[1]+=d2;
2731                 }
2732                 else {
2733                         a_cnt+=1;
2734                         dc[0]+=d2;
2735                 }
2736
2737                 dc[2]+=d2;
2738         }
2739
2740         dc[0]*=(1.0/(6.0*moldyn->time*a_cnt));
2741         dc[1]*=(1.0/(6.0*moldyn->time*b_cnt));
2742         dc[2]*=(1.0/(6.0*moldyn->time*moldyn->count));
2743                 
2744         return 0;
2745 }
2746
2747 int bonding_analyze(t_moldyn *moldyn,double *cnt) {
2748
2749         return 0;
2750 }
2751
2752 int calculate_pair_correlation_process(t_moldyn *moldyn,t_atom *itom,
2753                                        t_atom *jtom,void *data,u8 bc) {
2754
2755         t_3dvec dist;
2756         double d;
2757         int s;
2758         t_pcc *pcc;
2759
2760         /* only count pairs once,
2761          * skip same atoms */
2762         if(itom->tag>=jtom->tag)
2763                 return 0;
2764
2765         /*
2766          * pair correlation calc
2767          */
2768
2769         /* get pcc data */
2770         pcc=data;
2771
2772         /* distance */
2773         v3_sub(&dist,&(jtom->r),&(itom->r));
2774         if(bc) check_per_bound(moldyn,&dist);
2775         d=v3_absolute_square(&dist);
2776
2777         /* ignore if greater cutoff */
2778         if(d>moldyn->cutoff_square)
2779                 return 0;
2780
2781         /* fill the slots */
2782         d=sqrt(d);
2783         s=(int)(d/pcc->dr);
2784
2785         /* should never happen but it does 8) -
2786          * related to -ffloat-store problem! */
2787         if(s>=pcc->o1) {
2788                 printf("[moldyn] WARNING: pcc (%d/%d)",
2789                        s,pcc->o1);
2790                 printf("\n");
2791                 s=pcc->o1-1;
2792         }
2793
2794         if(itom->brand!=jtom->brand) {
2795                 /* mixed */
2796                 pcc->stat[s]+=1;
2797         }
2798         else {
2799                 /* type a - type a bonds */
2800                 if(itom->brand==0)
2801                         pcc->stat[s+pcc->o1]+=1;
2802                 else
2803                 /* type b - type b bonds */
2804                         pcc->stat[s+pcc->o2]+=1;
2805         }
2806
2807         return 0;
2808 }
2809
2810 int calculate_pair_correlation(t_moldyn *moldyn,double dr,void *ptr) {
2811
2812         t_pcc pcc;
2813         double norm;
2814         int i;
2815
2816         pcc.dr=dr;
2817         pcc.o1=moldyn->cutoff/dr;
2818         pcc.o2=2*pcc.o1;
2819
2820         if(pcc.o1*dr<=moldyn->cutoff)
2821                 printf("[moldyn] WARNING: pcc (low #slots)\n");
2822
2823         printf("[moldyn] pair correlation calc info:\n");
2824         printf("  time: %f\n",moldyn->time);
2825         printf("  count: %d\n",moldyn->count);
2826         printf("  cutoff: %f\n",moldyn->cutoff);
2827         printf("  temperature: cur=%f avg=%f\n",moldyn->t,moldyn->t_avg);
2828
2829         if(ptr!=NULL) {
2830                 pcc.stat=(double *)ptr;
2831         }
2832         else {
2833                 pcc.stat=(double *)malloc(3*pcc.o1*sizeof(double));
2834                 if(pcc.stat==NULL) {
2835                         perror("[moldyn] pair correlation malloc");
2836                         return -1;
2837                 }
2838         }
2839
2840         memset(pcc.stat,0,3*pcc.o1*sizeof(double));
2841
2842         /* process */
2843         process_2b_bonds(moldyn,&pcc,calculate_pair_correlation_process);
2844
2845         /* normalization */
2846         for(i=1;i<pcc.o1;i++) {
2847                  // normalization: 4 pi r^2 dr
2848                  // here: not double counting pairs -> 2 pi r r dr
2849                  // ... and actually it's a constant times r^2
2850                 norm=i*i*dr*dr;
2851                 pcc.stat[i]/=norm;
2852                 pcc.stat[pcc.o1+i]/=norm;
2853                 pcc.stat[pcc.o2+i]/=norm;
2854         }
2855         /* */
2856
2857         if(ptr==NULL) {
2858                 /* todo: store/print pair correlation function */
2859                 free(pcc.stat);
2860         }
2861
2862         return 0;
2863 }
2864
2865 int bond_analyze_process(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2866                          void *data,u8 bc) {
2867
2868         t_ba *ba;
2869         t_3dvec dist;
2870         double d;
2871
2872         if(itom->tag>=jtom->tag)
2873                 return 0;
2874
2875         /* distance */
2876         v3_sub(&dist,&(jtom->r),&(itom->r));
2877         if(bc) check_per_bound(moldyn,&dist);
2878         d=v3_absolute_square(&dist);
2879
2880         /* ignore if greater or equal cutoff */
2881         if(d>moldyn->cutoff_square)
2882                 return 0;
2883
2884         /* check for potential bond */
2885         if(moldyn->check_2b_bond(moldyn,itom,jtom,bc)==FALSE)
2886                 return 0;
2887
2888         /* now count this bonding ... */
2889         ba=data;
2890
2891         /* increase total bond counter
2892          * ... double counting!
2893          */
2894         ba->tcnt+=2;
2895
2896         if(itom->brand==0)
2897                 ba->acnt[jtom->tag]+=1;
2898         else
2899                 ba->bcnt[jtom->tag]+=1;
2900         
2901         if(jtom->brand==0)
2902                 ba->acnt[itom->tag]+=1;
2903         else
2904                 ba->bcnt[itom->tag]+=1;
2905
2906         return 0;
2907 }
2908
2909 int bond_analyze(t_moldyn *moldyn,double *quality) {
2910
2911         // by now: # bonds of type 'a-4b' and 'b-4a' / # bonds total
2912
2913         int qcnt;
2914         int ccnt,cset;
2915         t_ba ba;
2916         int i;
2917         t_atom *atom;
2918
2919         ba.acnt=malloc(moldyn->count*sizeof(int));
2920         if(ba.acnt==NULL) {
2921                 perror("[moldyn] bond analyze malloc (a)");
2922                 return -1;
2923         }
2924         memset(ba.acnt,0,moldyn->count*sizeof(int));
2925
2926         ba.bcnt=malloc(moldyn->count*sizeof(int));
2927         if(ba.bcnt==NULL) {
2928                 perror("[moldyn] bond analyze malloc (b)");
2929                 return -1;
2930         }
2931         memset(ba.bcnt,0,moldyn->count*sizeof(int));
2932
2933         ba.tcnt=0;
2934         qcnt=0;
2935         ccnt=0;
2936         cset=0;
2937
2938         atom=moldyn->atom;
2939
2940         process_2b_bonds(moldyn,&ba,bond_analyze_process);
2941
2942         for(i=0;i<moldyn->count;i++) {
2943                 if(atom[i].brand==0) {
2944                         if((ba.acnt[i]==0)&(ba.bcnt[i]==4))
2945                                 qcnt+=4;
2946                 }
2947                 else {
2948                         if((ba.acnt[i]==4)&(ba.bcnt[i]==0)) {
2949                                 qcnt+=4;
2950                                 ccnt+=1;
2951                         }
2952                         cset+=1;
2953                 }
2954         }
2955
2956         printf("[moldyn] bond analyze: c_cnt=%d | set=%d\n",ccnt,cset);
2957         printf("[moldyn] bond analyze: q_cnt=%d | tot=%d\n",qcnt,ba.tcnt);
2958
2959         if(quality) {
2960                 quality[0]=1.0*ccnt/cset;
2961                 quality[1]=1.0*qcnt/ba.tcnt;
2962         }
2963         else {
2964                 printf("[moldyn] bond analyze: c_bnd_q=%f\n",1.0*qcnt/ba.tcnt);
2965                 printf("[moldyn] bond analyze:   tot_q=%f\n",1.0*qcnt/ba.tcnt);
2966         }
2967
2968         return 0;
2969 }
2970
2971 /*
2972  * visualization code
2973  */
2974
2975 int visual_init(t_moldyn *moldyn,char *filebase) {
2976
2977         strncpy(moldyn->vis.fb,filebase,128);
2978
2979         return 0;
2980 }
2981
2982 int visual_bonds_process(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2983                          void *data,u8 bc) {
2984
2985         t_vb *vb;
2986
2987         vb=data;
2988
2989         if(itom->tag>=jtom->tag)
2990                 return 0;
2991         
2992         if(moldyn->check_2b_bond(moldyn,itom,jtom,bc)==FALSE)
2993                 return 0;
2994
2995         if((itom->attr&ATOM_ATTR_VB)|(jtom->attr&ATOM_ATTR_VB))
2996                 dprintf(vb->fd,"# [B] %f %f %f %f %f %f\n",
2997                         itom->r.x,itom->r.y,itom->r.z,
2998                         jtom->r.x,jtom->r.y,jtom->r.z);
2999
3000         return 0;
3001 }
3002
3003 #ifdef PTHREADS
3004 void *visual_atoms(void *ptr) {
3005 #else
3006 int visual_atoms(t_moldyn *moldyn) {
3007 #endif
3008
3009         int i;
3010         char file[128+64];
3011         t_3dvec dim;
3012         double help;
3013         t_visual *v;
3014         t_atom *atom;
3015         t_vb vb;
3016 #ifdef PTHREADS
3017         t_moldyn *moldyn;
3018
3019         moldyn=ptr;
3020 #endif
3021
3022         v=&(moldyn->vis);
3023         dim.x=v->dim.x;
3024         dim.y=v->dim.y;
3025         dim.z=v->dim.z;
3026         atom=moldyn->atom;
3027
3028         help=(dim.x+dim.y);
3029
3030         sprintf(file,"%s/atomic_conf_%08.f.xyz",v->fb,moldyn->time);
3031         vb.fd=open(file,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
3032         if(vb.fd<0) {
3033                 perror("open visual save file fd");
3034 #ifndef PTHREADS
3035                 return -1;
3036 #endif
3037         }
3038
3039         /* write the actual data file */
3040
3041         // povray header
3042         dprintf(vb.fd,"# [P] %d %08.f <%f,%f,%f>\n",
3043                 moldyn->count,moldyn->time,help/40.0,help/40.0,-0.8*help);
3044
3045         // atomic configuration
3046         for(i=0;i<moldyn->count;i++)
3047                 // atom type, positions, color and kinetic energy
3048                 dprintf(vb.fd,"%s %f %f %f %s %f\n",pse_name[atom[i].element],
3049                                                     atom[i].r.x,
3050                                                     atom[i].r.y,
3051                                                     atom[i].r.z,
3052                                                     pse_col[atom[i].element],
3053                                                     atom[i].ekin);
3054         
3055         // bonds between atoms
3056         process_2b_bonds(moldyn,&vb,visual_bonds_process);
3057         
3058         // boundaries
3059         if(dim.x) {
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                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3074                         -dim.x/2,-dim.y/2,dim.z/2,
3075                         dim.x/2,-dim.y/2,dim.z/2);
3076                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3077                         -dim.x/2,-dim.y/2,dim.z/2,
3078                         -dim.x/2,dim.y/2,dim.z/2);
3079                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3080                         dim.x/2,dim.y/2,dim.z/2,
3081                         dim.x/2,-dim.y/2,dim.z/2);
3082                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3083                         -dim.x/2,dim.y/2,dim.z/2,
3084                         dim.x/2,dim.y/2,dim.z/2);
3085
3086                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3087                         -dim.x/2,-dim.y/2,dim.z/2,
3088                         -dim.x/2,-dim.y/2,-dim.z/2);
3089                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3090                         -dim.x/2,dim.y/2,dim.z/2,
3091                         -dim.x/2,dim.y/2,-dim.z/2);
3092                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3093                         dim.x/2,-dim.y/2,dim.z/2,
3094                         dim.x/2,-dim.y/2,-dim.z/2);
3095                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3096                         dim.x/2,dim.y/2,dim.z/2,
3097                         dim.x/2,dim.y/2,-dim.z/2);
3098         }
3099
3100         close(vb.fd);
3101
3102 #ifdef PTHREADS
3103         pthread_exit(NULL);
3104
3105 }
3106 #else
3107
3108         return 0;
3109 }
3110 #endif
3111
3112 /*
3113  * fpu cntrol functions
3114  */
3115
3116 // set rounding to double (eliminates -ffloat-store!)
3117 int fpu_set_rtd(void) {
3118
3119         fpu_control_t ctrl;
3120
3121         _FPU_GETCW(ctrl);
3122
3123         ctrl&=~_FPU_EXTENDED;
3124         ctrl|=_FPU_DOUBLE;
3125
3126         _FPU_SETCW(ctrl);
3127
3128         return 0;
3129 }
3130