Merge release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / mdlib / qmmm.c
1 /*
2  * 
3  *                This source code is part of
4  * 
5  *                 G   R   O   M   A   C   S
6  * 
7  *          GROningen MAchine for Chemical Simulations
8  * 
9  *                        VERSION 3.2.0
10  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12  * Copyright (c) 2001-2004, The GROMACS development team,
13  * check out http://www.gromacs.org for more information.
14  
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version 2
18  * of the License, or (at your option) any later version.
19  * 
20  * If you want to redistribute modifications, please consider that
21  * scientific software is very special. Version control is crucial -
22  * bugs must be traceable. We will be happy to consider code for
23  * inclusion in the official distribution, but derived work must not
24  * be called official GROMACS. Details are found in the README & COPYING
25  * files - if they are missing, get the official version at www.gromacs.org.
26  * 
27  * To help us fund GROMACS development, we humbly ask that you cite
28  * the papers on the package - you can find them in the top README file.
29  * 
30  * For more info, check our website at http://www.gromacs.org
31  * 
32  * And Hey:
33  * GROwing Monsters And Cloning Shrimps
34  */
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #include <math.h>
40 #include "sysstuff.h"
41 #include "typedefs.h"
42 #include "macros.h"
43 #include "smalloc.h"
44 #include "physics.h"
45 #include "macros.h"
46 #include "vec.h"
47 #include "force.h"
48 #include "invblock.h"
49 #include "confio.h"
50 #include "names.h"
51 #include "network.h"
52 #include "pbc.h"
53 #include "ns.h"
54 #include "nrnb.h"
55 #include "bondf.h"
56 #include "mshift.h"
57 #include "txtdump.h"
58 #include "copyrite.h"
59 #include "qmmm.h"
60 #include <stdio.h>
61 #include <string.h>
62 #include "gmx_fatal.h"
63 #include "typedefs.h"
64 #include <stdlib.h>
65 #include "mtop_util.h"
66
67
68 /* declarations of the interfaces to the QM packages. The _SH indicate
69  * the QM interfaces can be used for Surface Hopping simulations 
70  */
71 #ifdef GMX_QMMM_GAMESS
72 /* GAMESS interface */
73
74 void 
75 init_gamess(t_commrec *cr, t_QMrec *qm, t_MMrec *mm);
76
77 real 
78 call_gamess(t_commrec *cr,t_forcerec *fr,
79             t_QMrec *qm, t_MMrec *mm,rvec f[], rvec fshift[]);
80
81 #elif defined GMX_QMMM_MOPAC
82 /* MOPAC interface */
83
84 void 
85 init_mopac(t_commrec *cr, t_QMrec *qm, t_MMrec *mm);
86
87 real 
88 call_mopac(t_commrec *cr,t_forcerec *fr, t_QMrec *qm, 
89            t_MMrec *mm,rvec f[], rvec fshift[]);
90
91 real 
92 call_mopac_SH(t_commrec *cr,t_forcerec *fr,t_QMrec *qm, 
93               t_MMrec *mm,rvec f[], rvec fshift[]);
94
95 #elif defined GMX_QMMM_GAUSSIAN
96 /* GAUSSIAN interface */
97
98 void 
99 init_gaussian(t_commrec *cr ,t_QMrec *qm, t_MMrec *mm);
100
101 real 
102 call_gaussian_SH(t_commrec *cr,t_forcerec *fr,t_QMrec *qm, 
103                  t_MMrec *mm,rvec f[], rvec fshift[]);
104
105 real 
106 call_gaussian(t_commrec *cr,t_forcerec *fr, t_QMrec *qm,
107               t_MMrec *mm,rvec f[], rvec fshift[]);
108
109 #elif defined GMX_QMMM_ORCA
110 /* ORCA interface */
111
112 void 
113 init_orca(t_commrec *cr ,t_QMrec *qm, t_MMrec *mm);
114
115 real 
116 call_orca(t_commrec *cr,t_forcerec *fr, t_QMrec *qm,
117               t_MMrec *mm,rvec f[], rvec fshift[]);
118
119 #endif
120
121
122
123
124 /* this struct and these comparison functions are needed for creating
125  * a QMMM input for the QM routines from the QMMM neighbor list.  
126  */
127
128 typedef struct {
129   int      j;
130   int      shift;
131 } t_j_particle;
132
133 static int struct_comp(const void *a, const void *b){
134
135   return (int)(((t_j_particle *)a)->j)-(int)(((t_j_particle *)b)->j);
136   
137 } /* struct_comp */
138
139 static int int_comp(const void *a,const void *b){
140   
141   return (*(int *)a) - (*(int *)b);
142   
143 } /* int_comp */
144
145 static int QMlayer_comp(const void *a, const void *b){
146   
147   return (int)(((t_QMrec *)a)->nrQMatoms)-(int)(((t_QMrec *)b)->nrQMatoms);
148   
149 } /* QMlayer_comp */
150
151 real call_QMroutine(t_commrec *cr, t_forcerec *fr, t_QMrec *qm, 
152                     t_MMrec *mm, rvec f[], rvec fshift[])
153 {
154   /* makes a call to the requested QM routine (qm->QMmethod) 
155    * Note that f is actually the gradient, i.e. -f
156    */
157   real
158     QMener=0.0;
159
160     /* do a semi-empiprical calculation */
161     
162     if (qm->QMmethod<eQMmethodRHF && !(mm->nrMMatoms))
163     {
164 #ifdef GMX_QMMM_MOPAC
165         if (qm->bSH)
166             QMener = call_mopac_SH(cr,fr,qm,mm,f,fshift);
167         else
168             QMener = call_mopac(cr,fr,qm,mm,f,fshift);
169 #else
170         gmx_fatal(FARGS,"Semi-empirical QM only supported with Mopac.");
171 #endif
172     }
173     else
174     {
175         /* do an ab-initio calculation */
176         if (qm->bSH && qm->QMmethod==eQMmethodCASSCF)
177         {
178 #ifdef GMX_QMMM_GAUSSIAN            
179             QMener = call_gaussian_SH(cr,fr,qm,mm,f,fshift);
180 #else
181             gmx_fatal(FARGS,"Ab-initio Surface-hopping only supported with Gaussian.");
182 #endif
183         }
184         else
185         {
186 #ifdef GMX_QMMM_GAMESS
187             QMener = call_gamess(cr,fr,qm,mm,f,fshift);
188 #elif defined GMX_QMMM_GAUSSIAN
189             QMener = call_gaussian(cr,fr,qm,mm,f,fshift);
190 #elif defined GMX_QMMM_ORCA
191             QMener = call_orca(cr,fr,qm,mm,f,fshift);
192 #else
193             gmx_fatal(FARGS,"Ab-initio calculation only supported with Gamess, Gaussian or ORCA.");
194 #endif
195         }
196     }
197     return (QMener);
198 }
199
200 void init_QMroutine(t_commrec *cr, t_QMrec *qm, t_MMrec *mm)
201 {
202     /* makes a call to the requested QM routine (qm->QMmethod) 
203      */
204     if (qm->QMmethod<eQMmethodRHF){
205 #ifdef GMX_QMMM_MOPAC
206         /* do a semi-empiprical calculation */
207         init_mopac(cr,qm,mm);
208 #else
209         gmx_fatal(FARGS,"Semi-empirical QM only supported with Mopac.");
210 #endif
211     }
212     else 
213     {
214         /* do an ab-initio calculation */
215 #ifdef GMX_QMMM_GAMESS
216         init_gamess(cr,qm,mm);
217 #elif defined GMX_QMMM_GAUSSIAN
218         init_gaussian(cr,qm,mm);
219 #elif defined GMX_QMMM_ORCA
220         init_orca(cr,qm,mm);
221 #else
222         gmx_fatal(FARGS,"Ab-initio calculation only supported with Gamess, Gaussian or ORCA.");   
223 #endif
224     }
225 } /* init_QMroutine */
226
227 void update_QMMM_coord(rvec x[],t_forcerec *fr, t_QMrec *qm, t_MMrec *mm)
228 {
229   /* shifts the QM and MM particles into the central box and stores
230    * these shifted coordinates in the coordinate arrays of the
231    * QMMMrec. These coordinates are passed on the QM subroutines.
232    */
233   int
234     i;
235
236   /* shift the QM atoms into the central box 
237    */
238   for(i=0;i<qm->nrQMatoms;i++){
239     rvec_sub(x[qm->indexQM[i]],fr->shift_vec[qm->shiftQM[i]],qm->xQM[i]);
240   }
241   /* also shift the MM atoms into the central box, if any 
242    */
243   for(i=0;i<mm->nrMMatoms;i++){
244         rvec_sub(x[mm->indexMM[i]],fr->shift_vec[mm->shiftMM[i]],mm->xMM[i]);   
245   }
246 } /* update_QMMM_coord */
247
248 static void punch_QMMM_excl(t_QMrec *qm,t_MMrec *mm,t_blocka *excls)
249 {
250   /* punch a file containing the bonded interactions of each QM
251    * atom with MM atoms. These need to be excluded in the QM routines
252    * Only needed in case of QM/MM optimizations
253    */
254   FILE
255     *out=NULL;
256   int
257     i,j,k,nrexcl=0,*excluded=NULL,max=0;
258   
259   
260   out = fopen("QMMMexcl.dat","w");
261   
262   /* this can be done more efficiently I think 
263    */
264   for(i=0;i<qm->nrQMatoms;i++){
265     nrexcl = 0;
266     for(j=excls->index[qm->indexQM[i]];
267         j<excls->index[qm->indexQM[i]+1];
268         j++){
269       for(k=0;k<mm->nrMMatoms;k++){
270         if(mm->indexMM[k]==excls->a[j]){/* the excluded MM atom */
271           if(nrexcl >= max){
272             max += 1000;
273             srenew(excluded,max);
274           }     
275           excluded[nrexcl++]=k;
276           continue;
277         }
278       }
279     }
280     /* write to file: */
281     fprintf(out,"%5d %5d\n",i+1,nrexcl);
282     for(j=0;j<nrexcl;j++){
283       fprintf(out,"%5d ",excluded[j]);
284     }
285     fprintf(out,"\n");
286   }
287   free(excluded);
288   fclose(out);
289 } /* punch_QMMM_excl */
290
291
292 /* end of QMMM subroutines */
293
294 /* QMMM core routines */
295
296 t_QMrec *mk_QMrec(void){
297   t_QMrec *qm;
298   snew(qm,1);
299   return qm;
300 } /* mk_QMrec */
301
302 t_MMrec *mk_MMrec(void){
303   t_MMrec *mm;
304   snew(mm,1);
305   return mm;
306 } /* mk_MMrec */
307
308 static void init_QMrec(int grpnr, t_QMrec *qm,int nr, int *atomarray, 
309                        gmx_mtop_t *mtop, t_inputrec *ir)
310 {
311   /* fills the t_QMrec struct of QM group grpnr 
312    */
313   int i;
314   gmx_mtop_atomlookup_t alook;
315   t_atom *atom;
316
317
318   qm->nrQMatoms = nr;
319   snew(qm->xQM,nr);
320   snew(qm->indexQM,nr);
321   snew(qm->shiftQM,nr); /* the shifts */
322   for(i=0;i<nr;i++){
323     qm->indexQM[i]=atomarray[i];
324   }
325
326   alook = gmx_mtop_atomlookup_init(mtop);
327
328   snew(qm->atomicnumberQM,nr);
329   for (i=0;i<qm->nrQMatoms;i++){
330     gmx_mtop_atomnr_to_atom(alook,qm->indexQM[i],&atom);
331     qm->nelectrons       += mtop->atomtypes.atomnumber[atom->type];
332     qm->atomicnumberQM[i] = mtop->atomtypes.atomnumber[atom->type];
333   }
334
335   gmx_mtop_atomlookup_destroy(alook);
336
337   qm->QMcharge       = ir->opts.QMcharge[grpnr];
338   qm->multiplicity   = ir->opts.QMmult[grpnr];
339   qm->nelectrons    -= ir->opts.QMcharge[grpnr];
340
341   qm->QMmethod       = ir->opts.QMmethod[grpnr];
342   qm->QMbasis        = ir->opts.QMbasis[grpnr];
343   /* trajectory surface hopping setup (Gaussian only) */
344   qm->bSH            = ir->opts.bSH[grpnr];
345   qm->CASorbitals    = ir->opts.CASorbitals[grpnr];
346   qm->CASelectrons   = ir->opts.CASelectrons[grpnr];
347   qm->SAsteps        = ir->opts.SAsteps[grpnr];
348   qm->SAon           = ir->opts.SAon[grpnr];
349   qm->SAoff          = ir->opts.SAoff[grpnr];
350   /* hack to prevent gaussian from reinitializing all the time */
351   qm->nQMcpus        = 0; /* number of CPU's to be used by g01, is set
352                            * upon initializing gaussian
353                            * (init_gaussian() 
354                            */
355   /* print the current layer to allow users to check their input */
356   fprintf(stderr,"Layer %d\nnr of QM atoms %d\n",grpnr,nr);
357   fprintf(stderr,"QMlevel: %s/%s\n\n",
358           eQMmethod_names[qm->QMmethod],eQMbasis_names[qm->QMbasis]);
359   
360   /* frontier atoms */
361   snew(qm->frontatoms,nr);
362   /* Lennard-Jones coefficients */ 
363   snew(qm->c6,nr);
364   snew(qm->c12,nr);
365   /* do we optimize the QM separately using the algorithms of the QM program??
366    */
367   qm->bTS      = ir->opts.bTS[grpnr];
368   qm->bOPT     = ir->opts.bOPT[grpnr];
369
370 } /* init_QMrec */  
371
372 t_QMrec *copy_QMrec(t_QMrec *qm)
373 {
374   /* copies the contents of qm into a new t_QMrec struct */
375   t_QMrec
376     *qmcopy;
377   int
378     i;
379   
380   qmcopy = mk_QMrec();
381   qmcopy->nrQMatoms = qm->nrQMatoms;
382   snew(qmcopy->xQM,qmcopy->nrQMatoms);
383   snew(qmcopy->indexQM,qmcopy->nrQMatoms);
384   snew(qmcopy->atomicnumberQM,qm->nrQMatoms);
385   snew(qmcopy->shiftQM,qmcopy->nrQMatoms); /* the shifts */
386   for (i=0;i<qmcopy->nrQMatoms;i++){
387     qmcopy->shiftQM[i]        = qm->shiftQM[i];
388     qmcopy->indexQM[i]        = qm->indexQM[i];
389     qmcopy->atomicnumberQM[i] = qm->atomicnumberQM[i];
390   }
391   qmcopy->nelectrons   = qm->nelectrons;
392   qmcopy->multiplicity = qm->multiplicity;
393   qmcopy->QMcharge     = qm->QMcharge;
394   qmcopy->nelectrons   = qm->nelectrons;
395   qmcopy->QMmethod     = qm->QMmethod; 
396   qmcopy->QMbasis      = qm->QMbasis;  
397   /* trajectory surface hopping setup (Gaussian only) */
398   qmcopy->bSH          = qm->bSH;
399   qmcopy->CASorbitals  = qm->CASorbitals;
400   qmcopy->CASelectrons = qm->CASelectrons;
401   qmcopy->SAsteps      = qm->SAsteps;
402   qmcopy->SAon         = qm->SAon;
403   qmcopy->SAoff        = qm->SAoff;
404   qmcopy->bOPT         = qm->bOPT;
405
406   /* Gaussian init. variables */
407   qmcopy->nQMcpus      = qm->nQMcpus;
408   for(i=0;i<DIM;i++)
409     qmcopy->SHbasis[i] = qm->SHbasis[i];
410   qmcopy->QMmem        = qm->QMmem;
411   qmcopy->accuracy     = qm->accuracy;
412   qmcopy->cpmcscf      = qm->cpmcscf;
413   qmcopy->SAstep       = qm->SAstep;
414   snew(qmcopy->frontatoms,qm->nrQMatoms);
415   snew(qmcopy->c12,qmcopy->nrQMatoms);
416   snew(qmcopy->c6,qmcopy->nrQMatoms);
417   if(qmcopy->bTS||qmcopy->bOPT){
418     for(i=1;i<qmcopy->nrQMatoms;i++){
419       qmcopy->frontatoms[i] = qm->frontatoms[i];
420       qmcopy->c12[i]        = qm->c12[i];
421       qmcopy->c6[i]         = qm->c6[i];
422     }
423   }
424
425   return(qmcopy);
426
427 } /*copy_QMrec */
428
429 t_QMMMrec *mk_QMMMrec(void)
430 {
431
432   t_QMMMrec *qr;
433
434   snew(qr,1);
435
436   return qr;
437
438 } /* mk_QMMMrec */
439
440 void init_QMMMrec(t_commrec *cr,
441                   matrix box,
442                   gmx_mtop_t *mtop,
443                   t_inputrec *ir,
444                   t_forcerec *fr)
445 {
446   /* we put the atomsnumbers of atoms that belong to the QMMM group in
447    * an array that will be copied later to QMMMrec->indexQM[..]. Also
448    * it will be used to create an QMMMrec->bQMMM index array that
449    * simply contains true/false for QM and MM (the other) atoms.
450    */
451
452   gmx_groups_t *groups;
453   atom_id   *qm_arr=NULL,vsite,ai,aj;
454   int       qm_max=0,qm_nr=0,i,j,jmax,k,l,nrvsite2=0;
455   t_QMMMrec *qr;
456   t_MMrec   *mm;
457   t_iatom   *iatoms;
458   real      c12au,c6au;
459   gmx_mtop_atomloop_all_t aloop;
460   t_atom    *atom;
461   gmx_mtop_ilistloop_all_t iloop;
462   int       a_offset;
463   t_ilist   *ilist_mol;
464   gmx_mtop_atomlookup_t alook;
465
466   c6au  = (HARTREE2KJ*AVOGADRO*pow(BOHR2NM,6)); 
467   c12au = (HARTREE2KJ*AVOGADRO*pow(BOHR2NM,12)); 
468   /* issue a fatal if the user wants to run with more than one node */
469   if ( PAR(cr)) gmx_fatal(FARGS,"QM/MM does not work in parallel, use a single node instead\n");
470
471   /* Make a local copy of the QMMMrec */
472   qr = fr->qr;
473
474   /* bQMMM[..] is an array containing TRUE/FALSE for atoms that are
475    * QM/not QM. We first set all elemenst at false. Afterwards we use
476    * the qm_arr (=MMrec->indexQM) to changes the elements
477    * corresponding to the QM atoms at TRUE.  */
478
479   qr->QMMMscheme     = ir->QMMMscheme;
480
481   /* we take the possibility into account that a user has
482    * defined more than one QM group:
483    */
484   /* an ugly work-around in case there is only one group In this case
485    * the whole system is treated as QM. Otherwise the second group is
486    * always the rest of the total system and is treated as MM.  
487    */
488
489   /* small problem if there is only QM.... so no MM */
490   
491   jmax = ir->opts.ngQM;
492
493   if(qr->QMMMscheme==eQMMMschemeoniom)
494     qr->nrQMlayers = jmax;
495   else
496     qr->nrQMlayers = 1; 
497
498   groups = &mtop->groups;
499
500   /* there are jmax groups of QM atoms. In case of multiple QM groups
501    * I assume that the users wants to do ONIOM. However, maybe it
502    * should also be possible to define more than one QM subsystem with
503    * independent neighbourlists. I have to think about
504    * that.. 11-11-2003 
505    */
506   snew(qr->qm,jmax);
507   for(j=0;j<jmax;j++){
508     /* new layer */
509     aloop = gmx_mtop_atomloop_all_init(mtop);
510     while (gmx_mtop_atomloop_all_next(aloop,&i,&atom)) {
511       if(qm_nr >= qm_max){
512         qm_max += 1000;
513         srenew(qm_arr,qm_max);
514       }
515       if (ggrpnr(groups,egcQMMM ,i) == j) {
516         /* hack for tip4p */
517         qm_arr[qm_nr++] = i;
518       }
519     }
520     if(qr->QMMMscheme==eQMMMschemeoniom){
521       /* add the atoms to the bQMMM array
522        */
523
524       /* I assume that users specify the QM groups from small to
525        * big(ger) in the mdp file 
526        */
527       qr->qm[j] = mk_QMrec(); 
528       /* we need to throw out link atoms that in the previous layer
529        * existed to separate this QMlayer from the previous
530        * QMlayer. We use the iatoms array in the idef for that
531        * purpose. If all atoms defining the current Link Atom (Dummy2)
532        * are part of the current QM layer it needs to be removed from
533        * qm_arr[].  */
534    
535       iloop = gmx_mtop_ilistloop_all_init(mtop);
536       while (gmx_mtop_ilistloop_all_next(iloop,&ilist_mol,&a_offset)) {
537         nrvsite2 = ilist_mol[F_VSITE2].nr;
538         iatoms   = ilist_mol[F_VSITE2].iatoms;
539         
540         for(k=0; k<nrvsite2; k+=4) {
541           vsite = a_offset + iatoms[k+1]; /* the vsite         */
542           ai    = a_offset + iatoms[k+2]; /* constructing atom */
543           aj    = a_offset + iatoms[k+3]; /* constructing atom */
544           if (ggrpnr(groups, egcQMMM, vsite) == ggrpnr(groups, egcQMMM, ai)
545               &&
546               ggrpnr(groups, egcQMMM, vsite) == ggrpnr(groups, egcQMMM, aj)) {
547             /* this dummy link atom needs to be removed from the qm_arr
548              * before making the QMrec of this layer!  
549              */
550             for(i=0;i<qm_nr;i++){
551               if(qm_arr[i]==vsite){
552                 /* drop the element */
553                 for(l=i;l<qm_nr;l++){
554                   qm_arr[l]=qm_arr[l+1];
555                 }
556                 qm_nr--;
557               }
558             }
559           }
560         }
561       }
562
563       /* store QM atoms in this layer in the QMrec and initialise layer 
564        */
565       init_QMrec(j,qr->qm[j],qm_nr,qm_arr,mtop,ir);
566       
567       /* we now store the LJ C6 and C12 parameters in QM rec in case
568        * we need to do an optimization 
569        */
570       if(qr->qm[j]->bOPT || qr->qm[j]->bTS){
571         for(i=0;i<qm_nr;i++){
572           qr->qm[j]->c6[i]  =  C6(fr->nbfp,mtop->ffparams.atnr,
573                                   atom->type,atom->type)/c6au;
574           qr->qm[j]->c12[i] = C12(fr->nbfp,mtop->ffparams.atnr,
575                                   atom->type,atom->type)/c12au;
576         }
577       }
578       /* now we check for frontier QM atoms. These occur in pairs that
579        * construct the vsite
580        */
581       iloop = gmx_mtop_ilistloop_all_init(mtop);
582       while (gmx_mtop_ilistloop_all_next(iloop,&ilist_mol,&a_offset)) {
583         nrvsite2 = ilist_mol[F_VSITE2].nr;
584         iatoms   = ilist_mol[F_VSITE2].iatoms;
585
586         for(k=0; k<nrvsite2; k+=4){
587           vsite = a_offset + iatoms[k+1]; /* the vsite         */
588           ai    = a_offset + iatoms[k+2]; /* constructing atom */
589           aj    = a_offset + iatoms[k+3]; /* constructing atom */
590           if(ggrpnr(groups,egcQMMM,ai) < (groups->grps[egcQMMM].nr-1) &&
591              (ggrpnr(groups,egcQMMM,aj) >= (groups->grps[egcQMMM].nr-1))){
592               /* mark ai as frontier atom */
593             for(i=0;i<qm_nr;i++){
594               if( (qm_arr[i]==ai) || (qm_arr[i]==vsite) ){
595                 qr->qm[j]->frontatoms[i]=TRUE;
596               }
597             }
598           }
599           else if(ggrpnr(groups,egcQMMM,aj) < (groups->grps[egcQMMM].nr-1) &&
600                   (ggrpnr(groups,egcQMMM,ai) >= (groups->grps[egcQMMM].nr-1))){
601             /* mark aj as frontier atom */
602             for(i=0;i<qm_nr;i++){
603               if( (qm_arr[i]==aj) || (qm_arr[i]==vsite)){
604                 qr->qm[j]->frontatoms[i]=TRUE;
605               }
606             }
607           }
608         }
609       }
610     }
611   }
612   if(qr->QMMMscheme!=eQMMMschemeoniom){
613
614     /* standard QMMM, all layers are merged together so there is one QM 
615      * subsystem and one MM subsystem. 
616      * Also we set the charges to zero in the md->charge arrays to prevent 
617      * the innerloops from doubly counting the electostatic QM MM interaction
618      */
619
620     alook = gmx_mtop_atomlookup_init(mtop);
621
622     for (k=0;k<qm_nr;k++){
623       gmx_mtop_atomnr_to_atom(alook,qm_arr[k],&atom);
624       atom->q  = 0.0;
625       atom->qB = 0.0;
626     } 
627     qr->qm[0] = mk_QMrec();
628     /* store QM atoms in the QMrec and initialise
629      */
630     init_QMrec(0,qr->qm[0],qm_nr,qm_arr,mtop,ir);
631     if(qr->qm[0]->bOPT || qr->qm[0]->bTS){
632       for(i=0;i<qm_nr;i++){
633         gmx_mtop_atomnr_to_atom(alook,qm_arr[i],&atom);
634         qr->qm[0]->c6[i]  =  C6(fr->nbfp,mtop->ffparams.atnr,
635                                 atom->type,atom->type)/c6au;
636         qr->qm[0]->c12[i] = C12(fr->nbfp,mtop->ffparams.atnr,
637                                 atom->type,atom->type)/c12au;
638       }
639       
640     }
641     
642
643
644     /* find frontier atoms and mark them true in the frontieratoms array.
645      */
646     for(i=0;i<qm_nr;i++) {
647       gmx_mtop_atomnr_to_ilist(alook,qm_arr[i],&ilist_mol,&a_offset);
648       nrvsite2 = ilist_mol[F_VSITE2].nr;
649       iatoms   = ilist_mol[F_VSITE2].iatoms;
650       
651       for(k=0;k<nrvsite2;k+=4){
652         vsite = a_offset + iatoms[k+1]; /* the vsite         */
653         ai    = a_offset + iatoms[k+2]; /* constructing atom */
654         aj    = a_offset + iatoms[k+3]; /* constructing atom */
655         if(ggrpnr(groups,egcQMMM,ai) < (groups->grps[egcQMMM].nr-1) &&
656            (ggrpnr(groups,egcQMMM,aj) >= (groups->grps[egcQMMM].nr-1))){
657         /* mark ai as frontier atom */
658           if ( (qm_arr[i]==ai) || (qm_arr[i]==vsite) ){
659             qr->qm[0]->frontatoms[i]=TRUE;
660           }
661         }
662         else if (ggrpnr(groups,egcQMMM,aj) < (groups->grps[egcQMMM].nr-1) &&
663                  (ggrpnr(groups,egcQMMM,ai) >=(groups->grps[egcQMMM].nr-1))) {
664           /* mark aj as frontier atom */
665           if ( (qm_arr[i]==aj) || (qm_arr[i]==vsite) ){
666             qr->qm[0]->frontatoms[i]=TRUE;
667           }
668         }
669       }
670     }
671
672     gmx_mtop_atomlookup_destroy(alook);
673
674     /* MM rec creation */
675     mm               = mk_MMrec(); 
676     mm->scalefactor  = ir->scalefactor;
677     mm->nrMMatoms    = (mtop->natoms)-(qr->qm[0]->nrQMatoms); /* rest of the atoms */
678     qr->mm           = mm;
679   } else {/* ONIOM */
680     /* MM rec creation */    
681     mm               = mk_MMrec(); 
682     mm->scalefactor  = ir->scalefactor;
683     mm->nrMMatoms    = 0;
684     qr->mm           = mm;
685   }
686   
687   /* these variables get updated in the update QMMMrec */
688
689   if(qr->nrQMlayers==1){
690     /* with only one layer there is only one initialisation
691      * needed. Multilayer is a bit more complicated as it requires
692      * re-initialisation at every step of the simulation. This is due
693      * to the use of COMMON blocks in the fortran QM subroutines.  
694      */
695     if (qr->qm[0]->QMmethod<eQMmethodRHF)
696     {
697 #ifdef GMX_QMMM_MOPAC
698         /* semi-empiprical 1-layer ONIOM calculation requested (mopac93) */
699         init_mopac(cr,qr->qm[0],qr->mm);
700 #else
701         gmx_fatal(FARGS,"Semi-empirical QM only supported with Mopac.");
702 #endif
703     }
704     else 
705     { 
706         /* ab initio calculation requested (gamess/gaussian/ORCA) */
707 #ifdef GMX_QMMM_GAMESS
708         init_gamess(cr,qr->qm[0],qr->mm);
709 #elif defined GMX_QMMM_GAUSSIAN
710         init_gaussian(cr,qr->qm[0],qr->mm);
711 #elif defined GMX_QMMM_ORCA
712         init_orca(cr,qr->qm[0],qr->mm);
713 #else
714         gmx_fatal(FARGS,"Ab-initio calculation only supported with Gamess, Gaussian or ORCA.");
715 #endif
716     }
717   }
718 } /* init_QMMMrec */
719
720 void update_QMMMrec(t_commrec *cr,
721                     t_forcerec *fr,
722                     rvec x[],
723                     t_mdatoms *md,
724                     matrix box,
725                     gmx_localtop_t *top)
726 {
727   /* updates the coordinates of both QM atoms and MM atoms and stores
728    * them in the QMMMrec.  
729    *
730    * NOTE: is NOT yet working if there are no PBC. Also in ns.c, simple
731    * ns needs to be fixed!  
732    */
733   int 
734     mm_max=0,mm_nr=0,mm_nr_new,i,j,is,k,shift;
735   t_j_particle 
736     *mm_j_particles=NULL,*qm_i_particles=NULL;
737   t_QMMMrec 
738     *qr; 
739   t_nblist 
740     QMMMlist;
741   rvec
742     dx,crd;
743   int
744     *MMatoms;
745   t_QMrec
746     *qm;
747   t_MMrec
748     *mm;
749   t_pbc
750     pbc;
751   int  
752     *parallelMMarray=NULL;
753   real
754     c12au,c6au;
755
756   c6au  = (HARTREE2KJ*AVOGADRO*pow(BOHR2NM,6)); 
757   c12au = (HARTREE2KJ*AVOGADRO*pow(BOHR2NM,12)); 
758
759   /* every cpu has this array. On every processor we fill this array
760    * with 1's and 0's. 1's indicate the atoms is a QM atom on the
761    * current cpu in a later stage these arrays are all summed. indexes
762    * > 0 indicate the atom is a QM atom. Every node therefore knows
763    * whcih atoms are part of the QM subsystem.  
764    */
765   /* copy some pointers */
766   qr          = fr->qr;
767   mm          = qr->mm;
768   QMMMlist    = fr->QMMMlist;
769
770   
771
772   /*  init_pbc(box);  needs to be called first, see pbc.h */
773   set_pbc_dd(&pbc,fr->ePBC,DOMAINDECOMP(cr) ? cr->dd : NULL,FALSE,box);
774   /* only in standard (normal) QMMM we need the neighbouring MM
775    * particles to provide a electric field of point charges for the QM
776    * atoms.  
777    */
778   if(qr->QMMMscheme==eQMMMschemenormal){ /* also implies 1 QM-layer */
779     /* we NOW create/update a number of QMMMrec entries:
780      *
781      * 1) the shiftQM, containing the shifts of the QM atoms
782      *
783      * 2) the indexMM array, containing the index of the MM atoms
784      * 
785      * 3) the shiftMM, containing the shifts of the MM atoms
786      *
787      * 4) the shifted coordinates of the MM atoms
788      *
789      * the shifts are used for computing virial of the QM/MM particles.
790      */
791     qm = qr->qm[0]; /* in case of normal QMMM, there is only one group */
792     snew(qm_i_particles,QMMMlist.nri);
793     if(QMMMlist.nri){
794       qm_i_particles[0].shift = XYZ2IS(0,0,0);
795       for(i=0;i<QMMMlist.nri;i++){
796         qm_i_particles[i].j     = QMMMlist.iinr[i];
797         
798         if(i){
799           qm_i_particles[i].shift = pbc_dx_aiuc(&pbc,x[QMMMlist.iinr[0]],
800                                                 x[QMMMlist.iinr[i]],dx);
801           
802         }
803         /* However, since nri >= nrQMatoms, we do a quicksort, and throw
804          * out double, triple, etc. entries later, as we do for the MM
805          * list too.  
806          */
807         
808         /* compute the shift for the MM j-particles with respect to
809          * the QM i-particle and store them. 
810          */
811         
812         crd[0] = IS2X(QMMMlist.shift[i]) + IS2X(qm_i_particles[i].shift);
813         crd[1] = IS2Y(QMMMlist.shift[i]) + IS2Y(qm_i_particles[i].shift);
814         crd[2] = IS2Z(QMMMlist.shift[i]) + IS2Z(qm_i_particles[i].shift);
815         is = XYZ2IS(crd[0],crd[1],crd[2]); 
816         for(j=QMMMlist.jindex[i];
817             j<QMMMlist.jindex[i+1];
818             j++){
819           if(mm_nr >= mm_max){
820             mm_max += 1000;
821             srenew(mm_j_particles,mm_max);
822           }       
823           
824           mm_j_particles[mm_nr].j = QMMMlist.jjnr[j];
825           mm_j_particles[mm_nr].shift = is;
826           mm_nr++;
827         }
828       }
829       
830       /* quicksort QM and MM shift arrays and throw away multiple entries */
831       
832
833
834       qsort(qm_i_particles,QMMMlist.nri,
835             (size_t)sizeof(qm_i_particles[0]),
836             struct_comp);
837       qsort(mm_j_particles,mm_nr,
838             (size_t)sizeof(mm_j_particles[0]),
839             struct_comp);
840       /* remove multiples in the QM shift array, since in init_QMMM() we
841        * went through the atom numbers from 0 to md.nr, the order sorted
842        * here matches the one of QMindex already.
843        */
844       j=0;
845       for(i=0;i<QMMMlist.nri;i++){
846         if (i==0 || qm_i_particles[i].j!=qm_i_particles[i-1].j){
847           qm_i_particles[j++] = qm_i_particles[i];
848         }
849       }
850       mm_nr_new = 0;
851       if(qm->bTS||qm->bOPT){
852         /* only remove double entries for the MM array */
853         for(i=0;i<mm_nr;i++){
854           if((i==0 || mm_j_particles[i].j!=mm_j_particles[i-1].j)
855              && !md->bQM[mm_j_particles[i].j]){
856             mm_j_particles[mm_nr_new++] = mm_j_particles[i];
857           }
858         }
859       }      
860       /* we also remove mm atoms that have no charges! 
861       * actually this is already done in the ns.c  
862       */
863       else{
864         for(i=0;i<mm_nr;i++){
865           if((i==0 || mm_j_particles[i].j!=mm_j_particles[i-1].j)
866              && !md->bQM[mm_j_particles[i].j] 
867              && (md->chargeA[mm_j_particles[i].j]
868                  || (md->chargeB && md->chargeB[mm_j_particles[i].j]))) {
869             mm_j_particles[mm_nr_new++] = mm_j_particles[i];
870           }
871         }
872       }
873       mm_nr = mm_nr_new;
874       /* store the data retrieved above into the QMMMrec
875        */    
876       k=0;
877       /* Keep the compiler happy,
878        * shift will always be set in the loop for i=0
879        */
880       shift = 0;
881       for(i=0;i<qm->nrQMatoms;i++){
882         /* not all qm particles might have appeared as i
883          * particles. They might have been part of the same charge
884          * group for instance.
885          */
886         if (qm->indexQM[i] == qm_i_particles[k].j) {
887           shift = qm_i_particles[k++].shift;
888         }
889         /* use previous shift, assuming they belong the same charge
890          * group anyway,
891          */
892         
893         qm->shiftQM[i] = shift;
894       }
895     }
896     /* parallel excecution */
897     if(PAR(cr)){
898       snew(parallelMMarray,2*(md->nr)); 
899       /* only MM particles have a 1 at their atomnumber. The second part
900        * of the array contains the shifts. Thus:
901        * p[i]=1/0 depending on wether atomnumber i is a MM particle in the QM
902        * step or not. p[i+md->nr] is the shift of atomnumber i.
903        */
904       for(i=0;i<2*(md->nr);i++){
905         parallelMMarray[i]=0;
906       }
907       
908       for(i=0;i<mm_nr;i++){
909         parallelMMarray[mm_j_particles[i].j]=1;
910         parallelMMarray[mm_j_particles[i].j+(md->nr)]=mm_j_particles[i].shift;
911       }
912       gmx_sumi(md->nr,parallelMMarray,cr);
913       mm_nr=0;
914       
915       mm_max = 0;
916       for(i=0;i<md->nr;i++){
917         if(parallelMMarray[i]){
918           if(mm_nr >= mm_max){
919             mm_max += 1000;
920             srenew(mm->indexMM,mm_max);
921             srenew(mm->shiftMM,mm_max);
922           }
923           mm->indexMM[mm_nr]  = i;
924           mm->shiftMM[mm_nr++]= parallelMMarray[i+md->nr]/parallelMMarray[i];
925         }
926       }
927       mm->nrMMatoms=mm_nr;
928       free(parallelMMarray);
929     }
930     /* serial execution */
931     else{
932       mm->nrMMatoms = mm_nr;
933       srenew(mm->shiftMM,mm_nr);
934       srenew(mm->indexMM,mm_nr);
935       for(i=0;i<mm_nr;i++){
936         mm->indexMM[i]=mm_j_particles[i].j;
937         mm->shiftMM[i]=mm_j_particles[i].shift;
938       }
939       
940     }
941     /* (re) allocate memory for the MM coordiate array. The QM
942      * coordinate array was already allocated in init_QMMM, and is
943      * only (re)filled in the update_QMMM_coordinates routine 
944      */
945     srenew(mm->xMM,mm->nrMMatoms);
946     /* now we (re) fill the array that contains the MM charges with
947      * the forcefield charges. If requested, these charges will be
948      * scaled by a factor 
949      */
950     srenew(mm->MMcharges,mm->nrMMatoms);
951     for(i=0;i<mm->nrMMatoms;i++){/* no free energy yet */
952       mm->MMcharges[i]=md->chargeA[mm->indexMM[i]]*mm->scalefactor; 
953     }  
954     if(qm->bTS||qm->bOPT){
955       /* store (copy) the c6 and c12 parameters into the MMrec struct 
956        */
957       srenew(mm->c6,mm->nrMMatoms);
958       srenew(mm->c12,mm->nrMMatoms);
959       for (i=0;i<mm->nrMMatoms;i++){
960         mm->c6[i]  = C6(fr->nbfp,top->idef.atnr,
961                         md->typeA[mm->indexMM[i]],
962                         md->typeA[mm->indexMM[i]])/c6au;
963         mm->c12[i] =C12(fr->nbfp,top->idef.atnr,
964                         md->typeA[mm->indexMM[i]],
965                         md->typeA[mm->indexMM[i]])/c12au;
966       }
967       punch_QMMM_excl(qr->qm[0],mm,&(top->excls));
968     }
969     /* the next routine fills the coordinate fields in the QMMM rec of
970      * both the qunatum atoms and the MM atoms, using the shifts
971      * calculated above.  
972      */
973
974     update_QMMM_coord(x,fr,qr->qm[0],qr->mm);
975     free(qm_i_particles);
976     free(mm_j_particles);
977   } 
978   else { /* ONIOM */ /* ????? */
979     mm->nrMMatoms=0;
980     /* do for each layer */
981     for (j=0;j<qr->nrQMlayers;j++){
982       qm = qr->qm[j];
983       qm->shiftQM[0]=XYZ2IS(0,0,0);
984       for(i=1;i<qm->nrQMatoms;i++){
985         qm->shiftQM[i] = pbc_dx_aiuc(&pbc,x[qm->indexQM[0]],x[qm->indexQM[i]],
986                                      dx);
987       }
988       update_QMMM_coord(x,fr,qm,mm);    
989     }
990   }
991 } /* update_QMMM_rec */
992
993
994 real calculate_QMMM(t_commrec *cr,
995                     rvec x[],rvec f[],
996                     t_forcerec *fr,
997                     t_mdatoms *md)
998 {
999   real
1000     QMener=0.0;
1001   /* a selection for the QM package depending on which is requested
1002    * (Gaussian, GAMESS-UK, MOPAC or ORCA) needs to be implemented here. Now
1003    * it works through defines.... Not so nice yet 
1004    */
1005   t_QMMMrec
1006     *qr;
1007   t_QMrec
1008     *qm,*qm2;
1009   t_MMrec
1010     *mm=NULL;
1011   rvec 
1012     *forces=NULL,*fshift=NULL,    
1013     *forces2=NULL, *fshift2=NULL; /* needed for multilayer ONIOM */
1014   int
1015     i,j,k;
1016   /* make a local copy the QMMMrec pointer 
1017    */
1018   qr = fr->qr;
1019   mm = qr->mm;
1020
1021   /* now different procedures are carried out for one layer ONION and
1022    * normal QMMM on one hand and multilayer oniom on the other
1023    */
1024   if(qr->QMMMscheme==eQMMMschemenormal || qr->nrQMlayers==1){
1025     qm = qr->qm[0];
1026     snew(forces,(qm->nrQMatoms+mm->nrMMatoms));
1027     snew(fshift,(qm->nrQMatoms+mm->nrMMatoms));
1028     QMener = call_QMroutine(cr,fr,qm,mm,forces,fshift);
1029     for(i=0;i<qm->nrQMatoms;i++){
1030       for(j=0;j<DIM;j++){
1031         f[qm->indexQM[i]][j]          -= forces[i][j];
1032         fr->fshift[qm->shiftQM[i]][j] += fshift[i][j];
1033       }
1034     }
1035     for(i=0;i<mm->nrMMatoms;i++){
1036       for(j=0;j<DIM;j++){
1037         f[mm->indexMM[i]][j]          -= forces[qm->nrQMatoms+i][j];
1038         fr->fshift[mm->shiftMM[i]][j] += fshift[qm->nrQMatoms+i][j];
1039       }
1040       
1041     }
1042     free(forces);
1043     free(fshift);
1044   }
1045   else{ /* Multi-layer ONIOM */
1046     for(i=0;i<qr->nrQMlayers-1;i++){ /* last layer is special */
1047       qm  = qr->qm[i];
1048       qm2 = copy_QMrec(qr->qm[i+1]);
1049
1050       qm2->nrQMatoms = qm->nrQMatoms;
1051     
1052       for(j=0;j<qm2->nrQMatoms;j++){
1053         for(k=0;k<DIM;k++)
1054           qm2->xQM[j][k]       = qm->xQM[j][k];
1055         qm2->indexQM[j]        = qm->indexQM[j];
1056         qm2->atomicnumberQM[j] = qm->atomicnumberQM[j];
1057         qm2->shiftQM[j]        = qm->shiftQM[j];
1058       }
1059
1060       qm2->QMcharge = qm->QMcharge;
1061       /* this layer at the higher level of theory */
1062       srenew(forces,qm->nrQMatoms);
1063       srenew(fshift,qm->nrQMatoms);
1064       /* we need to re-initialize the QMroutine every step... */
1065       init_QMroutine(cr,qm,mm);
1066       QMener += call_QMroutine(cr,fr,qm,mm,forces,fshift);
1067
1068       /* this layer at the lower level of theory */
1069       srenew(forces2,qm->nrQMatoms);
1070       srenew(fshift2,qm->nrQMatoms);
1071       init_QMroutine(cr,qm2,mm);
1072       QMener -= call_QMroutine(cr,fr,qm2,mm,forces2,fshift2);
1073       /* E = E1high-E1low The next layer includes the current layer at
1074        * the lower level of theory, which provides + E2low
1075        * this is similar for gradients
1076        */
1077       for(i=0;i<qm->nrQMatoms;i++){
1078         for(j=0;j<DIM;j++){
1079           f[qm->indexQM[i]][j]          -= (forces[i][j]-forces2[i][j]);
1080           fr->fshift[qm->shiftQM[i]][j] += (fshift[i][j]-fshift2[i][j]);
1081         }
1082       }
1083       free(qm2);
1084     }
1085     /* now the last layer still needs to be done: */
1086     qm      = qr->qm[qr->nrQMlayers-1]; /* C counts from 0 */
1087     init_QMroutine(cr,qm,mm);
1088     srenew(forces,qm->nrQMatoms);
1089     srenew(fshift,qm->nrQMatoms);
1090     QMener += call_QMroutine(cr,fr,qm,mm,forces,fshift);
1091     for(i=0;i<qm->nrQMatoms;i++){
1092       for(j=0;j<DIM;j++){
1093         f[qm->indexQM[i]][j]          -= forces[i][j];
1094         fr->fshift[qm->shiftQM[i]][j] += fshift[i][j];
1095       }
1096     }
1097     free(forces);
1098     free(fshift);
1099     free(forces2);
1100     free(fshift2);
1101   }
1102   if(qm->bTS||qm->bOPT){
1103     /* qm[0] still contains the largest ONIOM QM subsystem 
1104      * we take the optimized coordiates and put the in x[]
1105      */
1106     for(i=0;i<qm->nrQMatoms;i++){
1107       for(j=0;j<DIM;j++){
1108         x[qm->indexQM[i]][j] = qm->xQM[i][j];
1109       }
1110     }
1111   }
1112   return(QMener);
1113 } /* calculate_QMMM */
1114
1115 /* end of QMMM core routines */