2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
52 #include <unordered_set>
53 #include <sys/types.h>
55 #include "gromacs/fileio/gmxfio.h"
56 #include "gromacs/fileio/warninp.h"
57 #include "gromacs/gmxpreprocess/gmxcpp.h"
58 #include "gromacs/gmxpreprocess/gpp_atomtype.h"
59 #include "gromacs/gmxpreprocess/gpp_bond_atomtype.h"
60 #include "gromacs/gmxpreprocess/gpp_nextnb.h"
61 #include "gromacs/gmxpreprocess/grompp_impl.h"
62 #include "gromacs/gmxpreprocess/readir.h"
63 #include "gromacs/gmxpreprocess/topdirs.h"
64 #include "gromacs/gmxpreprocess/toppush.h"
65 #include "gromacs/gmxpreprocess/topshake.h"
66 #include "gromacs/gmxpreprocess/toputil.h"
67 #include "gromacs/gmxpreprocess/vsite_parm.h"
68 #include "gromacs/math/units.h"
69 #include "gromacs/math/utilities.h"
70 #include "gromacs/mdtypes/inputrec.h"
71 #include "gromacs/mdtypes/md_enums.h"
72 #include "gromacs/pbcutil/pbc.h"
73 #include "gromacs/topology/block.h"
74 #include "gromacs/topology/exclusionblocks.h"
75 #include "gromacs/topology/ifunc.h"
76 #include "gromacs/topology/symtab.h"
77 #include "gromacs/topology/topology.h"
78 #include "gromacs/utility/cstringutil.h"
79 #include "gromacs/utility/fatalerror.h"
80 #include "gromacs/utility/futil.h"
81 #include "gromacs/utility/gmxassert.h"
82 #include "gromacs/utility/pleasecite.h"
83 #include "gromacs/utility/smalloc.h"
85 #define OPENDIR '[' /* starting sign for directive */
86 #define CLOSEDIR ']' /* ending sign for directive */
88 static void gen_pairs(const InteractionTypeParameters &nbs, InteractionTypeParameters *pairs, real fudge, int comb)
92 int nnn = static_cast<int>(std::sqrt(static_cast<double>(ntp)));
93 GMX_ASSERT(nnn * nnn == ntp, "Number of pairs of generated non-bonded parameters should be a perfect square");
94 int nrfp = NRFP(F_LJ);
95 int nrfpA = interaction_function[F_LJ14].nrfpA;
96 int nrfpB = interaction_function[F_LJ14].nrfpB;
98 if ((nrfp != nrfpA) || (nrfpA != nrfpB))
100 gmx_incons("Number of force parameters in gen_pairs wrong");
103 fprintf(stderr, "Generating 1-4 interactions: fudge = %g\n", fudge);
104 pairs->interactionTypes.clear();
106 std::array<int, 2> atomNumbers;
107 std::array<real, MAXFORCEPARAM> forceParam = {NOTSET};
108 for (const auto &type : nbs.interactionTypes)
110 /* Copy type.atoms */
111 atomNumbers = {i / nnn, i % nnn };
112 /* Copy normal and FEP parameters and multiply by fudge factor */
113 gmx::ArrayRef<const real> existingParam = type.forceParam();
114 GMX_RELEASE_ASSERT(2*nrfp <= MAXFORCEPARAM, "Can't have more parameters than half of maximum p arameter number");
115 for (int j = 0; j < nrfp; j++)
117 /* If we are using sigma/epsilon values, only the epsilon values
118 * should be scaled, but not sigma.
119 * The sigma values have even indices 0,2, etc.
121 if ((comb == eCOMB_ARITHMETIC || comb == eCOMB_GEOM_SIG_EPS) && (j%2 == 0))
130 forceParam[j] = scaling*existingParam[j];
131 forceParam[nrfp+j] = scaling*existingParam[j];
133 pairs->interactionTypes.emplace_back(InteractionType(atomNumbers, forceParam));
138 double check_mol(const gmx_mtop_t *mtop, warninp *wi)
145 /* Check mass and charge */
148 for (const gmx_molblock_t &molb : mtop->molblock)
150 const t_atoms *atoms = &mtop->moltype[molb.type].atoms;
151 for (i = 0; (i < atoms->nr); i++)
153 q += molb.nmol*atoms->atom[i].q;
154 m = atoms->atom[i].m;
155 mB = atoms->atom[i].mB;
156 pt = atoms->atom[i].ptype;
157 /* If the particle is an atom or a nucleus it must have a mass,
158 * else, if it is a shell, a vsite or a bondshell it can have mass zero
160 if (((m <= 0.0) || (mB <= 0.0)) && ((pt == eptAtom) || (pt == eptNucleus)))
162 ri = atoms->atom[i].resind;
163 sprintf(buf, "atom %s (Res %s-%d) has mass %g (state A) / %g (state B)\n",
164 *(atoms->atomname[i]),
165 *(atoms->resinfo[ri].name),
166 atoms->resinfo[ri].nr,
168 warning_error(wi, buf);
171 if (((m != 0) || (mB != 0)) && (pt == eptVSite))
173 ri = atoms->atom[i].resind;
174 sprintf(buf, "virtual site %s (Res %s-%d) has non-zero mass %g (state A) / %g (state B)\n"
175 " Check your topology.\n",
176 *(atoms->atomname[i]),
177 *(atoms->resinfo[ri].name),
178 atoms->resinfo[ri].nr,
180 warning_error(wi, buf);
181 /* The following statements make LINCS break! */
182 /* atoms->atom[i].m=0; */
189 /*! \brief Returns the rounded charge of a molecule, when close to integer, otherwise returns the original charge.
191 * The results of this routine are only used for checking and for
192 * printing warning messages. Thus we can assume that charges of molecules
193 * should be integer. If the user wanted non-integer molecular charge,
194 * an undesired warning is printed and the user should use grompp -maxwarn 1.
196 * \param qMol The total, unrounded, charge of the molecule
197 * \param sumAbsQ The sum of absolute values of the charges, used for determining the tolerance for the rounding.
199 static double roundedMoleculeCharge(double qMol, double sumAbsQ)
201 /* We use a tolerance of 1e-6 for inaccuracies beyond the 6th decimal
202 * of the charges for ascii float truncation in the topology files.
203 * Although the summation here uses double precision, the charges
204 * are read and stored in single precision when real=float. This can
205 * lead to rounding errors of half the least significant bit.
206 * Note that, unfortunately, we can not assume addition of random
207 * rounding errors. It is not entirely unlikely that many charges
208 * have a near half-bit rounding error with the same sign.
210 double tolAbs = 1e-6;
211 double tol = std::max(tolAbs, 0.5*GMX_REAL_EPS*sumAbsQ);
212 double qRound = std::round(qMol);
213 if (std::abs(qMol - qRound) <= tol)
223 static void sum_q(const t_atoms *atoms, int numMols,
224 double *qTotA, double *qTotB)
231 for (int i = 0; i < atoms->nr; i++)
233 qmolA += atoms->atom[i].q;
234 qmolB += atoms->atom[i].qB;
235 sumAbsQA += std::abs(atoms->atom[i].q);
236 sumAbsQB += std::abs(atoms->atom[i].qB);
239 *qTotA += numMols*roundedMoleculeCharge(qmolA, sumAbsQA);
240 *qTotB += numMols*roundedMoleculeCharge(qmolB, sumAbsQB);
243 static void get_nbparm(char *nb_str, char *comb_str, int *nb, int *comb,
247 char warn_buf[STRLEN];
250 for (i = 1; (i < eNBF_NR); i++)
252 if (gmx_strcasecmp(nb_str, enbf_names[i]) == 0)
259 *nb = strtol(nb_str, nullptr, 10);
261 if ((*nb < 1) || (*nb >= eNBF_NR))
263 sprintf(warn_buf, "Invalid nonbond function selector '%s' using %s",
264 nb_str, enbf_names[1]);
265 warning_error(wi, warn_buf);
269 for (i = 1; (i < eCOMB_NR); i++)
271 if (gmx_strcasecmp(comb_str, ecomb_names[i]) == 0)
278 *comb = strtol(comb_str, nullptr, 10);
280 if ((*comb < 1) || (*comb >= eCOMB_NR))
282 sprintf(warn_buf, "Invalid combination rule selector '%s' using %s",
283 comb_str, ecomb_names[1]);
284 warning_error(wi, warn_buf);
289 static char ** cpp_opts(const char *define, const char *include,
294 const char *cppadds[2];
295 char **cppopts = nullptr;
296 const char *option[2] = { "-D", "-I" };
297 const char *nopt[2] = { "define", "include" };
301 char warn_buf[STRLEN];
304 cppadds[1] = include;
305 for (n = 0; (n < 2); n++)
312 while ((*ptr != '\0') && isspace(*ptr))
317 while ((*rptr != '\0') && !isspace(*rptr))
325 strncpy(buf, ptr, len);
326 if (strstr(ptr, option[n]) != ptr)
328 set_warning_line(wi, "mdp file", -1);
329 sprintf(warn_buf, "Malformed %s option %s", nopt[n], buf);
330 warning(wi, warn_buf);
334 srenew(cppopts, ++ncppopts);
335 cppopts[ncppopts-1] = gmx_strdup(buf);
343 srenew(cppopts, ++ncppopts);
344 cppopts[ncppopts-1] = nullptr;
350 static void make_atoms_sys(gmx::ArrayRef<const gmx_molblock_t> molblock,
351 gmx::ArrayRef<const MoleculeInformation> molinfo,
355 atoms->atom = nullptr;
357 for (const gmx_molblock_t &molb : molblock)
359 const t_atoms &mol_atoms = molinfo[molb.type].atoms;
361 srenew(atoms->atom, atoms->nr + molb.nmol*mol_atoms.nr);
363 for (int m = 0; m < molb.nmol; m++)
365 for (int a = 0; a < mol_atoms.nr; a++)
367 atoms->atom[atoms->nr++] = mol_atoms.atom[a];
374 static char **read_topol(const char *infile, const char *outfile,
375 const char *define, const char *include,
377 PreprocessingAtomTypes *atypes,
378 std::vector<MoleculeInformation> *molinfo,
379 std::unique_ptr<MoleculeInformation> *intermolecular_interactions,
380 gmx::ArrayRef<InteractionTypeParameters> plist,
381 int *combination_rule,
385 std::vector<gmx_molblock_t> *molblock,
386 bool *ffParametrizedWithHBondConstraints,
389 bool usingFullRangeElectrostatics,
394 char *pline = nullptr, **title = nullptr;
395 char line[STRLEN], errbuf[256], comb_str[256], nb_str[256];
397 char *dirstr, *dummy2;
398 int nrcopies, nscan, ncombs, ncopy;
399 double fLJ, fQQ, fPOW;
400 MoleculeInformation *mi0 = nullptr;
403 t_nbparam **nbparam, **pair;
404 real fudgeLJ = -1; /* Multiplication factor to generate 1-4 from LJ */
405 bool bReadDefaults, bReadMolType, bGenPairs, bWarn_copy_A_B;
406 double qt = 0, qBt = 0; /* total charge */
407 gpp_bond_atomtype *batype;
409 int dcatt = -1, nmol_couple;
410 /* File handling variables */
414 char *tmp_line = nullptr;
415 char warn_buf[STRLEN];
416 const char *floating_point_arithmetic_tip =
417 "Total charge should normally be an integer. See\n"
418 "http://www.gromacs.org/Documentation/Floating_Point_Arithmetic\n"
419 "for discussion on how close it should be to an integer.\n";
420 /* We need to open the output file before opening the input file,
421 * because cpp_open_file can change the current working directory.
425 out = gmx_fio_fopen(outfile, "w");
432 /* open input file */
433 auto cpp_opts_return = cpp_opts(define, include, wi);
434 status = cpp_open_file(infile, &handle, cpp_opts_return);
437 gmx_fatal(FARGS, "%s", cpp_error(&handle, status));
440 /* some local variables */
441 DS_Init(&DS); /* directive stack */
442 d = Directive::d_invalid; /* first thing should be a directive */
443 nbparam = nullptr; /* The temporary non-bonded matrix */
444 pair = nullptr; /* The temporary pair interaction matrix */
445 std::vector < std::vector < gmx::ExclusionBlock>> exclusionBlocks;
448 *reppow = 12.0; /* Default value for repulsion power */
450 /* Init the number of CMAP torsion angles and grid spacing */
451 plist[F_CMAP].cmakeGridSpacing = 0;
452 plist[F_CMAP].cmapAngles = 0;
454 bWarn_copy_A_B = bFEP;
456 batype = init_bond_atomtype();
457 /* parse the actual file */
458 bReadDefaults = FALSE;
460 bReadMolType = FALSE;
465 status = cpp_read_line(&handle, STRLEN, line);
466 done = (status == eCPP_EOF);
469 if (status != eCPP_OK)
471 gmx_fatal(FARGS, "%s", cpp_error(&handle, status));
475 fprintf(out, "%s\n", line);
478 set_warning_line(wi, cpp_cur_file(&handle), cpp_cur_linenr(&handle));
480 pline = gmx_strdup(line);
482 /* Strip trailing '\' from pline, if it exists */
484 if ((sl > 0) && (pline[sl-1] == CONTINUE))
489 /* build one long line from several fragments - necessary for CMAP */
490 while (continuing(line))
492 status = cpp_read_line(&handle, STRLEN, line);
493 set_warning_line(wi, cpp_cur_file(&handle), cpp_cur_linenr(&handle));
495 /* Since we depend on the '\' being present to continue to read, we copy line
496 * to a tmp string, strip the '\' from that string, and cat it to pline
498 tmp_line = gmx_strdup(line);
500 sl = strlen(tmp_line);
501 if ((sl > 0) && (tmp_line[sl-1] == CONTINUE))
503 tmp_line[sl-1] = ' ';
506 done = (status == eCPP_EOF);
509 if (status != eCPP_OK)
511 gmx_fatal(FARGS, "%s", cpp_error(&handle, status));
515 fprintf(out, "%s\n", line);
519 srenew(pline, strlen(pline)+strlen(tmp_line)+1);
520 strcat(pline, tmp_line);
524 /* skip trailing and leading spaces and comment text */
525 strip_comment (pline);
528 /* if there is something left... */
529 if (static_cast<int>(strlen(pline)) > 0)
531 if (pline[0] == OPENDIR)
533 /* A directive on this line: copy the directive
534 * without the brackets into dirstr, then
535 * skip spaces and tabs on either side of directive
537 dirstr = gmx_strdup((pline+1));
538 if ((dummy2 = strchr (dirstr, CLOSEDIR)) != nullptr)
544 if ((newd = str2dir(dirstr)) == Directive::d_invalid)
546 sprintf(errbuf, "Invalid directive %s", dirstr);
547 warning_error(wi, errbuf);
551 /* Directive found */
552 if (DS_Check_Order (DS, newd))
559 /* we should print here which directives should have
560 been present, and which actually are */
561 gmx_fatal(FARGS, "%s\nInvalid order for directive %s",
562 cpp_error(&handle, eCPP_SYNTAX), dir2str(newd));
563 /* d = Directive::d_invalid; */
566 if (d == Directive::d_intermolecular_interactions)
568 if (*intermolecular_interactions == nullptr)
570 /* We (mis)use the moleculetype processing
571 * to process the intermolecular interactions
572 * by making a "molecule" of the size of the system.
574 *intermolecular_interactions = std::make_unique<MoleculeInformation>( );
575 mi0 = intermolecular_interactions->get();
577 make_atoms_sys(*molblock, *molinfo,
584 else if (d != Directive::d_invalid)
586 /* Not a directive, just a plain string
587 * use a gigantic switch to decode,
588 * if there is a valid directive!
592 case Directive::d_defaults:
595 gmx_fatal(FARGS, "%s\nFound a second defaults directive.\n",
596 cpp_error(&handle, eCPP_SYNTAX));
598 bReadDefaults = TRUE;
599 nscan = sscanf(pline, "%s%s%s%lf%lf%lf",
600 nb_str, comb_str, genpairs, &fLJ, &fQQ, &fPOW);
611 get_nbparm(nb_str, comb_str, &nb_funct, combination_rule, wi);
614 bGenPairs = (gmx_strncasecmp(genpairs, "Y", 1) == 0);
615 if (nb_funct != eNBF_LJ && bGenPairs)
617 gmx_fatal(FARGS, "Generating pair parameters is only supported with LJ non-bonded interactions");
633 nb_funct = ifunc_index(Directive::d_nonbond_params, nb_funct);
636 case Directive::d_atomtypes:
637 push_at(symtab, atypes, batype, pline, nb_funct,
638 &nbparam, bGenPairs ? &pair : nullptr, wi);
641 case Directive::d_bondtypes:
642 push_bt(d, plist, 2, nullptr, batype, pline, wi);
644 case Directive::d_constrainttypes:
645 push_bt(d, plist, 2, nullptr, batype, pline, wi);
647 case Directive::d_pairtypes:
650 push_nbt(d, pair, atypes, pline, F_LJ14, wi);
654 push_bt(d, plist, 2, atypes, nullptr, pline, wi);
657 case Directive::d_angletypes:
658 push_bt(d, plist, 3, nullptr, batype, pline, wi);
660 case Directive::d_dihedraltypes:
661 /* Special routine that can read both 2 and 4 atom dihedral definitions. */
662 push_dihedraltype(d, plist, batype, pline, wi);
665 case Directive::d_nonbond_params:
666 push_nbt(d, nbparam, atypes, pline, nb_funct, wi);
669 case Directive::d_implicit_genborn_params:
670 // Skip this line, so old topologies with
671 // GB parameters can be read.
674 case Directive::d_implicit_surface_params:
675 // Skip this line, so that any topologies
676 // with surface parameters can be read
677 // (even though these were never formally
681 case Directive::d_cmaptypes:
682 push_cmaptype(d, plist, 5, atypes, batype, pline, wi);
685 case Directive::d_moleculetype:
690 if (opts->couple_moltype != nullptr &&
691 (opts->couple_lam0 == ecouplamNONE ||
692 opts->couple_lam0 == ecouplamQ ||
693 opts->couple_lam1 == ecouplamNONE ||
694 opts->couple_lam1 == ecouplamQ))
696 dcatt = add_atomtype_decoupled(symtab, atypes,
697 &nbparam, bGenPairs ? &pair : nullptr);
699 ntype = atypes->size();
700 ncombs = (ntype*(ntype+1))/2;
701 generate_nbparams(*combination_rule, nb_funct, &(plist[nb_funct]), atypes, wi);
702 ncopy = copy_nbparams(nbparam, nb_funct, &(plist[nb_funct]),
704 fprintf(stderr, "Generated %d of the %d non-bonded parameter combinations\n", ncombs-ncopy, ncombs);
705 free_nbparam(nbparam, ntype);
708 gen_pairs((plist[nb_funct]), &(plist[F_LJ14]), fudgeLJ, *combination_rule);
709 ncopy = copy_nbparams(pair, nb_funct, &(plist[F_LJ14]),
711 fprintf(stderr, "Generated %d of the %d 1-4 parameter combinations\n", ncombs-ncopy, ncombs);
712 free_nbparam(pair, ntype);
714 /* Copy GBSA parameters to atomtype array? */
719 push_molt(symtab, molinfo, pline, wi);
720 exclusionBlocks.emplace_back();
721 mi0 = &molinfo->back();
722 mi0->atoms.haveMass = TRUE;
723 mi0->atoms.haveCharge = TRUE;
724 mi0->atoms.haveType = TRUE;
725 mi0->atoms.haveBState = TRUE;
726 mi0->atoms.havePdbInfo = FALSE;
729 case Directive::d_atoms:
730 push_atom(symtab, &(mi0->cgs), &(mi0->atoms), atypes, pline, &lastcg, wi);
733 case Directive::d_pairs:
734 GMX_RELEASE_ASSERT(mi0, "Need to have a valid MoleculeInformation object to work on");
735 push_bond(d, plist, mi0->plist, &(mi0->atoms), atypes, pline, FALSE,
736 bGenPairs, *fudgeQQ, bZero, &bWarn_copy_A_B, wi);
738 case Directive::d_pairs_nb:
739 GMX_RELEASE_ASSERT(mi0, "Need to have a valid MoleculeInformation object to work on");
740 push_bond(d, plist, mi0->plist, &(mi0->atoms), atypes, pline, FALSE,
741 FALSE, 1.0, bZero, &bWarn_copy_A_B, wi);
744 case Directive::d_vsites2:
745 case Directive::d_vsites3:
746 case Directive::d_vsites4:
747 case Directive::d_bonds:
748 case Directive::d_angles:
749 case Directive::d_constraints:
750 case Directive::d_settles:
751 case Directive::d_position_restraints:
752 case Directive::d_angle_restraints:
753 case Directive::d_angle_restraints_z:
754 case Directive::d_distance_restraints:
755 case Directive::d_orientation_restraints:
756 case Directive::d_dihedral_restraints:
757 case Directive::d_dihedrals:
758 case Directive::d_polarization:
759 case Directive::d_water_polarization:
760 case Directive::d_thole_polarization:
761 GMX_RELEASE_ASSERT(mi0, "Need to have a valid MoleculeInformation object to work on");
762 push_bond(d, plist, mi0->plist, &(mi0->atoms), atypes, pline, TRUE,
763 bGenPairs, *fudgeQQ, bZero, &bWarn_copy_A_B, wi);
765 case Directive::d_cmap:
766 GMX_RELEASE_ASSERT(mi0, "Need to have a valid MoleculeInformation object to work on");
767 push_cmap(d, plist, mi0->plist, &(mi0->atoms), atypes, pline, wi);
770 case Directive::d_vsitesn:
771 GMX_RELEASE_ASSERT(mi0, "Need to have a valid MoleculeInformation object to work on");
772 push_vsitesn(d, mi0->plist, &(mi0->atoms), pline, wi);
774 case Directive::d_exclusions:
775 GMX_ASSERT(!exclusionBlocks.empty(), "exclusionBlocks must always be allocated so exclusions can be processed");
776 if (exclusionBlocks.back().empty())
778 GMX_RELEASE_ASSERT(mi0, "Need to have a valid MoleculeInformation object to work on");
779 exclusionBlocks.back().resize(mi0->atoms.nr);
781 push_excl(pline, exclusionBlocks.back(), wi);
783 case Directive::d_system:
785 title = put_symtab(symtab, pline);
787 case Directive::d_molecules:
792 push_mol(*molinfo, pline, &whichmol, &nrcopies, wi);
793 mi0 = &((*molinfo)[whichmol]);
794 molblock->resize(molblock->size() + 1);
795 molblock->back().type = whichmol;
796 molblock->back().nmol = nrcopies;
798 bCouple = (opts->couple_moltype != nullptr &&
799 (gmx_strcasecmp("system", opts->couple_moltype) == 0 ||
800 strcmp(*(mi0->name), opts->couple_moltype) == 0));
803 nmol_couple += nrcopies;
806 if (mi0->atoms.nr == 0)
808 gmx_fatal(FARGS, "Molecule type '%s' contains no atoms",
812 "Excluding %d bonded neighbours molecule type '%s'\n",
813 mi0->nrexcl, *mi0->name);
814 sum_q(&mi0->atoms, nrcopies, &qt, &qBt);
815 if (!mi0->bProcessed)
818 generate_excl(mi0->nrexcl,
823 gmx::mergeExclusions(&(mi0->excls), exclusionBlocks[whichmol]);
824 make_shake(mi0->plist, &mi0->atoms, opts->nshake);
830 convert_moltype_couple(mi0, dcatt, *fudgeQQ,
831 opts->couple_lam0, opts->couple_lam1,
833 nb_funct, &(plist[nb_funct]), wi);
835 stupid_fill_block(&mi0->mols, mi0->atoms.nr, TRUE);
836 mi0->bProcessed = TRUE;
841 fprintf (stderr, "case: %d\n", static_cast<int>(d));
842 gmx_incons("unknown directive");
852 // Check that all strings defined with -D were used when processing topology
853 std::string unusedDefineWarning = checkAndWarnForUnusedDefines(*handle);
854 if (!unusedDefineWarning.empty())
856 warning(wi, unusedDefineWarning);
859 sfree(cpp_opts_return);
866 /* List of GROMACS define names for force fields that have been
867 * parametrized using constraints involving hydrogens only.
869 * We should avoid hardcoded names, but this is hopefully only
870 * needed temparorily for discouraging use of constraints=all-bonds.
872 const std::array<std::string, 3> ffDefines = {
877 *ffParametrizedWithHBondConstraints = false;
878 for (const std::string &ffDefine : ffDefines)
880 if (cpp_find_define(&handle, ffDefine))
882 *ffParametrizedWithHBondConstraints = true;
888 if (opts->couple_moltype)
890 if (nmol_couple == 0)
892 gmx_fatal(FARGS, "Did not find any molecules of type '%s' for coupling",
893 opts->couple_moltype);
895 fprintf(stderr, "Coupling %d copies of molecule type '%s'\n",
896 nmol_couple, opts->couple_moltype);
899 /* this is not very clean, but fixes core dump on empty system name */
902 title = put_symtab(symtab, "");
907 sprintf(warn_buf, "System has non-zero total charge: %.6f\n%s\n", qt, floating_point_arithmetic_tip);
908 warning_note(wi, warn_buf);
910 if (fabs(qBt) > 1e-4 && !gmx_within_tol(qBt, qt, 1e-6))
912 sprintf(warn_buf, "State B has non-zero total charge: %.6f\n%s\n", qBt, floating_point_arithmetic_tip);
913 warning_note(wi, warn_buf);
915 if (usingFullRangeElectrostatics && (fabs(qt) > 1e-4 || fabs(qBt) > 1e-4))
917 warning(wi, "You are using Ewald electrostatics in a system with net charge. This can lead to severe artifacts, such as ions moving into regions with low dielectric, due to the uniform background charge. We suggest to neutralize your system with counter ions, possibly in combination with a physiological salt concentration.");
918 please_cite(stdout, "Hub2014a");
923 done_bond_atomtype(&batype);
925 if (*intermolecular_interactions != nullptr)
927 sfree(intermolecular_interactions->get()->atoms.atom);
933 char **do_top(bool bVerbose,
935 const char *topppfile,
939 gmx::ArrayRef<InteractionTypeParameters> plist,
940 int *combination_rule,
941 double *repulsion_power,
943 PreprocessingAtomTypes *atypes,
944 std::vector<MoleculeInformation> *molinfo,
945 std::unique_ptr<MoleculeInformation> *intermolecular_interactions,
946 const t_inputrec *ir,
947 std::vector<gmx_molblock_t> *molblock,
948 bool *ffParametrizedWithHBondConstraints,
951 /* Tmpfile might contain a long path */
966 printf("processing topology...\n");
968 title = read_topol(topfile, tmpfile, opts->define, opts->include,
970 molinfo, intermolecular_interactions,
971 plist, combination_rule, repulsion_power,
972 opts, fudgeQQ, molblock,
973 ffParametrizedWithHBondConstraints,
974 ir->efep != efepNO, bZero,
975 EEL_FULL(ir->coulombtype), wi);
977 if ((*combination_rule != eCOMB_GEOMETRIC) &&
978 (ir->vdwtype == evdwUSER))
980 warning(wi, "Using sigma/epsilon based combination rules with"
981 " user supplied potential function may produce unwanted"
989 * Generate exclusion lists for QM/MM.
991 * This routine updates the exclusion lists for QM atoms in order to include all other QM
992 * atoms of this molecule. Moreover, this routine replaces bonds between QM atoms with
993 * CONNBOND and, when MiMiC is not used, removes bonded interactions between QM and link atoms.
994 * Finally, in case if MiMiC QM/MM is used - charges of QM atoms are set to 0
996 * @param molt molecule type with QM atoms
997 * @param grpnr group informatio
998 * @param ir input record
999 * @param qmmmMode QM/MM mode switch: original/MiMiC
1001 static void generate_qmexcl_moltype(gmx_moltype_t *molt, const unsigned char *grpnr,
1002 t_inputrec *ir, GmxQmmmMode qmmmMode)
1004 /* This routine expects molt->ilist to be of size F_NRE and ordered. */
1006 /* generates the exclusions between the individual QM atoms, as
1007 * these interactions should be handled by the QM subroutines and
1008 * not by the gromacs routines
1010 int qm_max = 0, qm_nr = 0, link_nr = 0, link_max = 0;
1011 int *qm_arr = nullptr, *link_arr = nullptr;
1012 bool *bQMMM, *blink;
1014 /* First we search and select the QM atoms in an qm_arr array that
1015 * we use to create the exclusions.
1017 * we take the possibility into account that a user has defined more
1018 * than one QM group:
1020 * for that we also need to do this an ugly work-about just in case
1021 * the QM group contains the entire system...
1024 /* we first search for all the QM atoms and put them in an array
1026 for (int j = 0; j < ir->opts.ngQM; j++)
1028 for (int i = 0; i < molt->atoms.nr; i++)
1030 if (qm_nr >= qm_max)
1033 srenew(qm_arr, qm_max);
1035 if ((grpnr ? grpnr[i] : 0) == j)
1037 qm_arr[qm_nr++] = i;
1038 molt->atoms.atom[i].q = 0.0;
1039 molt->atoms.atom[i].qB = 0.0;
1043 /* bQMMM[..] is an array containin TRUE/FALSE for atoms that are
1044 * QM/not QM. We first set all elements to false. Afterwards we use
1045 * the qm_arr to change the elements corresponding to the QM atoms
1048 snew(bQMMM, molt->atoms.nr);
1049 for (int i = 0; i < molt->atoms.nr; i++)
1053 for (int i = 0; i < qm_nr; i++)
1055 bQMMM[qm_arr[i]] = TRUE;
1058 /* We remove all bonded interactions (i.e. bonds,
1059 * angles, dihedrals, 1-4's), involving the QM atoms. The way they
1060 * are removed is as follows: if the interaction invloves 2 atoms,
1061 * it is removed if both atoms are QMatoms. If it involves 3 atoms,
1062 * it is removed if at least two of the atoms are QM atoms, if the
1063 * interaction involves 4 atoms, it is removed if there are at least
1064 * 2 QM atoms. Since this routine is called once before any forces
1065 * are computed, the top->idef.il[N].iatom[] array (see idef.h) can
1066 * be rewritten at this poitn without any problem. 25-9-2002 */
1068 /* first check whether we already have CONNBONDS.
1069 * Note that if we don't, we don't add a param entry and set ftype=0,
1070 * which is ok, since CONNBONDS does not use parameters.
1072 int ftype_connbond = 0;
1073 int ind_connbond = 0;
1074 if (molt->ilist[F_CONNBONDS].size() != 0)
1076 fprintf(stderr, "nr. of CONNBONDS present already: %d\n",
1077 molt->ilist[F_CONNBONDS].size()/3);
1078 ftype_connbond = molt->ilist[F_CONNBONDS].iatoms[0];
1079 ind_connbond = molt->ilist[F_CONNBONDS].size();
1081 /* now we delete all bonded interactions, except the ones describing
1082 * a chemical bond. These are converted to CONNBONDS
1084 for (int ftype = 0; ftype < F_NRE; ftype++)
1086 if (!(interaction_function[ftype].flags & IF_BOND) ||
1087 ftype == F_CONNBONDS)
1091 int nratoms = interaction_function[ftype].nratoms;
1093 while (j < molt->ilist[ftype].size())
1099 /* Remove an interaction between two atoms when both are
1100 * in the QM region. Note that we don't have to worry about
1101 * link atoms here, as they won't have 2-atom interactions.
1103 int a1 = molt->ilist[ftype].iatoms[1 + j + 0];
1104 int a2 = molt->ilist[ftype].iatoms[1 + j + 1];
1105 bexcl = (bQMMM[a1] && bQMMM[a2]);
1106 /* A chemical bond between two QM atoms will be copied to
1107 * the F_CONNBONDS list, for reasons mentioned above.
1109 if (bexcl && IS_CHEMBOND(ftype))
1111 InteractionList &ilist = molt->ilist[F_CONNBONDS];
1112 ilist.iatoms.resize(ind_connbond + 3);
1113 ilist.iatoms[ind_connbond++] = ftype_connbond;
1114 ilist.iatoms[ind_connbond++] = a1;
1115 ilist.iatoms[ind_connbond++] = a2;
1120 /* MM interactions have to be excluded if they are included
1121 * in the QM already. Because we use a link atom (H atom)
1122 * when the QM/MM boundary runs through a chemical bond, this
1123 * means that as long as one atom is MM, we still exclude,
1124 * as the interaction is included in the QM via:
1125 * QMatom1-QMatom2-QMatom-3-Linkatom.
1128 for (int jj = j + 1; jj < j + 1 + nratoms; jj++)
1130 if (bQMMM[molt->ilist[ftype].iatoms[jj]])
1136 /* MiMiC treats link atoms as quantum atoms - therefore
1137 * we do not need do additional exclusions here */
1138 if (qmmmMode == GmxQmmmMode::GMX_QMMM_MIMIC)
1140 bexcl = numQmAtoms == nratoms;
1144 bexcl = (numQmAtoms >= nratoms - 1);
1147 if (bexcl && ftype == F_SETTLE)
1149 gmx_fatal(FARGS, "Can not apply QM to molecules with SETTLE, replace the moleculetype using QM and SETTLE by one without SETTLE");
1154 /* since the interaction involves QM atoms, these should be
1155 * removed from the MM ilist
1157 InteractionList &ilist = molt->ilist[ftype];
1158 for (int k = j; k < ilist.size() - (nratoms + 1); k++)
1160 ilist.iatoms[k] = ilist.iatoms[k + (nratoms + 1)];
1162 ilist.iatoms.resize(ilist.size() - (nratoms + 1));
1166 j += nratoms+1; /* the +1 is for the functype */
1170 /* Now, we search for atoms bonded to a QM atom because we also want
1171 * to exclude their nonbonded interactions with the QM atoms. The
1172 * reason for this is that this interaction is accounted for in the
1173 * linkatoms interaction with the QMatoms and would be counted
1176 if (qmmmMode != GmxQmmmMode::GMX_QMMM_MIMIC)
1178 for (int i = 0; i < F_NRE; i++)
1183 while (j < molt->ilist[i].size())
1185 int a1 = molt->ilist[i].iatoms[j + 1];
1186 int a2 = molt->ilist[i].iatoms[j + 2];
1187 if ((bQMMM[a1] && !bQMMM[a2]) || (!bQMMM[a1] && bQMMM[a2]))
1189 if (link_nr >= link_max)
1192 srenew(link_arr, link_max);
1196 link_arr[link_nr++] = a2;
1200 link_arr[link_nr++] = a1;
1208 snew(blink, molt->atoms.nr);
1209 for (int i = 0; i < molt->atoms.nr; i++)
1214 if (qmmmMode != GmxQmmmMode::GMX_QMMM_MIMIC)
1216 for (int i = 0; i < link_nr; i++)
1218 blink[link_arr[i]] = TRUE;
1221 /* creating the exclusion block for the QM atoms. Each QM atom has
1222 * as excluded elements all the other QMatoms (and itself).
1225 qmexcl.nr = molt->atoms.nr;
1226 qmexcl.nra = qm_nr*(qm_nr+link_nr)+link_nr*qm_nr;
1227 snew(qmexcl.index, qmexcl.nr+1);
1228 snew(qmexcl.a, qmexcl.nra);
1230 for (int i = 0; i < qmexcl.nr; i++)
1232 qmexcl.index[i] = j;
1235 for (int k = 0; k < qm_nr; k++)
1237 qmexcl.a[k+j] = qm_arr[k];
1239 for (int k = 0; k < link_nr; k++)
1241 qmexcl.a[qm_nr+k+j] = link_arr[k];
1243 j += (qm_nr+link_nr);
1247 for (int k = 0; k < qm_nr; k++)
1249 qmexcl.a[k+j] = qm_arr[k];
1254 qmexcl.index[qmexcl.nr] = j;
1256 /* and merging with the exclusions already present in sys.
1259 std::vector<gmx::ExclusionBlock> qmexcl2(molt->atoms.nr);
1260 gmx::blockaToExclusionBlocks(&qmexcl, qmexcl2);
1261 gmx::mergeExclusions(&(molt->excls), qmexcl2);
1263 /* Finally, we also need to get rid of the pair interactions of the
1264 * classical atom bonded to the boundary QM atoms with the QMatoms,
1265 * as this interaction is already accounted for by the QM, so also
1266 * here we run the risk of double counting! We proceed in a similar
1267 * way as we did above for the other bonded interactions: */
1268 for (int i = F_LJ14; i < F_COUL14; i++)
1270 int nratoms = interaction_function[i].nratoms;
1272 while (j < molt->ilist[i].size())
1274 int a1 = molt->ilist[i].iatoms[j+1];
1275 int a2 = molt->ilist[i].iatoms[j+2];
1276 bool bexcl = ((bQMMM[a1] && bQMMM[a2]) ||
1277 (blink[a1] && bQMMM[a2]) ||
1278 (bQMMM[a1] && blink[a2]));
1281 /* since the interaction involves QM atoms, these should be
1282 * removed from the MM ilist
1284 InteractionList &ilist = molt->ilist[i];
1285 for (int k = j; k < ilist.size() - (nratoms + 1); k++)
1287 ilist.iatoms[k] = ilist.iatoms[k + (nratoms + 1)];
1289 ilist.iatoms.resize(ilist.size() - (nratoms + 1));
1293 j += nratoms+1; /* the +1 is for the functype */
1302 } /* generate_qmexcl */
1304 void generate_qmexcl(gmx_mtop_t *sys, t_inputrec *ir, warninp *wi, GmxQmmmMode qmmmMode)
1306 /* This routine expects molt->molt[m].ilist to be of size F_NRE and ordered.
1309 unsigned char *grpnr;
1310 int mol, nat_mol, nr_mol_with_qm_atoms = 0;
1311 gmx_molblock_t *molb;
1313 int index_offset = 0;
1316 grpnr = sys->groups.grpnr[egcQMMM];
1318 for (size_t mb = 0; mb < sys->molblock.size(); mb++)
1320 molb = &sys->molblock[mb];
1321 nat_mol = sys->moltype[molb->type].atoms.nr;
1322 for (mol = 0; mol < molb->nmol; mol++)
1325 for (int i = 0; i < nat_mol; i++)
1327 if ((grpnr ? grpnr[i] : 0) < (ir->opts.ngQM))
1336 nr_mol_with_qm_atoms++;
1339 /* We need to split this molblock */
1342 /* Split the molblock at this molecule */
1343 auto pos = sys->molblock.begin() + mb + 1;
1344 sys->molblock.insert(pos, sys->molblock[mb]);
1345 sys->molblock[mb ].nmol = mol;
1346 sys->molblock[mb+1].nmol -= mol;
1348 molb = &sys->molblock[mb];
1352 /* Split the molblock after this molecule */
1353 auto pos = sys->molblock.begin() + mb + 1;
1354 sys->molblock.insert(pos, sys->molblock[mb]);
1355 molb = &sys->molblock[mb];
1356 sys->molblock[mb ].nmol = 1;
1357 sys->molblock[mb+1].nmol -= 1;
1360 /* Create a copy of a moltype for a molecule
1361 * containing QM atoms and append it in the end of the list
1363 std::vector<gmx_moltype_t> temp(sys->moltype.size());
1364 for (size_t i = 0; i < sys->moltype.size(); ++i)
1366 copy_moltype(&sys->moltype[i], &temp[i]);
1368 sys->moltype.resize(sys->moltype.size() + 1);
1369 for (size_t i = 0; i < temp.size(); ++i)
1371 copy_moltype(&temp[i], &sys->moltype[i]);
1373 copy_moltype(&sys->moltype[molb->type], &sys->moltype.back());
1374 /* Copy the exclusions to a new array, since this is the only
1375 * thing that needs to be modified for QMMM.
1377 copy_blocka(&sys->moltype[molb->type].excls,
1378 &sys->moltype.back().excls);
1379 /* Set the molecule type for the QMMM molblock */
1380 molb->type = sys->moltype.size() - 1;
1382 generate_qmexcl_moltype(&sys->moltype[molb->type], grpnr, ir, qmmmMode);
1388 index_offset += nat_mol;
1391 if (qmmmMode == GmxQmmmMode::GMX_QMMM_ORIGINAL &&
1392 nr_mol_with_qm_atoms > 1)
1394 /* generate a warning is there are QM atoms in different
1395 * topologies. In this case it is not possible at this stage to
1396 * mutualy exclude the non-bonded interactions via the
1397 * exclusions (AFAIK). Instead, the user is advised to use the
1398 * energy group exclusions in the mdp file
1401 "\nThe QM subsystem is divided over multiple topologies. "
1402 "The mutual non-bonded interactions cannot be excluded. "
1403 "There are two ways to achieve this:\n\n"
1404 "1) merge the topologies, such that the atoms of the QM "
1405 "subsystem are all present in one single topology file. "
1406 "In this case this warning will dissappear\n\n"
1407 "2) exclude the non-bonded interactions explicitly via the "
1408 "energygrp-excl option in the mdp file. if this is the case "
1409 "this warning may be ignored"