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 The GROMACS development team.
7 * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
8 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9 * and including many others, as listed in the AUTHORS file in the
10 * top-level source directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
45 #include "gromacs/domdec/ga2la.h"
46 #include "gromacs/domdec/localatomsetmanager.h"
47 #include "gromacs/gmxlib/network.h"
48 #include "gromacs/linearalgebra/nrjac.h"
49 #include "gromacs/math/do_fit.h"
50 #include "gromacs/math/functions.h"
51 #include "gromacs/math/vec.h"
52 #include "gromacs/mdrunutility/multisim.h"
53 #include "gromacs/mdtypes/commrec.h"
54 #include "gromacs/mdtypes/fcdata.h"
55 #include "gromacs/mdtypes/inputrec.h"
56 #include "gromacs/mdtypes/mdatom.h"
57 #include "gromacs/mdtypes/state.h"
58 #include "gromacs/pbcutil/ishift.h"
59 #include "gromacs/pbcutil/pbc.h"
60 #include "gromacs/topology/ifunc.h"
61 #include "gromacs/topology/mtop_util.h"
62 #include "gromacs/topology/topology.h"
63 #include "gromacs/utility/arrayref.h"
64 #include "gromacs/utility/exceptions.h"
65 #include "gromacs/utility/pleasecite.h"
66 #include "gromacs/utility/smalloc.h"
71 // TODO This implementation of ensemble orientation restraints is nasty because
72 // a user can't just do multi-sim with single-sim orientation restraints.
74 void extendStateWithOriresHistory(const gmx_mtop_t& mtop, const t_inputrec& ir, t_state* globalState)
76 GMX_RELEASE_ASSERT(globalState != nullptr,
77 "We need a valid global state in extendStateWithOriresHistory()");
79 const int numRestraints = gmx_mtop_ftype_count(mtop, F_ORIRES);
80 if (numRestraints > 0 && ir.orires_tau > 0)
82 /* Extend the state with the orires history */
83 globalState->flags |= enumValueToBitMask(StateEntry::OrireInitF);
84 globalState->hist.orire_initf = 1;
85 globalState->flags |= enumValueToBitMask(StateEntry::OrireDtav);
86 globalState->hist.orire_Dtav.resize(numRestraints * 5);
93 //! Creates and returns a list of global atom indices of the orientation restraint fit group
94 std::vector<gmx::index> fitGlobalAtomIndices(const gmx_mtop_t& mtop)
96 std::vector<gmx::index> indices;
98 for (int i = 0; i < mtop.natoms; i++)
100 if (getGroupType(mtop.groups, SimulationAtomGroupType::OrientationRestraintsFit, i) == 0)
102 indices.push_back(i);
111 t_oriresdata::t_oriresdata(FILE* fplog,
112 const gmx_mtop_t& mtop,
113 const t_inputrec& ir,
114 const gmx_multisim_t* ms,
115 t_state* globalState,
116 gmx::LocalAtomSetManager* localAtomSetManager) :
117 numRestraints(gmx_mtop_ftype_count(mtop, F_ORIRES)),
118 fitLocalAtomSet_(localAtomSetManager->add(fitGlobalAtomIndices(mtop)))
120 GMX_RELEASE_ASSERT(numRestraints > 0,
121 "orires() should only be called with orientation restraints present");
123 const int numFitParams = 5;
124 if (numRestraints <= numFitParams)
126 const std::string mesg = gmx::formatString(
127 "The system has %d orientation restraints, but at least %d are required, since "
128 "there are %d fitting parameters.",
132 GMX_THROW(gmx::InvalidInputError(mesg));
135 if (ir.bPeriodicMols)
137 /* Since we apply fitting, we need to make molecules whole and this
138 * can not be done when periodic molecules are present.
140 GMX_THROW(gmx::InvalidInputError(
141 "Orientation restraints can not be applied when periodic molecules are present "
145 GMX_RELEASE_ASSERT(globalState != nullptr, "We need a valid global state in t_oriresdata()");
150 std::vector<int> nr_ex;
153 for (const auto il : IListRange(mtop))
155 const int numOrires = il.list()[F_ORIRES].size();
156 if (il.nmol() > 1 && numOrires > 0)
158 const std::string mesg = gmx::formatString(
159 "Found %d copies of a molecule with orientation restrains while the current "
160 "code only supports a single copy. If you want to ensemble average, run "
161 "multiple copies of the system using the multi-sim feature of mdrun.",
163 GMX_THROW(gmx::InvalidInputError(mesg));
166 for (int i = 0; i < numOrires; i += 3)
168 int type = il.list()[F_ORIRES].iatoms[i];
169 int ex = mtop.ffparams.iparams[type].orires.ex;
170 if (ex >= numExperiments)
172 nr_ex.resize(ex + 1, 0);
173 numExperiments = ex + 1;
177 typeMin = std::min(typeMin, type);
178 typeMax = std::max(typeMax, type);
181 /* With domain decomposition we use the type index for indexing in global arrays */
183 typeMax - typeMin + 1 == numRestraints,
184 "All orientation restraint parameter entries in the topology should be consecutive");
186 snew(orderTensors, numExperiments);
187 /* When not doing time averaging, the instaneous and time averaged data
188 * are indentical and the pointers can point to the same memory.
190 snew(DTensors, numRestraints);
194 snew(DTensorsEnsembleAv, numRestraints);
198 DTensorsEnsembleAv = DTensors;
201 if (ir.orires_tau == 0)
203 DTensorsTimeAndEnsembleAv = DTensorsEnsembleAv;
209 snew(DTensorsTimeAndEnsembleAv, numRestraints);
210 edt = std::exp(-ir.delta_t / ir.orires_tau);
213 timeAveragingInitFactor_ = std::reference_wrapper<real>(globalState->hist.orire_initf);
214 DTensorsTimeAveragedHistory_ = globalState->hist.orire_Dtav;
217 orientations.resize(numRestraints);
220 orientationsEnsembleAvBuffer.resize(numRestraints);
221 orientationsEnsembleAv = orientationsEnsembleAvBuffer;
225 orientationsEnsembleAv = orientations;
227 if (ir.orires_tau == 0)
229 orientationsTimeAndEnsembleAv = orientationsEnsembleAv;
233 orientationsTimeAndEnsembleAvBuffer.resize(numRestraints);
234 orientationsTimeAndEnsembleAv = orientationsTimeAndEnsembleAvBuffer;
236 tmpEq.resize(numExperiments);
238 eigenOutput.resize(numExperiments * c_numEigenRealsPerExperiment);
240 /* Determine the reference structure on the master node.
241 * Copy it to the other nodes after checking multi compatibility,
242 * so we are sure the subsystems match before copying.
244 auto x = makeConstArrayRef(globalState->x);
245 rvec com = { 0, 0, 0 };
248 for (const AtomProxy atomP : AtomRange(mtop))
250 const t_atom& local = atomP.atom();
251 int i = atomP.globalAtomNumber();
252 if (getGroupType(mtop.groups, SimulationAtomGroupType::OrientationRestraintsFit, i) == 0)
254 // Not correct for free-energy with changing masses
255 const real mass = local.m;
256 // Note that only one rank per sim is supported.
259 referenceCoordinates_.push_back(x[i]);
260 for (int d = 0; d < DIM; d++)
262 com[d] += mass * x[i][d];
265 fitMasses_.push_back(mass);
271 svmul(1.0 / mtot, com, com);
274 for (auto& refCoord : referenceCoordinates_)
280 const size_t numFitAtoms = referenceCoordinates_.size();
281 fitLocalAtomIndices_.resize(numFitAtoms);
282 xTmp_.resize(numFitAtoms);
286 fprintf(fplog, "Found %d orientation experiments\n", numExperiments);
287 for (int i = 0; i < numExperiments; i++)
289 fprintf(fplog, " experiment %d has %d restraints\n", i + 1, nr_ex[i]);
292 fprintf(fplog, " the fit group consists of %zu atoms and has total mass %g\n", numFitAtoms, mtot);
300 " the orientation restraints are ensemble averaged over %d systems\n",
301 ms->numSimulations_);
304 check_multi_int(fplog, ms, numRestraints, "the number of orientation restraints", FALSE);
306 fplog, ms, numFitAtoms, "the number of fit atoms for orientation restraining", FALSE);
307 check_multi_int(fplog, ms, ir.nsteps, "nsteps", FALSE);
308 /* Copy the reference coordinates from the master to the other nodes */
309 gmx_sum_sim(DIM * referenceCoordinates_.size(), as_rvec_array(referenceCoordinates_.data())[0], ms);
312 please_cite(fplog, "Hess2003");
315 t_oriresdata::~t_oriresdata()
318 if (DTensorsTimeAndEnsembleAv != DTensorsEnsembleAv)
320 sfree(DTensorsTimeAndEnsembleAv);
322 if (DTensorsEnsembleAv != DTensors)
324 sfree(DTensorsEnsembleAv);
329 void diagonalize_orires_tensors(t_oriresdata* od)
331 for (int ex = 0; ex < od->numExperiments; ex++)
333 /* Rotate the S tensor back to the reference frame */
335 mmul(od->rotationMatrix, od->orderTensors[ex], TMP);
336 mtmul(TMP, od->rotationMatrix, S);
337 for (int i = 0; i < DIM; i++)
339 for (int j = 0; j < DIM; j++)
341 od->M[i][j] = S[i][j];
345 jacobi(od->M, od->eig_diag, od->v);
348 for (int i = 0; i < DIM; i++)
352 for (int i = 0; i < DIM; i++)
354 for (int j = i + 1; j < DIM; j++)
356 if (gmx::square(od->eig_diag[ord[j]]) > gmx::square(od->eig_diag[ord[i]]))
365 for (int i = 0; i < DIM; i++)
367 od->eigenOutput[ex * t_oriresdata::c_numEigenRealsPerExperiment + i] = od->eig_diag[ord[i]];
369 for (int i = 0; i < DIM; i++)
371 for (int j = 0; j < DIM; j++)
373 od->eigenOutput[ex * t_oriresdata::c_numEigenRealsPerExperiment + 3 + 3 * i + j] =
380 void print_orires_log(FILE* log, t_oriresdata* od)
382 diagonalize_orires_tensors(od);
384 for (int ex = 0; ex < od->numExperiments; ex++)
386 const real* eig = od->eigenOutput.data() + ex * t_oriresdata::c_numEigenRealsPerExperiment;
387 fprintf(log, " Orientation experiment %d:\n", ex + 1);
388 fprintf(log, " order parameter: %g\n", eig[0]);
389 for (int i = 0; i < DIM; i++)
392 " eig: %6.3f %6.3f %6.3f %6.3f\n",
393 (eig[0] != 0) ? eig[i] / eig[0] : eig[i],
394 eig[DIM + i * DIM + XX],
395 eig[DIM + i * DIM + YY],
396 eig[DIM + i * DIM + ZZ]);
402 real calc_orires_dev(const gmx_multisim_t* ms,
404 const t_iatom forceatoms[],
405 const t_iparams ip[],
406 ArrayRef<const RVec> xWholeMolecules,
411 real invn, pfac, r2, invr, corrfac, wsv2, sw, dev;
412 rvec com, r_unrot, r;
413 const real two_thr = 2.0 / 3.0;
415 const bool bTAV = (od->edt != 0);
416 const real edt = od->edt;
417 const real edt_1 = od->edt_1;
418 gmx::ArrayRef<OriresMatEq> matEq = od->tmpEq;
419 gmx::ArrayRef<gmx::RVec> xFit = od->xTmp();
423 od->exp_min_t_tau = od->timeAveragingInitFactor() * edt;
425 /* Correction factor to correct for the lack of history
428 corrfac = 1.0 / (1.0 - od->exp_min_t_tau);
437 invn = 1.0 / ms->numSimulations_;
444 // Extract the local atom indices involved in the fit group
445 const auto fitLocalAtomIndices = od->fitLocalAtomSet().localIndex();
446 // We need all atoms in the fit group to be local available. This means that
447 // orientation restraining is limited to one PP-rank. This should be ensured
448 // by the mdrun setup code. We assert here to catch incorrect setup code.
449 GMX_RELEASE_ASSERT(fitLocalAtomIndices.size() == od->referenceCoordinates().size(),
450 "All fit atoms should be locally available");
454 gmx::index referenceListIndex = 0;
455 for (const int fitLocalAtomIndex : fitLocalAtomIndices)
457 const gmx::RVec& x = xWholeMolecules[fitLocalAtomIndex];
458 const real mass = od->fitMasses()[referenceListIndex];
459 xFit[referenceListIndex] = x;
460 for (int d = 0; d < DIM; d++)
462 com[d] += mass * x[d];
465 referenceListIndex++;
467 svmul(1.0 / mtot, com, com);
468 for (auto& xFitCoord : xFit)
472 /* Calculate the rotation matrix to rotate x to the reference orientation */
475 od->fitMasses().data(),
476 as_rvec_array(od->referenceCoordinates().data()),
477 as_rvec_array(xFit.data()),
480 for (int fa = 0; fa < nfa; fa += 3)
482 const int type = forceatoms[fa];
483 const int restraintIndex = type - od->typeMin;
486 pbc_dx_aiuc(pbc, x[forceatoms[fa + 1]], x[forceatoms[fa + 2]], r_unrot);
490 rvec_sub(x[forceatoms[fa + 1]], x[forceatoms[fa + 2]], r_unrot);
492 mvmul(od->rotationMatrix, r_unrot, r);
494 invr = gmx::invsqrt(r2);
495 /* Calculate the prefactor for the D tensor, this includes the factor 3! */
496 pfac = ip[type].orires.c * invr * invr * 3;
497 for (int i = 0; i < ip[type].orires.power; i++)
501 rvec5& Dinsl = od->DTensors[restraintIndex];
502 Dinsl[0] = pfac * (2 * r[0] * r[0] + r[1] * r[1] - r2);
503 Dinsl[1] = pfac * (2 * r[0] * r[1]);
504 Dinsl[2] = pfac * (2 * r[0] * r[2]);
505 Dinsl[3] = pfac * (2 * r[1] * r[1] + r[0] * r[0] - r2);
506 Dinsl[4] = pfac * (2 * r[1] * r[2]);
510 for (int i = 0; i < 5; i++)
512 od->DTensorsEnsembleAv[restraintIndex][i] = Dinsl[i] * invn;
519 gmx_sum_sim(5 * od->numRestraints, od->DTensorsEnsembleAv[0], ms);
522 /* Calculate the order tensor S for each experiment via optimization */
523 for (int ex = 0; ex < od->numExperiments; ex++)
525 for (int i = 0; i < 5; i++)
527 matEq[ex].rhs[i] = 0;
528 for (int j = 0; j <= i; j++)
530 matEq[ex].mat[i][j] = 0;
535 for (int fa = 0; fa < nfa; fa += 3)
537 const int type = forceatoms[fa];
538 const int restraintIndex = type - od->typeMin;
539 rvec5& Dtav = od->DTensorsTimeAndEnsembleAv[restraintIndex];
542 /* Here we update DTensorsTimeAndEnsembleAv in t_fcdata using the data in history_t.
543 * Thus the results stay correct when this routine
544 * is called multiple times.
546 for (int i = 0; i < 5; i++)
548 Dtav[i] = edt * od->DTensorsTimeAveragedHistory()[restraintIndex * 5 + i]
549 + edt_1 * od->DTensorsEnsembleAv[restraintIndex][i];
553 int ex = ip[type].orires.ex;
554 real weight = ip[type].orires.kfac;
555 /* Calculate the vector rhs and half the matrix T for the 5 equations */
556 for (int i = 0; i < 5; i++)
558 matEq[ex].rhs[i] += Dtav[i] * ip[type].orires.obs * weight;
559 for (int j = 0; j <= i; j++)
561 matEq[ex].mat[i][j] += Dtav[i] * Dtav[j] * weight;
565 /* Now we have all the data we can calculate S */
566 for (int ex = 0; ex < od->numExperiments; ex++)
568 OriresMatEq& eq = matEq[ex];
569 /* Correct corrfac and copy one half of T to the other half */
570 for (int i = 0; i < 5; i++)
572 eq.rhs[i] *= corrfac;
573 eq.mat[i][i] *= gmx::square(corrfac);
574 for (int j = 0; j < i; j++)
576 eq.mat[i][j] *= gmx::square(corrfac);
577 eq.mat[j][i] = eq.mat[i][j];
580 m_inv_gen(&eq.mat[0][0], 5, &eq.mat[0][0]);
581 /* Calculate the orientation tensor S for this experiment */
582 matrix& S = od->orderTensors[ex];
588 for (int i = 0; i < 5; i++)
590 S[0][0] += 1.5 * eq.mat[0][i] * eq.rhs[i];
591 S[0][1] += 1.5 * eq.mat[1][i] * eq.rhs[i];
592 S[0][2] += 1.5 * eq.mat[2][i] * eq.rhs[i];
593 S[1][1] += 1.5 * eq.mat[3][i] * eq.rhs[i];
594 S[1][2] += 1.5 * eq.mat[4][i] * eq.rhs[i];
599 S[2][2] = -S[0][0] - S[1][1];
602 const matrix* S = od->orderTensors;
607 for (int fa = 0; fa < nfa; fa += 3)
609 const int type = forceatoms[fa];
610 const int restraintIndex = type - od->typeMin;
611 const int ex = ip[type].orires.ex;
613 const rvec5& Dtav = od->DTensorsTimeAndEnsembleAv[restraintIndex];
614 od->orientationsTimeAndEnsembleAv[restraintIndex] =
616 * (S[ex][0][0] * Dtav[0] + S[ex][0][1] * Dtav[1] + S[ex][0][2] * Dtav[2]
617 + S[ex][1][1] * Dtav[3] + S[ex][1][2] * Dtav[4]);
620 const rvec5& Dins = od->DTensorsEnsembleAv[restraintIndex];
621 od->orientationsEnsembleAv[restraintIndex] =
623 * (S[ex][0][0] * Dins[0] + S[ex][0][1] * Dins[1] + S[ex][0][2] * Dins[2]
624 + S[ex][1][1] * Dins[3] + S[ex][1][2] * Dins[4]);
628 /* When ensemble averaging is used recalculate the local orientation
629 * for output to the energy file.
631 const rvec5& Dinsl = od->DTensors[restraintIndex];
632 od->orientations[restraintIndex] =
634 * (S[ex][0][0] * Dinsl[0] + S[ex][0][1] * Dinsl[1] + S[ex][0][2] * Dinsl[2]
635 + S[ex][1][1] * Dinsl[3] + S[ex][1][2] * Dinsl[4]);
638 dev = od->orientationsTimeAndEnsembleAv[restraintIndex] - ip[type].orires.obs;
640 wsv2 += ip[type].orires.kfac * gmx::square(dev);
641 sw += ip[type].orires.kfac;
643 od->rmsdev = std::sqrt(wsv2 / sw);
645 /* Rotate the S matrices back, so we get the correct grad(tr(S D)) */
646 for (int ex = 0; ex < od->numExperiments; ex++)
649 tmmul(od->rotationMatrix, od->orderTensors[ex], RS);
650 mmul(RS, od->rotationMatrix, od->orderTensors[ex]);
655 /* Approx. 120*nfa/3 flops */
659 const t_iatom forceatoms[],
660 const t_iparams ip[],
665 real gmx_unused lambda,
666 real gmx_unused* dvdlambda,
667 gmx::ArrayRef<const real> /*charge*/,
668 t_fcdata gmx_unused* fcd,
669 t_disresdata gmx_unused* disresdata,
670 t_oriresdata* oriresdata,
671 int gmx_unused* global_atom_index)
673 int ex, power, ki = gmx::c_centralShiftIndex;
674 real r2, invr, invr2, fc, smooth_fc, dev, devins, pfac;
681 if (oriresdata->fc != 0)
683 bTAV = (oriresdata->edt != 0);
685 smooth_fc = oriresdata->fc;
688 /* Smoothly switch on the restraining when time averaging is used */
689 smooth_fc *= (1.0 - oriresdata->exp_min_t_tau);
692 for (int fa = 0; fa < nfa; fa += 3)
694 const int type = forceatoms[fa];
695 const int ai = forceatoms[fa + 1];
696 const int aj = forceatoms[fa + 2];
697 const int restraintIndex = type - oriresdata->typeMin;
700 ki = pbc_dx_aiuc(pbc, x[ai], x[aj], r);
704 rvec_sub(x[ai], x[aj], r);
707 invr = gmx::invsqrt(r2);
709 ex = ip[type].orires.ex;
710 power = ip[type].orires.power;
711 fc = smooth_fc * ip[type].orires.kfac;
712 dev = oriresdata->orientationsTimeAndEnsembleAv[restraintIndex] - ip[type].orires.obs;
715 * there is no real potential when time averaging is applied
717 vtot += 0.5 * fc * gmx::square(dev);
721 /* Calculate the force as the sqrt of tav times instantaneous */
722 devins = oriresdata->orientationsEnsembleAv[restraintIndex] - ip[type].orires.obs;
723 if (dev * devins <= 0)
729 dev = std::sqrt(dev * devins);
737 pfac = fc * ip[type].orires.c * invr2;
738 for (int i = 0; i < power; i++)
742 mvmul(oriresdata->orderTensors[ex], r, Sr);
743 for (int i = 0; i < DIM; i++)
745 fij[i] = -pfac * dev * (4 * Sr[i] - 2 * (2 + power) * invr2 * iprod(Sr, r) * r[i]);
748 for (int i = 0; i < DIM; i++)
754 fshift[ki][i] += fij[i];
755 fshift[gmx::c_centralShiftIndex][i] -= fij[i];
763 /* Approx. 80*nfa/3 flops */
766 void t_oriresdata::updateHistory()
770 /* Copy the new time averages that have been calculated
771 * in calc_orires_dev.
773 *timeAveragingInitFactor_ = exp_min_t_tau;
774 for (int pair = 0; pair < numRestraints; pair++)
776 for (int i = 0; i < 5; i++)
778 DTensorsTimeAveragedHistory_[pair * 5 + i] = DTensorsTimeAndEnsembleAv[pair][i];