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