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