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