added pthreads (for io only by now) + refresh screen for i count +
[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 /* helper / special functions */
1612
1613 #ifdef PTHREADS
1614 void *write_save_file(void *ptr) {
1615
1616         int fd;
1617         char dir[128];
1618         t_moldyn *moldyn;
1619
1620         moldyn=ptr;
1621
1622         snprintf(dir,128,"%s/s-%08.f.save",moldyn->vlsdir,moldyn->time);
1623         fd=open(dir,O_WRONLY|O_TRUNC|O_CREAT,S_IRUSR|S_IWUSR);
1624         if(fd<0) perror("[moldyn] save fd open");
1625         else {
1626                 write(fd,moldyn,sizeof(t_moldyn));
1627                 write(fd,moldyn->atom,moldyn->count*sizeof(t_atom));
1628         }
1629
1630         close(fd);
1631
1632         pthread_exit(NULL);
1633
1634         return 0;
1635 }
1636 #endif
1637
1638 /* start the integration */
1639
1640 int moldyn_integrate(t_moldyn *moldyn) {
1641
1642         int i;
1643         unsigned int e,m,s,v,p,t,a;
1644         t_3dvec momentum;
1645         t_moldyn_schedule *sched;
1646         t_atom *atom;
1647 #ifndef PTHREADS
1648         int fd;
1649         char dir[128];
1650 #endif
1651         double ds;
1652         double energy_scale;
1653         struct timeval t1,t2;
1654         //double tp;
1655
1656 #ifdef PTHREADS
1657         u8 first,change;
1658         pthread_t io_thread;
1659         int ret;
1660         t_moldyn md_copy;
1661         t_atom *atom_copy;
1662
1663         first=1;
1664         change=0;
1665 #endif
1666
1667         sched=&(moldyn->schedule);
1668         atom=moldyn->atom;
1669
1670         /* initialize linked cell method */
1671         link_cell_init(moldyn,VERBOSE);
1672
1673         /* logging & visualization */
1674         e=moldyn->ewrite;
1675         m=moldyn->mwrite;
1676         s=moldyn->swrite;
1677         v=moldyn->vwrite;
1678         a=moldyn->awrite;
1679         p=moldyn->pwrite;
1680         t=moldyn->twrite;
1681
1682         /* sqaure of some variables */
1683         moldyn->tau_square=moldyn->tau*moldyn->tau;
1684
1685         /* get current time */
1686         gettimeofday(&t1,NULL);
1687
1688         /* calculate initial forces */
1689         potential_force_calc(moldyn);
1690 #ifdef DEBUG
1691 //return 0;
1692 #endif
1693
1694         /* some stupid checks before we actually start calculating bullshit */
1695         if(moldyn->cutoff>0.5*moldyn->dim.x)
1696                 printf("[moldyn] WARNING: cutoff > 0.5 x dim.x\n");
1697         if(moldyn->cutoff>0.5*moldyn->dim.y)
1698                 printf("[moldyn] WARNING: cutoff > 0.5 x dim.y\n");
1699         if(moldyn->cutoff>0.5*moldyn->dim.z)
1700                 printf("[moldyn] WARNING: cutoff > 0.5 x dim.z\n");
1701         if(moldyn->count) {
1702                 ds=0.5*atom[0].f.x*moldyn->tau_square/atom[0].mass;
1703                 if(ds>0.05*moldyn->nnd)
1704                 printf("[moldyn] WARNING: forces too high / tau too small!\n");
1705         }
1706
1707         /* zero absolute time */
1708         // should have right values!
1709         //moldyn->time=0.0;
1710         //moldyn->total_steps=0;
1711
1712         /* debugging, ignore */
1713         moldyn->debug=0;
1714
1715         /* zero & init moldyn copy */
1716 #ifdef PTHREADS
1717         memset(&md_copy,0,sizeof(t_moldyn));
1718         atom_copy=malloc(moldyn->count*sizeof(t_atom));
1719         if(atom_copy==NULL) {
1720                 perror("[moldyn] malloc atom copy (init)");
1721                 return -1;
1722         }
1723 #endif
1724
1725         /* tell the world */
1726         printf("[moldyn] integration start, go get a coffee ...\n");
1727
1728         /* executing the schedule */
1729         sched->count=0;
1730         while(sched->count<sched->total_sched) {
1731
1732                 /* setting amount of runs and finite time step size */
1733                 moldyn->tau=sched->tau[sched->count];
1734                 moldyn->tau_square=moldyn->tau*moldyn->tau;
1735                 moldyn->time_steps=sched->runs[sched->count];
1736
1737                 /* energy scaling factor (might change!) */
1738                 energy_scale=moldyn->count*EV;
1739
1740         /* integration according to schedule */
1741
1742         for(i=0;i<moldyn->time_steps;i++) {
1743
1744                 /* integration step */
1745                 moldyn->integrate(moldyn);
1746
1747                 /* calculate kinetic energy, temperature and pressure */
1748                 e_kin_calc(moldyn);
1749                 temperature_calc(moldyn);
1750                 virial_sum(moldyn);
1751                 pressure_calc(moldyn);
1752                 /*
1753                 thermodynamic_pressure_calc(moldyn);
1754                 printf("\n\nDEBUG: numeric pressure calc: %f\n\n",
1755                        moldyn->tp/BAR);
1756                 */
1757
1758                 /* calculate fluctuations + averages */
1759                 average_and_fluctuation_calc(moldyn);
1760
1761                 /* p/t scaling */
1762                 if(moldyn->pt_scale&(T_SCALE_BERENDSEN|T_SCALE_DIRECT))
1763                         scale_velocity(moldyn,FALSE);
1764                 if(moldyn->pt_scale&(P_SCALE_BERENDSEN|P_SCALE_DIRECT))
1765                         scale_volume(moldyn);
1766
1767                 /* check for log & visualization */
1768                 if(e) {
1769                         if(!(moldyn->total_steps%e))
1770                                 dprintf(moldyn->efd,
1771                                         "%f %f %f %f\n",
1772                                         moldyn->time,moldyn->ekin/energy_scale,
1773                                         moldyn->energy/energy_scale,
1774                                         get_total_energy(moldyn)/energy_scale);
1775                 }
1776                 if(m) {
1777                         if(!(moldyn->total_steps%m)) {
1778                                 momentum=get_total_p(moldyn);
1779                                 dprintf(moldyn->mfd,
1780                                         "%f %f %f %f %f\n",moldyn->time,
1781                                         momentum.x,momentum.y,momentum.z,
1782                                         v3_norm(&momentum));
1783                         }
1784                 }
1785                 if(p) {
1786                         if(!(moldyn->total_steps%p)) {
1787                                 dprintf(moldyn->pfd,
1788                                         "%f %f %f %f %f %f %f\n",moldyn->time,
1789                                          moldyn->p/BAR,moldyn->p_avg/BAR,
1790                                          moldyn->gp/BAR,moldyn->gp_avg/BAR,
1791                                          moldyn->tp/BAR,moldyn->tp_avg/BAR);
1792                         }
1793                 }
1794                 if(t) {
1795                         if(!(moldyn->total_steps%t)) {
1796                                 dprintf(moldyn->tfd,
1797                                         "%f %f %f\n",
1798                                         moldyn->time,moldyn->t,moldyn->t_avg);
1799                         }
1800                 }
1801                 if(v) {
1802                         if(!(moldyn->total_steps%v)) {
1803                                 dprintf(moldyn->vfd,
1804                                         "%f %f\n",moldyn->time,moldyn->volume);
1805                         }
1806                 }
1807                 if(s) {
1808                         if(!(moldyn->total_steps%s)) {
1809 #ifdef PTHREADS
1810         /* check whether thread has not terminated yet */
1811         if(!first) {
1812                 ret=pthread_join(io_thread,NULL);
1813         }
1814         first=0;
1815         /* prepare and start thread */
1816         if(moldyn->count!=md_copy.count) {
1817                 free(atom_copy);
1818                 change=1;
1819         }
1820         memcpy(&md_copy,moldyn,sizeof(t_moldyn));
1821         if(change) {
1822                 atom_copy=malloc(moldyn->count*sizeof(t_atom));
1823                 if(atom_copy==NULL) {
1824                         perror("[moldyn] malloc atom copy (change)");
1825                         return -1;
1826                 }
1827         }
1828         md_copy.atom=atom_copy;
1829         memcpy(atom_copy,moldyn->atom,moldyn->count*sizeof(t_atom));
1830         change=0;
1831         ret=pthread_create(&io_thread,NULL,write_save_file,&md_copy);
1832         if(ret) {
1833                 perror("[moldyn] create save file thread\n");
1834                 return -1;
1835         }
1836 #else
1837                                 snprintf(dir,128,"%s/s-%08.f.save",
1838                                          moldyn->vlsdir,moldyn->time);
1839                                 fd=open(dir,O_WRONLY|O_TRUNC|O_CREAT,
1840                                         S_IRUSR|S_IWUSR);
1841                                 if(fd<0) perror("[moldyn] save fd open");
1842                                 else {
1843                                         write(fd,moldyn,sizeof(t_moldyn));
1844                                         write(fd,moldyn->atom,
1845                                               moldyn->count*sizeof(t_atom));
1846                                 }
1847                                 close(fd);
1848 #endif
1849                         }       
1850                 }
1851                 if(a) {
1852                         if(!(moldyn->total_steps%a)) {
1853                                 visual_atoms(moldyn);
1854                         }
1855                 }
1856
1857                 /* display progress */
1858                 if(!(i%10)) {
1859                         /* get current time */
1860                         gettimeofday(&t2,NULL);
1861
1862 printf("\rsched:%d, steps:%d/%d, T:%4.1f/%4.1f P:%4.1f/%4.1f V:%6.1f (%d)",
1863        sched->count,i,moldyn->total_steps,
1864        moldyn->t,moldyn->t_avg,
1865        moldyn->p/BAR,moldyn->p_avg/BAR,
1866        //moldyn->p/BAR,(moldyn->p-2.0*moldyn->ekin/(3.0*moldyn->volume))/BAR,
1867        moldyn->volume,
1868        (int)(t2.tv_sec-t1.tv_sec));
1869
1870                         fflush(stdout);
1871
1872                         /* copy over time */
1873                         t1=t2;
1874                 }
1875
1876                 /* increase absolute time */
1877                 moldyn->time+=moldyn->tau;
1878                 moldyn->total_steps+=1;
1879
1880         }
1881
1882                 /* check for hooks */
1883                 if(sched->hook) {
1884                         printf("\n ## schedule hook %d start ##\n",
1885                                sched->count);
1886                         sched->hook(moldyn,sched->hook_params);
1887                         printf(" ## schedule hook end ##\n");
1888                 }
1889
1890                 /* increase the schedule counter */
1891                 sched->count+=1;
1892
1893         }
1894
1895         return 0;
1896 }
1897
1898 /* velocity verlet */
1899
1900 int velocity_verlet(t_moldyn *moldyn) {
1901
1902         int i,count;
1903         double tau,tau_square,h;
1904         t_3dvec delta;
1905         t_atom *atom;
1906
1907         atom=moldyn->atom;
1908         count=moldyn->count;
1909         tau=moldyn->tau;
1910         tau_square=moldyn->tau_square;
1911
1912         for(i=0;i<count;i++) {
1913                 /* check whether fixed atom */
1914                 if(atom[i].attr&ATOM_ATTR_FP)
1915                         continue;
1916                 /* new positions */
1917                 h=0.5/atom[i].mass;
1918                 v3_scale(&delta,&(atom[i].v),tau);
1919                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
1920                 v3_scale(&delta,&(atom[i].f),h*tau_square);
1921                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
1922                 check_per_bound(moldyn,&(atom[i].r));
1923
1924                 /* velocities [actually v(t+tau/2)] */
1925                 v3_scale(&delta,&(atom[i].f),h*tau);
1926                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
1927         }
1928
1929         /* criticial check */
1930         moldyn_bc_check(moldyn);
1931
1932         /* neighbour list update */
1933         link_cell_update(moldyn);
1934
1935         /* forces depending on chosen potential */
1936 #ifndef ALBE_FAST
1937         potential_force_calc(moldyn);
1938 #else
1939         albe_potential_force_calc(moldyn);
1940 #endif
1941
1942         for(i=0;i<count;i++) {
1943                 /* check whether fixed atom */
1944                 if(atom[i].attr&ATOM_ATTR_FP)
1945                         continue;
1946                 /* again velocities [actually v(t+tau)] */
1947                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
1948                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
1949         }
1950
1951         return 0;
1952 }
1953
1954
1955 /*
1956  *
1957  * potentials & corresponding forces & virial routine
1958  * 
1959  */
1960
1961 /* generic potential and force calculation */
1962
1963 int potential_force_calc(t_moldyn *moldyn) {
1964
1965         int i,j,k,count;
1966         t_atom *itom,*jtom,*ktom;
1967         t_virial *virial;
1968         t_linkcell *lc;
1969 #ifdef STATIC_LISTS
1970         int *neighbour_i[27];
1971         int p,q;
1972         t_atom *atom;
1973 #elif LOWMEM_LISTS
1974         int neighbour_i[27];
1975         int p,q;
1976 #else
1977         t_list neighbour_i[27];
1978         t_list neighbour_i2[27];
1979         t_list *this,*that;
1980 #endif
1981         u8 bc_ij,bc_ik;
1982         int dnlc;
1983
1984         count=moldyn->count;
1985         itom=moldyn->atom;
1986         lc=&(moldyn->lc);
1987 #ifdef STATIC_LISTS
1988         atom=moldyn->atom;
1989 #endif
1990
1991         /* reset energy */
1992         moldyn->energy=0.0;
1993
1994         /* reset global virial */
1995         memset(&(moldyn->gvir),0,sizeof(t_virial));
1996
1997         /* reset force, site energy and virial of every atom */
1998 #ifdef PARALLEL
1999         i=omp_get_thread_num();
2000         #pragma omp parallel for private(virial)
2001 #endif
2002         for(i=0;i<count;i++) {
2003
2004                 /* reset force */
2005                 v3_zero(&(itom[i].f));
2006
2007                 /* reset virial */
2008                 virial=(&(itom[i].virial));
2009                 virial->xx=0.0;
2010                 virial->yy=0.0;
2011                 virial->zz=0.0;
2012                 virial->xy=0.0;
2013                 virial->xz=0.0;
2014                 virial->yz=0.0;
2015         
2016                 /* reset site energy */
2017                 itom[i].e=0.0;
2018
2019         }
2020
2021         /* get energy, force and virial of every atom */
2022
2023         /* first (and only) loop over atoms i */
2024         for(i=0;i<count;i++) {
2025
2026                 /* single particle potential/force */
2027                 if(itom[i].attr&ATOM_ATTR_1BP)
2028                         if(moldyn->func1b)
2029                                 moldyn->func1b(moldyn,&(itom[i]));
2030
2031                 if(!(itom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)))
2032                         continue;
2033
2034                 /* 2 body pair potential/force */
2035         
2036                 link_cell_neighbour_index(moldyn,
2037                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
2038                                           (itom[i].r.y+moldyn->dim.y/2)/lc->y,
2039                                           (itom[i].r.z+moldyn->dim.z/2)/lc->z,
2040                                           neighbour_i);
2041
2042                 dnlc=lc->dnlc;
2043
2044                 /* first loop over atoms j */
2045                 if(moldyn->func2b) {
2046                         for(j=0;j<27;j++) {
2047
2048                                 bc_ij=(j<dnlc)?0:1;
2049 #ifdef STATIC_LISTS
2050                                 p=0;
2051
2052                                 while(neighbour_i[j][p]!=-1) {
2053
2054                                         jtom=&(atom[neighbour_i[j][p]]);
2055                                         p++;
2056 #elif LOWMEM_LISTS
2057                                 p=neighbour_i[j];
2058
2059                                 while(p!=-1) {
2060
2061                                         jtom=&(itom[p]);
2062                                         p=lc->subcell->list[p];
2063 #else
2064                                 this=&(neighbour_i[j]);
2065                                 list_reset_f(this);
2066
2067                                 if(this->start==NULL)
2068                                         continue;
2069
2070                                 do {
2071                                         jtom=this->current->data;
2072 #endif
2073
2074                                         if(jtom==&(itom[i]))
2075                                                 continue;
2076
2077                                         if((jtom->attr&ATOM_ATTR_2BP)&
2078                                            (itom[i].attr&ATOM_ATTR_2BP)) {
2079                                                 moldyn->func2b(moldyn,
2080                                                                &(itom[i]),
2081                                                                jtom,
2082                                                                bc_ij);
2083                                         }
2084 #ifdef STATIC_LISTS
2085                                 }
2086 #elif LOWMEM_LISTS
2087                                 }
2088 #else
2089                                 } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2090 #endif
2091
2092                         }
2093                 }
2094
2095                 /* 3 body potential/force */
2096
2097                 if(!(itom[i].attr&ATOM_ATTR_3BP))
2098                         continue;
2099
2100                 /* copy the neighbour lists */
2101 #ifdef STATIC_LISTS
2102                 /* no copy needed for static lists */
2103 #elif LOWMEM_LISTS
2104                 /* no copy needed for lowmem lists */
2105 #else
2106                 memcpy(neighbour_i2,neighbour_i,27*sizeof(t_list));
2107 #endif
2108
2109                 /* second loop over atoms j */
2110                 for(j=0;j<27;j++) {
2111
2112                         bc_ij=(j<dnlc)?0:1;
2113 #ifdef STATIC_LISTS
2114                         p=0;
2115
2116                         while(neighbour_i[j][p]!=-1) {
2117
2118                                 jtom=&(atom[neighbour_i[j][p]]);
2119                                 p++;
2120 #elif LOWMEM_LISTS
2121                                 p=neighbour_i[j];
2122
2123                                 while(p!=-1) {
2124
2125                                         jtom=&(itom[p]);
2126                                         p=lc->subcell->list[p];
2127 #else
2128                         this=&(neighbour_i[j]);
2129                         list_reset_f(this);
2130
2131                         if(this->start==NULL)
2132                                 continue;
2133
2134                         do {
2135
2136                                 jtom=this->current->data;
2137 #endif
2138
2139                                 if(jtom==&(itom[i]))
2140                                         continue;
2141
2142                                 if(!(jtom->attr&ATOM_ATTR_3BP))
2143                                         continue;
2144
2145                                 /* reset 3bp run */
2146                                 moldyn->run3bp=1;
2147
2148                                 if(moldyn->func3b_j1)
2149                                         moldyn->func3b_j1(moldyn,
2150                                                           &(itom[i]),
2151                                                           jtom,
2152                                                           bc_ij);
2153
2154                                 /* in first j loop, 3bp run can be skipped */
2155                                 if(!(moldyn->run3bp))
2156                                         continue;
2157                         
2158                                 /* first loop over atoms k */
2159                                 if(moldyn->func3b_k1) {
2160
2161                                 for(k=0;k<27;k++) {
2162
2163                                         bc_ik=(k<dnlc)?0:1;
2164 #ifdef STATIC_LISTS
2165                                         q=0;
2166
2167                                         while(neighbour_i[k][q]!=-1) {
2168
2169                                                 ktom=&(atom[neighbour_i[k][q]]);
2170                                                 q++;
2171 #elif LOWMEM_LISTS
2172                                         q=neighbour_i[k];
2173
2174                                         while(q!=-1) {
2175
2176                                                 ktom=&(itom[q]);
2177                                                 q=lc->subcell->list[q];
2178 #else
2179                                         that=&(neighbour_i2[k]);
2180                                         list_reset_f(that);
2181                                         
2182                                         if(that->start==NULL)
2183                                                 continue;
2184
2185                                         do {
2186                                                 ktom=that->current->data;
2187 #endif
2188
2189                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
2190                                                         continue;
2191
2192                                                 if(ktom==jtom)
2193                                                         continue;
2194
2195                                                 if(ktom==&(itom[i]))
2196                                                         continue;
2197
2198                                                 moldyn->func3b_k1(moldyn,
2199                                                                   &(itom[i]),
2200                                                                   jtom,
2201                                                                   ktom,
2202                                                                   bc_ik|bc_ij);
2203 #ifdef STATIC_LISTS
2204                                         }
2205 #elif LOWMEM_LISTS
2206                                         }
2207 #else
2208                                         } while(list_next_f(that)!=\
2209                                                 L_NO_NEXT_ELEMENT);
2210 #endif
2211
2212                                 }
2213
2214                                 }
2215
2216                                 if(moldyn->func3b_j2)
2217                                         moldyn->func3b_j2(moldyn,
2218                                                           &(itom[i]),
2219                                                           jtom,
2220                                                           bc_ij);
2221
2222                                 /* second loop over atoms k */
2223                                 if(moldyn->func3b_k2) {
2224
2225                                 for(k=0;k<27;k++) {
2226
2227                                         bc_ik=(k<dnlc)?0:1;
2228 #ifdef STATIC_LISTS
2229                                         q=0;
2230
2231                                         while(neighbour_i[k][q]!=-1) {
2232
2233                                                 ktom=&(atom[neighbour_i[k][q]]);
2234                                                 q++;
2235 #elif LOWMEM_LISTS
2236                                         q=neighbour_i[k];
2237
2238                                         while(q!=-1) {
2239
2240                                                 ktom=&(itom[q]);
2241                                                 q=lc->subcell->list[q];
2242 #else
2243                                         that=&(neighbour_i2[k]);
2244                                         list_reset_f(that);
2245                                         
2246                                         if(that->start==NULL)
2247                                                 continue;
2248
2249                                         do {
2250                                                 ktom=that->current->data;
2251 #endif
2252
2253                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
2254                                                         continue;
2255
2256                                                 if(ktom==jtom)
2257                                                         continue;
2258
2259                                                 if(ktom==&(itom[i]))
2260                                                         continue;
2261
2262                                                 moldyn->func3b_k2(moldyn,
2263                                                                   &(itom[i]),
2264                                                                   jtom,
2265                                                                   ktom,
2266                                                                   bc_ik|bc_ij);
2267
2268 #ifdef STATIC_LISTS
2269                                         }
2270 #elif LOWMEM_LISTS
2271                                         }
2272 #else
2273                                         } while(list_next_f(that)!=\
2274                                                 L_NO_NEXT_ELEMENT);
2275 #endif
2276
2277                                 }
2278                                 
2279                                 }
2280
2281                                 /* 2bp post function */
2282                                 if(moldyn->func3b_j3) {
2283                                         moldyn->func3b_j3(moldyn,
2284                                                           &(itom[i]),
2285                                                           jtom,bc_ij);
2286                                 }
2287 #ifdef STATIC_LISTS
2288                         }
2289 #elif LOWMEM_LISTS
2290                         }
2291 #else
2292                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2293 #endif
2294                 
2295                 }
2296                 
2297 #ifdef DEBUG
2298         //printf("\n\n");
2299 #endif
2300 #ifdef VDEBUG
2301         printf("\n\n");
2302 #endif
2303
2304         }
2305
2306 #ifdef DEBUG
2307         //printf("\nATOM 0: %f %f %f\n\n",itom->f.x,itom->f.y,itom->f.z);
2308         if(moldyn->time>DSTART&&moldyn->time<DEND) {
2309                 printf("force:\n");
2310                 printf("  x: %0.40f\n",moldyn->atom[DATOM].f.x);
2311                 printf("  y: %0.40f\n",moldyn->atom[DATOM].f.y);
2312                 printf("  z: %0.40f\n",moldyn->atom[DATOM].f.z);
2313         }
2314 #endif
2315
2316         /* some postprocessing */
2317 #ifdef PARALLEL
2318         #pragma omp parallel for
2319 #endif
2320         for(i=0;i<count;i++) {
2321                 /* calculate global virial */
2322                 moldyn->gvir.xx+=itom[i].r.x*itom[i].f.x;
2323                 moldyn->gvir.yy+=itom[i].r.y*itom[i].f.y;
2324                 moldyn->gvir.zz+=itom[i].r.z*itom[i].f.z;
2325                 moldyn->gvir.xy+=itom[i].r.y*itom[i].f.x;
2326                 moldyn->gvir.xz+=itom[i].r.z*itom[i].f.x;
2327                 moldyn->gvir.yz+=itom[i].r.z*itom[i].f.y;
2328
2329                 /* check forces regarding the given timestep */
2330                 if(v3_norm(&(itom[i].f))>\
2331                    0.1*moldyn->nnd*itom[i].mass/moldyn->tau_square)
2332                         printf("[moldyn] WARNING: pfc (high force: atom %d)\n",
2333                                i);
2334         }
2335
2336         return 0;
2337 }
2338
2339 /*
2340  * virial calculation
2341  */
2342
2343 //inline int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
2344 int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
2345
2346         a->virial.xx+=f->x*d->x;
2347         a->virial.yy+=f->y*d->y;
2348         a->virial.zz+=f->z*d->z;
2349         a->virial.xy+=f->x*d->y;
2350         a->virial.xz+=f->x*d->z;
2351         a->virial.yz+=f->y*d->z;
2352
2353         return 0;
2354 }
2355
2356 /*
2357  * periodic boundary checking
2358  */
2359
2360 //inline int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
2361 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
2362         
2363         double x,y,z;
2364         t_3dvec *dim;
2365
2366         dim=&(moldyn->dim);
2367
2368         x=dim->x/2;
2369         y=dim->y/2;
2370         z=dim->z/2;
2371
2372         if(moldyn->status&MOLDYN_STAT_PBX) {
2373                 if(a->x>=x) a->x-=dim->x;
2374                 else if(-a->x>x) a->x+=dim->x;
2375         }
2376         if(moldyn->status&MOLDYN_STAT_PBY) {
2377                 if(a->y>=y) a->y-=dim->y;
2378                 else if(-a->y>y) a->y+=dim->y;
2379         }
2380         if(moldyn->status&MOLDYN_STAT_PBZ) {
2381                 if(a->z>=z) a->z-=dim->z;
2382                 else if(-a->z>z) a->z+=dim->z;
2383         }
2384
2385         return 0;
2386 }
2387         
2388 /*
2389  * debugging / critical check functions
2390  */
2391
2392 int moldyn_bc_check(t_moldyn *moldyn) {
2393
2394         t_atom *atom;
2395         t_3dvec *dim;
2396         int i;
2397         double x;
2398         u8 byte;
2399         int j,k;
2400
2401         atom=moldyn->atom;
2402         dim=&(moldyn->dim);
2403         x=dim->x/2;
2404
2405         for(i=0;i<moldyn->count;i++) {
2406                 if(atom[i].r.x>=dim->x/2||-atom[i].r.x>dim->x/2) {
2407                         printf("FATAL: atom %d: x: %.20f (%.20f)\n",
2408                                i,atom[i].r.x,dim->x/2);
2409                         printf("diagnostic:\n");
2410                         printf("-----------\natom.r.x:\n");
2411                         for(j=0;j<8;j++) {
2412                                 memcpy(&byte,(u8 *)(&(atom[i].r.x))+j,1);
2413                                 for(k=0;k<8;k++)
2414                                         printf("%d%c",
2415                                         ((byte)&(1<<k))?1:0,
2416                                         (k==7)?'\n':'|');
2417                         }
2418                         printf("---------------\nx=dim.x/2:\n");
2419                         for(j=0;j<8;j++) {
2420                                 memcpy(&byte,(u8 *)(&x)+j,1);
2421                                 for(k=0;k<8;k++)
2422                                         printf("%d%c",
2423                                         ((byte)&(1<<k))?1:0,
2424                                         (k==7)?'\n':'|');
2425                         }
2426                         if(atom[i].r.x==x) printf("the same!\n");
2427                         else printf("different!\n");
2428                 }
2429                 if(atom[i].r.y>=dim->y/2||-atom[i].r.y>dim->y/2)
2430                         printf("FATAL: atom %d: y: %.20f (%.20f)\n",
2431                                i,atom[i].r.y,dim->y/2);
2432                 if(atom[i].r.z>=dim->z/2||-atom[i].r.z>dim->z/2)
2433                         printf("FATAL: atom %d: z: %.20f (%.20f)\n",
2434                                i,atom[i].r.z,dim->z/2);
2435         }
2436
2437         return 0;
2438 }
2439
2440 /*
2441  * restore function
2442  */
2443
2444 int moldyn_read_save_file(t_moldyn *moldyn,char *file) {
2445
2446         int fd;
2447         int cnt,size;
2448         int fsize;
2449         int corr;
2450
2451         fd=open(file,O_RDONLY);
2452         if(fd<0) {
2453                 perror("[moldyn] load save file open");
2454                 return fd;
2455         }
2456
2457         fsize=lseek(fd,0,SEEK_END);
2458         lseek(fd,0,SEEK_SET);
2459
2460         size=sizeof(t_moldyn);
2461
2462         while(size) {
2463                 cnt=read(fd,moldyn,size);
2464                 if(cnt<0) {
2465                         perror("[moldyn] load save file read (moldyn)");
2466                         return cnt;
2467                 }
2468                 size-=cnt;
2469         }
2470
2471         size=moldyn->count*sizeof(t_atom);
2472
2473         /* correcting possible atom data offset */
2474         corr=0;
2475         if(fsize!=sizeof(t_moldyn)+size) {
2476                 corr=fsize-sizeof(t_moldyn)-size;
2477                 printf("[moldyn] WARNING: lsf (illegal file size)\n");
2478                 printf("  moifying offset:\n");
2479                 printf("  - current pos: %d\n",sizeof(t_moldyn));
2480                 printf("  - atom size: %d\n",size);
2481                 printf("  - file size: %d\n",fsize);
2482                 printf("  => correction: %d\n",corr);
2483                 lseek(fd,corr,SEEK_CUR);
2484         }
2485
2486         moldyn->atom=(t_atom *)malloc(size);
2487         if(moldyn->atom==NULL) {
2488                 perror("[moldyn] load save file malloc (atoms)");
2489                 return -1;
2490         }
2491
2492         while(size) {
2493                 cnt=read(fd,moldyn->atom,size);
2494                 if(cnt<0) {
2495                         perror("[moldyn] load save file read (atoms)");
2496                         return cnt;
2497                 }
2498                 size-=cnt;
2499         }
2500
2501         // hooks etc ...
2502
2503         return 0;
2504 }
2505
2506 int moldyn_free_save_file(t_moldyn *moldyn) {
2507
2508         free(moldyn->atom);
2509
2510         return 0;
2511 }
2512
2513 int moldyn_load(t_moldyn *moldyn) {
2514
2515         // later ...
2516
2517         return 0;
2518 }
2519
2520 /*
2521  * function to find/callback all combinations of 2 body bonds
2522  */
2523
2524 int process_2b_bonds(t_moldyn *moldyn,void *data,
2525                      int (*process)(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2526                                     void *data,u8 bc)) {
2527
2528         t_linkcell *lc;
2529 #ifdef STATIC_LISTS
2530         int *neighbour[27];
2531         int p;
2532 #elif LOWMEM_LISTS
2533         int neighbour[27];
2534         int p;
2535 #else
2536         t_list neighbour[27];
2537         t_list *this;
2538 #endif
2539         u8 bc;
2540         t_atom *itom,*jtom;
2541         int i,j;
2542
2543         lc=&(moldyn->lc);
2544         itom=moldyn->atom;
2545         
2546         for(i=0;i<moldyn->count;i++) {
2547                 /* neighbour indexing */
2548                 link_cell_neighbour_index(moldyn,
2549                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
2550                                           (itom[i].r.y+moldyn->dim.y/2)/lc->x,
2551                                           (itom[i].r.z+moldyn->dim.z/2)/lc->x,
2552                                           neighbour);
2553
2554                 for(j=0;j<27;j++) {
2555
2556                         bc=(j<lc->dnlc)?0:1;
2557
2558 #ifdef STATIC_LISTS
2559                         p=0;
2560
2561                         while(neighbour[j][p]!=-1) {
2562
2563                                 jtom=&(moldyn->atom[neighbour[j][p]]);
2564                                 p++;
2565 #elif LOWMEM_LISTS
2566                         p=neighbour[j];
2567
2568                         while(p!=-1) {
2569
2570                                 jtom=&(itom[p]);
2571                                 p=lc->subcell->list[p];
2572 #else
2573                         this=&(neighbour[j]);
2574                         list_reset_f(this);
2575
2576                         if(this->start==NULL)
2577                                 continue;
2578
2579                         do {
2580
2581                                 jtom=this->current->data;
2582 #endif
2583
2584                                 /* process bond */
2585                                 process(moldyn,&(itom[i]),jtom,data,bc);
2586
2587 #ifdef STATIC_LISTS
2588                         }
2589 #elif LOWMEM_LISTS
2590                         }
2591 #else
2592                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2593 #endif
2594                 }
2595         }
2596
2597         return 0;
2598
2599 }
2600
2601 /*
2602  * function to find neighboured atoms
2603  */
2604
2605 int process_neighbours(t_moldyn *moldyn,void *data,t_atom *atom,
2606                        int (*process)(t_moldyn *moldyn,t_atom *atom,t_atom *natom,
2607                                       void *data,u8 bc)) {
2608
2609         t_linkcell *lc;
2610 #ifdef STATIC_LISTS
2611         int *neighbour[27];
2612         int p;
2613 #elif LOWMEM_LISTS
2614         int neighbour[27];
2615         int p;
2616 #else
2617         t_list neighbour[27];
2618         t_list *this;
2619 #endif
2620         u8 bc;
2621         t_atom *natom;
2622         int j;
2623
2624         lc=&(moldyn->lc);
2625         
2626         /* neighbour indexing */
2627         link_cell_neighbour_index(moldyn,
2628                                   (atom->r.x+moldyn->dim.x/2)/lc->x,
2629                                   (atom->r.y+moldyn->dim.y/2)/lc->x,
2630                                   (atom->r.z+moldyn->dim.z/2)/lc->x,
2631                                   neighbour);
2632
2633         for(j=0;j<27;j++) {
2634
2635                 bc=(j<lc->dnlc)?0:1;
2636
2637 #ifdef STATIC_LISTS
2638                 p=0;
2639
2640                 while(neighbour[j][p]!=-1) {
2641
2642                         natom=&(moldyn->atom[neighbour[j][p]]);
2643                         p++;
2644 #elif LOWMEM_LISTS
2645                 p=neighbour[j];
2646
2647                 while(p!=-1) {
2648
2649                         natom=&(moldyn->atom[p]);
2650                         p=lc->subcell->list[p];
2651 #else
2652                 this=&(neighbour[j]);
2653                 list_reset_f(this);
2654
2655                 if(this->start==NULL)
2656                         continue;
2657
2658                 do {
2659
2660                         natom=this->current->data;
2661 #endif
2662
2663                         /* process bond */
2664                         process(moldyn,atom,natom,data,bc);
2665
2666 #ifdef STATIC_LISTS
2667                 }
2668 #elif LOWMEM_LISTS
2669                 }
2670 #else
2671                 } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
2672 #endif
2673         }
2674
2675         return 0;
2676
2677 }
2678
2679 /*
2680  * post processing functions
2681  */
2682
2683 int get_line(int fd,char *line,int max) {
2684
2685         int count,ret;
2686
2687         count=0;
2688
2689         while(1) {
2690                 if(count==max) return count;
2691                 ret=read(fd,line+count,1);
2692                 if(ret<=0) return ret;
2693                 if(line[count]=='\n') {
2694                         memset(line+count,0,max-count-1);
2695                         //line[count]='\0';
2696                         return count+1;
2697                 }
2698                 count+=1;
2699         }
2700 }
2701
2702 int pair_correlation_init(t_moldyn *moldyn,double dr) {
2703
2704         
2705         return 0;
2706 }
2707
2708 int calculate_diffusion_coefficient(t_moldyn *moldyn,double *dc) {
2709
2710         int i;
2711         t_atom *atom;
2712         t_3dvec dist;
2713         double d2;
2714         int a_cnt;
2715         int b_cnt;
2716
2717         atom=moldyn->atom;
2718         dc[0]=0;
2719         dc[1]=0;
2720         dc[2]=0;
2721         a_cnt=0;
2722         b_cnt=0;
2723
2724         for(i=0;i<moldyn->count;i++) {
2725
2726                 v3_sub(&dist,&(atom[i].r),&(atom[i].r_0));
2727                 check_per_bound(moldyn,&dist);
2728                 d2=v3_absolute_square(&dist);
2729
2730                 if(atom[i].brand) {
2731                         b_cnt+=1;
2732                         dc[1]+=d2;
2733                 }
2734                 else {
2735                         a_cnt+=1;
2736                         dc[0]+=d2;
2737                 }
2738
2739                 dc[2]+=d2;
2740         }
2741
2742         dc[0]*=(1.0/(6.0*moldyn->time*a_cnt));
2743         dc[1]*=(1.0/(6.0*moldyn->time*b_cnt));
2744         dc[2]*=(1.0/(6.0*moldyn->time*moldyn->count));
2745                 
2746         return 0;
2747 }
2748
2749 int bonding_analyze(t_moldyn *moldyn,double *cnt) {
2750
2751         return 0;
2752 }
2753
2754 int calculate_pair_correlation_process(t_moldyn *moldyn,t_atom *itom,
2755                                        t_atom *jtom,void *data,u8 bc) {
2756
2757         t_3dvec dist;
2758         double d;
2759         int s;
2760         t_pcc *pcc;
2761
2762         /* only count pairs once,
2763          * skip same atoms */
2764         if(itom->tag>=jtom->tag)
2765                 return 0;
2766
2767         /*
2768          * pair correlation calc
2769          */
2770
2771         /* get pcc data */
2772         pcc=data;
2773
2774         /* distance */
2775         v3_sub(&dist,&(jtom->r),&(itom->r));
2776         if(bc) check_per_bound(moldyn,&dist);
2777         d=v3_absolute_square(&dist);
2778
2779         /* ignore if greater cutoff */
2780         if(d>moldyn->cutoff_square)
2781                 return 0;
2782
2783         /* fill the slots */
2784         d=sqrt(d);
2785         s=(int)(d/pcc->dr);
2786
2787         /* should never happen but it does 8) -
2788          * related to -ffloat-store problem! */
2789         if(s>=pcc->o1) {
2790                 printf("[moldyn] WARNING: pcc (%d/%d)",
2791                        s,pcc->o1);
2792                 printf("\n");
2793                 s=pcc->o1-1;
2794         }
2795
2796         if(itom->brand!=jtom->brand) {
2797                 /* mixed */
2798                 pcc->stat[s]+=1;
2799         }
2800         else {
2801                 /* type a - type a bonds */
2802                 if(itom->brand==0)
2803                         pcc->stat[s+pcc->o1]+=1;
2804                 else
2805                 /* type b - type b bonds */
2806                         pcc->stat[s+pcc->o2]+=1;
2807         }
2808
2809         return 0;
2810 }
2811
2812 int calculate_pair_correlation(t_moldyn *moldyn,double dr,void *ptr) {
2813
2814         t_pcc pcc;
2815         double norm;
2816         int i;
2817
2818         pcc.dr=dr;
2819         pcc.o1=moldyn->cutoff/dr;
2820         pcc.o2=2*pcc.o1;
2821
2822         if(pcc.o1*dr<=moldyn->cutoff)
2823                 printf("[moldyn] WARNING: pcc (low #slots)\n");
2824
2825         printf("[moldyn] pair correlation calc info:\n");
2826         printf("  time: %f\n",moldyn->time);
2827         printf("  count: %d\n",moldyn->count);
2828         printf("  cutoff: %f\n",moldyn->cutoff);
2829         printf("  temperature: cur=%f avg=%f\n",moldyn->t,moldyn->t_avg);
2830
2831         if(ptr!=NULL) {
2832                 pcc.stat=(double *)ptr;
2833         }
2834         else {
2835                 pcc.stat=(double *)malloc(3*pcc.o1*sizeof(double));
2836                 if(pcc.stat==NULL) {
2837                         perror("[moldyn] pair correlation malloc");
2838                         return -1;
2839                 }
2840         }
2841
2842         memset(pcc.stat,0,3*pcc.o1*sizeof(double));
2843
2844         /* process */
2845         process_2b_bonds(moldyn,&pcc,calculate_pair_correlation_process);
2846
2847         /* normalization */
2848         for(i=1;i<pcc.o1;i++) {
2849                  // normalization: 4 pi r^2 dr
2850                  // here: not double counting pairs -> 2 pi r r dr
2851                  // ... and actually it's a constant times r^2
2852                 norm=i*i*dr*dr;
2853                 pcc.stat[i]/=norm;
2854                 pcc.stat[pcc.o1+i]/=norm;
2855                 pcc.stat[pcc.o2+i]/=norm;
2856         }
2857         /* */
2858
2859         if(ptr==NULL) {
2860                 /* todo: store/print pair correlation function */
2861                 free(pcc.stat);
2862         }
2863
2864         return 0;
2865 }
2866
2867 int bond_analyze_process(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2868                          void *data,u8 bc) {
2869
2870         t_ba *ba;
2871         t_3dvec dist;
2872         double d;
2873
2874         if(itom->tag>=jtom->tag)
2875                 return 0;
2876
2877         /* distance */
2878         v3_sub(&dist,&(jtom->r),&(itom->r));
2879         if(bc) check_per_bound(moldyn,&dist);
2880         d=v3_absolute_square(&dist);
2881
2882         /* ignore if greater or equal cutoff */
2883         if(d>moldyn->cutoff_square)
2884                 return 0;
2885
2886         /* check for potential bond */
2887         if(moldyn->check_2b_bond(moldyn,itom,jtom,bc)==FALSE)
2888                 return 0;
2889
2890         /* now count this bonding ... */
2891         ba=data;
2892
2893         /* increase total bond counter
2894          * ... double counting!
2895          */
2896         ba->tcnt+=2;
2897
2898         if(itom->brand==0)
2899                 ba->acnt[jtom->tag]+=1;
2900         else
2901                 ba->bcnt[jtom->tag]+=1;
2902         
2903         if(jtom->brand==0)
2904                 ba->acnt[itom->tag]+=1;
2905         else
2906                 ba->bcnt[itom->tag]+=1;
2907
2908         return 0;
2909 }
2910
2911 int bond_analyze(t_moldyn *moldyn,double *quality) {
2912
2913         // by now: # bonds of type 'a-4b' and 'b-4a' / # bonds total
2914
2915         int qcnt;
2916         int ccnt,cset;
2917         t_ba ba;
2918         int i;
2919         t_atom *atom;
2920
2921         ba.acnt=malloc(moldyn->count*sizeof(int));
2922         if(ba.acnt==NULL) {
2923                 perror("[moldyn] bond analyze malloc (a)");
2924                 return -1;
2925         }
2926         memset(ba.acnt,0,moldyn->count*sizeof(int));
2927
2928         ba.bcnt=malloc(moldyn->count*sizeof(int));
2929         if(ba.bcnt==NULL) {
2930                 perror("[moldyn] bond analyze malloc (b)");
2931                 return -1;
2932         }
2933         memset(ba.bcnt,0,moldyn->count*sizeof(int));
2934
2935         ba.tcnt=0;
2936         qcnt=0;
2937         ccnt=0;
2938         cset=0;
2939
2940         atom=moldyn->atom;
2941
2942         process_2b_bonds(moldyn,&ba,bond_analyze_process);
2943
2944         for(i=0;i<moldyn->count;i++) {
2945                 if(atom[i].brand==0) {
2946                         if((ba.acnt[i]==0)&(ba.bcnt[i]==4))
2947                                 qcnt+=4;
2948                 }
2949                 else {
2950                         if((ba.acnt[i]==4)&(ba.bcnt[i]==0)) {
2951                                 qcnt+=4;
2952                                 ccnt+=1;
2953                         }
2954                         cset+=1;
2955                 }
2956         }
2957
2958         printf("[moldyn] bond analyze: c_cnt=%d | set=%d\n",ccnt,cset);
2959         printf("[moldyn] bond analyze: q_cnt=%d | tot=%d\n",qcnt,ba.tcnt);
2960
2961         if(quality) {
2962                 quality[0]=1.0*ccnt/cset;
2963                 quality[1]=1.0*qcnt/ba.tcnt;
2964         }
2965         else {
2966                 printf("[moldyn] bond analyze: c_bnd_q=%f\n",1.0*qcnt/ba.tcnt);
2967                 printf("[moldyn] bond analyze:   tot_q=%f\n",1.0*qcnt/ba.tcnt);
2968         }
2969
2970         return 0;
2971 }
2972
2973 /*
2974  * visualization code
2975  */
2976
2977 int visual_init(t_moldyn *moldyn,char *filebase) {
2978
2979         strncpy(moldyn->vis.fb,filebase,128);
2980
2981         return 0;
2982 }
2983
2984 int visual_bonds_process(t_moldyn *moldyn,t_atom *itom,t_atom *jtom,
2985                          void *data,u8 bc) {
2986
2987         t_vb *vb;
2988
2989         vb=data;
2990
2991         if(itom->tag>=jtom->tag)
2992                 return 0;
2993         
2994         if(moldyn->check_2b_bond(moldyn,itom,jtom,bc)==FALSE)
2995                 return 0;
2996
2997         if((itom->attr&ATOM_ATTR_VB)|(jtom->attr&ATOM_ATTR_VB))
2998                 dprintf(vb->fd,"# [B] %f %f %f %f %f %f\n",
2999                         itom->r.x,itom->r.y,itom->r.z,
3000                         jtom->r.x,jtom->r.y,jtom->r.z);
3001
3002         return 0;
3003 }
3004
3005 int visual_atoms(t_moldyn *moldyn) {
3006
3007         int i;
3008         char file[128+64];
3009         t_3dvec dim;
3010         double help;
3011         t_visual *v;
3012         t_atom *atom;
3013         t_vb vb;
3014
3015         v=&(moldyn->vis);
3016         dim.x=v->dim.x;
3017         dim.y=v->dim.y;
3018         dim.z=v->dim.z;
3019         atom=moldyn->atom;
3020
3021         help=(dim.x+dim.y);
3022
3023         sprintf(file,"%s/atomic_conf_%08.f.xyz",v->fb,moldyn->time);
3024         vb.fd=open(file,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
3025         if(vb.fd<0) {
3026                 perror("open visual save file fd");
3027                 return -1;
3028         }
3029
3030         /* write the actual data file */
3031
3032         // povray header
3033         dprintf(vb.fd,"# [P] %d %08.f <%f,%f,%f>\n",
3034                 moldyn->count,moldyn->time,help/40.0,help/40.0,-0.8*help);
3035
3036         // atomic configuration
3037         for(i=0;i<moldyn->count;i++)
3038                 // atom type, positions, color and kinetic energy
3039                 dprintf(vb.fd,"%s %f %f %f %s %f\n",pse_name[atom[i].element],
3040                                                     atom[i].r.x,
3041                                                     atom[i].r.y,
3042                                                     atom[i].r.z,
3043                                                     pse_col[atom[i].element],
3044                                                     atom[i].ekin);
3045         
3046         // bonds between atoms
3047         process_2b_bonds(moldyn,&vb,visual_bonds_process);
3048         
3049         // boundaries
3050         if(dim.x) {
3051                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3052                         -dim.x/2,-dim.y/2,-dim.z/2,
3053                         dim.x/2,-dim.y/2,-dim.z/2);
3054                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3055                         -dim.x/2,-dim.y/2,-dim.z/2,
3056                         -dim.x/2,dim.y/2,-dim.z/2);
3057                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3058                         dim.x/2,dim.y/2,-dim.z/2,
3059                         dim.x/2,-dim.y/2,-dim.z/2);
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
3064                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3065                         -dim.x/2,-dim.y/2,dim.z/2,
3066                         dim.x/2,-dim.y/2,dim.z/2);
3067                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3068                         -dim.x/2,-dim.y/2,dim.z/2,
3069                         -dim.x/2,dim.y/2,dim.z/2);
3070                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3071                         dim.x/2,dim.y/2,dim.z/2,
3072                         dim.x/2,-dim.y/2,dim.z/2);
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
3077                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3078                         -dim.x/2,-dim.y/2,dim.z/2,
3079                         -dim.x/2,-dim.y/2,-dim.z/2);
3080                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3081                         -dim.x/2,dim.y/2,dim.z/2,
3082                         -dim.x/2,dim.y/2,-dim.z/2);
3083                 dprintf(vb.fd,"# [D] %f %f %f %f %f %f\n",
3084                         dim.x/2,-dim.y/2,dim.z/2,
3085                         dim.x/2,-dim.y/2,-dim.z/2);
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         }
3090
3091         close(vb.fd);
3092
3093         return 0;
3094 }
3095
3096 /*
3097  * fpu cntrol functions
3098  */
3099
3100 // set rounding to double (eliminates -ffloat-store!)
3101 int fpu_set_rtd(void) {
3102
3103         fpu_control_t ctrl;
3104
3105         _FPU_GETCW(ctrl);
3106
3107         ctrl&=~_FPU_EXTENDED;
3108         ctrl|=_FPU_DOUBLE;
3109
3110         _FPU_SETCW(ctrl);
3111
3112         return 0;
3113 }
3114