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