more changes ...
[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 int moldyn_usage(char **argv) {
27
28         printf("\n%s usage:\n\n",argv[0]);
29         printf("--- general options ---\n");
30         printf("-E <steps> <file> (log total energy)\n");
31         printf("-M <steps> <file> (log total momentum)\n");
32         printf("-D <steps> <file> (dump total information)\n");
33         printf("-S <steps> <filebase> (single save file)\n");
34         printf("-V <steps> <filebase> (rasmol file)\n");
35         printf("--- physics options ---\n");
36         printf("-T <temperature> [K] (%f)\n",MOLDYN_TEMP);
37         printf("-t <timestep tau> [s] (%.15f)\n",MOLDYN_TAU);
38         printf("-C <cutoff radius> [m] (%.15f)\n",MOLDYN_CUTOFF);
39         printf("-R <runs> (%d)\n",MOLDYN_RUNS);
40         printf(" -- integration algo --\n");
41         printf("  -I <number> (%d)\n",MOLDYN_INTEGRATE_DEFAULT);
42         printf("     0: velocity verlet\n");
43         printf(" -- potential --\n");
44         printf("  -P <number> <param1 param2 ...>\n");
45         printf("     0: harmonic oscillator\n");
46         printf("        param1: spring constant\n");
47         printf("        param2: equilibrium distance\n");
48         printf("     1: lennard jones\n");
49         printf("        param1: epsilon\n");
50         printf("        param2: sigma\n");
51         printf("\n");
52
53         return 0;
54 }
55
56 int moldyn_parse_argv(t_moldyn *moldyn,int argc,char **argv) {
57
58         int i;
59
60         memset(moldyn,0,sizeof(t_moldyn));
61
62         /* default values */
63         moldyn->t=MOLDYN_TEMP;
64         moldyn->tau=MOLDYN_TAU;
65         moldyn->time_steps=MOLDYN_RUNS;
66         moldyn->integrate=velocity_verlet;
67
68         /* parse argv */
69         for(i=1;i<argc;i++) {
70                 if(argv[i][0]=='-') {
71                         switch(argv[i][1]){
72                                 case 'E':
73                                         moldyn->ewrite=atoi(argv[++i]);
74                                         strncpy(moldyn->efb,argv[++i],64);
75                                         break;
76                                 case 'M':
77                                         moldyn->mwrite=atoi(argv[++i]);
78                                         strncpy(moldyn->mfb,argv[++i],64);
79                                         break;
80                                 case 'S':
81                                         moldyn->swrite=atoi(argv[++i]);
82                                         strncpy(moldyn->sfb,argv[++i],64);
83                                         break;
84                                 case 'V':
85                                         moldyn->vwrite=atoi(argv[++i]);
86                                         strncpy(moldyn->vfb,argv[++i],64);
87                                         break;
88                                 case 'T':
89                                         moldyn->t=atof(argv[++i]);
90                                         break;
91                                 case 't':
92                                         moldyn->tau=atof(argv[++i]);
93                                         break;
94                                 case 'C':
95                                         moldyn->cutoff=atof(argv[++i]);
96                                         break;
97                                 case 'R':
98                                         moldyn->time_steps=atoi(argv[++i]);
99                                         break;
100                                 case 'I':
101         /* integration algorithm */
102         switch(atoi(argv[++i])) {
103                 case MOLDYN_INTEGRATE_VERLET:
104                         moldyn->integrate=velocity_verlet;
105                         break;
106                 default:
107                         printf("unknown integration algo %s\n",argv[i]);
108                         moldyn_usage(argv);
109                         return -1;
110         }
111
112                                 case 'P':
113         /* potential + params */
114         switch(atoi(argv[++i])) {
115                 case MOLDYN_POTENTIAL_HO:
116                         hop.spring_constant=atof(argv[++i]);
117                         hop.equilibrium_distance=atof(argv[++i]);
118                         moldyn->pot_params=malloc(sizeof(t_ho_params));
119                         memcpy(moldyn->pot_params,&hop,sizeof(t_ho_params));
120                         moldyn->potential_force_function=harmonic_oscillator;
121                         break;
122                 case MOLDYN_POTENTIAL_LJ:
123                         e=atof(argv[++i]);
124                         s=atof(argv[++i]);
125                         ljp.epsilon4=4*e;
126                         ljp.sigma6=s*s*s*s*s*s;
127                         ljp.sigma12=ljp.sigma6*ljp.sigma6;
128                         moldyn->pot_params=malloc(sizeof(t_lj_params));
129                         memcpy(moldyn->pot_params,&ljp,sizeof(t_lj_params));
130                         moldyn->potential_force_function=lennard_jones;
131                         break;
132                 default:
133                         printf("unknown potential %s\n",argv[i]);
134                         moldyn_usage(argv);
135                         return -1;
136         }
137
138                                 default:
139                                         printf("unknown option %s\n",argv[i]);
140                                         moldyn_usage(argv);
141                                         return -1;
142                         }
143                 } else {
144                         moldyn_usage(argv);
145                         return -1;
146                 }
147         }
148
149         return 0;
150 }
151
152 int moldyn_log_init(t_moldyn *moldyn) {
153
154         moldyn->lvstat=0;
155         t_visual *vis;
156
157         vis=&(moldyn->vis);
158
159         if(moldyn->ewrite) {
160                 moldyn->efd=open(moldyn->efb,O_WRONLY|O_CREAT|O_TRUNC);
161                 if(moldyn->efd<0) {
162                         perror("[moldyn] efd open");
163                         return moldyn->efd;
164                 }
165                 dprintf(moldyn->efd,"# moldyn total energy logfile\n");
166                 moldyn->lvstat|=MOLDYN_LVSTAT_TOTAL_E;
167         }
168
169         if(moldyn->mwrite) {
170                 moldyn->mfd=open(moldyn->mfb,O_WRONLY|O_CREAT|O_TRUNC);
171                 if(moldyn->mfd<0) {
172                         perror("[moldyn] mfd open");
173                         return moldyn->mfd;
174                 }
175                 dprintf(moldyn->mfd,"# moldyn total momentum logfile\n");
176                 moldyn->lvstat|=MOLDYN_LVSTAT_TOTAL_M;
177         }
178
179         if(moldyn->swrite)
180                 moldyn->lvstat|=MOLDYN_LVSTAT_SAVE;
181
182         if((moldyn->vwrite)&&(vis)) {
183                 moldyn->visual=vis;
184                 visual_init(vis,moldyn->vfb);
185                 moldyn->lvstat|=MOLDYN_LVSTAT_VISUAL;
186         }
187
188         moldyn->lvstat|=MOLDYN_LVSTAT_INITIALIZED;
189
190         return 0;
191 }
192
193 int moldyn_log_shutdown(t_moldyn *moldyn) {
194
195         if(moldyn->efd) close(moldyn->efd);
196         if(moldyn->mfd) close(moldyn->efd);
197         if(moldyn->dfd) close(moldyn->efd);
198         if(moldyn->visual) visual_tini(moldyn->visual);
199
200         return 0;
201 }
202
203 int moldyn_init(t_moldyn *moldyn,int argc,char **argv) {
204
205         int ret;
206
207         ret=moldyn_parse_argv(moldyn,argc,argv);
208         if(ret<0) return ret;
209
210         ret=moldyn_log_init(moldyn);
211         if(ret<0) return ret;
212
213         rand_init(&(moldyn->random),NULL,1);
214         moldyn->random.status|=RAND_STAT_VERBOSE;
215
216         moldyn->status=0;
217
218         return 0;
219 }
220
221 int moldyn_shutdown(t_moldyn *moldyn) {
222
223         moldyn_log_shutdown(moldyn);
224         rand_close(&(moldyn->random));
225         free(moldyn->atom);
226
227         return 0;
228 }
229
230 int create_lattice(u8 type,int element,double mass,double lc,
231                    int a,int b,int c,t_atom **atom) {
232
233         int count;
234         int ret;
235         t_3dvec origin;
236
237         count=a*b*c;
238
239         if(type==FCC) count*=4;
240         if(type==DIAMOND) count*=8;
241
242         *atom=malloc(count*sizeof(t_atom));
243         if(*atom==NULL) {
244                 perror("malloc (atoms)");
245                 return -1;
246         }
247
248         v3_zero(&origin);
249
250         switch(type) {
251                 case FCC:
252                         ret=fcc_init(a,b,c,lc,*atom,&origin);
253                         break;
254                 case DIAMOND:
255                         ret=diamond_init(a,b,c,lc,*atom,&origin);
256                         break;
257                 default:
258                         printf("unknown lattice type (%02x)\n",type);
259                         return -1;
260         }
261
262         /* debug */
263         if(ret!=count) {
264                 printf("ok, there is something wrong ...\n");
265                 printf("calculated -> %d atoms\n",count);
266                 printf("created -> %d atoms\n",ret);
267                 return -1;
268         }
269
270         while(count) {
271                 (*atom)[count-1].element=element;
272                 (*atom)[count-1].mass=mass;
273                 count-=1;
274         }
275
276         return ret;
277 }
278
279 int destroy_lattice(t_atom *atom) {
280
281         if(atom) free(atom);
282
283         return 0;
284 }
285
286 int thermal_init(t_moldyn *moldyn) {
287
288         /*
289          * - gaussian distribution of velocities
290          * - zero total momentum
291          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
292          */
293
294         int i;
295         double v,sigma;
296         t_3dvec p_total,delta;
297         t_atom *atom;
298         t_random *random;
299
300         atom=moldyn->atom;
301         random=&(moldyn->random);
302
303         /* gaussian distribution of velocities */
304         v3_zero(&p_total);
305         for(i=0;i<moldyn->count;i++) {
306                 sigma=sqrt(2.0*K_BOLTZMANN*moldyn->t/atom[i].mass);
307                 /* x direction */
308                 v=sigma*rand_get_gauss(random);
309                 atom[i].v.x=v;
310                 p_total.x+=atom[i].mass*v;
311                 /* y direction */
312                 v=sigma*rand_get_gauss(random);
313                 atom[i].v.y=v;
314                 p_total.y+=atom[i].mass*v;
315                 /* z direction */
316                 v=sigma*rand_get_gauss(random);
317                 atom[i].v.z=v;
318                 p_total.z+=atom[i].mass*v;
319         }
320
321         /* zero total momentum */
322         v3_scale(&p_total,&p_total,1.0/moldyn->count);
323         for(i=0;i<moldyn->count;i++) {
324                 v3_scale(&delta,&p_total,1.0/atom[i].mass);
325                 v3_sub(&(atom[i].v),&(atom[i].v),&delta);
326         }
327
328         /* velocity scaling */
329         scale_velocity(moldyn);
330
331         return 0;
332 }
333
334 int scale_velocity(t_moldyn *moldyn) {
335
336         int i;
337         double e,c;
338         t_atom *atom;
339
340         atom=moldyn->atom;
341
342         /*
343          * - velocity scaling (E = 3/2 N k T), E: kinetic energy
344          */
345         e=0.0;
346         for(i=0;i<moldyn->count;i++)
347                 e+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
348         c=sqrt((2.0*e)/(3.0*moldyn->count*K_BOLTZMANN*moldyn->t));
349         for(i=0;i<moldyn->count;i++)
350                 v3_scale(&(atom[i].v),&(atom[i].v),(1.0/c));
351
352         return 0;
353 }
354
355 double get_e_kin(t_atom *atom,int count) {
356
357         int i;
358         double e;
359
360         e=0.0;
361
362         for(i=0;i<count;i++) {
363                 e+=0.5*atom[i].mass*v3_absolute_square(&(atom[i].v));
364         }
365
366         return e;
367 }
368
369 double get_e_pot(t_moldyn *moldyn) {
370
371         return moldyn->energy;
372 }
373
374 double get_total_energy(t_moldyn *moldyn) {
375
376         double e;
377
378         e=get_e_kin(moldyn->atom,moldyn->count);
379         e+=get_e_pot(moldyn);
380
381         return e;
382 }
383
384 t_3dvec get_total_p(t_atom *atom, int count) {
385
386         t_3dvec p,p_total;
387         int i;
388
389         v3_zero(&p_total);
390         for(i=0;i<count;i++) {
391                 v3_scale(&p,&(atom[i].v),atom[i].mass);
392                 v3_add(&p_total,&p_total,&p);
393         }
394
395         return p_total;
396 }
397
398 double estimate_time_step(t_moldyn *moldyn,double nn_dist,double t) {
399
400         double tau;
401
402         tau=0.05*nn_dist/(sqrt(3.0*K_BOLTZMANN*t/moldyn->atom[0].mass));
403         tau*=1.0E-9;
404         if(tau<moldyn->tau)
405                 printf("[moldyn] warning: time step  (%f > %.15f)\n",
406                        moldyn->tau,tau);
407
408         return tau;     
409 }
410
411 /*
412  * numerical tricks
413  */
414
415 /* linked list / cell method */
416
417 int link_cell_init(t_moldyn *moldyn) {
418
419         t_linkcell *lc;
420         int i;
421
422         lc=&(moldyn->lc);
423
424         /* list log fd */
425         lc->listfd=open("/dev/null",O_WRONLY);
426
427         /* partitioning the md cell */
428         lc->nx=moldyn->dim.x/moldyn->cutoff;
429         lc->x=moldyn->dim.x/lc->nx;
430         lc->ny=moldyn->dim.y/moldyn->cutoff;
431         lc->y=moldyn->dim.y/lc->ny;
432         lc->nz=moldyn->dim.z/moldyn->cutoff;
433         lc->z=moldyn->dim.z/lc->nz;
434
435         lc->cells=lc->nx*lc->ny*lc->nz;
436         lc->subcell=malloc(lc->cells*sizeof(t_list));
437
438         printf("initializing linked cells (%d)\n",lc->cells);
439
440         for(i=0;i<lc->cells;i++)
441                 //list_init(&(lc->subcell[i]),1);
442                 list_init(&(lc->subcell[i]));
443
444         link_cell_update(moldyn);
445         
446         return 0;
447 }
448
449 int link_cell_update(t_moldyn *moldyn) {
450
451         int count,i,j,k;
452         int nx,ny,nz;
453         t_atom *atom;
454         t_linkcell *lc;
455
456         atom=moldyn->atom;
457         lc=&(moldyn->lc);
458
459         nx=lc->nx;
460         ny=lc->ny;
461         nz=lc->nz;
462
463         for(i=0;i<lc->cells;i++)
464                 list_destroy(&(moldyn->lc.subcell[i]));
465         
466         for(count=0;count<moedyn->count;count++) {
467                 i=(atom[count].r.x+(moldyn->dim.x/2))/lc->x;
468                 j=(atom[count].r.y+(moldyn->dim.y/2))/lc->y;
469                 k=(atom[count].r.z+(moldyn->dim.z/2))/lc->z;
470                 list_add_immediate_ptr(&(moldyn->lc.subcell[i+j*nx+k*nx*ny]),
471                                        &(atom[count]));
472         }
473
474         return 0;
475 }
476
477 int link_cell_neighbour_index(t_moldyn *moldyn,int i,int j,int k,t_list *cell) {
478
479         t_linkcell *lc;
480         int a;
481         int count1,count2;
482         int ci,cj,ck;
483         int nx,ny,nz;
484         int x,y,z;
485         u8 bx,by,bz;
486
487         lc=&(moldyn->lc);
488         nx=lc->nx;
489         ny=lc->ny;
490         nz=lc->nz;
491         count1=1;
492         count2=27;
493         a=nx*ny;
494
495
496         cell[0]=lc->subcell[i+j*nx+k*a];
497         for(ci=-1;ci<=1;ci++) {
498                 bx=0;
499                 x=i+ci;
500                 if((x<0)||(x>=nx)) {
501                         x=(x+nx)%nx;
502                         bx=1;
503                 }
504                 for(cj=-1;cj<=1;cj++) {
505                         by=0;
506                         y=j+cj;
507                         if((y<0)||(y>=ny)) {
508                                 y=(y+ny)%ny;
509                                 by=1;
510                         }
511                         for(ck=-1;ck<=1;ck++) {
512                                 bz=0;
513                                 z=k+ck;
514                                 if((z<0)||(z>=nz)) {
515                                         z=(z+nz)%nz;
516                                         bz=1;
517                                 }
518                                 if(!(ci|cj|ck)) continue;
519                                 if(bx|by|bz) {
520                                         cell[--count2]=lc->subcell[x+y*nx+z*a];
521                                 }
522                                 else {
523                                         cell[count1++]=lc->subcell[x+y*nx+z*a];
524                                 }
525                         }
526                 }
527         }
528
529         lc->dnlc=count2;
530         lc->countn=27;
531
532         return count2;
533 }
534
535 int link_cell_shutdown(t_moldyn *moldyn) {
536
537         int i;
538         t_linkcell *lc;
539
540         lc=&(moldyn->lc);
541
542         for(i=0;i<lc->nx*lc->ny*lc->nz;i++)
543                 list_shutdown(&(moldyn->lc.subcell[i]));
544
545         if(lc->listfd) close(lc->listfd);
546
547         return 0;
548 }
549
550 /*
551  *
552  * 'integration of newtons equation' - algorithms
553  *
554  */
555
556 /* start the integration */
557
558 int moldyn_integrate(t_moldyn *moldyn) {
559
560         int i,sched;
561         unsigned int e,m,s,d,v;
562         t_3dvec p;
563
564         int fd;
565         char fb[128];
566
567         /* initialize linked cell method */
568         link_cell_init(moldyn);
569
570         /* logging & visualization */
571         e=moldyn->ewrite;
572         m=moldyn->mwrite;
573         s=moldyn->swrite;
574         d=moldyn->dwrite;
575         v=moldyn->vwrite;
576
577         if(!(moldyn->lvstat&MOLDYN_LVSTAT_INITIALIZED)) {
578                 printf("[moldyn] warning, lv system not initialized\n");
579                 return -1;
580         }
581
582         /* sqaure of some variables */
583         moldyn->tau_square=moldyn->tau*moldyn->tau;
584         moldyn->cutoff_square=moldyn->cutoff*moldyn->cutoff;
585
586         /* calculate initial forces */
587         moldyn->potential_force_function(moldyn);
588
589         for(sched=0;sched<moldyn->schedule.content_count;sched++) {
590                 moldyn->tau=;
591                 moldyn->tau_square=;
592
593         // hier weiter ...
594
595         for(i=0;i<moldyn->time_steps;i++) {
596
597                 /* integration step */
598                 moldyn->integrate(moldyn);
599
600                 /* check for log & visualization */
601                 if(e) {
602                         if(!(i%e))
603                                 dprintf(moldyn->efd,
604                                         "%.15f %.45f\n",i*moldyn->tau,
605                                         get_total_energy(moldyn));
606                 }
607                 if(m) {
608                         if(!(i%m)) {
609                                 p=get_total_p(moldyn->atom,moldyn->count);
610                                 dprintf(moldyn->mfd,
611                                         "%.15f %.45f\n",i*moldyn->tau,
612                                         v3_norm(&p));
613                         }
614                 }
615                 if(s) {
616                         if(!(i%s)) {
617                                 snprintf(fb,128,"%s-%f-%.15f.save",moldyn->sfb,
618                                          moldyn->t,i*moldyn->tau);
619                                 fd=open(fb,O_WRONLY|O_TRUNC|O_CREAT);
620                                 if(fd<0) perror("[moldyn] save fd open");
621                                 else {
622                                         write(fd,moldyn,sizeof(t_moldyn));
623                                         write(fd,moldyn->atom,
624                                               moldyn->count*sizeof(t_atom));
625                                 }
626                                 close(fd);
627                         }       
628                 }
629                 if(v) {
630                         if(!(i%v)) {
631                                 visual_atoms(moldyn->visual,i*moldyn->tau,
632                                              moldyn->atom,moldyn->count);
633                                 printf("\rsteps: %d",i);
634                                 fflush(stdout);
635                         }
636                 }
637         }
638
639         return 0;
640 }
641
642 /* velocity verlet */
643
644 int velocity_verlet(t_moldyn *moldyn) {
645
646         int i,count;
647         double tau,tau_square;
648         t_3dvec delta;
649         t_atom *atom;
650
651         atom=moldyn->atom;
652         count=moldyn->count;
653         tau=moldyn->tau;
654         tau_square=moldyn->tau_square;
655
656         for(i=0;i<count;i++) {
657                 /* new positions */
658                 v3_scale(&delta,&(atom[i].v),tau);
659                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
660                 v3_scale(&delta,&(atom[i].f),0.5*tau_square/atom[i].mass);
661                 v3_add(&(atom[i].r),&(atom[i].r),&delta);
662                 v3_per_bound(&(atom[i].r),&(moldyn->dim));
663
664                 /* velocities */
665                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
666                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
667         }
668
669         /* neighbour list update */
670 printf("list update ...\n");
671         link_cell_update(moldyn);
672 printf("done\n");
673
674         /* forces depending on chosen potential */
675 printf("calc potential/force ...\n");
676         potential_force_calc(moldyn);
677         //moldyn->potential_force_function(moldyn);
678 printf("done\n");
679
680         for(i=0;i<count;i++) {
681                 /* again velocities */
682                 v3_scale(&delta,&(atom[i].f),0.5*tau/atom[i].mass);
683                 v3_add(&(atom[i].v),&(atom[i].v),&delta);
684         }
685
686         return 0;
687 }
688
689
690 /*
691  *
692  * potentials & corresponding forces
693  * 
694  */
695
696 /* generic potential and force calculation */
697
698 int potential_force_calc(t_moldyn *moldyn) {
699
700         int i,count;
701         t_atom *atom;
702         t_linkcell *lc;
703         t_list neighbour[27];
704         t_list *this;
705         double u;
706         u8 bc,bc3;
707         int countn,dnlc;
708
709         count=moldyn->count;
710         atom=moldyn->atom;
711         lc=&(moldyn->lc);
712
713         /* reset energy */
714         moldyn->energy=0.0;
715
716         for(i=0;i<count;i++) {
717         
718                 /* reset force */
719                 v3_zero(&(atom[i].f));
720
721                 /* single particle potential/force */
722                 if(atom[i].attr&ATOM_ATTR_1BP)
723                         moldyn->pf_func1b(moldyn,&(atom[i]));
724
725                 /* 2 body pair potential/force */
726                 if(atom[i].attr&(ATOM_ATTR_2BP|ATOM_ATTR_3BP)) {
727                 
728                         link_cell_neighbour_index(moldyn,
729                                 (atom[i].r.x+moldyn->dim.x/2)/lc->x,
730                                 (atom[i].r.y+moldyn->dim.y/2)/lc->y,
731                                 (atom[i].r.z+moldyn->dim.z/2)/lc->z,
732                                 neighbour);
733
734                         countn=lc->countn;
735                         dnlc=lc->dnlc;
736
737                         for(j=0;j<countn;j++) {
738
739                                 this=&(neighbour[j]);
740                                 list_reset(this);
741
742                                 if(this->start==NULL)
743                                         continue;
744
745                                 bc=(j<dnlc)?0:1;
746
747                                 do {
748                                         btom=this->current->data;
749
750                                         if(btom==&(atom[i]))
751                                                 continue;
752
753                                         if((btom->attr&ATOM_ATTR_2BP)&
754                                            (atom[i].attr&ATOM_ATTR_2BP))
755                                                 moldyn->pf_func2b(moldyn,
756                                                                   &(atom[i]),
757                                                                   btom,
758                                                                   bc);
759
760                                         /* 3 body potential/force */
761
762                                         if(!(atom[i].attr&ATOM_ATTR_3BP)||
763                                            !(btom->attr&ATOM_ATTR_3BP))
764                                                 continue;
765
766                                         link_cell_neighbour_index(moldyn,
767                                            (btom->r.x+moldyn->dim.x/2)/lc->x,
768                                            (btom->r.y+moldyn->dim.y/2)/lc->y,
769                                            (btom->r.z+moldyn->dim.z/2)/lc->z,
770                                            neighbourk);
771
772                                         for(k=0;k<lc->countn;k++) {
773
774                                                 thisk=&(neighbourk[k]);
775                                                 list_reset(thisk);
776                                         
777                                                 if(thisk->start==NULL)
778                                                         continue;
779
780                                                 bck=(k<lc->dnlc)?0:1;
781
782                                                 do {
783
784                         ktom=thisk->current->data;
785
786                         if(!(ktom->attr&ATOM_ATTR_3BP))
787                                 continue;
788
789                         if(ktom==btom)
790                                 continue;
791
792                         if(ktom==&(atom[i]))
793                                 continue;
794
795                         moldyn->pf_func3b(moldyn,&(atom[i]),btom,ktom,bck);
796
797                                                 } while(list_next(thisk)!=\
798                                                         L_NO_NEXT_ELEMENT);
799                                         
800                                 } while(list_next(this)!=L_NO_NEXT_ELEMENT);
801                         }
802                 }
803         }
804
805         return 0;
806 }
807
808 /*
809  * periodic boundayr checking
810  */
811
812 int check_per_bound(t_moldyn *moldyn,t_3dvec *a) {
813         
814         double x,y,z;
815
816         x=0.5*dim->x;
817         y=0.5*dim->y;
818         z=0.5*dim->z;
819
820         if(moldyn->MOLDYN_ATTR_PBX)
821                 if(a->x>=x) a->x-=dim->x;
822                 else if(-a->x>x) a->x+=dim->x;
823         if(moldyn->MOLDYN_ATTR_PBY)
824                 if(a->y>=y) a->y-=dim->y;
825                 else if(-a->y>y) a->y+=dim->y;
826         if(moldyn->MOLDYN_ATTR_PBZ)
827                 if(a->z>=z) a->z-=dim->z;
828                 else if(-a->z>z) a->z+=dim->z;
829
830         return 0;
831 }
832         
833
834 /*
835  * example potentials
836  */
837
838 /* harmonic oscillator potential and force */
839
840 int harmonic_oscillator(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc)) {
841
842         t_ho_params *params;
843         t_3dvec force,distance;
844         double d;
845         double sc,equi_dist;
846
847         params=moldyn->pot2b_params;
848         sc=params->spring_constant;
849         equi_dist=params->equilibrium_distance;
850
851         v3_sub(&distance,&(ai->r),&(aj->r);
852         
853         v3_per_bound(&distance,&(moldyn->dim));
854         if(bc) check_per_bound(moldyn,&distance);
855         d=v3_norm(&distance);
856         if(d<=moldyn->cutoff) {
857                 /* energy is 1/2 (d-d0)^2, but we will add this twice ... */
858                 moldyn->energy+=(0.25*sc*(d-equi_dist)*(d-equi_dist));
859                 v3_scale(&force,&distance,-sc*(1.0-(equi_dist/d)));
860                 v3_add(&(ai->f),&(ai->f),&force);
861         }
862
863         return 0;
864 }
865
866 /* lennard jones potential & force for one sort of atoms */
867  
868 int lennard_jones(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
869
870         t_lj_params *params;
871         t_3dvec force,distance;
872         double d,h1,h2,u;
873         double eps,sig6,sig12;
874
875         params=moldyn->pot_params;
876         eps=params->epsilon4;
877         sig6=params->sigma6;
878         sig12=params->sigma12;
879
880         v3_sub(&distance,&(ai->r),&(aj->r));
881         if(bc) check_per_bound(moldyn,&distance);
882         d=v3_absolute_square(&distance);        /* 1/r^2 */
883         if(d<=moldyn->cutoff_square) {
884                 d=1.0/d;                        /* 1/r^2 */
885                 h2=d*d;                         /* 1/r^4 */
886                 h2*=d;                          /* 1/r^6 */
887                 h1=h2*h2;                       /* 1/r^12 */
888                 /* energy is eps*..., but we will add this twice ... */
889                 moldyn->energy+=0.5*eps*(sig12*h1-sig6*h2);
890                 h2*=d;                          /* 1/r^8 */
891                 h1*=d;                          /* 1/r^14 */
892                 h2*=6*sig6;
893                 h1*=12*sig12;
894                 d=+h1-h2;
895                 d*=eps;
896                 v3_scale(&force,&distance,d);
897                 v3_add(&(ai->f),&(aj->f),&force);
898         }
899
900         return 0;
901 }
902
903 /*
904  * tersoff potential & force for 2 sorts of atoms
905  */
906
907 /* tersoff 1 body part */
908 int tersoff_mult_1bp(t_moldyn *moldyn,t_atom *ai) {
909
910         int num;
911         t_tersoff_mult_params *params;
912         t_tersoff_exchange *exchange;
913         
914         num=ai->bnum;
915         params=moldyn->pot1b_params;
916         exchange=&(params->exchange);
917
918         /*
919          * simple: point constant parameters only depending on atom i to
920          *         their right values
921          */
922
923         exchange->beta=&(params->beta[num]);
924         exchange->n=&(params->n[num]);
925         exchange->c=&(params->c[num]);
926         exchange->d=&(params->d[num]);
927         exchange->h=&(params->h[num]);
928
929         exchange->betan=pow(*(exchange->beta),*(exchange->n));
930         exchange->c2=params->c[num]*params->c[num];
931         exchange->d2=params->d[num]*params->d[num];
932         exchange->c2d2=exchange->c2/exchange->d2;
933
934         return 0;
935 }
936         
937 /* tersoff 2 body part */
938 int tersoff_mult_2bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,u8 bc) {
939
940         t_tersoff_mult_params *params;
941         t_tersoff_exchange *exchange;
942         t_3dvec dist_ij;
943         double d_ij;
944         double A,B,R,S,lambda;
945         int num;
946
947         params=moldyn->pot_params;
948         num=ai->bnum;
949         exchange=&(params->exchange);
950
951         exchange->run3bp=0;
952         
953         /*
954          * we need: f_c, df_c, f_r, df_r
955          *
956          * therefore we need: R, S, A, lambda
957          */
958
959         v3_sub(&dist_ij,&(ai->r),&(aj->r));
960
961         if(bc) check_per_bound(moldyn,&dist_ij);
962
963         /* save for use in 3bp */ /* REALLY ?!?!?! */
964         exchange->dist_ij=dist_ij;
965
966         /* constants */
967         if(num==aj->bnum) {
968                 S=params->S[num];
969                 R=params->R[num];
970                 A=params->A[num];
971                 lambda=params->lambda[num];
972                 /* more constants depending of atoms i and j, needed in 3bp */
973                 params->exchange.B=&(params->B[num]);
974                 params->exchange.mu=params->mu[num];
975                 params->exchange.chi=1.0;
976         }
977         else {
978                 S=params->Smixed;
979                 R=params->Rmixed;
980                 A=params->Amixed;
981                 lambda=params->lambda_m;
982                 /* more constants depending of atoms i and j, needed in 3bp */
983                 params->exchange.B=&(params->Bmixed);
984                 params->exchange.mu=&(params->mu_m);
985                 params->exchange.chi=params->chi;
986         }
987
988         d_ij=v3_norm(&dist_ij);
989
990         /* save for use in 3bp */
991         exchange->d_ij=d_ij;
992
993         if(d_ij>S)
994                 return 0;
995
996         f_r=A*exp(-lamda*d_ij);
997         df_r=-lambda*f_r/d_ij;
998
999         /* f_a, df_a calc + save for 3bp use */
1000         exchange->f_a=-B*exp(-mu*d_ij);
1001         exchange->df_a=-mu*exchange->f_a/d_ij;
1002
1003         if(d_ij<R) {
1004                 /* f_c = 1, df_c = 0 */
1005                 f_c=1.0;
1006                 df_c=0.0;
1007                 v3_scale(&force,&dist_ij,df_r);
1008         }
1009         else {
1010                 s_r=S-R;
1011                 arg=PI*(d_ij-R)/s_r;
1012                 f_c=0.5+0.5*cos(arg);
1013                 df_c=-0.5*sin(arg)*(PI/(s_r*d_ij));
1014                 scale=df_c*f_r+df_r*f_c;
1015                 v3_scale(&force,&dist_ij,scale);
1016         }
1017
1018         /* add forces */
1019         v3_add(&(ai->f),&(ai->f),&force);
1020         /* energy is 0.5 f_r f_c, but we will sum it up twice ... */
1021         moldyn->energy+=(0.25*f_r*f_c);
1022
1023         /* save for use in 3bp */
1024         exchange->f_c=f_c;
1025         exchange->df_c=df_c;
1026
1027         /* enable the run of 3bp function */
1028         exchange->run3bp=1;
1029
1030         return 0;
1031 }
1032
1033 /* tersoff 3 body part */
1034
1035 int tersoff_mult_3bp(t_moldyn *moldyn,t_atom *ai,t_atom *aj,t_atom *ak,u8 bc) {
1036
1037         t_tersoff_mult_params *params;
1038         t_tersoff_exchange *exchange;
1039         t_3dvec dist_ij,dist_ik,dist_jk;
1040         t_3dvec temp,force;
1041         double R,S,s_r;
1042         double d_ij,d_ik,d_jk;
1043         double f_c,df_c,b_ij,f_a,df_a;
1044         double n,c,d,h,neta,betan,betan_1;
1045         double theta,cos_theta,sin_theta;
1046         int num;
1047
1048         params=moldyn->pot_params;
1049         num=ai->bnum;
1050         exchange=params->exchange;
1051
1052         if(!(exchange->run3bp))
1053                 return 0;
1054
1055         /*
1056          * we need: f_c, d_fc, b_ij, db_ij, f_a, df_a
1057          *
1058          * we got f_c, df_c, f_a, df_a from 2bp calculation
1059          */
1060
1061         d_ij=exchange->d_ij;
1062         d_ij2=exchange->d_ij2;
1063
1064         f_a=params->exchange.f_a;
1065         df_a=params->exchange.df_a;
1066         
1067         /* d_ij is <= S, as we didn't return so far! */
1068
1069         /*
1070          * calc of b_ij (scalar) and db_ij (vector)
1071          *
1072          * - for b_ij: chi, beta, f_c_ik, w(=1), c, d, h, n, cos_theta
1073          *
1074          * - for db_ij: d_theta, sin_theta, cos_theta, f_c_ik, df_c_ik,
1075          *              w_ik,
1076          *
1077          */
1078
1079         
1080         v3_sub(&dist_ik,&(aj->i),&(ak->r));
1081         if(bc) check_per_bound(moldyn,&dist_ik);
1082         d_ik=v3_norm(&dist_ik);
1083
1084         /* constants for f_c_ik calc */
1085         if(num==ak->bnum) {
1086                 R=params->R[num];
1087                 S=params->S[num];
1088         }
1089         else {
1090                 R=params->Rmixed;
1091                 S=params->Smixed;
1092         }
1093
1094         /* calc of f_c_ik */
1095         if(d_ik>S)
1096                 return 0;
1097
1098         if(d_ik<R) {
1099                 /* f_c_ik = 1, df_c_ik = 0 */
1100                 f_c_ik=1.0;
1101                 df_c_ik=0.0;
1102         }
1103         else {
1104                 s_r=S-R;
1105                 arg=PI*(d_ik-R)/s_r;
1106                 f_c_ik=0.5+0.5*cos(arg);
1107                 df_c_ik=-0.5*sin(arg)*(PI/(s_r*d_ik));
1108         }
1109         
1110         v3_sub(&dist_jk,&(aj->r),&(ak->r));
1111         if(bc) check_per_bound(moldyn,&dist_jk);
1112         d_jk=v3_norm(&dist_jk);
1113
1114         beta=*(exchange->beta);
1115         betan=exchange->betan;
1116         n=*(exchange->n);
1117         c=*(exchange->c);
1118         d=*(exchange->d);
1119         h=*(exchange->h);
1120         c2=exchange->c2;
1121         d2=exchange->d2;
1122         c2d2=exchange->c2d2;
1123
1124         numer=d_ij2+d_ik*d_ik-d_jk*d_jk;
1125         denom=2*d_ij*d_ik;
1126         cos_theta=numer/denom;
1127         sin_theta=sqrt(1.0-(cos_theta*cos_theta));
1128         theta=arccos(cos_theta);
1129         d_theta=(-1.0/sqrt(1.0-cos_theta*cos_theta))/(denom*denom);
1130         d_theta1=2*denom-numer*2*d_ik/d_ij;
1131         d_theta2=2*denom-numer*2*d_ij/d_ik;
1132         d_theta1*=d_theta;
1133         d_theta2*=d_theta;
1134
1135         h_cos=(h-cos_theta);
1136         h_cos2=h_cos*h_cos;
1137         d2_h_cos2=d2-h_cos2;
1138
1139         /* some usefull expressions */
1140         frac1=c2/(d2-h_cos2);
1141         bracket1=1+c2d2-frac1;
1142         bracket2=f_c_ik*bracket1;
1143         bracket2_n_1=pow(bracket2,n-1.0);
1144         bracket2_n=bracket2_n_1*bracket2;
1145         bracket3=1+betan*bracket2_n;
1146         bracket3_pow_1=pow(bracket3,(-1.0/(2.0*n))-1.0);
1147         bracket3_pow=bracket3_pow_1*bracket3;
1148
1149         /* now go on with calc of b_ij and derivation of b_ij */
1150         b_ij=chi*bracket3_pow;
1151
1152         /* derivation of theta */
1153         v3_scale(&force,&dist_ij,d1_theta);
1154         v3_scale(&temp,&dist_ik,d_theta2);
1155         v3_add(&force,&force,&temp);
1156
1157         /* part 1 of derivation of b_ij */
1158         v3_scale(&force,sin_theta*2*h_cos*f_c_ik*frac1);
1159
1160         /* part 2 of derivation of b_ij */
1161         v3_scale(&temp,&dist_ik,df_c_ik*bracket1);
1162
1163         /* sum up and scale ... */
1164         v3_add(&temp,&temp,&force);
1165         scale=bracket2_n_1*n*betan*(1+betan*bracket3_pow_1)*chi*(1.0/(2.0*n));
1166         v3_scale(&temp,&temp,scale);
1167
1168         /* now construct an energy and a force out of that */
1169         v3_scale(&temp,&temp,f_a);
1170         v3_scale(&force,&dist_ij,df_a*b_ij);
1171         v3_add(&temp,&temp,&force);
1172         v3_scale(&temp,&temp,f_c);
1173         v3_scale(&force,&dist_ij,df_c*b_ij*f_a);
1174         v3_add(&force,&force,&temp);
1175
1176         /* add forces */
1177         v3_add(&(ai->f),&(ai->f),&force);
1178         /* energy is 0.5 f_r f_c, but we will sum it up twice ... */
1179         moldyn->energy+=(0.25*f_a*b_ij*f_c);
1180                                 
1181         return 0;
1182 }
1183