safety checkin, gergo here!
[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 <math.h>
17
18 #include "moldyn.h"
19 #include "report/report.h"
20
21 int moldyn_init(t_moldyn *moldyn,int argc,char **argv) {
22
23         printf("[moldyn] init\n");
24
25         memset(moldyn,0,sizeof(t_moldyn));
26
27         rand_init(&(moldyn->random),NULL,1);
28         moldyn->random.status|=RAND_STAT_VERBOSE;
29
30         return 0;
31 }
32
33 int moldyn_shutdown(t_moldyn *moldyn) {
34
35         printf("[moldyn] shutdown\n");
36
37         moldyn_log_shutdown(moldyn);
38         link_cell_shutdown(moldyn);
39         rand_close(&(moldyn->random));
40         free(moldyn->atom);
41
42         return 0;
43 }
44
45 int set_int_alg(t_moldyn *moldyn,u8 algo) {
46
47         printf("[moldyn] integration algorithm: ");
48
49         switch(algo) {
50                 case MOLDYN_INTEGRATE_VERLET:
51                         moldyn->integrate=velocity_verlet;
52                         printf("velocity verlet\n");
53                         break;
54                 default:
55                         printf("unknown integration algorithm: %02x\n",algo);
56                         printf("unknown\n");
57                         return -1;
58         }
59
60         return 0;
61 }
62
63 int set_cutoff(t_moldyn *moldyn,double cutoff) {
64
65         moldyn->cutoff=cutoff;
66
67         printf("[moldyn] cutoff [A]: %f\n",moldyn->cutoff);
68
69         return 0;
70 }
71
72 int set_temperature(t_moldyn *moldyn,double t_ref) {
73
74         moldyn->t_ref=t_ref;
75
76         printf("[moldyn] temperature [K]: %f\n",moldyn->t_ref);
77
78         return 0;
79 }
80
81 int set_pressure(t_moldyn *moldyn,double p_ref) {
82
83         moldyn->p_ref=p_ref;
84
85         printf("[moldyn] pressure [bar]: %f\n",moldyn->p_ref/BAR);
86
87         return 0;
88 }
89
90 int set_pt_scale(t_moldyn *moldyn,u8 ptype,double ptc,u8 ttype,double ttc) {
91
92         moldyn->pt_scale=(ptype|ttype);
93         moldyn->t_tc=ttc;
94         moldyn->p_tc=ptc;
95
96         printf("[moldyn] p/t scaling:\n");
97
98         printf("  p: %s",ptype?"yes":"no ");
99         if(ptype)
100                 printf(" | type: %02x | factor: %f",ptype,ptc);
101         printf("\n");
102
103         printf("  t: %s",ttype?"yes":"no ");
104         if(ttype)
105                 printf(" | type: %02x | factor: %f",ttype,ttc);
106         printf("\n");
107
108         return 0;
109 }
110
111 int set_dim(t_moldyn *moldyn,double x,double y,double z,u8 visualize) {
112
113         moldyn->dim.x=x;
114         moldyn->dim.y=y;
115         moldyn->dim.z=z;
116
117         moldyn->volume=x*y*z;
118
119         if(visualize) {
120                 moldyn->vis.dim.x=x;
121                 moldyn->vis.dim.y=y;
122                 moldyn->vis.dim.z=z;
123         }
124
125         moldyn->dv=0.000001*moldyn->volume;
126
127         printf("[moldyn] dimensions in A and A^3 respectively:\n");
128         printf("  x: %f\n",moldyn->dim.x);
129         printf("  y: %f\n",moldyn->dim.y);
130         printf("  z: %f\n",moldyn->dim.z);
131         printf("  volume: %f\n",moldyn->volume);
132         printf("  visualize simulation box: %s\n",visualize?"yes":"no");
133         printf("  delta volume (pressure calc): %f\n",moldyn->dv);
134
135         return 0;
136 }
137
138 int set_nn_dist(t_moldyn *moldyn,double dist) {
139
140         moldyn->nnd=dist;
141
142         return 0;
143 }
144
145 int set_pbc(t_moldyn *moldyn,u8 x,u8 y,u8 z) {
146
147         printf("[moldyn] periodic boundary conditions:\n");
148
149         if(x)
150                 moldyn->status|=MOLDYN_STAT_PBX;
151
152         if(y)
153                 moldyn->status|=MOLDYN_STAT_PBY;
154
155         if(z)
156                 moldyn->status|=MOLDYN_STAT_PBZ;
157
158         printf("  x: %s\n",x?"yes":"no");
159         printf("  y: %s\n",y?"yes":"no");
160         printf("  z: %s\n",z?"yes":"no");
161
162         return 0;
163 }
164
165 int set_potential1b(t_moldyn *moldyn,pf_func1b func) {
166
167         moldyn->func1b=func;
168
169         return 0;
170 }
171
172 int set_potential2b(t_moldyn *moldyn,pf_func2b func) {
173
174         moldyn->func2b=func;
175
176         return 0;
177 }
178
179 int set_potential3b_j1(t_moldyn *moldyn,pf_func2b func) {
180
181         moldyn->func3b_j1=func;
182
183         return 0;
184 }
185
186 int set_potential3b_j2(t_moldyn *moldyn,pf_func2b func) {
187
188         moldyn->func3b_j2=func;
189
190         return 0;
191 }
192
193 int set_potential3b_j3(t_moldyn *moldyn,pf_func2b func) {
194
195         moldyn->func3b_j3=func;
196
197         return 0;
198 }
199
200 int set_potential3b_k1(t_moldyn *moldyn,pf_func3b func) {
201
202         moldyn->func3b_k1=func;
203
204         return 0;
205 }
206
207 int set_potential3b_k2(t_moldyn *moldyn,pf_func3b func) {
208
209         moldyn->func3b_k2=func;
210
211         return 0;
212 }
213
214 int set_potential_params(t_moldyn *moldyn,void *params) {
215
216         moldyn->pot_params=params;
217
218         return 0;
219 }
220
221 int set_avg_skip(t_moldyn *moldyn,int skip) {
222
223         printf("[moldyn] skip %d steps before starting average calc\n",skip);
224         moldyn->avg_skip=skip;
225
226         return 0;
227 }
228
229 int moldyn_set_log_dir(t_moldyn *moldyn,char *dir) {
230
231         strncpy(moldyn->vlsdir,dir,127);
232
233         return 0;
234 }
235
236 int moldyn_set_report(t_moldyn *moldyn,char *author,char *title) {
237
238         strncpy(moldyn->rauthor,author,63);
239         strncpy(moldyn->rtitle,title,63);
240
241         return 0;
242 }
243         
244 int moldyn_set_log(t_moldyn *moldyn,u8 type,int timer) {
245
246         char filename[128];
247         int ret;
248
249         printf("[moldyn] set log: ");
250
251         switch(type) {
252                 case LOG_TOTAL_ENERGY:
253                         moldyn->ewrite=timer;
254                         snprintf(filename,127,"%s/energy",moldyn->vlsdir);
255                         moldyn->efd=open(filename,
256                                          O_WRONLY|O_CREAT|O_EXCL,
257                                          S_IRUSR|S_IWUSR);
258                         if(moldyn->efd<0) {
259                                 perror("[moldyn] energy log fd open");
260                                 return moldyn->efd;
261                         }
262                         dprintf(moldyn->efd,"# total energy log file\n");
263                         printf("total energy (%d)\n",timer);
264                         break;
265                 case LOG_TOTAL_MOMENTUM:
266                         moldyn->mwrite=timer;
267                         snprintf(filename,127,"%s/momentum",moldyn->vlsdir);
268                         moldyn->mfd=open(filename,
269                                          O_WRONLY|O_CREAT|O_EXCL,
270                                          S_IRUSR|S_IWUSR);
271                         if(moldyn->mfd<0) {
272                                 perror("[moldyn] momentum log fd open");
273                                 return moldyn->mfd;
274                         }
275                         dprintf(moldyn->efd,"# total momentum log file\n");
276                         printf("total momentum (%d)\n",timer);
277                         break;
278                 case LOG_PRESSURE:
279                         moldyn->pwrite=timer;
280                         snprintf(filename,127,"%s/pressure",moldyn->vlsdir);
281                         moldyn->pfd=open(filename,
282                                          O_WRONLY|O_CREAT|O_EXCL,
283                                          S_IRUSR|S_IWUSR);
284                         if(moldyn->pfd<0) {
285                                 perror("[moldyn] pressure log file\n");
286                                 return moldyn->pfd;
287                         }
288                         dprintf(moldyn->pfd,"# pressure log file\n");
289                         printf("pressure (%d)\n",timer);
290                         break;
291                 case LOG_TEMPERATURE:
292                         moldyn->twrite=timer;
293                         snprintf(filename,127,"%s/temperature",moldyn->vlsdir);
294                         moldyn->tfd=open(filename,
295                                          O_WRONLY|O_CREAT|O_EXCL,
296                                          S_IRUSR|S_IWUSR);
297                         if(moldyn->tfd<0) {
298                                 perror("[moldyn] temperature log file\n");
299                                 return moldyn->tfd;
300                         }
301                         dprintf(moldyn->tfd,"# temperature log file\n");
302                         printf("temperature (%d)\n",timer);
303                         break;
304                 case SAVE_STEP:
305                         moldyn->swrite=timer;
306                         printf("save file (%d)\n",timer);
307                         break;
308                 case VISUAL_STEP:
309                         moldyn->vwrite=timer;
310                         ret=visual_init(&(moldyn->vis),moldyn->vlsdir);
311                         if(ret<0) {
312                                 printf("[moldyn] visual init failure\n");
313                                 return ret;
314                         }
315                         printf("visual file (%d)\n",timer);
316                         break;
317                 case CREATE_REPORT:
318                         snprintf(filename,127,"%s/report.tex",moldyn->vlsdir);
319                         moldyn->rfd=open(filename,
320                                          O_WRONLY|O_CREAT|O_EXCL,
321                                          S_IRUSR|S_IWUSR);
322                         if(moldyn->rfd<0) {
323                                 perror("[moldyn] report fd open");      
324                                 return moldyn->rfd;
325                         }
326                         printf("report -> ");
327                         if(moldyn->efd) {
328                                 snprintf(filename,127,"%s/e_plot.scr",
329                                          moldyn->vlsdir);
330                                 moldyn->epfd=open(filename,
331                                                  O_WRONLY|O_CREAT|O_EXCL,
332                                                  S_IRUSR|S_IWUSR);
333                                 if(moldyn->epfd<0) {
334                                         perror("[moldyn] energy plot fd open");
335                                         return moldyn->epfd;
336                                 }
337                                 dprintf(moldyn->epfd,e_plot_script);
338                                 close(moldyn->epfd);
339                                 printf("energy ");
340                         }
341                         if(moldyn->pfd) {
342                                 snprintf(filename,127,"%s/pressure_plot.scr",
343                                          moldyn->vlsdir);
344                                 moldyn->ppfd=open(filename,
345                                                   O_WRONLY|O_CREAT|O_EXCL,
346                                                   S_IRUSR|S_IWUSR);
347                                 if(moldyn->ppfd<0) {
348                                         perror("[moldyn] p plot fd open");
349                                         return moldyn->ppfd;
350                                 }
351                                 dprintf(moldyn->ppfd,pressure_plot_script);
352                                 close(moldyn->ppfd);
353                                 printf("pressure ");
354                         }
355                         if(moldyn->tfd) {
356                                 snprintf(filename,127,"%s/temperature_plot.scr",
357                                          moldyn->vlsdir);
358                                 moldyn->tpfd=open(filename,
359                                                   O_WRONLY|O_CREAT|O_EXCL,
360                                                   S_IRUSR|S_IWUSR);
361                                 if(moldyn->tpfd<0) {
362                                         perror("[moldyn] t plot fd open");
363                                         return moldyn->tpfd;
364                                 }
365                                 dprintf(moldyn->tpfd,temperature_plot_script);
366                                 close(moldyn->tpfd);
367                                 printf("temperature ");
368                         }
369                         dprintf(moldyn->rfd,report_start,
370                                 moldyn->rauthor,moldyn->rtitle);
371                         printf("\n");
372                         break;
373                 default:
374                         printf("unknown log type: %02x\n",type);
375                         return -1;
376         }
377
378         return 0;
379 }
380
381 int moldyn_log_shutdown(t_moldyn *moldyn) {
382
383         char sc[256];
384
385         printf("[moldyn] log shutdown\n");
386         if(moldyn->efd) {
387                 close(moldyn->efd);
388                 if(moldyn->rfd) {
389                         dprintf(moldyn->rfd,report_energy);
390                         snprintf(sc,255,"cd %s && gnuplot e_plot.scr",
391                                  moldyn->vlsdir);
392                         system(sc);
393                 }
394         }
395         if(moldyn->mfd) close(moldyn->mfd);
396         if(moldyn->pfd) {
397                 close(moldyn->pfd);
398                 if(moldyn->rfd)
399                         dprintf(moldyn->rfd,report_pressure);
400                         snprintf(sc,255,"cd %s && gnuplot pressure_plot.scr",
401                                  moldyn->vlsdir);
402                         system(sc);
403         }
404         if(moldyn->tfd) {
405                 close(moldyn->tfd);
406                 if(moldyn->rfd)
407                         dprintf(moldyn->rfd,report_temperature);
408                         snprintf(sc,255,"cd %s && gnuplot temperature_plot.scr",
409                                  moldyn->vlsdir);
410                         system(sc);
411         }
412         if(moldyn->rfd) {
413                 dprintf(moldyn->rfd,report_end);
414                 close(moldyn->rfd);
415                 snprintf(sc,255,"cd %s && pdflatex report >/dev/null 2>&1",
416                          moldyn->vlsdir);
417                 system(sc);
418                 snprintf(sc,255,"cd %s && pdflatex report >/dev/null 2>&1",
419                          moldyn->vlsdir);
420                 system(sc);
421                 snprintf(sc,255,"cd %s && dvipdf report >/dev/null 2>&1",
422                          moldyn->vlsdir);
423                 system(sc);
424         }
425         if(&(moldyn->vis)) visual_tini(&(moldyn->vis));
426
427         return 0;
428 }
429
430 /*
431  * creating lattice functions
432  */
433
434 int create_lattice(t_moldyn *moldyn,u8 type,double lc,int element,double mass,
435                    u8 attr,u8 brand,int a,int b,int c,t_3dvec *origin) {
436
437         int new,count;
438         int ret;
439         t_3dvec orig;
440         void *ptr;
441         t_atom *atom;
442
443         new=a*b*c;
444         count=moldyn->count;
445
446         /* how many atoms do we expect */
447         if(type==CUBIC) new*=1;
448         if(type==FCC) new*=4;
449         if(type==DIAMOND) new*=8;
450
451         /* allocate space for atoms */
452         ptr=realloc(moldyn->atom,(count+new)*sizeof(t_atom));
453         if(!ptr) {
454                 perror("[moldyn] realloc (create lattice)");
455                 return -1;
456         }
457         moldyn->atom=ptr;
458         atom=&(moldyn->atom[count]);
459
460         /* no atoms on the boundaries (only reason: it looks better!) */
461         if(!origin) {
462                 orig.x=0.5*lc;
463                 orig.y=0.5*lc;
464                 orig.z=0.5*lc;
465         }
466         else {
467                 orig.x=origin->x;
468                 orig.y=origin->y;
469                 orig.z=origin->z;
470         }
471
472         switch(type) {
473                 case CUBIC:
474                         set_nn_dist(moldyn,lc);
475                         ret=cubic_init(a,b,c,lc,atom,&orig);
476                         break;
477                 case FCC:
478                         if(!origin)
479                                 v3_scale(&orig,&orig,0.5);
480                         set_nn_dist(moldyn,0.5*sqrt(2.0)*lc);
481                         ret=fcc_init(a,b,c,lc,atom,&orig);
482                         break;
483                 case DIAMOND:
484                         if(!origin)
485                                 v3_scale(&orig,&orig,0.25);
486                         set_nn_dist(moldyn,0.25*sqrt(3.0)*lc);
487                         ret=diamond_init(a,b,c,lc,atom,&orig);
488                         break;
489                 default:
490                         printf("unknown lattice type (%02x)\n",type);
491                         return -1;
492         }
493
494         /* debug */
495         if(ret!=new) {
496                 printf("[moldyn] creating lattice failed\n");
497                 printf("  amount of atoms\n");
498                 printf("  - expected: %d\n",new);
499                 printf("  - created: %d\n",ret);
500                 return -1;
501         }
502
503         moldyn->count+=new;
504         printf("[moldyn] created lattice with %d atoms\n",new);
505
506         for(ret=0;ret<new;ret++) {
507                 atom[ret].element=element;
508                 atom[ret].mass=mass;
509                 atom[ret].attr=attr;
510                 atom[ret].brand=brand;
511                 atom[ret].tag=count+ret;
512                 check_per_bound(moldyn,&(atom[ret].r));
513         }
514
515         /* update total system mass */
516         total_mass_calc(moldyn);
517
518         return ret;
519 }
520
521 /* cubic init */
522 int cubic_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
523
524         int count;
525         t_3dvec r;
526         int i,j,k;
527         t_3dvec o;
528
529         count=0;
530         if(origin)
531                 v3_copy(&o,origin);
532         else
533                 v3_zero(&o);
534
535         r.x=o.x;
536         for(i=0;i<a;i++) {
537                 r.y=o.y;
538                 for(j=0;j<b;j++) {
539                         r.z=o.z;
540                         for(k=0;k<c;k++) {
541                                 v3_copy(&(atom[count].r),&r);
542                                 count+=1;
543                                 r.z+=lc;
544                         }
545                         r.y+=lc;
546                 }
547                 r.x+=lc;
548         }
549
550         for(i=0;i<count;i++) {
551                 atom[i].r.x-=(a*lc)/2.0;
552                 atom[i].r.y-=(b*lc)/2.0;
553                 atom[i].r.z-=(c*lc)/2.0;
554         }
555
556         return count;
557 }
558
559 /* fcc lattice init */
560 int fcc_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
561
562         int count;
563         int i,j,k,l;
564         t_3dvec o,r,n;
565         t_3dvec basis[3];
566
567         count=0;
568         if(origin)
569                 v3_copy(&o,origin);
570         else
571                 v3_zero(&o);
572
573         /* construct the basis */
574         memset(basis,0,3*sizeof(t_3dvec));
575         basis[0].x=0.5*lc;
576         basis[0].y=0.5*lc;
577         basis[1].x=0.5*lc;
578         basis[1].z=0.5*lc;
579         basis[2].y=0.5*lc;
580         basis[2].z=0.5*lc;
581
582         /* fill up the room */
583         r.x=o.x;
584         for(i=0;i<a;i++) {
585                 r.y=o.y;
586                 for(j=0;j<b;j++) {
587                         r.z=o.z;
588                         for(k=0;k<c;k++) {
589                                 /* first atom */
590                                 v3_copy(&(atom[count].r),&r);
591                                 count+=1;
592                                 r.z+=lc;
593                                 /* the three face centered atoms */
594                                 for(l=0;l<3;l++) {
595                                         v3_add(&n,&r,&basis[l]);
596                                         v3_copy(&(atom[count].r),&n);
597                                         count+=1;
598                                 }
599                         }
600                         r.y+=lc;
601                 }
602                 r.x+=lc;
603         }
604                                 
605         /* coordinate transformation */
606         for(i=0;i<count;i++) {
607                 atom[i].r.x-=(a*lc)/2.0;
608                 atom[i].r.y-=(b*lc)/2.0;
609                 atom[i].r.z-=(c*lc)/2.0;
610         }
611
612         return count;
613 }
614
615 int diamond_init(int a,int b,int c,double lc,t_atom *atom,t_3dvec *origin) {
616
617         int count;
618         t_3dvec o;
619
620         count=fcc_init(a,b,c,lc,atom,origin);
621
622         o.x=0.25*lc;
623         o.y=0.25*lc;
624         o.z=0.25*lc;
625
626         if(origin) v3_add(&o,&o,origin);
627
628         count+=fcc_init(a,b,c,lc,&atom[count],&o);
629
630         return count;
631 }
632
633 int add_atom(t_moldyn *moldyn,int element,double mass,u8 brand,u8 attr,
634              t_3dvec *r,t_3dvec *v) {
635
636         t_atom *atom;
637         void *ptr;
638         int count;
639         
640         atom=moldyn->atom;
641         count=(moldyn->count)++;
642
643         ptr=realloc(atom,(count+1)*sizeof(t_atom));
644         if(!ptr) {
645                 perror("[moldyn] realloc (add atom)");
646                 return -1;
647         }
648         moldyn->atom=ptr;
649
650         atom=moldyn->atom;
651         atom[count].r=*r;
652         atom[count].v=*v;
653         atom[count].element=element;
654         atom[count].mass=mass;
655         atom[count].brand=brand;
656         atom[count].tag=count;
657         atom[count].attr=attr;
658
659         /* update total system mass */
660         total_mass_calc(moldyn);
661
662         return 0;
663 }
664
665 int destroy_atoms(t_moldyn *moldyn) {
666
667         if(moldyn->atom) free(moldyn->atom);
668
669         return 0;
670 }
671
672 int thermal_init(t_moldyn *moldyn,u8 equi_init) {
673
674         /*
675          * - gaussian distribution of velocities
676          * - zero total momentum
677          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
678          */
679
680         int i;
681         double v,sigma;
682         t_3dvec p_total,delta;
683         t_atom *atom;
684         t_random *random;
685
686         atom=moldyn->atom;
687         random=&(moldyn->random);
688
689         printf("[moldyn] thermal init (equi init: %s)\n",equi_init?"yes":"no");
690
691         /* gaussian distribution of velocities */
692         v3_zero(&p_total);
693         for(i=0;i<moldyn->count;i++) {
694                 sigma=sqrt(2.0*K_BOLTZMANN*moldyn->t_ref/atom[i].mass);
695                 /* x direction */
696                 v=sigma*rand_get_gauss(random);
697                 atom[i].v.x=v;
698                 p_total.x+=atom[i].mass*v;
699                 /* y direction */
700                 v=sigma*rand_get_gauss(random);
701                 atom[i].v.y=v;
702                 p_total.y+=atom[i].mass*v;
703                 /* z direction */
704                 v=sigma*rand_get_gauss(random);
705                 atom[i].v.z=v;
706                 p_total.z+=atom[i].mass*v;
707         }
708
709         /* zero total momentum */
710         v3_scale(&p_total,&p_total,1.0/moldyn->count);
711         for(i=0;i<moldyn->count;i++) {
712                 v3_scale(&delta,&p_total,1.0/atom[i].mass);
713                 v3_sub(&(atom[i].v),&(atom[i].v),&delta);
714         }
715
716         /* velocity scaling */
717         scale_velocity(moldyn,equi_init);
718
719         return 0;
720 }
721
722 double total_mass_calc(t_moldyn *moldyn) {
723
724         int i;
725
726         moldyn->mass=0.0;
727
728         for(i=0;i<moldyn->count;i++)
729                 moldyn->mass+=moldyn->atom[i].mass;
730
731         return moldyn->mass;
732 }
733
734 double temperature_calc(t_moldyn *moldyn) {
735
736         /* assume up to date kinetic energy, which is 3/2 N k_B T */
737
738         moldyn->t=(2.0*moldyn->ekin)/(3.0*K_BOLTZMANN*moldyn->count);
739
740         return moldyn->t;
741 }
742
743 double get_temperature(t_moldyn *moldyn) {
744
745         return moldyn->t;
746 }
747
748 int scale_velocity(t_moldyn *moldyn,u8 equi_init) {
749
750         int i;
751         double e,scale;
752         t_atom *atom;
753         int count;
754
755         atom=moldyn->atom;
756
757         /*
758          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
759          */
760
761         /* get kinetic energy / temperature & count involved atoms */
762         e=0.0;
763         count=0;
764         for(i=0;i<moldyn->count;i++) {
765                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB)) {
766                         e+=atom[i].mass*v3_absolute_square(&(atom[i].v));
767                         count+=1;
768                 }
769         }
770         e*=0.5;
771         if(count!=0) moldyn->t=e/(1.5*count*K_BOLTZMANN);
772         else return 0;  /* no atoms involved in scaling! */
773         
774         /* (temporary) hack for e,t = 0 */
775         if(e==0.0) {
776         moldyn->t=0.0;
777                 if(moldyn->t_ref!=0.0) {
778                         thermal_init(moldyn,equi_init);
779                         return 0;
780                 }
781                 else
782                         return 0; /* no scaling needed */
783         }
784
785
786         /* get scaling factor */
787         scale=moldyn->t_ref/moldyn->t;
788         if(equi_init&TRUE)
789                 scale*=2.0;
790         else
791                 if(moldyn->pt_scale&T_SCALE_BERENDSEN)
792                         scale=1.0+(scale-1.0)/moldyn->t_tc;
793         scale=sqrt(scale);
794
795         /* velocity scaling */
796         for(i=0;i<moldyn->count;i++) {
797                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB))
798                         v3_scale(&(atom[i].v),&(atom[i].v),scale);
799         }
800
801         return 0;
802 }
803
804 double ideal_gas_law_pressure(t_moldyn *moldyn) {
805
806         double p;
807
808         p=moldyn->count*moldyn->t*K_BOLTZMANN/moldyn->volume;
809
810         return p;
811 }
812
813 double pressure_calc(t_moldyn *moldyn) {
814
815         int i;
816         double v;
817         t_virial *virial;
818
819         /*
820          * PV = NkT + <W>
821          * with W = 1/3 sum_i f_i r_i (- skipped!)
822          * virial = sum_i f_i r_i
823          * 
824          * => P = (2 Ekin + virial) / (3V)
825          */
826
827         v=0.0;
828         for(i=0;i<moldyn->count;i++) {
829                 virial=&(moldyn->atom[i].virial);
830                 v+=(virial->xx+virial->yy+virial->zz);
831         }
832
833         /* virial sum and average virial */
834         if(moldyn->total_steps>=moldyn->avg_skip) {
835                 moldyn->virial_sum+=v;
836                 moldyn->virial_avg=moldyn->virial_sum/
837                                    (moldyn->total_steps+1-moldyn->avg_skip);
838                 moldyn->p=2.0*moldyn->k_avg+moldyn->virial_avg;
839                 moldyn->p/=(3.0*moldyn->volume);
840                 moldyn->p_sum+=moldyn->p;
841                 moldyn->p_avg=moldyn->p_sum/
842                               (moldyn->total_steps+1-moldyn->avg_skip);
843         }
844
845         /* pressure from 'absolute coordinates' virial */
846         virial=&(moldyn->virial);
847         v=virial->xx+virial->yy+virial->zz;
848         moldyn->gp=2.0*moldyn->ekin+v;
849         moldyn->gp/=(3.0*moldyn->volume);
850         if(moldyn->total_steps>=moldyn->avg_skip) {
851                 moldyn->gp_sum+=moldyn->gp;
852                 moldyn->gp_avg=moldyn->gp_sum/
853                                (moldyn->total_steps+1-moldyn->avg_skip);
854         }
855
856         return moldyn->p;
857 }
858
859 int average_and_fluctuation_calc(t_moldyn *moldyn) {
860
861         if(moldyn->total_steps<moldyn->avg_skip)
862                 return 0;
863
864         /* assume up to date energies, temperature, pressure etc */
865
866         /* kinetic energy */
867         moldyn->k_sum+=moldyn->ekin;
868         moldyn->k2_sum+=(moldyn->ekin*moldyn->ekin);
869         moldyn->k_avg=moldyn->k_sum/(moldyn->total_steps+1-moldyn->avg_skip);
870         moldyn->k2_avg=moldyn->k2_sum/(moldyn->total_steps+1-moldyn->avg_skip);
871         moldyn->dk2_avg=moldyn->k2_avg-(moldyn->k_avg*moldyn->k_avg);
872
873         /* potential energy */
874         moldyn->v_sum+=moldyn->energy;
875         moldyn->v2_sum+=(moldyn->energy*moldyn->energy);
876         moldyn->v_avg=moldyn->v_sum/(moldyn->total_steps+1-moldyn->avg_skip);
877         moldyn->v2_avg=moldyn->v2_sum/(moldyn->total_steps+1-moldyn->avg_skip);
878         moldyn->dv2_avg=moldyn->v2_avg-(moldyn->v_avg*moldyn->v_avg);
879
880         /* temperature */
881         moldyn->t_sum+=moldyn->t;
882         moldyn->t_avg=moldyn->t_sum/(moldyn->total_steps+1-moldyn->avg_skip);
883
884         /* virial */
885         
886
887         /* pressure */
888
889
890         return 0;
891 }
892
893 int get_heat_capacity(t_moldyn *moldyn) {
894
895         double temp2,ighc;
896
897         /* averages needed for heat capacity calc */
898         if(moldyn->total_steps<moldyn->avg_skip)
899                 return 0;
900
901         /* (temperature average)^2 */
902         temp2=moldyn->t_avg*moldyn->t_avg;
903         printf("[moldyn] specific heat capacity for T=%f K [J/(kg K)]\n",
904                moldyn->t_avg);
905
906         /* ideal gas contribution */
907         ighc=3.0*moldyn->count*K_BOLTZMANN/2.0;
908         printf("  ideal gas contribution: %f\n",
909                ighc/moldyn->mass*KILOGRAM/JOULE);
910
911         /* specific heat for nvt ensemble */
912         moldyn->c_v_nvt=moldyn->dv2_avg/(K_BOLTZMANN*temp2)+ighc;
913         moldyn->c_v_nvt/=moldyn->mass;
914
915         /* specific heat for nve ensemble */
916         moldyn->c_v_nve=ighc/(1.0-(moldyn->dv2_avg/(ighc*K_BOLTZMANN*temp2)));
917         moldyn->c_v_nve/=moldyn->mass;
918
919         printf("  NVE: %f\n",moldyn->c_v_nve*KILOGRAM/JOULE);
920         printf("  NVT: %f\n",moldyn->c_v_nvt*KILOGRAM/JOULE);
921 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)));
922
923         return 0;
924 }
925
926 double thermodynamic_pressure_calc(t_moldyn *moldyn) {
927
928         t_3dvec dim,*tp;
929         double u_up,u_down,dv;
930         double scale,p;
931         t_atom *store;
932
933         /*
934          * dU = - p dV
935          *
936          * => p = - dU/dV
937          *
938          */
939
940         scale=0.00001;
941         dv=8*scale*scale*scale*moldyn->volume;
942
943         store=malloc(moldyn->count*sizeof(t_atom));
944         if(store==NULL) {
945                 printf("[moldyn] allocating store mem failed\n");
946                 return -1;
947         }
948
949         /* save unscaled potential energy + atom/dim configuration */
950         memcpy(store,moldyn->atom,moldyn->count*sizeof(t_atom));
951         dim=moldyn->dim;
952
953         /* scale up dimension and atom positions */
954         scale_dim(moldyn,SCALE_UP,scale,TRUE,TRUE,TRUE);
955         scale_atoms(moldyn,SCALE_UP,scale,TRUE,TRUE,TRUE);
956         link_cell_shutdown(moldyn);
957         link_cell_init(moldyn,QUIET);
958         potential_force_calc(moldyn);
959         u_up=moldyn->energy;
960
961         /* restore atomic configuration + dim */
962         memcpy(moldyn->atom,store,moldyn->count*sizeof(t_atom));
963         moldyn->dim=dim;
964
965         /* scale down dimension and atom positions */
966         scale_dim(moldyn,SCALE_DOWN,scale,TRUE,TRUE,TRUE);
967         scale_atoms(moldyn,SCALE_DOWN,scale,TRUE,TRUE,TRUE);
968         link_cell_shutdown(moldyn);
969         link_cell_init(moldyn,QUIET);
970         potential_force_calc(moldyn);
971         u_down=moldyn->energy;
972         
973         /* calculate pressure */
974         p=-(u_up-u_down)/dv;
975 printf("-------> %.10f %.10f %f\n",u_up/EV/moldyn->count,u_down/EV/moldyn->count,p/BAR);
976
977         /* restore atomic configuration + dim */
978         memcpy(moldyn->atom,store,moldyn->count*sizeof(t_atom));
979         moldyn->dim=dim;
980
981         /* restore energy */
982         potential_force_calc(moldyn);
983
984         link_cell_shutdown(moldyn);
985         link_cell_init(moldyn,QUIET);
986
987         return p;
988 }
989
990 double get_pressure(t_moldyn *moldyn) {
991
992         return moldyn->p;
993
994 }
995
996 int scale_dim(t_moldyn *moldyn,u8 dir,double scale,u8 x,u8 y,u8 z) {
997
998         t_3dvec *dim;
999
1000         dim=&(moldyn->dim);
1001
1002         if(dir==SCALE_UP)
1003                 scale=1.0+scale;
1004
1005         if(dir==SCALE_DOWN)
1006                 scale=1.0-scale;
1007
1008         if(x) dim->x*=scale;
1009         if(y) dim->y*=scale;
1010         if(z) dim->z*=scale;
1011
1012         return 0;
1013 }
1014
1015 int scale_atoms(t_moldyn *moldyn,u8 dir,double scale,u8 x,u8 y,u8 z) {
1016
1017         int i;
1018         t_3dvec *r;
1019
1020         if(dir==SCALE_UP)
1021                 scale=1.0+scale;
1022
1023         if(dir==SCALE_DOWN)
1024                 scale=1.0-scale;
1025
1026         for(i=0;i<moldyn->count;i++) {
1027                 r=&(moldyn->atom[i].r);
1028                 if(x) r->x*=scale;
1029                 if(y) r->y*=scale;
1030                 if(z) r->z*=scale;
1031         }
1032
1033         return 0;
1034 }
1035
1036 int scale_volume(t_moldyn *moldyn) {
1037
1038         t_3dvec *dim,*vdim;
1039         double scale;
1040         t_linkcell *lc;
1041
1042         vdim=&(moldyn->vis.dim);
1043         dim=&(moldyn->dim);
1044         lc=&(moldyn->lc);
1045
1046         /* scaling factor */
1047         if(moldyn->pt_scale&P_SCALE_BERENDSEN) {
1048                 scale=1.0-(moldyn->p_ref-moldyn->p)/moldyn->p_tc;
1049                 scale=pow(scale,ONE_THIRD);
1050         }
1051         else {
1052                 scale=pow(moldyn->p/moldyn->p_ref,ONE_THIRD);
1053         }
1054 moldyn->debug=scale;
1055
1056         /* scale the atoms and dimensions */
1057         scale_atoms(moldyn,SCALE_DIRECT,scale,TRUE,TRUE,TRUE);
1058         scale_dim(moldyn,SCALE_DIRECT,scale,TRUE,TRUE,TRUE);
1059
1060         /* visualize dimensions */
1061         if(vdim->x!=0) {
1062                 vdim->x=dim->x;
1063                 vdim->y=dim->y;
1064                 vdim->z=dim->z;
1065         }
1066
1067         /* recalculate scaled volume */
1068         moldyn->volume=dim->x*dim->y*dim->z;
1069
1070         /* adjust/reinit linkcell */
1071         if(((int)(dim->x/moldyn->cutoff)!=lc->nx)||
1072            ((int)(dim->y/moldyn->cutoff)!=lc->ny)||
1073            ((int)(dim->z/moldyn->cutoff)!=lc->nx)) {
1074                 link_cell_shutdown(moldyn);
1075                 link_cell_init(moldyn,QUIET);
1076         } else {
1077                 lc->x*=scale;
1078                 lc->y*=scale;
1079                 lc->z*=scale;
1080         }
1081
1082         return 0;
1083
1084 }
1085
1086 double e_kin_calc(t_moldyn *moldyn) {
1087
1088         int i;
1089         t_atom *atom;
1090
1091         atom=moldyn->atom;
1092         moldyn->ekin=0.0;
1093
1094         for(i=0;i<moldyn->count;i++)
1095                 moldyn->ekin+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
1096
1097         return moldyn->ekin;
1098 }
1099
1100 double get_total_energy(t_moldyn *moldyn) {
1101
1102         return(moldyn->ekin+moldyn->energy);
1103 }
1104
1105 t_3dvec get_total_p(t_moldyn *moldyn) {
1106
1107         t_3dvec p,p_total;
1108         int i;
1109         t_atom *atom;
1110
1111         atom=moldyn->atom;
1112
1113         v3_zero(&p_total);
1114         for(i=0;i<moldyn->count;i++) {
1115                 v3_scale(&p,&(atom[i].v),atom[i].mass);
1116                 v3_add(&p_total,&p_total,&p);
1117         }
1118
1119         return p_total;
1120 }
1121
1122 double estimate_time_step(t_moldyn *moldyn,double nn_dist) {
1123
1124         double tau;
1125
1126         /* nn_dist is the nearest neighbour distance */
1127
1128         tau=(0.05*nn_dist*moldyn->atom[0].mass)/sqrt(3.0*K_BOLTZMANN*moldyn->t);
1129
1130         return tau;     
1131 }
1132
1133 /*
1134  * numerical tricks
1135  */
1136
1137 /* linked list / cell method */
1138
1139 int link_cell_init(t_moldyn *moldyn,u8 vol) {
1140
1141         t_linkcell *lc;
1142         int i;
1143
1144         lc=&(moldyn->lc);
1145
1146         /* partitioning the md cell */
1147         lc->nx=moldyn->dim.x/moldyn->cutoff;
1148         lc->x=moldyn->dim.x/lc->nx;
1149         lc->ny=moldyn->dim.y/moldyn->cutoff;
1150         lc->y=moldyn->dim.y/lc->ny;
1151         lc->nz=moldyn->dim.z/moldyn->cutoff;
1152         lc->z=moldyn->dim.z/lc->nz;
1153
1154         lc->cells=lc->nx*lc->ny*lc->nz;
1155         lc->subcell=malloc(lc->cells*sizeof(t_list));
1156
1157         if(lc->cells<27)
1158                 printf("[moldyn] FATAL: less then 27 subcells!\n");
1159
1160         if(vol) {
1161                 printf("[moldyn] initializing linked cells (%d)\n",lc->cells);
1162                 printf("  x: %d x %f A\n",lc->nx,lc->x);
1163                 printf("  y: %d x %f A\n",lc->ny,lc->y);
1164                 printf("  z: %d x %f A\n",lc->nz,lc->z);
1165         }
1166
1167         for(i=0;i<lc->cells;i++)
1168                 list_init_f(&(lc->subcell[i]));
1169
1170         link_cell_update(moldyn);
1171         
1172         return 0;
1173 }
1174
1175 int link_cell_update(t_moldyn *moldyn) {
1176
1177         int count,i,j,k;
1178         int nx,ny;
1179         t_atom *atom;
1180         t_linkcell *lc;
1181         double x,y,z;
1182
1183         atom=moldyn->atom;
1184         lc=&(moldyn->lc);
1185
1186         nx=lc->nx;
1187         ny=lc->ny;
1188
1189         x=moldyn->dim.x/2;
1190         y=moldyn->dim.y/2;
1191         z=moldyn->dim.z/2;
1192
1193         for(i=0;i<lc->cells;i++)
1194                 list_destroy_f(&(lc->subcell[i]));
1195         
1196         for(count=0;count<moldyn->count;count++) {
1197                 i=((atom[count].r.x+(moldyn->dim.x/2))/lc->x);
1198                 j=((atom[count].r.y+(moldyn->dim.y/2))/lc->y);
1199                 k=((atom[count].r.z+(moldyn->dim.z/2))/lc->z);
1200                 list_add_immediate_f(&(lc->subcell[i+j*nx+k*nx*ny]),
1201                                      &(atom[count]));
1202         }
1203
1204         return 0;
1205 }
1206
1207 int link_cell_neighbour_index(t_moldyn *moldyn,int i,int j,int k,t_list *cell) {
1208
1209         t_linkcell *lc;
1210         int a;
1211         int count1,count2;
1212         int ci,cj,ck;
1213         int nx,ny,nz;
1214         int x,y,z;
1215         u8 bx,by,bz;
1216
1217         lc=&(moldyn->lc);
1218         nx=lc->nx;
1219         ny=lc->ny;
1220         nz=lc->nz;
1221         count1=1;
1222         count2=27;
1223         a=nx*ny;
1224
1225         cell[0]=lc->subcell[i+j*nx+k*a];
1226         for(ci=-1;ci<=1;ci++) {
1227                 bx=0;
1228                 x=i+ci;
1229                 if((x<0)||(x>=nx)) {
1230                         x=(x+nx)%nx;
1231                         bx=1;
1232                 }
1233                 for(cj=-1;cj<=1;cj++) {
1234                         by=0;
1235                         y=j+cj;
1236                         if((y<0)||(y>=ny)) {
1237                                 y=(y+ny)%ny;
1238                                 by=1;
1239                         }
1240                         for(ck=-1;ck<=1;ck++) {
1241                                 bz=0;
1242                                 z=k+ck;
1243                                 if((z<0)||(z>=nz)) {
1244                                         z=(z+nz)%nz;
1245                                         bz=1;
1246                                 }
1247                                 if(!(ci|cj|ck)) continue;
1248                                 if(bx|by|bz) {
1249                                         cell[--count2]=lc->subcell[x+y*nx+z*a];
1250                                 }
1251                                 else {
1252                                         cell[count1++]=lc->subcell[x+y*nx+z*a];
1253                                 }
1254                         }
1255                 }
1256         }
1257
1258         lc->dnlc=count1;
1259
1260         return count1;
1261 }
1262
1263 int link_cell_shutdown(t_moldyn *moldyn) {
1264
1265         int i;
1266         t_linkcell *lc;
1267
1268         lc=&(moldyn->lc);
1269
1270         for(i=0;i<lc->nx*lc->ny*lc->nz;i++)
1271                 list_destroy_f(&(moldyn->lc.subcell[i]));
1272
1273         free(lc->subcell);
1274
1275         return 0;
1276 }
1277
1278 int moldyn_add_schedule(t_moldyn *moldyn,int runs,double tau) {
1279
1280         int count;
1281         void *ptr;
1282         t_moldyn_schedule *schedule;
1283
1284         schedule=&(moldyn->schedule);
1285         count=++(schedule->total_sched);
1286
1287         ptr=realloc(schedule->runs,count*sizeof(int));
1288         if(!ptr) {
1289                 perror("[moldyn] realloc (runs)");
1290                 return -1;
1291         }
1292         schedule->runs=ptr;
1293         schedule->runs[count-1]=runs;
1294
1295         ptr=realloc(schedule->tau,count*sizeof(double));
1296         if(!ptr) {
1297                 perror("[moldyn] realloc (tau)");
1298                 return -1;
1299         }
1300         schedule->tau=ptr;
1301         schedule->tau[count-1]=tau;
1302
1303         printf("[moldyn] schedule added:\n");
1304         printf("  number: %d | runs: %d | tau: %f\n",count-1,runs,tau);
1305                                        
1306
1307         return 0;
1308 }
1309
1310 int moldyn_set_schedule_hook(t_moldyn *moldyn,set_hook hook,void *hook_params) {
1311
1312         moldyn->schedule.hook=hook;
1313         moldyn->schedule.hook_params=hook_params;
1314         
1315         return 0;
1316 }
1317
1318 /*
1319  *
1320  * 'integration of newtons equation' - algorithms
1321  *
1322  */
1323
1324 /* start the integration */
1325
1326 int moldyn_integrate(t_moldyn *moldyn) {
1327
1328         int i;
1329         unsigned int e,m,s,v,p,t;
1330         t_3dvec momentum;
1331         t_moldyn_schedule *sched;
1332         t_atom *atom;
1333         int fd;
1334         char dir[128];
1335         double ds;
1336         double energy_scale;
1337         //double tp;
1338
1339         sched=&(moldyn->schedule);
1340         atom=moldyn->atom;
1341
1342         /* initialize linked cell method */
1343         link_cell_init(moldyn,VERBOSE);
1344
1345         /* logging & visualization */
1346         e=moldyn->ewrite;
1347         m=moldyn->mwrite;
1348         s=moldyn->swrite;
1349         v=moldyn->vwrite;
1350         p=moldyn->pwrite;
1351         t=moldyn->twrite;
1352
1353         /* sqaure of some variables */
1354         moldyn->tau_square=moldyn->tau*moldyn->tau;
1355         moldyn->cutoff_square=moldyn->cutoff*moldyn->cutoff;
1356
1357         /* energy scaling factor */
1358         energy_scale=moldyn->count*EV;
1359
1360         /* calculate initial forces */
1361         potential_force_calc(moldyn);
1362 #ifdef DEBUG
1363 return 0;
1364 #endif
1365
1366         /* some stupid checks before we actually start calculating bullshit */
1367         if(moldyn->cutoff>0.5*moldyn->dim.x)
1368                 printf("[moldyn] warning: cutoff > 0.5 x dim.x\n");
1369         if(moldyn->cutoff>0.5*moldyn->dim.y)
1370                 printf("[moldyn] warning: cutoff > 0.5 x dim.y\n");
1371         if(moldyn->cutoff>0.5*moldyn->dim.z)
1372                 printf("[moldyn] warning: cutoff > 0.5 x dim.z\n");
1373         ds=0.5*atom[0].f.x*moldyn->tau_square/atom[0].mass;
1374         if(ds>0.05*moldyn->nnd)
1375                 printf("[moldyn] warning: forces too high / tau too small!\n");
1376
1377         /* zero absolute time */
1378         moldyn->time=0.0;
1379         moldyn->total_steps=0;
1380
1381         /* debugging, ignore */
1382         moldyn->debug=0;
1383
1384         /* tell the world */
1385         printf("[moldyn] integration start, go get a coffee ...\n");
1386
1387         /* executing the schedule */
1388         for(sched->count=0;sched->count<sched->total_sched;sched->count++) {
1389
1390                 /* setting amount of runs and finite time step size */
1391                 moldyn->tau=sched->tau[sched->count];
1392                 moldyn->tau_square=moldyn->tau*moldyn->tau;
1393                 moldyn->time_steps=sched->runs[sched->count];
1394
1395         /* integration according to schedule */
1396
1397         for(i=0;i<moldyn->time_steps;i++) {
1398
1399                 /* integration step */
1400                 moldyn->integrate(moldyn);
1401
1402                 /* calculate kinetic energy, temperature and pressure */
1403                 e_kin_calc(moldyn);
1404                 temperature_calc(moldyn);
1405                 pressure_calc(moldyn);
1406                 average_and_fluctuation_calc(moldyn);
1407
1408                 /* p/t scaling */
1409                 if(moldyn->pt_scale&(T_SCALE_BERENDSEN|T_SCALE_DIRECT))
1410                         scale_velocity(moldyn,FALSE);
1411                 if(moldyn->pt_scale&(P_SCALE_BERENDSEN|P_SCALE_DIRECT))
1412                         scale_volume(moldyn);
1413
1414                 /* check for log & visualization */
1415                 if(e) {
1416                         if(!(i%e))
1417                                 dprintf(moldyn->efd,
1418                                         "%f %f %f %f\n",
1419                                         moldyn->time,moldyn->ekin/energy_scale,
1420                                         moldyn->energy/energy_scale,
1421                                         get_total_energy(moldyn)/energy_scale);
1422                 }
1423                 if(m) {
1424                         if(!(i%m)) {
1425                                 momentum=get_total_p(moldyn);
1426                                 dprintf(moldyn->mfd,
1427                                         "%f %f %f %f %f\n",moldyn->time,
1428                                         momentum.x,momentum.y,momentum.z,
1429                                         v3_norm(&momentum));
1430                         }
1431                 }
1432                 if(p) {
1433                         if(!(i%p)) {
1434                                 dprintf(moldyn->pfd,
1435                                         "%f %f %f %f %f\n",moldyn->time,
1436                                          moldyn->p/BAR,moldyn->p_avg/BAR,
1437                                          moldyn->gp/BAR,moldyn->gp_avg/BAR);
1438                         }
1439                 }
1440                 if(t) {
1441                         if(!(i%t)) {
1442                                 dprintf(moldyn->tfd,
1443                                         "%f %f %f\n",
1444                                         moldyn->time,moldyn->t,moldyn->t_avg);
1445                         }
1446                 }
1447                 if(s) {
1448                         if(!(i%s)) {
1449                                 snprintf(dir,128,"%s/s-%07.f.save",
1450                                          moldyn->vlsdir,moldyn->time);
1451                                 fd=open(dir,O_WRONLY|O_TRUNC|O_CREAT);
1452                                 if(fd<0) perror("[moldyn] save fd open");
1453                                 else {
1454                                         write(fd,moldyn,sizeof(t_moldyn));
1455                                         write(fd,moldyn->atom,
1456                                               moldyn->count*sizeof(t_atom));
1457                                 }
1458                                 close(fd);
1459                         }       
1460                 }
1461                 if(v) {
1462                         if(!(i%v)) {
1463                                 visual_atoms(&(moldyn->vis),moldyn->time,
1464                                              moldyn->atom,moldyn->count);
1465                         }
1466                 }
1467
1468                 /* display progress */
1469                 if(!(i%10)) {
1470                         printf("\rsched: %d, steps: %d, T: %f, P: %f %f V: %f",
1471                                sched->count,i,
1472                                moldyn->t_avg,
1473                                //moldyn->p_avg/BAR,
1474                                moldyn->p/BAR,
1475                                moldyn->gp_avg/BAR,
1476                                moldyn->volume);
1477                         fflush(stdout);
1478                 }
1479
1480                 /* increase absolute time */
1481                 moldyn->time+=moldyn->tau;
1482                 moldyn->total_steps+=1;
1483
1484         }
1485
1486                 /* check for hooks */
1487                 if(sched->count+1<sched->total_sched)
1488                         if(sched->hook) {
1489                                 printf("\n ## schedule hook %d/%d start ##\n",
1490                                        sched->count+1,sched->total_sched);
1491                                 sched->hook(moldyn,sched->hook_params);
1492                                 printf(" ## schedule hook end ##\n");
1493                         }
1494
1495         }
1496
1497         return 0;
1498 }
1499
1500 /* velocity verlet */
1501
1502 int velocity_verlet(t_moldyn *moldyn) {
1503
1504         int i,count;
1505         double tau,tau_square,h;
1506         t_3dvec delta;
1507         t_atom *atom;
1508
1509         atom=moldyn->atom;
1510         count=moldyn->count;
1511         tau=moldyn->tau;
1512         tau_square=moldyn->tau_square;
1513
1514         for(i=0;i<count;i++) {
1515                 /* new positions */
1516                 h=0.5/atom[i].mass;
1517                 v3_scale(&delta,&(atom[i].v),tau);
1518                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
1519                 v3_scale(&delta,&(atom[i].f),h*tau_square);
1520                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
1521                 check_per_bound(moldyn,&(atom[i].r));
1522
1523                 /* velocities [actually v(t+tau/2)] */
1524                 v3_scale(&delta,&(atom[i].f),h*tau);
1525                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
1526         }
1527
1528         /* neighbour list update */
1529         link_cell_update(moldyn);
1530
1531         /* forces depending on chosen potential */
1532         potential_force_calc(moldyn);
1533
1534         for(i=0;i<count;i++) {
1535                 /* again velocities [actually v(t+tau)] */
1536                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
1537                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
1538         }
1539
1540         return 0;
1541 }
1542
1543
1544 /*
1545  *
1546  * potentials & corresponding forces & virial routine
1547  * 
1548  */
1549
1550 /* generic potential and force calculation */
1551
1552 int potential_force_calc(t_moldyn *moldyn) {
1553
1554         int i,j,k,count;
1555         t_atom *itom,*jtom,*ktom;
1556         t_virial *virial;
1557         t_linkcell *lc;
1558         t_list neighbour_i[27];
1559         t_list neighbour_i2[27];
1560         t_list *this,*that;
1561         u8 bc_ij,bc_ik;
1562         int dnlc;
1563
1564         count=moldyn->count;
1565         itom=moldyn->atom;
1566         lc=&(moldyn->lc);
1567
1568         /* reset energy */
1569         moldyn->energy=0.0;
1570
1571         /* reset global virial */
1572         memset(&(moldyn->virial),0,sizeof(t_virial));
1573
1574         /* reset force, site energy and virial of every atom */
1575         for(i=0;i<count;i++) {
1576
1577                 /* reset force */
1578                 v3_zero(&(itom[i].f));
1579
1580                 /* reset virial */
1581                 virial=(&(itom[i].virial));
1582                 virial->xx=0.0;
1583                 virial->yy=0.0;
1584                 virial->zz=0.0;
1585                 virial->xy=0.0;
1586                 virial->xz=0.0;
1587                 virial->yz=0.0;
1588         
1589                 /* reset site energy */
1590                 itom[i].e=0.0;
1591
1592         }
1593
1594         /* get energy, force and virial of every atom */
1595
1596         /* first (and only) loop over atoms i */
1597         for(i=0;i<count;i++) {
1598
1599                 /* single particle potential/force */
1600                 if(itom[i].attr&ATOM_ATTR_1BP)
1601                         if(moldyn->func1b)
1602                                 moldyn->func1b(moldyn,&(itom[i]));
1603
1604                 if(!(itom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)))
1605                         continue;
1606
1607                 /* 2 body pair potential/force */
1608         
1609                 link_cell_neighbour_index(moldyn,
1610                                           (itom[i].r.x+moldyn->dim.x/2)/lc->x,
1611                                           (itom[i].r.y+moldyn->dim.y/2)/lc->y,
1612                                           (itom[i].r.z+moldyn->dim.z/2)/lc->z,
1613                                           neighbour_i);
1614
1615                 dnlc=lc->dnlc;
1616
1617                 /* first loop over atoms j */
1618                 if(moldyn->func2b) {
1619                         for(j=0;j<27;j++) {
1620
1621                                 this=&(neighbour_i[j]);
1622                                 list_reset_f(this);
1623
1624                                 if(this->start==NULL)
1625                                         continue;
1626
1627                                 bc_ij=(j<dnlc)?0:1;
1628
1629                                 do {
1630                                         jtom=this->current->data;
1631
1632                                         if(jtom==&(itom[i]))
1633                                                 continue;
1634
1635                                         if((jtom->attr&ATOM_ATTR_2BP)&
1636                                            (itom[i].attr&ATOM_ATTR_2BP)) {
1637                                                 moldyn->func2b(moldyn,
1638                                                                &(itom[i]),
1639                                                                jtom,
1640                                                                bc_ij);
1641                                         }
1642                                 } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
1643
1644                         }
1645                 }
1646
1647                 /* 3 body potential/force */
1648
1649                 if(!(itom[i].attr&ATOM_ATTR_3BP))
1650                         continue;
1651
1652                 /* copy the neighbour lists */
1653                 memcpy(neighbour_i2,neighbour_i,27*sizeof(t_list));
1654
1655                 /* second loop over atoms j */
1656                 for(j=0;j<27;j++) {
1657
1658                         this=&(neighbour_i[j]);
1659                         list_reset_f(this);
1660
1661                         if(this->start==NULL)
1662                                 continue;
1663
1664                         bc_ij=(j<dnlc)?0:1;
1665
1666                         do {
1667                                 jtom=this->current->data;
1668
1669                                 if(jtom==&(itom[i]))
1670                                         continue;
1671
1672                                 if(!(jtom->attr&ATOM_ATTR_3BP))
1673                                         continue;
1674
1675                                 /* reset 3bp run */
1676                                 moldyn->run3bp=1;
1677
1678                                 if(moldyn->func3b_j1)
1679                                         moldyn->func3b_j1(moldyn,
1680                                                           &(itom[i]),
1681                                                           jtom,
1682                                                           bc_ij);
1683
1684                                 /* in first j loop, 3bp run can be skipped */
1685                                 if(!(moldyn->run3bp))
1686                                         continue;
1687                         
1688                                 /* first loop over atoms k */
1689                                 if(moldyn->func3b_k1) {
1690
1691                                 for(k=0;k<27;k++) {
1692
1693                                         that=&(neighbour_i2[k]);
1694                                         list_reset_f(that);
1695                                         
1696                                         if(that->start==NULL)
1697                                                 continue;
1698
1699                                         bc_ik=(k<dnlc)?0:1;
1700
1701                                         do {
1702
1703                                                 ktom=that->current->data;
1704
1705                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
1706                                                         continue;
1707
1708                                                 if(ktom==jtom)
1709                                                         continue;
1710
1711                                                 if(ktom==&(itom[i]))
1712                                                         continue;
1713
1714                                                 moldyn->func3b_k1(moldyn,
1715                                                                   &(itom[i]),
1716                                                                   jtom,
1717                                                                   ktom,
1718                                                                   bc_ik|bc_ij);
1719
1720                                         } while(list_next_f(that)!=\
1721                                                 L_NO_NEXT_ELEMENT);
1722
1723                                 }
1724
1725                                 }
1726
1727                                 if(moldyn->func3b_j2)
1728                                         moldyn->func3b_j2(moldyn,
1729                                                           &(itom[i]),
1730                                                           jtom,
1731                                                           bc_ij);
1732
1733                                 /* second loop over atoms k */
1734                                 if(moldyn->func3b_k2) {
1735
1736                                 for(k=0;k<27;k++) {
1737
1738                                         that=&(neighbour_i2[k]);
1739                                         list_reset_f(that);
1740                                         
1741                                         if(that->start==NULL)
1742                                                 continue;
1743
1744                                         bc_ik=(k<dnlc)?0:1;
1745
1746                                         do {
1747
1748                                                 ktom=that->current->data;
1749
1750                                                 if(!(ktom->attr&ATOM_ATTR_3BP))
1751                                                         continue;
1752
1753                                                 if(ktom==jtom)
1754                                                         continue;
1755
1756                                                 if(ktom==&(itom[i]))
1757                                                         continue;
1758
1759                                                 moldyn->func3b_k2(moldyn,
1760                                                                   &(itom[i]),
1761                                                                   jtom,
1762                                                                   ktom,
1763                                                                   bc_ik|bc_ij);
1764
1765                                         } while(list_next_f(that)!=\
1766                                                 L_NO_NEXT_ELEMENT);
1767
1768                                 }
1769                                 
1770                                 }
1771
1772                                 /* 2bp post function */
1773                                 if(moldyn->func3b_j3) {
1774                                         moldyn->func3b_j3(moldyn,
1775                                                           &(itom[i]),
1776                                                           jtom,bc_ij);
1777                                 }
1778                                         
1779                         } while(list_next_f(this)!=L_NO_NEXT_ELEMENT);
1780                 
1781                 }
1782                 
1783 #ifdef DEBUG
1784         //printf("\n\n");
1785 #endif
1786 #ifdef VDEBUG
1787         printf("\n\n");
1788 #endif
1789
1790         }
1791
1792 #ifdef DEBUG
1793         printf("\nATOM 0: %f %f %f\n\n",itom->f.x,itom->f.y,itom->f.z);
1794 #endif
1795
1796         /* calculate global virial */
1797         for(i=0;i<count;i++) {
1798                 moldyn->virial.xx+=moldyn->atom[i].r.x*moldyn->atom[i].f.x;
1799                 moldyn->virial.yy+=moldyn->atom[i].r.y*moldyn->atom[i].f.y;
1800                 moldyn->virial.zz+=moldyn->atom[i].r.z*moldyn->atom[i].f.z;
1801                 moldyn->virial.xy+=moldyn->atom[i].r.y*moldyn->atom[i].f.x;
1802                 moldyn->virial.xz+=moldyn->atom[i].r.z*moldyn->atom[i].f.x;
1803                 moldyn->virial.yz+=moldyn->atom[i].r.z*moldyn->atom[i].f.y;
1804         }
1805
1806         return 0;
1807 }
1808
1809 /*
1810  * virial calculation
1811  */
1812
1813 //inline int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
1814 int virial_calc(t_atom *a,t_3dvec *f,t_3dvec *d) {
1815
1816         a->virial.xx+=f->x*d->x;
1817         a->virial.yy+=f->y*d->y;
1818         a->virial.zz+=f->z*d->z;
1819         a->virial.xy+=f->x*d->y;
1820         a->virial.xz+=f->x*d->z;
1821         a->virial.yz+=f->y*d->z;
1822
1823         return 0;
1824 }
1825
1826 /*
1827  * periodic boundary checking
1828  */
1829
1830 //inline int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
1831 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
1832         
1833         double x,y,z;
1834         t_3dvec *dim;
1835
1836         dim=&(moldyn->dim);
1837
1838         x=dim->x/2;
1839         y=dim->y/2;
1840         z=dim->z/2;
1841
1842         if(moldyn->status&MOLDYN_STAT_PBX) {
1843                 if(a->x>=x) a->x-=dim->x;
1844                 else if(-a->x>x) a->x+=dim->x;
1845         }
1846         if(moldyn->status&MOLDYN_STAT_PBY) {
1847                 if(a->y>=y) a->y-=dim->y;
1848                 else if(-a->y>y) a->y+=dim->y;
1849         }
1850         if(moldyn->status&MOLDYN_STAT_PBZ) {
1851                 if(a->z>=z) a->z-=dim->z;
1852                 else if(-a->z>z) a->z+=dim->z;
1853         }
1854
1855         return 0;
1856 }
1857         
1858 /*
1859  * debugging / critical check functions
1860  */
1861
1862 int moldyn_bc_check(t_moldyn *moldyn) {
1863
1864         t_atom *atom;
1865         t_3dvec *dim;
1866         int i;
1867         double x;
1868         u8 byte;
1869         int j,k;
1870
1871         atom=moldyn->atom;
1872         dim=&(moldyn->dim);
1873         x=dim->x/2;
1874
1875         for(i=0;i<moldyn->count;i++) {
1876                 if(atom[i].r.x>=dim->x/2||-atom[i].r.x>dim->x/2) {
1877                         printf("FATAL: atom %d: x: %.20f (%.20f)\n",
1878                                i,atom[i].r.x,dim->x/2);
1879                         printf("diagnostic:\n");
1880                         printf("-----------\natom.r.x:\n");
1881                         for(j=0;j<8;j++) {
1882                                 memcpy(&byte,(u8 *)(&(atom[i].r.x))+j,1);
1883                                 for(k=0;k<8;k++)
1884                                         printf("%d%c",
1885                                         ((byte)&(1<<k))?1:0,
1886                                         (k==7)?'\n':'|');
1887                         }
1888                         printf("---------------\nx=dim.x/2:\n");
1889                         for(j=0;j<8;j++) {
1890                                 memcpy(&byte,(u8 *)(&x)+j,1);
1891                                 for(k=0;k<8;k++)
1892                                         printf("%d%c",
1893                                         ((byte)&(1<<k))?1:0,
1894                                         (k==7)?'\n':'|');
1895                         }
1896                         if(atom[i].r.x==x) printf("the same!\n");
1897                         else printf("different!\n");
1898                 }
1899                 if(atom[i].r.y>=dim->y/2||-atom[i].r.y>dim->y/2)
1900                         printf("FATAL: atom %d: y: %.20f (%.20f)\n",
1901                                i,atom[i].r.y,dim->y/2);
1902                 if(atom[i].r.z>=dim->z/2||-atom[i].r.z>dim->z/2)
1903                         printf("FATAL: atom %d: z: %.20f (%.20f)\n",
1904                                i,atom[i].r.z,dim->z/2);
1905         }
1906
1907         return 0;
1908 }
1909
1910 /*
1911  * post processing functions
1912  */
1913
1914 int get_line(int fd,char *line,int max) {
1915
1916         int count,ret;
1917
1918         count=0;
1919
1920         while(1) {
1921                 if(count==max) return count;
1922                 ret=read(fd,line+count,1);
1923                 if(ret<=0) return ret;
1924                 if(line[count]=='\n') {
1925                         line[count]='\0';
1926                         return count+1;
1927                 }
1928                 count+=1;
1929         }
1930 }
1931