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 by 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.
38 /* This file is completely threadsafe - keep it that way! */
47 #include "gromacs/math/paddedvector.h"
48 #include "gromacs/math/vec.h"
49 #include "gromacs/math/veccompare.h"
50 #include "gromacs/mdtypes/awh_history.h"
51 #include "gromacs/mdtypes/df_history.h"
52 #include "gromacs/mdtypes/inputrec.h"
53 #include "gromacs/mdtypes/md_enums.h"
54 #include "gromacs/mdtypes/pull_params.h"
55 #include "gromacs/mdtypes/swaphistory.h"
56 #include "gromacs/pbcutil/boxutilities.h"
57 #include "gromacs/pbcutil/pbc.h"
58 #include "gromacs/utility/compare.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/smalloc.h"
61 #include "gromacs/utility/stringutil.h"
63 #include "checkpointdata.h"
65 /* The source code in this file should be thread-safe.
66 Please keep it that way. */
68 history_t::history_t() : disre_initf(0), orire_initf(0) {}
70 ekinstate_t::ekinstate_t() :
81 clear_mat(ekin_total);
87 * \brief Enum describing the contents ekinstate_t writes to modular checkpoint
89 * When changing the checkpoint content, add a new element just above Count, and adjust the
90 * checkpoint functionality.
92 enum class CheckpointVersion
94 Base, //!< First version of modular checkpointing
95 Count //!< Number of entries. Add new versions right above this!
97 constexpr auto c_currentVersion = CheckpointVersion(int(CheckpointVersion::Count) - 1);
100 template<gmx::CheckpointDataOperation operation>
101 void ekinstate_t::doCheckpoint(gmx::CheckpointData<operation> checkpointData)
103 gmx::checkpointVersion(&checkpointData, "ekinstate_t version", c_currentVersion);
105 checkpointData.scalar("bUpToDate", &bUpToDate);
110 auto numOfTensors = ekin_n;
111 checkpointData.scalar("ekin_n", &numOfTensors);
112 if (operation == gmx::CheckpointDataOperation::Read)
114 // If this isn't matching, we haven't allocated the right amount of data
115 GMX_RELEASE_ASSERT(numOfTensors == ekin_n,
116 "ekinstate_t checkpoint reading: Tensor size mismatch.");
118 for (int idx = 0; idx < numOfTensors; ++idx)
120 checkpointData.tensor(gmx::formatString("ekinh %d", idx), ekinh[idx]);
121 checkpointData.tensor(gmx::formatString("ekinf %d", idx), ekinf[idx]);
122 checkpointData.tensor(gmx::formatString("ekinh_old %d", idx), ekinh_old[idx]);
124 checkpointData.arrayRef("ekinscalef_nhc", gmx::makeCheckpointArrayRef<operation>(ekinscalef_nhc));
125 checkpointData.arrayRef("ekinscaleh_nhc", gmx::makeCheckpointArrayRef<operation>(ekinscaleh_nhc));
126 checkpointData.arrayRef("vscale_nhc", gmx::makeCheckpointArrayRef<operation>(vscale_nhc));
127 checkpointData.scalar("dekindl", &dekindl);
128 checkpointData.scalar("mvcos", &mvcos);
130 if (operation == gmx::CheckpointDataOperation::Read)
132 hasReadEkinState = true;
136 // Explicit template instantiation
137 template void ekinstate_t::doCheckpoint(gmx::CheckpointData<gmx::CheckpointDataOperation::Read> checkpointData);
138 template void ekinstate_t::doCheckpoint(gmx::CheckpointData<gmx::CheckpointDataOperation::Write> checkpointData);
140 void init_gtc_state(t_state* state, int ngtc, int nnhpres, int nhchainlength)
143 state->nnhpres = nnhpres;
144 state->nhchainlength = nhchainlength;
145 state->nosehoover_xi.resize(state->nhchainlength * state->ngtc, 0);
146 state->nosehoover_vxi.resize(state->nhchainlength * state->ngtc, 0);
147 state->therm_integral.resize(state->ngtc, 0);
148 state->baros_integral = 0.0;
149 state->nhpres_xi.resize(state->nhchainlength * nnhpres, 0);
150 state->nhpres_vxi.resize(state->nhchainlength * nnhpres, 0);
154 /* Checkpoint code relies on this function having no effect if
155 state->natoms is > 0 and passed as natoms. */
156 void state_change_natoms(t_state* state, int natoms)
158 state->natoms = natoms;
160 /* We need padding, since we might use SIMD access, but the
161 * containers here all ensure that. */
162 if (state->flags & enumValueToBitMask(StateEntry::X))
164 state->x.resizeWithPadding(natoms);
166 if (state->flags & enumValueToBitMask(StateEntry::V))
168 state->v.resizeWithPadding(natoms);
170 if (state->flags & enumValueToBitMask(StateEntry::Cgp))
172 state->cg_p.resizeWithPadding(natoms);
179 * \brief Enum describing the contents df_history_t writes to modular checkpoint
181 * When changing the checkpoint content, add a new element just above Count, and adjust the
182 * checkpoint functionality.
184 enum class DFHistoryCheckpointVersion
186 Base, //!< First version of modular checkpointing
187 Count //!< Number of entries. Add new versions right above this!
189 constexpr auto c_dfHistoryCurrentVersion =
190 DFHistoryCheckpointVersion(int(DFHistoryCheckpointVersion::Count) - 1);
193 template<gmx::CheckpointDataOperation operation>
194 void df_history_t::doCheckpoint(gmx::CheckpointData<operation> checkpointData, LambdaWeightCalculation elamstats)
196 gmx::checkpointVersion(&checkpointData, "df_history_t version", c_dfHistoryCurrentVersion);
198 auto numLambdas = nlambda;
199 checkpointData.scalar("nlambda", &numLambdas);
200 if (operation == gmx::CheckpointDataOperation::Read)
202 // If this isn't matching, we haven't allocated the right amount of data
203 GMX_RELEASE_ASSERT(numLambdas == nlambda,
204 "df_history_t checkpoint reading: Lambda vectors size mismatch.");
207 checkpointData.scalar("bEquil", &bEquil);
208 checkpointData.arrayRef("n_at_lam", gmx::makeCheckpointArrayRefFromArray<operation>(n_at_lam, nlambda));
210 checkpointData.arrayRef("sum_weights",
211 gmx::makeCheckpointArrayRefFromArray<operation>(sum_weights, nlambda));
212 checkpointData.arrayRef("sum_dg", gmx::makeCheckpointArrayRefFromArray<operation>(sum_dg, nlambda));
213 for (int idx = 0; idx < nlambda; idx++)
215 checkpointData.arrayRef(gmx::formatString("Tij[%d]", idx),
216 gmx::makeCheckpointArrayRefFromArray<operation>(Tij[idx], nlambda));
217 checkpointData.arrayRef(
218 gmx::formatString("Tij_empirical[%d]", idx),
219 gmx::makeCheckpointArrayRefFromArray<operation>(Tij_empirical[idx], nlambda));
224 checkpointData.arrayRef("wl_histo",
225 gmx::makeCheckpointArrayRefFromArray<operation>(wl_histo, nlambda));
226 checkpointData.scalar("wl_delta", &wl_delta);
228 if ((elamstats == LambdaWeightCalculation::Minvar) || (elamstats == LambdaWeightCalculation::Barker)
229 || (elamstats == LambdaWeightCalculation::Metropolis))
231 checkpointData.arrayRef(
232 "sum_minvar", gmx::makeCheckpointArrayRefFromArray<operation>(sum_minvar, nlambda));
233 checkpointData.arrayRef("sum_variance",
234 gmx::makeCheckpointArrayRefFromArray<operation>(sum_variance, nlambda));
235 for (int idx = 0; idx < nlambda; idx++)
237 checkpointData.arrayRef(gmx::formatString("accum_p[%d]", idx),
238 gmx::makeCheckpointArrayRefFromArray<operation>(accum_p[idx], nlambda));
239 checkpointData.arrayRef(gmx::formatString("accum_m[%d]", idx),
240 gmx::makeCheckpointArrayRefFromArray<operation>(accum_m[idx], nlambda));
241 checkpointData.arrayRef(
242 gmx::formatString("accum_p2[%d]", idx),
243 gmx::makeCheckpointArrayRefFromArray<operation>(accum_p2[idx], nlambda));
244 checkpointData.arrayRef(
245 gmx::formatString("accum_m2[%d]", idx),
246 gmx::makeCheckpointArrayRefFromArray<operation>(accum_m2[idx], nlambda));
251 // explicit template instantiation
252 template void df_history_t::doCheckpoint(gmx::CheckpointData<gmx::CheckpointDataOperation::Read> checkpointData,
253 LambdaWeightCalculation elamstats);
254 template void df_history_t::doCheckpoint(gmx::CheckpointData<gmx::CheckpointDataOperation::Write> checkpointData,
255 LambdaWeightCalculation elamstats);
257 void init_dfhist_state(t_state* state, int dfhistNumLambda)
259 if (dfhistNumLambda > 0)
261 snew(state->dfhist, 1);
262 init_df_history(state->dfhist, dfhistNumLambda);
266 state->dfhist = nullptr;
270 void comp_state(const t_state* st1, const t_state* st2, gmx_bool bRMSD, real ftol, real abstol)
274 fprintf(stdout, "comparing flags\n");
275 cmp_int(stdout, "flags", -1, st1->flags, st2->flags);
276 fprintf(stdout, "comparing box\n");
277 cmp_rvecs(stdout, "box", DIM, st1->box, st2->box, FALSE, ftol, abstol);
278 fprintf(stdout, "comparing box_rel\n");
279 cmp_rvecs(stdout, "box_rel", DIM, st1->box_rel, st2->box_rel, FALSE, ftol, abstol);
280 fprintf(stdout, "comparing boxv\n");
281 cmp_rvecs(stdout, "boxv", DIM, st1->boxv, st2->boxv, FALSE, ftol, abstol);
282 if (st1->flags & enumValueToBitMask(StateEntry::SVirPrev))
284 fprintf(stdout, "comparing shake vir_prev\n");
285 cmp_rvecs(stdout, "svir_prev", DIM, st1->svir_prev, st2->svir_prev, FALSE, ftol, abstol);
287 if (st1->flags & enumValueToBitMask(StateEntry::FVirPrev))
289 fprintf(stdout, "comparing force vir_prev\n");
290 cmp_rvecs(stdout, "fvir_prev", DIM, st1->fvir_prev, st2->fvir_prev, FALSE, ftol, abstol);
292 if (st1->flags & enumValueToBitMask(StateEntry::PressurePrevious))
294 fprintf(stdout, "comparing prev_pres\n");
295 cmp_rvecs(stdout, "pres_prev", DIM, st1->pres_prev, st2->pres_prev, FALSE, ftol, abstol);
297 cmp_int(stdout, "ngtc", -1, st1->ngtc, st2->ngtc);
298 cmp_int(stdout, "nhchainlength", -1, st1->nhchainlength, st2->nhchainlength);
299 if (st1->ngtc == st2->ngtc && st1->nhchainlength == st2->nhchainlength)
301 for (i = 0; i < st1->ngtc; i++)
303 nc = i * st1->nhchainlength;
304 for (j = 0; j < nc; j++)
306 cmp_real(stdout, "nosehoover_xi", i, st1->nosehoover_xi[nc + j], st2->nosehoover_xi[nc + j], ftol, abstol);
310 cmp_int(stdout, "nnhpres", -1, st1->nnhpres, st2->nnhpres);
311 if (st1->nnhpres == st2->nnhpres && st1->nhchainlength == st2->nhchainlength)
313 for (i = 0; i < st1->nnhpres; i++)
315 nc = i * st1->nhchainlength;
316 for (j = 0; j < nc; j++)
318 cmp_real(stdout, "nosehoover_xi", i, st1->nhpres_xi[nc + j], st2->nhpres_xi[nc + j], ftol, abstol);
323 cmp_int(stdout, "natoms", -1, st1->natoms, st2->natoms);
324 if (st1->natoms == st2->natoms)
326 if ((st1->flags & enumValueToBitMask(StateEntry::X))
327 && (st2->flags & enumValueToBitMask(StateEntry::X)))
329 fprintf(stdout, "comparing x\n");
330 cmp_rvecs(stdout, "x", st1->natoms, st1->x.rvec_array(), st2->x.rvec_array(), bRMSD, ftol, abstol);
332 if ((st1->flags & enumValueToBitMask(StateEntry::V))
333 && (st2->flags & enumValueToBitMask(StateEntry::V)))
335 fprintf(stdout, "comparing v\n");
336 cmp_rvecs(stdout, "v", st1->natoms, st1->v.rvec_array(), st2->v.rvec_array(), bRMSD, ftol, abstol);
341 rvec* makeRvecArray(gmx::ArrayRef<const gmx::RVec> v, gmx::index n)
343 GMX_ASSERT(v.ssize() >= n, "We can't copy more elements than the vector size");
349 const rvec* vPtr = as_rvec_array(v.data());
350 for (gmx::index i = 0; i < n; i++)
352 copy_rvec(vPtr[i], dest[i]);
379 // It would be nicer to initialize these with {} or {{0}} in the
380 // above initialization list, but uncrustify doesn't understand
382 // TODO Fix this if we switch to clang-format some time.
387 clear_mat(pres_prev);
388 clear_mat(svir_prev);
389 clear_mat(fvir_prev);
392 void set_box_rel(const t_inputrec* ir, t_state* state)
394 /* Make sure the box obeys the restrictions before we fix the ratios */
395 correct_box(nullptr, 0, state->box);
397 clear_mat(state->box_rel);
399 if (inputrecPreserveShape(ir))
401 const int ndim = ir->epct == PressureCouplingType::SemiIsotropic ? 2 : 3;
402 do_box_rel(ndim, ir->deform, state->box_rel, state->box, true);
406 void preserve_box_shape(const t_inputrec* ir, matrix box_rel, matrix box)
408 if (inputrecPreserveShape(ir))
410 const int ndim = ir->epct == PressureCouplingType::SemiIsotropic ? 2 : 3;
411 do_box_rel(ndim, ir->deform, box_rel, box, false);
415 void printLambdaStateToLog(FILE* fplog, gmx::ArrayRef<const real> lambda, const bool isInitialOutput)
417 if (fplog != nullptr)
419 fprintf(fplog, "%s vector of lambda components:[ ", isInitialOutput ? "Initial" : "Current");
420 for (const auto& l : lambda)
422 fprintf(fplog, "%10.4f ", l);
424 fprintf(fplog, "]\n%s", isInitialOutput ? "" : "\n");
428 void initialize_lambdas(FILE* fplog,
429 const FreeEnergyPerturbationType freeEnergyPerturbationType,
430 const bool haveSimulatedTempering,
432 gmx::ArrayRef<const real> simulatedTemperingTemps,
433 gmx::ArrayRef<real> ref_t,
436 gmx::ArrayRef<real> lambda)
438 /* TODO: Clean up initialization of fep_state and lambda in
439 t_state. This function works, but could probably use a logic
440 rewrite to keep all the different types of efep straight. */
442 if ((freeEnergyPerturbationType == FreeEnergyPerturbationType::No) && (!haveSimulatedTempering))
449 *fep_state = fep.init_fep_state; /* this might overwrite the checkpoint
450 if checkpoint is set -- a kludge is in for now
454 for (int i = 0; i < static_cast<int>(FreeEnergyPerturbationCouplingType::Count); i++)
457 /* overwrite lambda state with init_lambda for now for backwards compatibility */
458 if (fep.init_lambda >= 0) /* if it's -1, it was never initialized */
460 thisLambda = fep.init_lambda;
464 thisLambda = fep.all_lambda[i][fep.init_fep_state];
468 lambda[i] = thisLambda;
471 if (haveSimulatedTempering)
473 /* need to rescale control temperatures to match current state */
474 for (int i = 0; i < ref_t.ssize(); i++)
478 ref_t[i] = simulatedTemperingTemps[fep.init_fep_state];
483 /* Send to the log the information on the current lambdas */
484 const bool isInitialOutput = true;
485 printLambdaStateToLog(fplog, lambda, isInitialOutput);