no segfaulst anymore BUT take care, definetly calculating bullshit
[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
20 #include "math/math.h"
21 #include "init/init.h"
22 #include "random/random.h"
23 #include "visual/visual.h"
24 #include "list/list.h"
25
26
27 int moldyn_init(t_moldyn *moldyn,int argc,char **argv) {
28
29         //int ret;
30
31         //ret=moldyn_parse_argv(moldyn,argc,argv);
32         //if(ret<0) return ret;
33
34         memset(moldyn,0,sizeof(t_moldyn));
35
36         rand_init(&(moldyn->random),NULL,1);
37         moldyn->random.status|=RAND_STAT_VERBOSE;
38
39         return 0;
40 }
41
42 int moldyn_shutdown(t_moldyn *moldyn) {
43
44         printf("[moldyn] shutdown\n");
45         moldyn_log_shutdown(moldyn);
46         link_cell_shutdown(moldyn);
47         rand_close(&(moldyn->random));
48         free(moldyn->atom);
49
50         return 0;
51 }
52
53 int set_int_alg(t_moldyn *moldyn,u8 algo) {
54
55         switch(algo) {
56                 case MOLDYN_INTEGRATE_VERLET:
57                         moldyn->integrate=velocity_verlet;
58                         break;
59                 default:
60                         printf("unknown integration algorithm: %02x\n",algo);
61                         return -1;
62         }
63
64         return 0;
65 }
66
67 int set_cutoff(t_moldyn *moldyn,double cutoff) {
68
69         moldyn->cutoff=cutoff;
70
71         return 0;
72 }
73
74 int set_temperature(t_moldyn *moldyn,double t_ref) {
75
76         moldyn->t_ref=t_ref;
77
78         return 0;
79 }
80
81 int set_pt_scale(t_moldyn *moldyn,u8 ptype,double ptc,u8 ttype,double ttc) {
82
83         moldyn->pt_scale=(ptype|ttype);
84         moldyn->t_tc=ttc;
85         moldyn->p_tc=ptc;
86
87         return 0;
88 }
89
90 int set_dim(t_moldyn *moldyn,double x,double y,double z,u8 visualize) {
91
92         moldyn->dim.x=x;
93         moldyn->dim.y=y;
94         moldyn->dim.z=z;
95
96         if(visualize) {
97                 moldyn->vis.dim.x=x;
98                 moldyn->vis.dim.y=y;
99                 moldyn->vis.dim.z=z;
100         }
101
102         return 0;
103 }
104
105 int set_nn_dist(t_moldyn *moldyn,double dist) {
106
107         moldyn->nnd=dist;
108
109         return 0;
110 }
111
112 int set_pbc(t_moldyn *moldyn,u8 x,u8 y,u8 z) {
113
114         if(x)
115                 moldyn->status|=MOLDYN_STAT_PBX;
116
117         if(y)
118                 moldyn->status|=MOLDYN_STAT_PBY;
119
120         if(z)
121                 moldyn->status|=MOLDYN_STAT_PBZ;
122
123         return 0;
124 }
125
126 int set_potential1b(t_moldyn *moldyn,pf_func1b func,void *params) {
127
128         moldyn->func1b=func;
129         moldyn->pot1b_params=params;
130
131         return 0;
132 }
133
134 int set_potential2b(t_moldyn *moldyn,pf_func2b func,void *params) {
135
136         moldyn->func2b=func;
137         moldyn->pot2b_params=params;
138
139         return 0;
140 }
141
142 int set_potential2b_post(t_moldyn *moldyn,pf_func2b_post func,void *params) {
143
144         moldyn->func2b=func;
145         moldyn->pot2b_params=params;
146
147         return 0;
148 }
149
150 int set_potential3b(t_moldyn *moldyn,pf_func3b func,void *params) {
151
152         moldyn->func3b=func;
153         moldyn->pot3b_params=params;
154
155         return 0;
156 }
157
158 int moldyn_set_log(t_moldyn *moldyn,u8 type,char *fb,int timer) {
159
160         switch(type) {
161                 case LOG_TOTAL_ENERGY:
162                         moldyn->ewrite=timer;
163                         moldyn->efd=open(fb,O_WRONLY|O_CREAT|O_TRUNC);
164                         if(moldyn->efd<0) {
165                                 perror("[moldyn] efd open");
166                                 return moldyn->efd;
167                         }
168                         dprintf(moldyn->efd,"# total energy log file\n");
169                         break;
170                 case LOG_TOTAL_MOMENTUM:
171                         moldyn->mwrite=timer;
172                         moldyn->mfd=open(fb,O_WRONLY|O_CREAT|O_TRUNC);
173                         if(moldyn->mfd<0) {
174                                 perror("[moldyn] mfd open");
175                                 return moldyn->mfd;
176                         }
177                         dprintf(moldyn->efd,"# total momentum log file\n");
178                         break;
179                 case SAVE_STEP:
180                         moldyn->swrite=timer;
181                         strncpy(moldyn->sfb,fb,63);
182                         break;
183                 case VISUAL_STEP:
184                         moldyn->vwrite=timer;
185                         strncpy(moldyn->vfb,fb,63);
186                         visual_init(&(moldyn->vis),fb);
187                         break;
188                 default:
189                         printf("unknown log mechanism: %02x\n",type);
190                         return -1;
191         }
192
193         return 0;
194 }
195
196 int moldyn_log_shutdown(t_moldyn *moldyn) {
197
198         printf("[moldyn] log shutdown\n");
199         if(moldyn->efd) close(moldyn->efd);
200         if(moldyn->mfd) close(moldyn->mfd);
201         if(&(moldyn->vis)) visual_tini(&(moldyn->vis));
202
203         return 0;
204 }
205
206 int create_lattice(t_moldyn *moldyn,u8 type,double lc,int element,double mass,
207                    u8 attr,u8 bnum,int a,int b,int c) {
208
209         int count;
210         int ret;
211         t_3dvec origin;
212
213         count=a*b*c;
214
215         if(type==FCC) count*=4;
216
217         if(type==DIAMOND) count*=8;
218
219         moldyn->atom=malloc(count*sizeof(t_atom));
220         if(moldyn->atom==NULL) {
221                 perror("malloc (atoms)");
222                 return -1;
223         }
224
225         v3_zero(&origin);
226
227         switch(type) {
228                 case FCC:
229                         ret=fcc_init(a,b,c,lc,moldyn->atom,&origin);
230                         break;
231                 case DIAMOND:
232                         ret=diamond_init(a,b,c,lc,moldyn->atom,&origin);
233                         break;
234                 default:
235                         printf("unknown lattice type (%02x)\n",type);
236                         return -1;
237         }
238
239         /* debug */
240         if(ret!=count) {
241                 printf("ok, there is something wrong ...\n");
242                 printf("calculated -> %d atoms\n",count);
243                 printf("created -> %d atoms\n",ret);
244                 return -1;
245         }
246
247         moldyn->count=count;
248         printf("[moldyn] created lattice with %d atoms\n",count);
249
250         while(count) {
251                 count-=1;
252                 moldyn->atom[count].element=element;
253                 moldyn->atom[count].mass=mass;
254                 moldyn->atom[count].attr=attr;
255                 moldyn->atom[count].bnum=bnum;
256                 check_per_bound(moldyn,&(moldyn->atom[count].r));
257         }
258
259
260         return ret;
261 }
262
263 int add_atom(t_moldyn *moldyn,int element,double mass,u8 bnum,u8 attr,
264              t_3dvec *r,t_3dvec *v) {
265
266         t_atom *atom;
267         void *ptr;
268         int count;
269         
270         atom=moldyn->atom;
271         count=++(moldyn->count);
272
273         ptr=realloc(atom,count*sizeof(t_atom));
274         if(!ptr) {
275                 perror("[moldyn] realloc (add atom)");
276                 return -1;
277         }
278         moldyn->atom=ptr;
279
280         atom=moldyn->atom;
281         atom[count-1].r=*r;
282         atom[count-1].v=*v;
283         atom[count-1].element=element;
284         atom[count-1].mass=mass;
285         atom[count-1].bnum=bnum;
286         atom[count-1].attr=attr;
287
288         return 0;
289 }
290
291 int destroy_atoms(t_moldyn *moldyn) {
292
293         if(moldyn->atom) free(moldyn->atom);
294
295         return 0;
296 }
297
298 int thermal_init(t_moldyn *moldyn,u8 equi_init) {
299
300         /*
301          * - gaussian distribution of velocities
302          * - zero total momentum
303          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
304          */
305
306         int i;
307         double v,sigma;
308         t_3dvec p_total,delta;
309         t_atom *atom;
310         t_random *random;
311
312         atom=moldyn->atom;
313         random=&(moldyn->random);
314
315         /* gaussian distribution of velocities */
316         v3_zero(&p_total);
317         for(i=0;i<moldyn->count;i++) {
318                 sigma=sqrt(2.0*K_BOLTZMANN*moldyn->t_ref/atom[i].mass);
319                 /* x direction */
320                 v=sigma*rand_get_gauss(random);
321                 atom[i].v.x=v;
322                 p_total.x+=atom[i].mass*v;
323                 /* y direction */
324                 v=sigma*rand_get_gauss(random);
325                 atom[i].v.y=v;
326                 p_total.y+=atom[i].mass*v;
327                 /* z direction */
328                 v=sigma*rand_get_gauss(random);
329                 atom[i].v.z=v;
330                 p_total.z+=atom[i].mass*v;
331         }
332
333         /* zero total momentum */
334         v3_scale(&p_total,&p_total,1.0/moldyn->count);
335         for(i=0;i<moldyn->count;i++) {
336                 v3_scale(&delta,&p_total,1.0/atom[i].mass);
337                 v3_sub(&(atom[i].v),&(atom[i].v),&delta);
338         }
339
340         /* velocity scaling */
341         scale_velocity(moldyn,equi_init);
342
343         return 0;
344 }
345
346 int scale_velocity(t_moldyn *moldyn,u8 equi_init) {
347
348         int i;
349         double e,scale;
350         t_atom *atom;
351         int count;
352
353         atom=moldyn->atom;
354
355         /*
356          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
357          */
358
359         /* get kinetic energy / temperature & count involved atoms */
360         e=0.0;
361         count=0;
362         for(i=0;i<moldyn->count;i++) {
363                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB)) {
364                         e+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
365                         count+=1;
366                 }
367         }
368         if(count!=0) moldyn->t=(2.0*e)/(3.0*count*K_BOLTZMANN);
369         else return 0;  /* no atoms involved in scaling! */
370         
371         /* (temporary) hack for e,t = 0 */
372         if(e==0.0) {
373         moldyn->t=0.0;
374                 if(moldyn->t_ref!=0.0)
375                         thermal_init(moldyn,equi_init);
376                 else
377                         return 0; /* no scaling needed */
378         }
379
380
381         /* get scaling factor */
382         scale=moldyn->t_ref/moldyn->t;
383         if(equi_init&TRUE)
384                 scale*=2.0;
385         else
386                 if(moldyn->pt_scale&T_SCALE_BERENDSEN)
387                         scale=1.0+moldyn->tau*(scale-1.0)/moldyn->t_tc;
388         scale=sqrt(scale);
389
390         /* velocity scaling */
391         for(i=0;i<moldyn->count;i++)
392                 if((equi_init&TRUE)||(atom[i].attr&ATOM_ATTR_HB))
393                         v3_scale(&(atom[i].v),&(atom[i].v),scale);
394
395         return 0;
396 }
397
398 double get_e_kin(t_moldyn *moldyn) {
399
400         int i;
401         t_atom *atom;
402
403         atom=moldyn->atom;
404         moldyn->ekin=0.0;
405
406         for(i=0;i<moldyn->count;i++)
407                 moldyn->ekin+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
408
409         return moldyn->ekin;
410 }
411
412 double get_e_pot(t_moldyn *moldyn) {
413
414         return moldyn->energy;
415 }
416
417 double update_e_kin(t_moldyn *moldyn) {
418
419         return(get_e_kin(moldyn));
420 }
421
422 double get_total_energy(t_moldyn *moldyn) {
423
424         return(moldyn->ekin+moldyn->energy);
425 }
426
427 t_3dvec get_total_p(t_moldyn *moldyn) {
428
429         t_3dvec p,p_total;
430         int i;
431         t_atom *atom;
432
433         atom=moldyn->atom;
434
435         v3_zero(&p_total);
436         for(i=0;i<moldyn->count;i++) {
437                 v3_scale(&p,&(atom[i].v),atom[i].mass);
438                 v3_add(&p_total,&p_total,&p);
439         }
440
441         return p_total;
442 }
443
444 double estimate_time_step(t_moldyn *moldyn,double nn_dist) {
445
446         double tau;
447
448         /* nn_dist is the nearest neighbour distance */
449
450         if(moldyn->t==5.0) {
451                 printf("[moldyn] i do not estimate timesteps below %f K!\n",
452                        MOLDYN_CRITICAL_EST_TEMP);
453                 return 23.42;
454         }
455
456         tau=(0.05*nn_dist*moldyn->atom[0].mass)/sqrt(3.0*K_BOLTZMANN*moldyn->t);
457
458         return tau;     
459 }
460
461 /*
462  * numerical tricks
463  */
464
465 /* linked list / cell method */
466
467 int link_cell_init(t_moldyn *moldyn) {
468
469         t_linkcell *lc;
470         int i;
471         int fd;
472
473         fd=open("/dev/null",O_WRONLY);
474
475         lc=&(moldyn->lc);
476
477         /* partitioning the md cell */
478         lc->nx=moldyn->dim.x/moldyn->cutoff;
479         lc->x=moldyn->dim.x/lc->nx;
480         lc->ny=moldyn->dim.y/moldyn->cutoff;
481         lc->y=moldyn->dim.y/lc->ny;
482         lc->nz=moldyn->dim.z/moldyn->cutoff;
483         lc->z=moldyn->dim.z/lc->nz;
484
485         lc->cells=lc->nx*lc->ny*lc->nz;
486         lc->subcell=malloc(lc->cells*sizeof(t_list));
487
488         printf("[moldyn] initializing linked cells (%d)\n",lc->cells);
489
490         for(i=0;i<lc->cells;i++)
491                 //list_init(&(lc->subcell[i]),1);
492                 list_init(&(lc->subcell[i]),fd);
493
494         link_cell_update(moldyn);
495         
496         return 0;
497 }
498
499 int link_cell_update(t_moldyn *moldyn) {
500
501         int count,i,j,k;
502         int nx,ny,nz;
503         t_atom *atom;
504         t_linkcell *lc;
505
506         atom=moldyn->atom;
507         lc=&(moldyn->lc);
508
509         nx=lc->nx;
510         ny=lc->ny;
511         nz=lc->nz;
512
513         for(i=0;i<lc->cells;i++)
514                 list_destroy(&(moldyn->lc.subcell[i]));
515         
516         for(count=0;count<moldyn->count;count++) {
517                 i=(atom[count].r.x+(moldyn->dim.x/2))/lc->x;
518                 j=(atom[count].r.y+(moldyn->dim.y/2))/lc->y;
519                 k=(atom[count].r.z+(moldyn->dim.z/2))/lc->z;
520                 list_add_immediate_ptr(&(moldyn->lc.subcell[i+j*nx+k*nx*ny]),
521                                        &(atom[count]));
522         }
523
524         return 0;
525 }
526
527 int link_cell_neighbour_index(t_moldyn *moldyn,int i,int j,int k,t_list *cell) {
528
529         t_linkcell *lc;
530         int a;
531         int count1,count2;
532         int ci,cj,ck;
533         int nx,ny,nz;
534         int x,y,z;
535         u8 bx,by,bz;
536
537         lc=&(moldyn->lc);
538         nx=lc->nx;
539         ny=lc->ny;
540         nz=lc->nz;
541         count1=1;
542         count2=27;
543         a=nx*ny;
544
545         cell[0]=lc->subcell[i+j*nx+k*a];
546         for(ci=-1;ci<=1;ci++) {
547                 bx=0;
548                 x=i+ci;
549                 if((x<0)||(x>=nx)) {
550                         x=(x+nx)%nx;
551                         bx=1;
552                 }
553                 for(cj=-1;cj<=1;cj++) {
554                         by=0;
555                         y=j+cj;
556                         if((y<0)||(y>=ny)) {
557                                 y=(y+ny)%ny;
558                                 by=1;
559                         }
560                         for(ck=-1;ck<=1;ck++) {
561                                 bz=0;
562                                 z=k+ck;
563                                 if((z<0)||(z>=nz)) {
564                                         z=(z+nz)%nz;
565                                         bz=1;
566                                 }
567                                 if(!(ci|cj|ck)) continue;
568                                 if(bx|by|bz) {
569                                         cell[--count2]=lc->subcell[x+y*nx+z*a];
570                                 }
571                                 else {
572                                         cell[count1++]=lc->subcell[x+y*nx+z*a];
573                                 }
574                         }
575                 }
576         }
577
578         lc->dnlc=count1;
579         lc->countn=27;
580
581         return count2;
582 }
583
584 int link_cell_shutdown(t_moldyn *moldyn) {
585
586         int i;
587         t_linkcell *lc;
588
589         lc=&(moldyn->lc);
590
591         for(i=0;i<lc->nx*lc->ny*lc->nz;i++)
592                 list_shutdown(&(moldyn->lc.subcell[i]));
593
594         return 0;
595 }
596
597 int moldyn_add_schedule(t_moldyn *moldyn,int runs,double tau) {
598
599         int count;
600         void *ptr;
601         t_moldyn_schedule *schedule;
602
603         schedule=&(moldyn->schedule);
604         count=++(schedule->content_count);
605
606         ptr=realloc(moldyn->schedule.runs,count*sizeof(int));
607         if(!ptr) {
608                 perror("[moldyn] realloc (runs)");
609                 return -1;
610         }
611         moldyn->schedule.runs=ptr;
612         moldyn->schedule.runs[count-1]=runs;
613
614         ptr=realloc(schedule->tau,count*sizeof(double));
615         if(!ptr) {
616                 perror("[moldyn] realloc (tau)");
617                 return -1;
618         }
619         moldyn->schedule.tau=ptr;
620         moldyn->schedule.tau[count-1]=tau;
621
622         return 0;
623 }
624
625 int moldyn_set_schedule_hook(t_moldyn *moldyn,void *hook,void *hook_params) {
626
627         moldyn->schedule.hook=hook;
628         moldyn->schedule.hook_params=hook_params;
629         
630         return 0;
631 }
632
633 /*
634  *
635  * 'integration of newtons equation' - algorithms
636  *
637  */
638
639 /* start the integration */
640
641 int moldyn_integrate(t_moldyn *moldyn) {
642
643         int i,sched;
644         unsigned int e,m,s,v;
645         t_3dvec p;
646         t_moldyn_schedule *schedule;
647         t_atom *atom;
648         int fd;
649         char fb[128];
650         double ds;
651
652         schedule=&(moldyn->schedule);
653         atom=moldyn->atom;
654
655         /* initialize linked cell method */
656         link_cell_init(moldyn);
657
658         /* logging & visualization */
659         e=moldyn->ewrite;
660         m=moldyn->mwrite;
661         s=moldyn->swrite;
662         v=moldyn->vwrite;
663
664         /* sqaure of some variables */
665         moldyn->tau_square=moldyn->tau*moldyn->tau;
666         moldyn->cutoff_square=moldyn->cutoff*moldyn->cutoff;
667         /* calculate initial forces */
668         potential_force_calc(moldyn);
669
670         /* do some checks before we actually start calculating bullshit */
671         if(moldyn->cutoff>0.5*moldyn->dim.x)
672                 printf("[moldyn] warning: cutoff > 0.5 x dim.x\n");
673         if(moldyn->cutoff>0.5*moldyn->dim.y)
674                 printf("[moldyn] warning: cutoff > 0.5 x dim.y\n");
675         if(moldyn->cutoff>0.5*moldyn->dim.z)
676                 printf("[moldyn] warning: cutoff > 0.5 x dim.z\n");
677         ds=0.5*atom[0].f.x*moldyn->tau_square/atom[0].mass;
678         if(ds>0.05*moldyn->nnd)
679                 printf("[moldyn] warning: forces too high / tau too small!\n");
680
681         /* zero absolute time */
682         moldyn->time=0.0;
683         for(sched=0;sched<moldyn->schedule.content_count;sched++) {
684
685                 /* setting amount of runs and finite time step size */
686                 moldyn->tau=schedule->tau[sched];
687                 moldyn->tau_square=moldyn->tau*moldyn->tau;
688                 moldyn->time_steps=schedule->runs[sched];
689
690         /* integration according to schedule */
691
692         for(i=0;i<moldyn->time_steps;i++) {
693
694                 /* integration step */
695                 moldyn->integrate(moldyn);
696
697                 /* p/t scaling */
698                 if(moldyn->pt_scale&(T_SCALE_BERENDSEN|T_SCALE_DIRECT))
699                         scale_velocity(moldyn,FALSE);
700
701                 /* increase absolute time */
702                 moldyn->time+=moldyn->tau;
703
704                 /* check for log & visualization */
705                 if(e) {
706                         if(!(i%e))
707                                 dprintf(moldyn->efd,
708                                         "%.15f %.45f %.45f %.45f\n",
709                                         moldyn->time,update_e_kin(moldyn),
710                                         moldyn->energy,
711                                         get_total_energy(moldyn));
712                 }
713                 if(m) {
714                         if(!(i%m)) {
715                                 p=get_total_p(moldyn);
716                                 dprintf(moldyn->mfd,
717                                         "%.15f %.45f\n",moldyn->time,
718                                         v3_norm(&p));
719                         }
720                 }
721                 if(s) {
722                         if(!(i%s)) {
723                                 snprintf(fb,128,"%s-%f-%.15f.save",moldyn->sfb,
724                                          moldyn->t,i*moldyn->tau);
725                                 fd=open(fb,O_WRONLY|O_TRUNC|O_CREAT);
726                                 if(fd<0) perror("[moldyn] save fd open");
727                                 else {
728                                         write(fd,moldyn,sizeof(t_moldyn));
729                                         write(fd,moldyn->atom,
730                                               moldyn->count*sizeof(t_atom));
731                                 }
732                                 close(fd);
733                         }       
734                 }
735                 if(v) {
736                         if(!(i%v)) {
737                                 visual_atoms(&(moldyn->vis),moldyn->time,
738                                              moldyn->atom,moldyn->count);
739                                 printf("\rsched: %d, steps: %d",sched,i);
740                                 fflush(stdout);
741                         }
742                 }
743
744         }
745
746                 /* check for hooks */
747                 if(schedule->hook)
748                         schedule->hook(moldyn,schedule->hook_params);
749
750         }
751
752         return 0;
753 }
754
755 /* velocity verlet */
756
757 int velocity_verlet(t_moldyn *moldyn) {
758
759         int i,count;
760         double tau,tau_square;
761         t_3dvec delta;
762         t_atom *atom;
763
764         atom=moldyn->atom;
765         count=moldyn->count;
766         tau=moldyn->tau;
767         tau_square=moldyn->tau_square;
768
769         for(i=0;i<count;i++) {
770                 /* new positions */
771                 v3_scale(&delta,&(atom[i].v),tau);
772                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
773                 v3_scale(&delta,&(atom[i].f),0.5*tau_square/atom[i].mass);
774                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
775                 check_per_bound(moldyn,&(atom[i].r));
776
777                 /* velocities */
778                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
779                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
780         }
781
782         /* neighbour list update */
783         link_cell_update(moldyn);
784
785         /* forces depending on chosen potential */
786         potential_force_calc(moldyn);
787         //moldyn->potential_force_function(moldyn);
788
789         for(i=0;i<count;i++) {
790                 /* again velocities */
791                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
792                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
793         }
794
795         return 0;
796 }
797
798
799 /*
800  *
801  * potentials & corresponding forces
802  * 
803  */
804
805 /* generic potential and force calculation */
806
807 int potential_force_calc(t_moldyn *moldyn) {
808
809         int i,j,k,count;
810         t_atom *itom,*jtom,*ktom;
811         t_linkcell *lc;
812         t_list neighbour_i[27];
813         t_list neighbour_i2[27];
814         //t_list neighbour_j[27];
815         t_list *this,*that;
816         u8 bc_ij,bc_ijk;
817         int countn,dnlc;
818
819         count=moldyn->count;
820         itom=moldyn->atom;
821         lc=&(moldyn->lc);
822
823         /* reset energy */
824         moldyn->energy=0.0;
825
826         for(i=0;i<count;i++) {
827
828                 /* reset force */
829                 v3_zero(&(itom[i].f));
830
831                 /* single particle potential/force */
832                 if(itom[i].attr&ATOM_ATTR_1BP)
833                         moldyn->func1b(moldyn,&(itom[i]));
834
835                 /* 2 body pair potential/force */
836                 if(itom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)) {
837         
838                         link_cell_neighbour_index(moldyn,
839                                 (itom[i].r.x+moldyn->dim.x/2)/lc->x,
840                                 (itom[i].r.y+moldyn->dim.y/2)/lc->y,
841                                 (itom[i].r.z+moldyn->dim.z/2)/lc->z,
842                                 neighbour_i);
843
844                         countn=lc->countn;
845                         dnlc=lc->dnlc;
846
847                         for(j=0;j<countn;j++) {
848
849                                 this=&(neighbour_i[j]);
850                                 list_reset(this);
851
852                                 if(this->start==NULL)
853                                         continue;
854
855                                 bc_ij=(j<dnlc)?0:1;
856
857                                 do {
858                                         jtom=this->current->data;
859
860                                         if(jtom==&(itom[i]))
861                                                 continue;
862
863                                         if((jtom->attr&ATOM_ATTR_2BP)&
864                                            (itom[i].attr&ATOM_ATTR_2BP))
865                                                 moldyn->func2b(moldyn,
866                                                                &(itom[i]),
867                                                                jtom,
868                                                                bc_ij);
869
870                                         /* 3 body potential/force */
871
872                                         if(!(itom[i].attr&ATOM_ATTR_3BP)||
873                                            !(jtom->attr&ATOM_ATTR_3BP))
874                                                 continue;
875
876                         /*
877                          * according to mr. nordlund, we dont need to take the 
878                          * sum over all atoms now, as 'this is centered' around
879                          * atom i ...
880                          * i am not quite sure though! there is a not vanishing
881                          * part even if f_c_ik is zero ...
882                          * this analytical potentials suck!
883                          * switching from mc to md to dft soon!
884                          */
885
886                         //              link_cell_neighbour_index(moldyn,
887                         //                 (jtom->r.x+moldyn->dim.x/2)/lc->x,
888                         //                 (jtom->r.y+moldyn->dim.y/2)/lc->y,
889                         //                 (jtom->r.z+moldyn->dim.z/2)/lc->z,
890                         //                 neighbour_j);
891
892 //                                      /* neighbours of j */
893 //                                      for(k=0;k<lc->countn;k++) {
894 //
895 //                                              that=&(neighbour_j[k]);
896 //                                              list_reset(that);
897 //                                      
898 //                                              if(that->start==NULL)
899 //                                                      continue;
900 //
901 //                                              bc_ijk=(k<lc->dnlc)?0:1;
902 //
903 //                                              do {
904 //
905 //                      ktom=that->current->data;
906 //
907 //                      if(!(ktom->attr&ATOM_ATTR_3BP))
908 //                              continue;
909 //
910 //                      if(ktom==jtom)
911 //                              continue;
912 //
913 //                      if(ktom==&(itom[i]))
914 //                              continue;
915 //
916 //                      moldyn->func3b(moldyn,&(itom[i]),jtom,ktom,bc_ijk);
917 //
918 /*                                              } while(list_next(that)!=\ */
919 //                                                      L_NO_NEXT_ELEMENT);
920 //
921 //                                      }
922                         
923                                         /* copy the neighbour lists */
924                                         memcpy(neighbour_i2,neighbour_i,
925                                                27*sizeof(t_list));
926
927                                         /* get neighbours of i */
928                                         for(k=0;k<countn;k++) {
929
930                                                 that=&(neighbour_i2[k]);
931                                                 list_reset(that);
932                                         
933                                                 if(that->start==NULL)
934                                                         continue;
935
936                                                 bc_ijk=(k<dnlc)?0:1;
937
938                                                 do {
939
940                         ktom=that->current->data;
941
942                         if(!(ktom->attr&ATOM_ATTR_3BP))
943                                 continue;
944
945                         if(ktom==jtom)
946                                 continue;
947
948                         if(ktom==&(itom[i]))
949                                 continue;
950
951 //printf("Debug: atom %d before 3bp: %08x %08x %08x | %.15f %.15f %.15f\n",i,&itom[i],jtom,ktom,itom[i].r.x,itom[i].f.x,itom[i].v.x);
952                         moldyn->func3b(moldyn,&(itom[i]),jtom,ktom,bc_ijk);
953 //printf("Debug: atom %d after 3bp: %08x %08x %08x | %.15f %.15f %.15f\n",i,&itom[i],jtom,ktom,itom[i].r.x,itom[i].f.x,itom[i].v.x);
954
955                                                 } while(list_next(that)!=\
956                                                         L_NO_NEXT_ELEMENT);
957
958                                         }
959                                         
960                                 } while(list_next(this)!=L_NO_NEXT_ELEMENT);
961                 
962                                 /* 2bp post function */
963                                 if(moldyn->func2b_post)
964                                         moldyn->func2b_post(moldyn,
965                                                             &(itom[i]),
966                                                             jtom,bc_ij);
967
968                         }
969                 }
970         }
971
972         return 0;
973 }
974
975 /*
976  * periodic boundayr checking
977  */
978
979 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
980         
981         double x,y,z;
982         t_3dvec *dim;
983
984         dim=&(moldyn->dim);
985
986         x=0.5*dim->x;
987         y=0.5*dim->y;
988         z=0.5*dim->z;
989
990         if(moldyn->status&MOLDYN_STAT_PBX) {
991                 if(a->x>=x) a->x-=dim->x;
992                 else if(-a->x>x) a->x+=dim->x;
993         }
994         if(moldyn->status&MOLDYN_STAT_PBY) {
995                 if(a->y>=y) a->y-=dim->y;
996                 else if(-a->y>y) a->y+=dim->y;
997         }
998         if(moldyn->status&MOLDYN_STAT_PBZ) {
999                 if(a->z>=z) a->z-=dim->z;
1000                 else if(-a->z>z) a->z+=dim->z;
1001         }
1002
1003         return 0;
1004 }
1005         
1006
1007 /*
1008  * example potentials
1009  */
1010
1011 /* harmonic oscillator potential and force */
1012
1013 int harmonic_oscillator(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1014
1015         t_ho_params *params;
1016         t_3dvec force,distance;
1017         double d;
1018         double sc,equi_dist;
1019
1020         params=moldyn->pot2b_params;
1021         sc=params->spring_constant;
1022         equi_dist=params->equilibrium_distance;
1023
1024         v3_sub(&distance,&(ai->r),&(aj->r));
1025         
1026         if(bc) check_per_bound(moldyn,&distance);
1027         d=v3_norm(&distance);
1028         if(d<=moldyn->cutoff) {
1029                 /* energy is 1/2 (d-d0)^2, but we will add this twice ... */
1030                 moldyn->energy+=(0.25*sc*(d-equi_dist)*(d-equi_dist));
1031                 v3_scale(&force,&distance,-sc*(1.0-(equi_dist/d)));
1032                 v3_add(&(ai->f),&(ai->f),&force);
1033         }
1034
1035         return 0;
1036 }
1037
1038 /* lennard jones potential & force for one sort of atoms */
1039  
1040 int lennard_jones(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1041
1042         t_lj_params *params;
1043         t_3dvec force,distance;
1044         double d,h1,h2;
1045         double eps,sig6,sig12;
1046
1047         params=moldyn->pot2b_params;
1048         eps=params->epsilon4;
1049         sig6=params->sigma6;
1050         sig12=params->sigma12;
1051
1052         v3_sub(&distance,&(ai->r),&(aj->r));
1053         if(bc) check_per_bound(moldyn,&distance);
1054         d=v3_absolute_square(&distance);        /* 1/r^2 */
1055         if(d<=moldyn->cutoff_square) {
1056                 d=1.0/d;                        /* 1/r^2 */
1057                 h2=d*d;                         /* 1/r^4 */
1058                 h2*=d;                          /* 1/r^6 */
1059                 h1=h2*h2;                       /* 1/r^12 */
1060                 /* energy is eps*..., but we will add this twice ... */
1061                 moldyn->energy+=0.5*eps*(sig12*h1-sig6*h2);
1062                 h2*=d;                          /* 1/r^8 */
1063                 h1*=d;                          /* 1/r^14 */
1064                 h2*=6*sig6;
1065                 h1*=12*sig12;
1066                 d=+h1-h2;
1067                 d*=eps;
1068                 v3_scale(&force,&distance,d);
1069                 v3_add(&(ai->f),&(ai->f),&force);
1070         }
1071
1072         return 0;
1073 }
1074
1075 /*
1076  * tersoff potential & force for 2 sorts of atoms
1077  */
1078
1079 /* create mixed terms from parameters and set them */
1080 int tersoff_mult_complete_params(t_tersoff_mult_params *p) {
1081
1082         printf("[moldyn] tersoff parameter completion\n");
1083         p->Smixed=sqrt(p->S[0]*p->S[1]);
1084         p->Rmixed=sqrt(p->R[0]*p->R[1]);
1085         p->Amixed=sqrt(p->A[0]*p->A[1]);
1086         p->Bmixed=sqrt(p->B[0]*p->B[1]);
1087         p->lambda_m=0.5*(p->lambda[0]+p->lambda[1]);
1088         p->mu_m=0.5*(p->mu[0]+p->mu[1]);
1089
1090         printf("[moldyn] tersoff mult parameter info:\n");
1091         printf("  S (m)  | %.12f | %.12f | %.12f\n",p->S[0],p->S[1],p->Smixed);
1092         printf("  R (m)  | %.12f | %.12f | %.12f\n",p->R[0],p->R[1],p->Rmixed);
1093         printf("  A (eV) | %f | %f | %f\n",p->A[0]/EV,p->A[1]/EV,p->Amixed/EV);
1094         printf("  B (eV) | %f | %f | %f\n",p->B[0]/EV,p->B[1]/EV,p->Bmixed/EV);
1095         printf("  lambda | %f | %f | %f\n",p->lambda[0],p->lambda[1],
1096                                           p->lambda_m);
1097         printf("  mu     | %f | %f | %f\n",p->mu[0],p->mu[1],p->mu_m);
1098         printf("  beta   | %.10f | %.10f\n",p->beta[0],p->beta[1]);
1099         printf("  n      | %f | %f\n",p->n[0],p->n[1]);
1100         printf("  c      | %f | %f\n",p->c[0],p->c[1]);
1101         printf("  d      | %f | %f\n",p->d[0],p->d[1]);
1102         printf("  h      | %f | %f\n",p->h[0],p->h[1]);
1103         printf("  chi    | %f \n",p->chi);
1104
1105         return 0;
1106 }
1107
1108 /* tersoff 1 body part */
1109 int tersoff_mult_1bp(t_moldyn *moldyn,t_atom *ai) {
1110
1111         int num;
1112         t_tersoff_mult_params *params;
1113         t_tersoff_exchange *exchange;
1114         
1115         num=ai->bnum;
1116         params=moldyn->pot1b_params;
1117         exchange=&(params->exchange);
1118
1119         /*
1120          * simple: point constant parameters only depending on atom i to
1121          *         their right values
1122          */
1123
1124         exchange->beta=&(params->beta[num]);
1125         exchange->n=&(params->n[num]);
1126         exchange->c=&(params->c[num]);
1127         exchange->d=&(params->d[num]);
1128         exchange->h=&(params->h[num]);
1129
1130         exchange->betan=pow(*(exchange->beta),*(exchange->n));
1131         exchange->n_betan=*(exchange->n)*exchange->betan;
1132         exchange->c2=params->c[num]*params->c[num];
1133         exchange->d2=params->d[num]*params->d[num];
1134         exchange->c2d2=exchange->c2/exchange->d2;
1135
1136         return 0;
1137 }
1138         
1139 /* tersoff 2 body part */
1140 int tersoff_mult_2bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1141
1142         t_tersoff_mult_params *params;
1143         t_tersoff_exchange *exchange;
1144         t_3dvec dist_ij,force;
1145         double d_ij;
1146         double A,B,R,S,lambda,mu;
1147         double f_r,df_r;
1148         double f_c,df_c;
1149         int num;
1150         double s_r;
1151         double arg;
1152         double scale;
1153
1154         params=moldyn->pot2b_params;
1155         num=ai->bnum;
1156         exchange=&(params->exchange);
1157
1158         exchange->run3bp=0;
1159         
1160         /*
1161          * we need: f_c, df_c, f_r, df_r
1162          *
1163          * therefore we need: R, S, A, lambda
1164          */
1165
1166         v3_sub(&dist_ij,&(ai->r),&(aj->r));
1167
1168         if(bc) check_per_bound(moldyn,&dist_ij);
1169
1170         d_ij=v3_norm(&dist_ij);
1171
1172         /* save for use in 3bp */
1173         exchange->d_ij=d_ij;
1174         exchange->dist_ij=dist_ij;
1175         exchange->d_ij2=d_ij*d_ij;
1176
1177         /* constants */
1178         if(num==aj->bnum) {
1179                 S=params->S[num];
1180                 R=params->R[num];
1181                 A=params->A[num];
1182                 B=params->B[num];
1183                 lambda=params->lambda[num];
1184                 mu=params->mu[num];
1185                 params->exchange.chi=1.0;
1186         }
1187         else {
1188                 S=params->Smixed;
1189                 R=params->Rmixed;
1190                 A=params->Amixed;
1191                 B=params->Bmixed;
1192                 lambda=params->lambda_m;
1193                 mu=params->mu_m;
1194                 params->exchange.chi=params->chi;
1195         }
1196
1197         if(d_ij>S)
1198                 return 0;
1199
1200         f_r=A*exp(-lambda*d_ij);
1201         df_r=-lambda*f_r/d_ij;
1202
1203         /* f_a, df_a calc + save for 3bp use */
1204         exchange->f_a=-B*exp(-mu*d_ij);
1205         exchange->df_a=-mu*exchange->f_a/d_ij;
1206
1207         if(d_ij<R) {
1208                 /* f_c = 1, df_c = 0 */
1209                 f_c=1.0;
1210                 df_c=0.0;
1211                 v3_scale(&force,&dist_ij,df_r);
1212         }
1213         else {
1214                 s_r=S-R;
1215                 arg=M_PI*(d_ij-R)/s_r;
1216                 f_c=0.5+0.5*cos(arg);
1217                 df_c=-0.5*sin(arg)*(M_PI/(s_r*d_ij));
1218                 scale=df_c*f_r+df_r*f_c;
1219                 v3_scale(&force,&dist_ij,scale);
1220         }
1221
1222         /* add forces */
1223         v3_add(&(ai->f),&(ai->f),&force);
1224         /* energy is 0.5 f_r f_c ... */
1225         moldyn->energy+=(0.5*f_r*f_c);
1226
1227         /* save for use in 3bp */
1228         exchange->f_c=f_c;
1229         exchange->df_c=df_c;
1230
1231         /* enable the run of 3bp function */
1232         exchange->run3bp=1;
1233
1234         /* reset 3bp sums */
1235         exchange->sum1_3bp=0.0;
1236         exchange->sum2_3bp=0.0;
1237         v3_zero(&(exchange->db_ij));
1238
1239         return 0;
1240 }
1241
1242 /* tersoff 2 body post part */
1243
1244 int tersoff_mult_post_2bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
1245
1246         /* here we have to allow for the 3bp sums */
1247
1248         t_tersoff_mult_params *params;
1249         t_tersoff_exchange *exchange;
1250
1251         t_3dvec force,temp,*db_ij,*dist_ij;
1252         double db_ij_scale1,db_ij_scale2;
1253         double b_ij;
1254         double f_c,df_c,f_a,df_a;
1255         double chi,betan;
1256         double help;
1257         double n;
1258
1259         params=moldyn->pot2b_params;
1260         exchange=&(params->exchange);
1261
1262         db_ij=&(exchange->db_ij);
1263         f_c=exchange->f_c;
1264         df_c=exchange->df_c;
1265         f_a=exchange->f_a;
1266         df_a=exchange->df_a;
1267         betan=exchange->betan;
1268         n=*(exchange->n);
1269         dist_ij=&(exchange->dist_ij);
1270
1271         db_ij_scale1=(1+betan*exchange->sum1_3bp);
1272         db_ij_scale2=(exchange->n_betan*exchange->sum2_3bp);
1273         help=pow(db_ij_scale1,-1.0/(2*n)-1);
1274         b_ij=chi*db_ij_scale1*help;
1275         db_ij_scale1=-chi/(2*n)*help;
1276
1277         v3_scale(db_ij,db_ij,(db_ij_scale1*db_ij_scale2));
1278         v3_scale(db_ij,db_ij,f_a);
1279
1280         v3_scale(&temp,dist_ij,b_ij*df_a);
1281
1282         v3_add(&force,&temp,db_ij);
1283         v3_scale(&force,&force,f_c);
1284
1285         v3_scale(&temp,dist_ij,f_a*b_ij*df_c);
1286
1287         /* add energy of 3bp sum */
1288         moldyn->energy+=(0.5*f_c*b_ij*f_a);
1289         /* add force of 3bp calculation */      
1290         v3_add(&(ai->f),&temp,&force);
1291
1292         return 0;
1293 }
1294
1295 /* tersoff 3 body part */
1296
1297 int tersoff_mult_3bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,t_atom *ak,u8 bc) {
1298
1299         t_tersoff_mult_params *params;
1300         t_tersoff_exchange *exchange;
1301         t_3dvec dist_ij,dist_ik,dist_jk;
1302         t_3dvec temp,force;
1303         double R,S,s_r;
1304         double d_ij,d_ij2,d_ik,d_jk;
1305         double f_c,df_c,f_a,df_a;
1306         double f_c_ik,df_c_ik,arg;
1307         double n,c,d,h;
1308         double c2,d2,c2d2;
1309         double numer,denom;
1310         double theta,cos_theta,sin_theta;
1311         double d_theta,d_theta1,d_theta2;
1312         double h_cos,d2_h_cos2;
1313         double frac,bracket,bracket_n_1,bracket_n;
1314         double g;
1315         int num;
1316
1317         params=moldyn->pot3b_params;
1318         num=ai->bnum;
1319         exchange=&(params->exchange);
1320
1321         if(!(exchange->run3bp))
1322                 return 0;
1323
1324         /*
1325          * we need: f_c, d_fc, b_ij, db_ij, f_a, df_a
1326          *
1327          * we got f_c, df_c, f_a, df_a from 2bp calculation
1328          */
1329
1330         d_ij=exchange->d_ij;
1331         d_ij2=exchange->d_ij2;
1332         dist_ij=exchange->dist_ij;
1333
1334         f_a=params->exchange.f_a;
1335         df_a=params->exchange.df_a;
1336
1337         f_c=exchange->f_c;
1338         df_c=exchange->df_c;
1339         
1340         /* d_ij is <= S, as we didn't return so far! */
1341
1342         /*
1343          * calc of b_ij (scalar) and db_ij (vector)
1344          *
1345          * - for b_ij: chi, beta, f_c_ik, w(=1), c, d, h, n, cos_theta
1346          *
1347          * - for db_ij: d_theta, sin_theta, cos_theta, f_c_ik, df_c_ik,
1348          *              w_ik,
1349          *
1350          */
1351
1352         v3_sub(&dist_ik,&(ai->r),&(ak->r));
1353         if(bc) check_per_bound(moldyn,&dist_ik);
1354         d_ik=v3_norm(&dist_ik);
1355
1356         /* constants for f_c_ik calc */
1357         if(num==ak->bnum) {
1358                 R=params->R[num];
1359                 S=params->S[num];
1360         }
1361         else {
1362                 R=params->Rmixed;
1363                 S=params->Smixed;
1364         }
1365
1366         /* calc of f_c_ik */
1367         if(d_ik>S) {
1368                 f_c_ik=0.0;
1369                 df_c_ik=0.0;
1370         }
1371         else if(d_ik<R) {
1372                 f_c_ik=1.0;
1373                 df_c_ik=0.0;
1374         }
1375         else {
1376                 s_r=S-R;
1377                 arg=M_PI*(d_ik-R)/s_r;
1378                 f_c_ik=0.5+0.5*cos(arg);
1379                 df_c_ik=-0.5*sin(arg)*(M_PI/(s_r*d_ik));
1380         }
1381         
1382         v3_sub(&dist_jk,&(aj->r),&(ak->r));
1383         if(bc) check_per_bound(moldyn,&dist_jk);
1384         d_jk=v3_norm(&dist_jk);
1385
1386         /* get exchange data */
1387         n=*(exchange->n);
1388         c=*(exchange->c);
1389         d=*(exchange->d);
1390         h=*(exchange->h);
1391         c2=exchange->c2;
1392         d2=exchange->d2;
1393         c2d2=exchange->c2d2;
1394
1395         numer=d_ij2+d_ik*d_ik-d_jk*d_jk;
1396         denom=2*d_ij*d_ik;
1397         cos_theta=numer/denom;
1398         /* prefere law of cosines, dot product -> nan (often) */
1399         //cos_theta=v3_scalar_product(&dist_ij,&dist_ik)/(d_ij*d_ik);
1400         sin_theta=sqrt(1.0-(cos_theta*cos_theta));
1401         theta=acos(cos_theta);
1402         d_theta=(-1.0/sqrt(1.0-cos_theta*cos_theta))/(denom*denom);
1403         d_theta1=2*denom-numer*2*d_ik/d_ij;
1404         d_theta2=2*denom-numer*2*d_ij/d_ik;
1405         d_theta1*=d_theta;
1406         d_theta2*=d_theta;
1407
1408         h_cos=(h-cos_theta);
1409         d2_h_cos2=d2+(h_cos*h_cos);
1410
1411         frac=c2/(d2_h_cos2);
1412         g=1.0+c2d2-frac;
1413
1414         if(f_c_ik==0.0) {
1415                 bracket=0.0;
1416                 bracket_n_1=0.0;
1417                 bracket_n=0.0;
1418                 printf("Foo -> 0: ");
1419         }
1420         else {
1421                 bracket=f_c_ik*g;
1422                 bracket_n_1=pow(bracket,n-1.0);
1423                 bracket_n=bracket_n_1*bracket;
1424                 printf("Foo -> 1: ");
1425         }
1426 //printf("%.15f %.15f %.15f\n",bracket_n_1,bracket_n,bracket);
1427
1428         /* calc of db_ij and the 2 sums */
1429         exchange->sum1_3bp+=bracket_n;
1430         exchange->sum2_3bp+=bracket_n_1;
1431
1432         /* derivation of theta */
1433         v3_scale(&force,&dist_ij,d_theta1);
1434         v3_scale(&temp,&dist_ik,d_theta2);
1435         v3_add(&force,&force,&temp);
1436
1437         /* part 1 of db_ij */
1438         v3_scale(&force,&force,sin_theta*2*h_cos*f_c_ik*frac/d2_h_cos2);
1439
1440         /* part 2 of db_ij */
1441         v3_scale(&temp,&dist_ik,df_c_ik*g);
1442
1443         /* sum up and add to db_ij */
1444         v3_add(&temp,&temp,&force);
1445         v3_add(&(exchange->db_ij),&(exchange->db_ij),&temp);
1446                                 
1447         return 0;
1448 }
1449