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