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.
40 /* This file is completely threadsafe - keep it that way! */
42 #include "gromacs/fileio/tpxio.h"
52 #include "gromacs/applied_forces/awh/read_params.h"
53 #include "gromacs/fileio/filetypes.h"
54 #include "gromacs/fileio/gmxfio.h"
55 #include "gromacs/fileio/gmxfio_xdr.h"
56 #include "gromacs/math/units.h"
57 #include "gromacs/math/vec.h"
58 #include "gromacs/mdtypes/awh_history.h"
59 #include "gromacs/mdtypes/awh_params.h"
60 #include "gromacs/mdtypes/inputrec.h"
61 #include "gromacs/mdtypes/md_enums.h"
62 #include "gromacs/mdtypes/multipletimestepping.h"
63 #include "gromacs/mdtypes/pull_params.h"
64 #include "gromacs/mdtypes/state.h"
65 #include "gromacs/pbcutil/boxutilities.h"
66 #include "gromacs/pbcutil/pbc.h"
67 #include "gromacs/topology/block.h"
68 #include "gromacs/topology/ifunc.h"
69 #include "gromacs/topology/mtop_util.h"
70 #include "gromacs/topology/symtab.h"
71 #include "gromacs/topology/topology.h"
72 #include "gromacs/utility/arraysize.h"
73 #include "gromacs/utility/baseversion.h"
74 #include "gromacs/utility/cstringutil.h"
75 #include "gromacs/utility/fatalerror.h"
76 #include "gromacs/utility/futil.h"
77 #include "gromacs/utility/gmxassert.h"
78 #include "gromacs/utility/inmemoryserializer.h"
79 #include "gromacs/utility/iserializer.h"
80 #include "gromacs/utility/keyvaluetreebuilder.h"
81 #include "gromacs/utility/keyvaluetreeserializer.h"
82 #include "gromacs/utility/smalloc.h"
83 #include "gromacs/utility/snprintf.h"
84 #include "gromacs/utility/txtdump.h"
86 #define TPX_TAG_RELEASE "release"
88 /*! \brief Tag string for the file format written to run input files
89 * written by this version of the code.
91 * Change this if you want to change the run input format in a feature
92 * branch. This ensures that there will not be different run input
93 * formats around which cannot be distinguished, while not causing
94 * problems rebasing the feature branch onto upstream changes. When
95 * merging with mainstream GROMACS, set this tag string back to
96 * TPX_TAG_RELEASE, and instead add an element to tpxv.
98 static const std::string tpx_tag = TPX_TAG_RELEASE;
100 /*! \brief Enum of values that describe the contents of a tpr file
101 * whose format matches a version number
103 * The enum helps the code be more self-documenting and ensure merges
104 * do not silently resolve when two patches make the same bump. When
105 * adding new functionality, add a new element just above tpxv_Count
106 * in this enumeration, and write code below that does the right thing
107 * according to the value of file_version.
111 tpxv_ComputationalElectrophysiology =
112 96, /**< support for ion/water position swaps (computational electrophysiology) */
113 tpxv_Use64BitRandomSeed, /**< change ld_seed from int to int64_t */
114 tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, /**< potentials for supporting coarse-grained force fields */
115 tpxv_InteractiveMolecularDynamics, /**< interactive molecular dynamics (IMD) */
116 tpxv_RemoveObsoleteParameters1, /**< remove optimize_fft, dihre_fc, nstcheckpoint */
117 tpxv_PullCoordTypeGeom, /**< add pull type and geometry per group and flat-bottom */
118 tpxv_PullGeomDirRel, /**< add pull geometry direction-relative */
119 tpxv_IntermolecularBondeds, /**< permit inter-molecular bonded interactions in the topology */
120 tpxv_CompElWithSwapLayerOffset, /**< added parameters for improved CompEl setups */
121 tpxv_CompElPolyatomicIonsAndMultipleIonTypes, /**< CompEl now can handle polyatomic ions and more than two types of ions */
122 tpxv_RemoveAdress, /**< removed support for AdResS */
123 tpxv_PullCoordNGroup, /**< add ngroup to pull coord */
124 tpxv_RemoveTwinRange, /**< removed support for twin-range interactions */
125 tpxv_ReplacePullPrintCOM12, /**< Replaced print-com-1, 2 with pull-print-com */
126 tpxv_PullExternalPotential, /**< Added pull type external potential */
127 tpxv_GenericParamsForElectricField, /**< Introduced KeyValueTree and moved electric field parameters */
128 tpxv_AcceleratedWeightHistogram, /**< sampling with accelerated weight histogram method (AWH) */
129 tpxv_RemoveImplicitSolvation, /**< removed support for implicit solvation */
130 tpxv_PullPrevStepCOMAsReference, /**< Enabled using the COM of the pull group of the last frame as reference for PBC */
131 tpxv_MimicQMMM, /**< Introduced support for MiMiC QM/MM interface */
132 tpxv_PullAverage, /**< Added possibility to output average pull force and position */
133 tpxv_GenericInternalParameters, /**< Added internal parameters for mdrun modules*/
134 tpxv_VSite2FD, /**< Added 2FD type virtual site */
135 tpxv_AddSizeField, /**< Added field with information about the size of the serialized tpr file in bytes, excluding the header */
136 tpxv_StoreNonBondedInteractionExclusionGroup, /**< Store the non bonded interaction exclusion group in the topology */
137 tpxv_VSite1, /**< Added 1 type virtual site */
138 tpxv_MTS, /**< Added multiple time stepping */
139 tpxv_RemovedConstantAcceleration, /**< Removed support for constant acceleration NEMD. */
140 tpxv_Count /**< the total number of tpxv versions */
143 /*! \brief Version number of the file format written to run input
144 * files by this version of the code.
146 * The tpx_version increases whenever the file format in the main
147 * development branch changes, due to an extension of the tpxv enum above.
148 * Backward compatibility for reading old run input files is maintained
149 * by checking this version number against that of the file and then using
150 * the correct code path.
152 * When developing a feature branch that needs to change the run input
153 * file format, change tpx_tag instead. */
154 static const int tpx_version = tpxv_Count - 1;
158 * Enum keeping track of incompatible changes for older TPR versions.
160 * The enum should be updated with a new field when editing the TOPOLOGY
161 * or HEADER of the tpx format. In particular, updating ftupd or
162 * changing the fields of TprHeaderVersion often trigger such needs.
164 * This way we can maintain forward compatibility too for all analysis tools
165 * and/or external programs that only need to know the atom/residue names,
166 * charges, and bond connectivity.
168 * It first appeared in tpx version 26, when I also moved the inputrecord
169 * to the end of the tpx file, so we can just skip it if we only
172 * In particular, it must be increased when adding new elements to
173 * ftupd, so that old code can read new .tpr files.
175 enum class TpxGeneration : int
177 Initial = 26, //! First version is 26
178 AddSizeField, //! TPR header modified for writing as a block.
179 AddVSite1, //! ftupd changed to include VSite1 type.
180 Count //! Number of entries.
183 //! Value of Current TPR generation.
184 static const int tpx_generation = static_cast<int>(TpxGeneration::Count) - 1;
186 /* This number should be the most recent backwards incompatible version
187 * I.e., if this number is 9, we cannot read tpx version 9 with this code.
189 static const int tpx_incompatible_version = 57; // GMX4.0 has version 58
192 /* Struct used to maintain tpx compatibility when function types are added */
195 int fvnr; /* file version number in which the function type first appeared */
196 int ftype; /* function type */
200 * TODO The following three lines make little sense, please clarify if
201 * you've had to work out how ftupd works.
203 * The entries should be ordered in:
204 * 1. ascending function type number
205 * 2. ascending file version number
207 * Because we support reading of old .tpr file versions (even when
208 * mdrun can no longer run the simulation), we need to be able to read
209 * obsolete t_interaction_function types. Any data read from such
210 * fields is discarded. Their names have _NOLONGERUSED appended to
211 * them to make things clear.
213 * When adding to or making breaking changes to reading this struct,
214 * update TpxGeneration.
216 static const t_ftupd ftupd[] = {
217 { 70, F_RESTRBONDS },
218 { tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_RESTRANGLES },
219 { 76, F_LINEAR_ANGLES },
220 { tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_RESTRDIHS },
221 { tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_CBTDIHS },
223 { 60, F_GB12_NOLONGERUSED },
224 { 61, F_GB13_NOLONGERUSED },
225 { 61, F_GB14_NOLONGERUSED },
226 { 72, F_GBPOL_NOLONGERUSED },
227 { 72, F_NPSOLVATION_NOLONGERUSED },
229 { 76, F_ANHARM_POL },
231 { tpxv_VSite1, F_VSITE1 },
232 { tpxv_VSite2FD, F_VSITE2FD },
233 { tpxv_GenericInternalParameters, F_DENSITYFITTING },
234 { 69, F_VTEMP_NOLONGERUSED },
245 { 79, F_DVDL_RESTRAINT },
246 { 79, F_DVDL_TEMPERATURE },
248 #define NFTUPD asize(ftupd)
250 /**************************************************************
252 * Now the higer level routines that do io of the structures and arrays
254 **************************************************************/
255 static void do_pullgrp_tpx_pre95(gmx::ISerializer* serializer, t_pull_group* pgrp, t_pull_coord* pcrd)
259 int numAtoms = pgrp->ind.size();
260 serializer->doInt(&numAtoms);
261 pgrp->ind.resize(numAtoms);
262 serializer->doIntArray(pgrp->ind.data(), numAtoms);
263 int numWeights = pgrp->weight.size();
264 serializer->doInt(&numWeights);
265 pgrp->weight.resize(numWeights);
266 serializer->doRealArray(pgrp->weight.data(), numWeights);
267 serializer->doInt(&pgrp->pbcatom);
268 serializer->doRvec(&pcrd->vec.as_vec());
269 clear_rvec(pcrd->origin);
270 serializer->doRvec(&tmp);
272 serializer->doReal(&pcrd->rate);
273 serializer->doReal(&pcrd->k);
274 serializer->doReal(&pcrd->kB);
277 static void do_pull_group(gmx::ISerializer* serializer, t_pull_group* pgrp)
279 int numAtoms = pgrp->ind.size();
280 serializer->doInt(&numAtoms);
281 pgrp->ind.resize(numAtoms);
282 serializer->doIntArray(pgrp->ind.data(), numAtoms);
283 int numWeights = pgrp->weight.size();
284 serializer->doInt(&numWeights);
285 pgrp->weight.resize(numWeights);
286 serializer->doRealArray(pgrp->weight.data(), numWeights);
287 serializer->doInt(&pgrp->pbcatom);
290 static void do_pull_coord(gmx::ISerializer* serializer,
293 PullingAlgorithm ePullOld,
294 PullGroupGeometry eGeomOld,
297 if (file_version >= tpxv_PullCoordNGroup)
299 serializer->doEnumAsInt(&pcrd->eType);
300 if (file_version >= tpxv_PullExternalPotential)
302 if (pcrd->eType == PullingAlgorithm::External)
305 if (serializer->reading())
307 serializer->doString(&buf);
308 pcrd->externalPotentialProvider = gmx_strdup(buf.c_str());
312 buf = pcrd->externalPotentialProvider;
313 serializer->doString(&buf);
318 pcrd->externalPotentialProvider.clear();
323 if (serializer->reading())
325 pcrd->externalPotentialProvider.clear();
328 /* Note that we try to support adding new geometries without
329 * changing the tpx version. This requires checks when printing the
330 * geometry string and a check and fatal_error in init_pull.
332 serializer->doEnumAsInt(&pcrd->eGeom);
333 serializer->doInt(&pcrd->ngroup);
334 if (pcrd->ngroup <= c_pullCoordNgroupMax)
336 serializer->doIntArray(pcrd->group.data(), pcrd->ngroup);
340 /* More groups in file than supported, this must be a new geometry
341 * that is not supported by our current code. Since we will not
342 * use the groups for this coord (checks in the pull and WHAM code
343 * ensure this), we can ignore the groups and set ngroup=0.
346 snew(dum, pcrd->ngroup);
347 serializer->doIntArray(dum, pcrd->ngroup);
352 serializer->doIvec(&pcrd->dim.as_vec());
357 serializer->doInt(&pcrd->group[0]);
358 serializer->doInt(&pcrd->group[1]);
359 if (file_version >= tpxv_PullCoordTypeGeom)
361 pcrd->ngroup = (pcrd->eGeom == PullGroupGeometry::DirectionRelative ? 4 : 2);
362 serializer->doEnumAsInt(&pcrd->eType);
363 serializer->doEnumAsInt(&pcrd->eGeom);
364 if (pcrd->ngroup == 4)
366 serializer->doInt(&pcrd->group[2]);
367 serializer->doInt(&pcrd->group[3]);
369 serializer->doIvec(&pcrd->dim.as_vec());
373 pcrd->eType = ePullOld;
374 pcrd->eGeom = eGeomOld;
375 copy_ivec(dimOld, pcrd->dim);
378 serializer->doRvec(&pcrd->origin.as_vec());
379 serializer->doRvec(&pcrd->vec.as_vec());
380 if (file_version >= tpxv_PullCoordTypeGeom)
382 serializer->doBool(&pcrd->bStart);
386 /* This parameter is only printed, but not actually used by mdrun */
387 pcrd->bStart = FALSE;
389 serializer->doReal(&pcrd->init);
390 serializer->doReal(&pcrd->rate);
391 serializer->doReal(&pcrd->k);
392 serializer->doReal(&pcrd->kB);
395 static void do_expandedvals(gmx::ISerializer* serializer, t_expanded* expand, t_lambda* fepvals, int file_version)
397 int n_lambda = fepvals->n_lambda;
399 /* reset the lambda calculation window */
400 fepvals->lambda_start_n = 0;
401 fepvals->lambda_stop_n = n_lambda;
402 if (file_version >= 79)
406 expand->init_lambda_weights.resize(n_lambda);
407 serializer->doRealArray(expand->init_lambda_weights.data(), n_lambda);
408 serializer->doBool(&expand->bInit_weights);
411 serializer->doInt(&expand->nstexpanded);
412 serializer->doEnumAsInt(&expand->elmcmove);
413 serializer->doEnumAsInt(&expand->elamstats);
414 serializer->doInt(&expand->lmc_repeats);
415 serializer->doInt(&expand->gibbsdeltalam);
416 serializer->doInt(&expand->lmc_forced_nstart);
417 serializer->doInt(&expand->lmc_seed);
418 serializer->doReal(&expand->mc_temp);
419 serializer->doBool(&expand->bSymmetrizedTMatrix);
420 serializer->doInt(&expand->nstTij);
421 serializer->doInt(&expand->minvarmin);
422 serializer->doInt(&expand->c_range);
423 serializer->doReal(&expand->wl_scale);
424 serializer->doReal(&expand->wl_ratio);
425 serializer->doReal(&expand->init_wl_delta);
426 serializer->doBool(&expand->bWLoneovert);
427 serializer->doEnumAsInt(&expand->elmceq);
428 serializer->doInt(&expand->equil_steps);
429 serializer->doInt(&expand->equil_samples);
430 serializer->doInt(&expand->equil_n_at_lam);
431 serializer->doReal(&expand->equil_wl_delta);
432 serializer->doReal(&expand->equil_ratio);
436 static void do_simtempvals(gmx::ISerializer* serializer, t_simtemp* simtemp, int n_lambda, int file_version)
438 if (file_version >= 79)
440 serializer->doEnumAsInt(&simtemp->eSimTempScale);
441 serializer->doReal(&simtemp->simtemp_high);
442 serializer->doReal(&simtemp->simtemp_low);
445 if (serializer->reading())
447 simtemp->temperatures.resize(n_lambda);
449 serializer->doRealArray(simtemp->temperatures.data(), n_lambda);
454 static void do_imd(gmx::ISerializer* serializer, t_IMD* imd)
456 serializer->doInt(&imd->nat);
457 if (serializer->reading())
459 snew(imd->ind, imd->nat);
461 serializer->doIntArray(imd->ind, imd->nat);
464 static void do_fepvals(gmx::ISerializer* serializer, t_lambda* fepvals, int file_version)
466 /* i is defined in the ndo_double macro; use g to iterate. */
469 /* free energy values */
471 if (file_version >= 79)
473 serializer->doInt(&fepvals->init_fep_state);
474 serializer->doDouble(&fepvals->init_lambda);
475 serializer->doDouble(&fepvals->delta_lambda);
477 else if (file_version >= 59)
479 serializer->doDouble(&fepvals->init_lambda);
480 serializer->doDouble(&fepvals->delta_lambda);
484 serializer->doReal(&rdum);
485 fepvals->init_lambda = rdum;
486 serializer->doReal(&rdum);
487 fepvals->delta_lambda = rdum;
489 if (file_version >= 79)
491 serializer->doInt(&fepvals->n_lambda);
492 for (auto g : keysOf(fepvals->all_lambda))
494 if (fepvals->n_lambda > 0)
496 fepvals->all_lambda[g].resize(fepvals->n_lambda);
497 serializer->doDoubleArray(fepvals->all_lambda[g].data(), fepvals->n_lambda);
498 serializer->doBoolArray(fepvals->separate_dvdl.begin(), fepvals->separate_dvdl.size());
500 else if (fepvals->init_lambda >= 0)
502 fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
506 else if (file_version >= 64)
508 serializer->doInt(&fepvals->n_lambda);
509 if (serializer->reading())
511 /* still allocate the all_lambda array's contents. */
512 for (auto g : keysOf(fepvals->all_lambda))
514 if (fepvals->n_lambda > 0)
516 fepvals->all_lambda[g].resize(fepvals->n_lambda);
520 serializer->doDoubleArray(fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep].data(),
522 if (fepvals->init_lambda >= 0)
524 fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
526 if (serializer->reading())
528 /* copy the contents of the efptFEP lambda component to all
529 the other components */
530 for (auto g : keysOf(fepvals->all_lambda))
532 for (int h = 0; h < fepvals->n_lambda; h++)
534 if (g != FreeEnergyPerturbationCouplingType::Fep)
536 fepvals->all_lambda[g][h] =
537 fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep][h];
546 fepvals->n_lambda = 0;
547 if (fepvals->init_lambda >= 0)
549 fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
552 serializer->doReal(&fepvals->sc_alpha);
553 serializer->doInt(&fepvals->sc_power);
554 if (file_version >= 79)
556 serializer->doReal(&fepvals->sc_r_power);
560 fepvals->sc_r_power = 6.0;
562 if (fepvals->sc_r_power != 6.0)
564 gmx_fatal(FARGS, "sc-r-power=48 is no longer supported");
566 serializer->doReal(&fepvals->sc_sigma);
567 if (serializer->reading())
569 if (file_version >= 71)
571 fepvals->sc_sigma_min = fepvals->sc_sigma;
575 fepvals->sc_sigma_min = 0;
578 if (file_version >= 79)
580 serializer->doBool(&fepvals->bScCoul);
584 fepvals->bScCoul = TRUE;
586 if (file_version >= 64)
588 serializer->doInt(&fepvals->nstdhdl);
592 fepvals->nstdhdl = 1;
595 if (file_version >= 73)
597 serializer->doEnumAsInt(&fepvals->separate_dhdl_file);
598 serializer->doEnumAsInt(&fepvals->dhdl_derivatives);
602 fepvals->separate_dhdl_file = SeparateDhdlFile::Yes;
603 fepvals->dhdl_derivatives = DhDlDerivativeCalculation::Yes;
605 if (file_version >= 71)
607 serializer->doInt(&fepvals->dh_hist_size);
608 serializer->doDouble(&fepvals->dh_hist_spacing);
612 fepvals->dh_hist_size = 0;
613 fepvals->dh_hist_spacing = 0.1;
615 if (file_version >= 79)
617 serializer->doEnumAsInt(&fepvals->edHdLPrintEnergy);
621 fepvals->edHdLPrintEnergy = FreeEnergyPrintEnergy::No;
624 /* handle lambda_neighbors */
625 if ((file_version >= 83 && file_version < 90) || file_version >= 92)
627 serializer->doInt(&fepvals->lambda_neighbors);
628 if ((fepvals->lambda_neighbors >= 0) && (fepvals->init_fep_state >= 0)
629 && (fepvals->init_lambda < 0))
631 fepvals->lambda_start_n = (fepvals->init_fep_state - fepvals->lambda_neighbors);
632 fepvals->lambda_stop_n = (fepvals->init_fep_state + fepvals->lambda_neighbors + 1);
633 if (fepvals->lambda_start_n < 0)
635 fepvals->lambda_start_n = 0;
637 if (fepvals->lambda_stop_n >= fepvals->n_lambda)
639 fepvals->lambda_stop_n = fepvals->n_lambda;
644 fepvals->lambda_start_n = 0;
645 fepvals->lambda_stop_n = fepvals->n_lambda;
650 fepvals->lambda_start_n = 0;
651 fepvals->lambda_stop_n = fepvals->n_lambda;
655 static void do_pull(gmx::ISerializer* serializer, pull_params_t* pull, int file_version, PullingAlgorithm ePullOld)
657 PullGroupGeometry eGeomOld = PullGroupGeometry::Count;
661 if (file_version >= 95)
663 serializer->doInt(&pull->ngroup);
665 serializer->doInt(&pull->ncoord);
666 if (file_version < 95)
668 pull->ngroup = pull->ncoord + 1;
670 if (file_version < tpxv_PullCoordTypeGeom)
674 serializer->doEnumAsInt(&eGeomOld);
675 serializer->doIvec(&dimOld);
676 /* The inner cylinder radius, now removed */
677 serializer->doReal(&dum);
679 serializer->doReal(&pull->cylinder_r);
680 serializer->doReal(&pull->constr_tol);
681 if (file_version >= 95)
683 serializer->doBool(&pull->bPrintCOM);
684 /* With file_version < 95 this value is set below */
686 if (file_version >= tpxv_ReplacePullPrintCOM12)
688 serializer->doBool(&pull->bPrintRefValue);
689 serializer->doBool(&pull->bPrintComp);
691 else if (file_version >= tpxv_PullCoordTypeGeom)
694 serializer->doInt(&idum); /* used to be bPrintCOM2 */
695 serializer->doBool(&pull->bPrintRefValue);
696 serializer->doBool(&pull->bPrintComp);
700 pull->bPrintRefValue = FALSE;
701 pull->bPrintComp = TRUE;
703 serializer->doInt(&pull->nstxout);
704 serializer->doInt(&pull->nstfout);
705 if (file_version >= tpxv_PullPrevStepCOMAsReference)
707 serializer->doBool(&pull->bSetPbcRefToPrevStepCOM);
711 pull->bSetPbcRefToPrevStepCOM = FALSE;
713 pull->group.resize(pull->ngroup);
714 pull->coord.resize(pull->ncoord);
715 if (file_version < 95)
717 /* epullgPOS for position pulling, before epullgDIRPBC was removed */
718 if (eGeomOld == PullGroupGeometry::DirectionPBC)
720 gmx_fatal(FARGS, "pull-geometry=position is no longer supported");
722 if (eGeomOld > PullGroupGeometry::DirectionPBC)
726 case (PullGroupGeometry::DirectionRelative):
727 eGeomOld = PullGroupGeometry::DirectionPBC;
729 case (PullGroupGeometry::Angle):
730 eGeomOld = PullGroupGeometry::DirectionRelative;
732 case (PullGroupGeometry::Dihedral): eGeomOld = PullGroupGeometry::Angle; break;
733 case (PullGroupGeometry::AngleAxis): eGeomOld = PullGroupGeometry::Dihedral; break;
734 case (PullGroupGeometry::Count): eGeomOld = PullGroupGeometry::AngleAxis; break;
735 default: GMX_RELEASE_ASSERT(false, "Unhandled old pull type");
739 for (g = 0; g < pull->ngroup; g++)
741 /* We read and ignore a pull coordinate for group 0 */
742 do_pullgrp_tpx_pre95(serializer, &pull->group[g], &pull->coord[std::max(g - 1, 0)]);
745 pull->coord[g - 1].group[0] = 0;
746 pull->coord[g - 1].group[1] = g;
750 pull->bPrintCOM = (!pull->group[0].ind.empty());
754 for (g = 0; g < pull->ngroup; g++)
756 do_pull_group(serializer, &pull->group[g]);
758 for (g = 0; g < pull->ncoord; g++)
760 do_pull_coord(serializer, &pull->coord[g], file_version, ePullOld, eGeomOld, dimOld);
761 if (serializer->reading())
763 pull->coord[g].coordIndex = g;
767 if (file_version >= tpxv_PullAverage)
771 v = pull->bXOutAverage;
772 serializer->doBool(&v);
773 pull->bXOutAverage = v;
774 v = pull->bFOutAverage;
775 serializer->doBool(&v);
776 pull->bFOutAverage = v;
781 static void do_rotgrp(gmx::ISerializer* serializer, t_rotgrp* rotg)
783 serializer->doEnumAsInt(&rotg->eType);
784 if (serializer->reading())
787 serializer->doInt(&temp);
788 rotg->bMassW = static_cast<bool>(temp);
792 int temp = static_cast<int>(rotg->bMassW);
793 serializer->doInt(&temp);
795 serializer->doInt(&rotg->nat);
796 if (serializer->reading())
798 snew(rotg->ind, rotg->nat);
800 serializer->doIntArray(rotg->ind, rotg->nat);
801 if (serializer->reading())
803 snew(rotg->x_ref, rotg->nat);
805 serializer->doRvecArray(rotg->x_ref, rotg->nat);
806 serializer->doRvec(&rotg->inputVec);
807 serializer->doRvec(&rotg->pivot);
808 serializer->doReal(&rotg->rate);
809 serializer->doReal(&rotg->k);
810 serializer->doReal(&rotg->slab_dist);
811 serializer->doReal(&rotg->min_gaussian);
812 serializer->doReal(&rotg->eps);
813 serializer->doEnumAsInt(&rotg->eFittype);
814 serializer->doInt(&rotg->PotAngle_nstep);
815 serializer->doReal(&rotg->PotAngle_step);
818 static void do_rot(gmx::ISerializer* serializer, t_rot* rot)
822 serializer->doInt(&rot->ngrp);
823 serializer->doInt(&rot->nstrout);
824 serializer->doInt(&rot->nstsout);
825 if (serializer->reading())
827 snew(rot->grp, rot->ngrp);
829 for (g = 0; g < rot->ngrp; g++)
831 do_rotgrp(serializer, &rot->grp[g]);
836 static void do_swapgroup(gmx::ISerializer* serializer, t_swapGroup* g)
839 /* Name of the group or molecule */
841 if (serializer->reading())
843 serializer->doString(&buf);
844 g->molname = gmx_strdup(buf.c_str());
849 serializer->doString(&buf);
852 /* Number of atoms in the group */
853 serializer->doInt(&g->nat);
855 /* The group's atom indices */
856 if (serializer->reading())
858 snew(g->ind, g->nat);
860 serializer->doIntArray(g->ind, g->nat);
862 /* Requested counts for compartments A and B */
863 serializer->doIntArray(g->nmolReq.data(), static_cast<int>(Compartment::Count));
866 static void do_swapcoords_tpx(gmx::ISerializer* serializer, t_swapcoords* swap, int file_version)
868 /* Enums for better readability of the code */
881 if (file_version >= tpxv_CompElPolyatomicIonsAndMultipleIonTypes)
883 /* The total number of swap groups is the sum of the fixed groups
884 * (split0, split1, solvent), and the user-defined groups (2+ types of ions)
886 serializer->doInt(&swap->ngrp);
887 if (serializer->reading())
889 snew(swap->grp, swap->ngrp);
891 for (int ig = 0; ig < swap->ngrp; ig++)
893 do_swapgroup(serializer, &swap->grp[ig]);
895 serializer->doBool(&swap->massw_split[eChannel0]);
896 serializer->doBool(&swap->massw_split[eChannel1]);
897 serializer->doInt(&swap->nstswap);
898 serializer->doInt(&swap->nAverage);
899 serializer->doReal(&swap->threshold);
900 serializer->doReal(&swap->cyl0r);
901 serializer->doReal(&swap->cyl0u);
902 serializer->doReal(&swap->cyl0l);
903 serializer->doReal(&swap->cyl1r);
904 serializer->doReal(&swap->cyl1u);
905 serializer->doReal(&swap->cyl1l);
909 /*** Support reading older CompEl .tpr files ***/
911 /* In the original CompEl .tpr files, we always have 5 groups: */
913 snew(swap->grp, swap->ngrp);
915 swap->grp[static_cast<int>(SwapGroupSplittingType::Split0)].molname = gmx_strdup("split0"); // group 0: split0
916 swap->grp[static_cast<int>(SwapGroupSplittingType::Split1)].molname = gmx_strdup("split1"); // group 1: split1
917 swap->grp[static_cast<int>(SwapGroupSplittingType::Solvent)].molname =
918 gmx_strdup("solvent"); // group 2: solvent
919 swap->grp[3].molname = gmx_strdup("anions"); // group 3: anions
920 swap->grp[4].molname = gmx_strdup("cations"); // group 4: cations
922 serializer->doInt(&swap->grp[3].nat);
923 serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Solvent)].nat);
924 serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Split0)].nat);
925 serializer->doBool(&swap->massw_split[eChannel0]);
926 serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Split1)].nat);
927 serializer->doBool(&swap->massw_split[eChannel1]);
928 serializer->doInt(&swap->nstswap);
929 serializer->doInt(&swap->nAverage);
930 serializer->doReal(&swap->threshold);
931 serializer->doReal(&swap->cyl0r);
932 serializer->doReal(&swap->cyl0u);
933 serializer->doReal(&swap->cyl0l);
934 serializer->doReal(&swap->cyl1r);
935 serializer->doReal(&swap->cyl1u);
936 serializer->doReal(&swap->cyl1l);
938 // The order[] array keeps compatibility with older .tpr files
939 // by reading in the groups in the classic order
941 const int order[4] = { 3,
942 static_cast<int>(SwapGroupSplittingType::Solvent),
943 static_cast<int>(SwapGroupSplittingType::Split0),
944 static_cast<int>(SwapGroupSplittingType::Split1) };
946 for (int ig = 0; ig < 4; ig++)
949 snew(swap->grp[g].ind, swap->grp[g].nat);
950 serializer->doIntArray(swap->grp[g].ind, swap->grp[g].nat);
954 for (int j = eCompA; j <= eCompB; j++)
956 serializer->doInt(&swap->grp[3].nmolReq[j]); // group 3 = anions
957 serializer->doInt(&swap->grp[4].nmolReq[j]); // group 4 = cations
959 } /* End support reading older CompEl .tpr files */
961 if (file_version >= tpxv_CompElWithSwapLayerOffset)
963 serializer->doReal(&swap->bulkOffset[eCompA]);
964 serializer->doReal(&swap->bulkOffset[eCompB]);
968 static void do_legacy_efield(gmx::ISerializer* serializer, gmx::KeyValueTreeObjectBuilder* root)
970 const char* const dimName[] = { "x", "y", "z" };
972 auto appliedForcesObj = root->addObject("applied-forces");
973 auto efieldObj = appliedForcesObj.addObject("electric-field");
974 // The content of the tpr file for this feature has
975 // been the same since gromacs 4.0 that was used for
977 for (int j = 0; j < DIM; ++j)
980 serializer->doInt(&n);
981 serializer->doInt(&nt);
982 std::vector<real> aa(n + 1), phi(nt + 1), at(nt + 1), phit(nt + 1);
983 serializer->doRealArray(aa.data(), n);
984 serializer->doRealArray(phi.data(), n);
985 serializer->doRealArray(at.data(), nt);
986 serializer->doRealArray(phit.data(), nt);
992 "Can not handle tpr files with more than one electric field term per "
995 auto dimObj = efieldObj.addObject(dimName[j]);
996 dimObj.addValue<real>("E0", aa[0]);
997 dimObj.addValue<real>("omega", at[0]);
998 dimObj.addValue<real>("t0", phi[0]);
999 dimObj.addValue<real>("sigma", phit[0]);
1005 static void do_inputrec(gmx::ISerializer* serializer, t_inputrec* ir, int file_version)
1007 int i, j, k, idum = 0;
1009 gmx_bool bdum = false;
1011 if (file_version != tpx_version)
1013 /* Give a warning about features that are not accessible */
1014 fprintf(stderr, "Note: file tpx version %d, software tpx version %d\n", file_version, tpx_version);
1017 if (file_version == 0)
1022 gmx::KeyValueTreeBuilder paramsBuilder;
1023 gmx::KeyValueTreeObjectBuilder paramsObj = paramsBuilder.rootObject();
1025 /* Basic inputrec stuff */
1026 serializer->doEnumAsInt(&ir->eI);
1027 if (file_version >= 62)
1029 serializer->doInt64(&ir->nsteps);
1033 serializer->doInt(&idum);
1037 if (file_version >= 62)
1039 serializer->doInt64(&ir->init_step);
1043 serializer->doInt(&idum);
1044 ir->init_step = idum;
1047 serializer->doInt(&ir->simulation_part);
1049 if (file_version >= tpxv_MTS)
1051 serializer->doBool(&ir->useMts);
1052 int numLevels = ir->mtsLevels.size();
1055 serializer->doInt(&numLevels);
1057 ir->mtsLevels.resize(numLevels);
1058 for (auto& mtsLevel : ir->mtsLevels)
1060 int forceGroups = mtsLevel.forceGroups.to_ulong();
1061 serializer->doInt(&forceGroups);
1062 mtsLevel.forceGroups = std::bitset<static_cast<int>(gmx::MtsForceGroups::Count)>(forceGroups);
1063 serializer->doInt(&mtsLevel.stepFactor);
1069 ir->mtsLevels.clear();
1072 if (file_version >= 67)
1074 serializer->doInt(&ir->nstcalcenergy);
1078 ir->nstcalcenergy = 1;
1080 if (file_version >= 81)
1082 serializer->doEnumAsInt(&ir->cutoff_scheme);
1083 if (file_version < 94)
1085 // Need to invert the scheme order
1086 switch (ir->cutoff_scheme)
1088 case (CutoffScheme::Group): ir->cutoff_scheme = CutoffScheme::Verlet; break;
1089 case (CutoffScheme::Verlet): ir->cutoff_scheme = CutoffScheme::Group; break;
1090 default: GMX_RELEASE_ASSERT(false, "Unhandled cutoff scheme type");
1096 ir->cutoff_scheme = CutoffScheme::Group;
1098 serializer->doInt(&idum); /* used to be ns_type; not used anymore */
1099 serializer->doInt(&ir->nstlist);
1100 serializer->doInt(&idum); /* used to be ndelta; not used anymore */
1102 serializer->doReal(&ir->rtpi);
1104 serializer->doInt(&ir->nstcomm);
1105 serializer->doEnumAsInt(&ir->comm_mode);
1107 /* ignore nstcheckpoint */
1108 if (file_version < tpxv_RemoveObsoleteParameters1)
1110 serializer->doInt(&idum);
1113 serializer->doInt(&ir->nstcgsteep);
1115 serializer->doInt(&ir->nbfgscorr);
1117 serializer->doInt(&ir->nstlog);
1118 serializer->doInt(&ir->nstxout);
1119 serializer->doInt(&ir->nstvout);
1120 serializer->doInt(&ir->nstfout);
1121 serializer->doInt(&ir->nstenergy);
1122 serializer->doInt(&ir->nstxout_compressed);
1123 if (file_version >= 59)
1125 serializer->doDouble(&ir->init_t);
1126 serializer->doDouble(&ir->delta_t);
1130 serializer->doReal(&rdum);
1132 serializer->doReal(&rdum);
1135 serializer->doReal(&ir->x_compression_precision);
1136 if (file_version >= 81)
1138 serializer->doReal(&ir->verletbuf_tol);
1142 ir->verletbuf_tol = 0;
1144 serializer->doReal(&ir->rlist);
1145 if (file_version >= 67 && file_version < tpxv_RemoveTwinRange)
1147 if (serializer->reading())
1149 // Reading such a file version could invoke the twin-range
1150 // scheme, about which mdrun should give a fatal error.
1151 real dummy_rlistlong = -1;
1152 serializer->doReal(&dummy_rlistlong);
1154 ir->useTwinRange = (ir->rlist > 0 && (dummy_rlistlong == 0 || dummy_rlistlong > ir->rlist));
1155 // When true, this forces mdrun to issue an error (regardless of
1156 // ir->cutoff_scheme).
1158 // Otherwise, grompp used to set rlistlong actively. Users
1159 // were probably also confused and set rlistlong == rlist.
1160 // However, in all remaining cases, it is safe to let
1161 // mdrun proceed normally.
1166 // No need to read or write anything
1167 ir->useTwinRange = false;
1169 if (file_version >= 82 && file_version != 90)
1171 // Multiple time-stepping is no longer enabled, but the old
1172 // support required the twin-range scheme, for which mdrun
1173 // already emits a fatal error.
1174 int dummy_nstcalclr = -1;
1175 serializer->doInt(&dummy_nstcalclr);
1177 serializer->doEnumAsInt(&ir->coulombtype);
1178 if (file_version >= 81)
1180 serializer->doEnumAsInt(&ir->coulomb_modifier);
1184 ir->coulomb_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
1185 : InteractionModifiers::None);
1187 serializer->doReal(&ir->rcoulomb_switch);
1188 serializer->doReal(&ir->rcoulomb);
1189 serializer->doEnumAsInt(&ir->vdwtype);
1190 if (file_version >= 81)
1192 serializer->doEnumAsInt(&ir->vdw_modifier);
1196 ir->vdw_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
1197 : InteractionModifiers::None);
1199 serializer->doReal(&ir->rvdw_switch);
1200 serializer->doReal(&ir->rvdw);
1201 serializer->doEnumAsInt(&ir->eDispCorr);
1202 serializer->doReal(&ir->epsilon_r);
1203 serializer->doReal(&ir->epsilon_rf);
1204 serializer->doReal(&ir->tabext);
1206 // This permits reading a .tpr file that used implicit solvent,
1207 // and later permitting mdrun to refuse to run it.
1208 if (serializer->reading())
1210 if (file_version < tpxv_RemoveImplicitSolvation)
1212 serializer->doInt(&idum);
1213 serializer->doInt(&idum);
1214 serializer->doReal(&rdum);
1215 serializer->doReal(&rdum);
1216 serializer->doInt(&idum);
1217 ir->implicit_solvent = (idum > 0);
1221 ir->implicit_solvent = false;
1223 if (file_version < tpxv_RemoveImplicitSolvation)
1225 serializer->doReal(&rdum);
1226 serializer->doReal(&rdum);
1227 serializer->doReal(&rdum);
1228 serializer->doReal(&rdum);
1229 if (file_version >= 60)
1231 serializer->doReal(&rdum);
1232 serializer->doInt(&idum);
1234 serializer->doReal(&rdum);
1238 if (file_version >= 81)
1240 serializer->doReal(&ir->fourier_spacing);
1244 ir->fourier_spacing = 0.0;
1246 serializer->doInt(&ir->nkx);
1247 serializer->doInt(&ir->nky);
1248 serializer->doInt(&ir->nkz);
1249 serializer->doInt(&ir->pme_order);
1250 serializer->doReal(&ir->ewald_rtol);
1252 if (file_version >= 93)
1254 serializer->doReal(&ir->ewald_rtol_lj);
1258 ir->ewald_rtol_lj = ir->ewald_rtol;
1260 serializer->doEnumAsInt(&ir->ewald_geometry);
1261 serializer->doReal(&ir->epsilon_surface);
1263 /* ignore bOptFFT */
1264 if (file_version < tpxv_RemoveObsoleteParameters1)
1266 serializer->doBool(&bdum);
1269 if (file_version >= 93)
1271 serializer->doEnumAsInt(&ir->ljpme_combination_rule);
1273 serializer->doBool(&ir->bContinuation);
1274 serializer->doEnumAsInt(&ir->etc);
1275 /* before version 18, ir->etc was a gmx_bool (ir->btc),
1276 * but the values 0 and 1 still mean no and
1277 * berendsen temperature coupling, respectively.
1279 if (file_version >= 79)
1281 serializer->doBool(&ir->bPrintNHChains);
1283 if (file_version >= 71)
1285 serializer->doInt(&ir->nsttcouple);
1289 ir->nsttcouple = ir->nstcalcenergy;
1291 serializer->doEnumAsInt(&ir->epc);
1292 serializer->doEnumAsInt(&ir->epct);
1293 if (file_version >= 71)
1295 serializer->doInt(&ir->nstpcouple);
1299 ir->nstpcouple = ir->nstcalcenergy;
1301 serializer->doReal(&ir->tau_p);
1302 serializer->doRvec(&ir->ref_p[XX]);
1303 serializer->doRvec(&ir->ref_p[YY]);
1304 serializer->doRvec(&ir->ref_p[ZZ]);
1305 serializer->doRvec(&ir->compress[XX]);
1306 serializer->doRvec(&ir->compress[YY]);
1307 serializer->doRvec(&ir->compress[ZZ]);
1308 serializer->doEnumAsInt(&ir->refcoord_scaling);
1309 serializer->doRvec(&ir->posres_com);
1310 serializer->doRvec(&ir->posres_comB);
1312 if (file_version < 79)
1314 serializer->doInt(&ir->andersen_seed);
1318 ir->andersen_seed = 0;
1321 serializer->doReal(&ir->shake_tol);
1323 serializer->doEnumAsInt(&ir->efep);
1324 if (serializer->reading())
1326 ir->fepvals = std::make_unique<t_lambda>();
1328 do_fepvals(serializer, ir->fepvals.get(), file_version);
1330 if (file_version >= 79)
1332 serializer->doBool(&ir->bSimTemp);
1335 ir->bSimTemp = TRUE;
1340 ir->bSimTemp = FALSE;
1344 if (serializer->reading())
1346 ir->simtempvals = std::make_unique<t_simtemp>();
1348 do_simtempvals(serializer, ir->simtempvals.get(), ir->fepvals->n_lambda, file_version);
1351 if (file_version >= 79)
1353 serializer->doBool(&ir->bExpanded);
1357 if (serializer->reading())
1359 ir->expandedvals = std::make_unique<t_expanded>();
1361 do_expandedvals(serializer, ir->expandedvals.get(), ir->fepvals.get(), file_version);
1364 serializer->doEnumAsInt(&ir->eDisre);
1365 serializer->doEnumAsInt(&ir->eDisreWeighting);
1366 serializer->doBool(&ir->bDisreMixed);
1367 serializer->doReal(&ir->dr_fc);
1368 serializer->doReal(&ir->dr_tau);
1369 serializer->doInt(&ir->nstdisreout);
1370 serializer->doReal(&ir->orires_fc);
1371 serializer->doReal(&ir->orires_tau);
1372 serializer->doInt(&ir->nstorireout);
1374 /* ignore dihre_fc */
1375 if (file_version < 79)
1377 serializer->doReal(&rdum);
1380 serializer->doReal(&ir->em_stepsize);
1381 serializer->doReal(&ir->em_tol);
1382 serializer->doBool(&ir->bShakeSOR);
1383 serializer->doInt(&ir->niter);
1384 serializer->doReal(&ir->fc_stepsize);
1385 serializer->doEnumAsInt(&ir->eConstrAlg);
1386 serializer->doInt(&ir->nProjOrder);
1387 serializer->doReal(&ir->LincsWarnAngle);
1388 serializer->doInt(&ir->nLincsIter);
1389 serializer->doReal(&ir->bd_fric);
1390 if (file_version >= tpxv_Use64BitRandomSeed)
1392 serializer->doInt64(&ir->ld_seed);
1396 serializer->doInt(&idum);
1400 for (i = 0; i < DIM; i++)
1402 serializer->doRvec(&ir->deform[i]);
1404 serializer->doReal(&ir->cos_accel);
1406 serializer->doInt(&ir->userint1);
1407 serializer->doInt(&ir->userint2);
1408 serializer->doInt(&ir->userint3);
1409 serializer->doInt(&ir->userint4);
1410 serializer->doReal(&ir->userreal1);
1411 serializer->doReal(&ir->userreal2);
1412 serializer->doReal(&ir->userreal3);
1413 serializer->doReal(&ir->userreal4);
1415 /* AdResS is removed, but we need to be able to read old files,
1416 and let mdrun refuse to run them */
1417 if (file_version >= 77 && file_version < tpxv_RemoveAdress)
1419 serializer->doBool(&ir->bAdress);
1422 int idum, numThermoForceGroups, numEnergyGroups;
1425 serializer->doInt(&idum);
1426 serializer->doReal(&rdum);
1427 serializer->doReal(&rdum);
1428 serializer->doReal(&rdum);
1429 serializer->doInt(&idum);
1430 serializer->doInt(&idum);
1431 serializer->doRvec(&rvecdum);
1432 serializer->doInt(&numThermoForceGroups);
1433 serializer->doReal(&rdum);
1434 serializer->doInt(&numEnergyGroups);
1435 serializer->doInt(&idum);
1437 if (numThermoForceGroups > 0)
1439 std::vector<int> idumn(numThermoForceGroups);
1440 serializer->doIntArray(idumn.data(), idumn.size());
1442 if (numEnergyGroups > 0)
1444 std::vector<int> idumn(numEnergyGroups);
1445 serializer->doIntArray(idumn.data(), idumn.size());
1451 ir->bAdress = FALSE;
1456 PullingAlgorithm ePullOld = PullingAlgorithm::Umbrella;
1458 if (file_version >= tpxv_PullCoordTypeGeom)
1460 serializer->doBool(&ir->bPull);
1464 serializer->doEnumAsInt(&ePullOld);
1465 ir->bPull = (ePullOld != PullingAlgorithm::Umbrella);
1466 /* We removed the first ePull=ePullNo for the enum */
1469 case (PullingAlgorithm::Umbrella): break; // this is equal to not using pulling
1470 case (PullingAlgorithm::Constraint): ePullOld = PullingAlgorithm::Umbrella; break;
1471 case (PullingAlgorithm::ConstantForce):
1472 ePullOld = PullingAlgorithm::Constraint;
1474 case (PullingAlgorithm::FlatBottom):
1475 ePullOld = PullingAlgorithm::ConstantForce;
1477 case (PullingAlgorithm::FlatBottomHigh):
1478 ePullOld = PullingAlgorithm::FlatBottom;
1480 case (PullingAlgorithm::External):
1481 ePullOld = PullingAlgorithm::FlatBottomHigh;
1483 case (PullingAlgorithm::Count): ePullOld = PullingAlgorithm::External; break;
1484 default: GMX_RELEASE_ASSERT(false, "Unhandled old pull algorithm");
1489 if (serializer->reading())
1491 ir->pull = std::make_unique<pull_params_t>();
1493 do_pull(serializer, ir->pull.get(), file_version, ePullOld);
1497 if (file_version >= tpxv_AcceleratedWeightHistogram)
1499 serializer->doBool(&ir->bDoAwh);
1503 if (serializer->reading())
1505 ir->awhParams = std::make_unique<gmx::AwhParams>(serializer);
1509 ir->awhParams->serialize(serializer);
1518 /* Enforced rotation */
1519 if (file_version >= 74)
1521 serializer->doBool(&ir->bRot);
1524 if (serializer->reading())
1528 do_rot(serializer, ir->rot);
1536 /* Interactive molecular dynamics */
1537 if (file_version >= tpxv_InteractiveMolecularDynamics)
1539 serializer->doBool(&ir->bIMD);
1542 if (serializer->reading())
1546 do_imd(serializer, ir->imd);
1551 /* We don't support IMD sessions for old .tpr files */
1556 serializer->doInt(&ir->opts.ngtc);
1557 if (file_version >= 69)
1559 serializer->doInt(&ir->opts.nhchainlength);
1563 ir->opts.nhchainlength = 1;
1565 int removedOptsNgacc = 0;
1566 if (serializer->reading() && file_version < tpxv_RemovedConstantAcceleration)
1568 serializer->doInt(&removedOptsNgacc);
1570 serializer->doInt(&ir->opts.ngfrz);
1571 serializer->doInt(&ir->opts.ngener);
1573 if (serializer->reading())
1575 snew(ir->opts.nrdf, ir->opts.ngtc);
1576 snew(ir->opts.ref_t, ir->opts.ngtc);
1577 snew(ir->opts.annealing, ir->opts.ngtc);
1578 snew(ir->opts.anneal_npoints, ir->opts.ngtc);
1579 snew(ir->opts.anneal_time, ir->opts.ngtc);
1580 snew(ir->opts.anneal_temp, ir->opts.ngtc);
1581 snew(ir->opts.tau_t, ir->opts.ngtc);
1582 snew(ir->opts.nFreeze, ir->opts.ngfrz);
1583 snew(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
1585 if (ir->opts.ngtc > 0)
1587 serializer->doRealArray(ir->opts.nrdf, ir->opts.ngtc);
1588 serializer->doRealArray(ir->opts.ref_t, ir->opts.ngtc);
1589 serializer->doRealArray(ir->opts.tau_t, ir->opts.ngtc);
1591 if (ir->opts.ngfrz > 0)
1593 serializer->doIvecArray(ir->opts.nFreeze, ir->opts.ngfrz);
1595 if (serializer->reading() && file_version < tpxv_RemovedConstantAcceleration && removedOptsNgacc > 0)
1597 std::vector<gmx::RVec> dummy;
1598 dummy.resize(removedOptsNgacc);
1599 serializer->doRvecArray(reinterpret_cast<rvec*>(dummy.data()), removedOptsNgacc);
1600 ir->useConstantAcceleration = std::any_of(dummy.begin(), dummy.end(), [](const gmx::RVec& vec) {
1601 return vec[XX] != 0.0 || vec[YY] != 0.0 || vec[ZZ] != 0.0;
1606 ir->useConstantAcceleration = false;
1608 serializer->doIntArray(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
1610 /* First read the lists with annealing and npoints for each group */
1611 serializer->doEnumArrayAsInt(ir->opts.annealing, ir->opts.ngtc);
1612 serializer->doIntArray(ir->opts.anneal_npoints, ir->opts.ngtc);
1613 for (j = 0; j < (ir->opts.ngtc); j++)
1615 k = ir->opts.anneal_npoints[j];
1616 if (serializer->reading())
1618 snew(ir->opts.anneal_time[j], k);
1619 snew(ir->opts.anneal_temp[j], k);
1621 serializer->doRealArray(ir->opts.anneal_time[j], k);
1622 serializer->doRealArray(ir->opts.anneal_temp[j], k);
1626 serializer->doInt(&ir->nwall);
1627 serializer->doEnumAsInt(&ir->wall_type);
1628 serializer->doReal(&ir->wall_r_linpot);
1629 serializer->doInt(&ir->wall_atomtype[0]);
1630 serializer->doInt(&ir->wall_atomtype[1]);
1631 serializer->doReal(&ir->wall_density[0]);
1632 serializer->doReal(&ir->wall_density[1]);
1633 serializer->doReal(&ir->wall_ewald_zfac);
1636 /* Cosine stuff for electric fields */
1637 if (file_version < tpxv_GenericParamsForElectricField)
1639 do_legacy_efield(serializer, ¶msObj);
1643 if (file_version >= tpxv_ComputationalElectrophysiology)
1645 serializer->doEnumAsInt(&ir->eSwapCoords);
1646 if (ir->eSwapCoords != SwapType::No)
1648 if (serializer->reading())
1652 do_swapcoords_tpx(serializer, ir->swap, file_version);
1656 /* QMMM reading - despite defunct we require reading for backwards
1657 * compability and correct serialization
1660 serializer->doBool(&ir->bQMMM);
1662 serializer->doInt(&qmmmScheme);
1663 real unusedScalefactor;
1664 serializer->doReal(&unusedScalefactor);
1666 // this is still used in Mimic
1667 serializer->doInt(&ir->opts.ngQM);
1668 if (ir->opts.ngQM > 0 && ir->bQMMM)
1670 /* We leave in dummy i/o for removed parameters to avoid
1671 * changing the tpr format.
1673 std::vector<int> dummyIntVec(4 * ir->opts.ngQM, 0);
1674 serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1675 dummyIntVec.clear();
1677 // std::vector<bool> has no data()
1678 std::vector<char> dummyBoolVec(ir->opts.ngQM * sizeof(bool) / sizeof(char));
1679 serializer->doBoolArray(reinterpret_cast<bool*>(dummyBoolVec.data()), dummyBoolVec.size());
1680 dummyBoolVec.clear();
1682 dummyIntVec.resize(2 * ir->opts.ngQM, 0);
1683 serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1684 dummyIntVec.clear();
1686 std::vector<real> dummyRealVec(2 * ir->opts.ngQM, 0);
1687 serializer->doRealArray(dummyRealVec.data(), dummyRealVec.size());
1688 dummyRealVec.clear();
1690 dummyIntVec.resize(3 * ir->opts.ngQM, 0);
1691 serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1692 dummyIntVec.clear();
1694 /* end of QMMM stuff */
1697 if (file_version >= tpxv_GenericParamsForElectricField)
1699 if (serializer->reading())
1701 paramsObj.mergeObject(gmx::deserializeKeyValueTree(serializer));
1705 GMX_RELEASE_ASSERT(ir->params != nullptr,
1706 "Parameters should be present when writing inputrec");
1707 gmx::serializeKeyValueTree(*ir->params, serializer);
1710 if (serializer->reading())
1712 ir->params = new gmx::KeyValueTreeObject(paramsBuilder.build());
1713 // Initialize internal parameters to an empty kvt for all tpr versions
1714 ir->internalParameters = std::make_unique<gmx::KeyValueTreeObject>();
1717 if (file_version >= tpxv_GenericInternalParameters)
1719 if (serializer->reading())
1721 ir->internalParameters =
1722 std::make_unique<gmx::KeyValueTreeObject>(gmx::deserializeKeyValueTree(serializer));
1726 GMX_RELEASE_ASSERT(ir->internalParameters != nullptr,
1727 "Parameters should be present when writing inputrec");
1728 gmx::serializeKeyValueTree(*ir->internalParameters, serializer);
1734 static void do_harm(gmx::ISerializer* serializer, t_iparams* iparams)
1736 serializer->doReal(&iparams->harmonic.rA);
1737 serializer->doReal(&iparams->harmonic.krA);
1738 serializer->doReal(&iparams->harmonic.rB);
1739 serializer->doReal(&iparams->harmonic.krB);
1742 static void do_iparams(gmx::ISerializer* serializer, t_functype ftype, t_iparams* iparams, int file_version)
1755 do_harm(serializer, iparams);
1756 if ((ftype == F_ANGRES || ftype == F_ANGRESZ) && serializer->reading())
1758 /* Correct incorrect storage of parameters */
1759 iparams->pdihs.phiB = iparams->pdihs.phiA;
1760 iparams->pdihs.cpB = iparams->pdihs.cpA;
1764 serializer->doReal(&iparams->harmonic.rA);
1765 serializer->doReal(&iparams->harmonic.krA);
1767 case F_LINEAR_ANGLES:
1768 serializer->doReal(&iparams->linangle.klinA);
1769 serializer->doReal(&iparams->linangle.aA);
1770 serializer->doReal(&iparams->linangle.klinB);
1771 serializer->doReal(&iparams->linangle.aB);
1774 serializer->doReal(&iparams->fene.bm);
1775 serializer->doReal(&iparams->fene.kb);
1779 serializer->doReal(&iparams->restraint.lowA);
1780 serializer->doReal(&iparams->restraint.up1A);
1781 serializer->doReal(&iparams->restraint.up2A);
1782 serializer->doReal(&iparams->restraint.kA);
1783 serializer->doReal(&iparams->restraint.lowB);
1784 serializer->doReal(&iparams->restraint.up1B);
1785 serializer->doReal(&iparams->restraint.up2B);
1786 serializer->doReal(&iparams->restraint.kB);
1792 serializer->doReal(&iparams->tab.kA);
1793 serializer->doInt(&iparams->tab.table);
1794 serializer->doReal(&iparams->tab.kB);
1796 case F_CROSS_BOND_BONDS:
1797 serializer->doReal(&iparams->cross_bb.r1e);
1798 serializer->doReal(&iparams->cross_bb.r2e);
1799 serializer->doReal(&iparams->cross_bb.krr);
1801 case F_CROSS_BOND_ANGLES:
1802 serializer->doReal(&iparams->cross_ba.r1e);
1803 serializer->doReal(&iparams->cross_ba.r2e);
1804 serializer->doReal(&iparams->cross_ba.r3e);
1805 serializer->doReal(&iparams->cross_ba.krt);
1807 case F_UREY_BRADLEY:
1808 serializer->doReal(&iparams->u_b.thetaA);
1809 serializer->doReal(&iparams->u_b.kthetaA);
1810 serializer->doReal(&iparams->u_b.r13A);
1811 serializer->doReal(&iparams->u_b.kUBA);
1812 if (file_version >= 79)
1814 serializer->doReal(&iparams->u_b.thetaB);
1815 serializer->doReal(&iparams->u_b.kthetaB);
1816 serializer->doReal(&iparams->u_b.r13B);
1817 serializer->doReal(&iparams->u_b.kUBB);
1821 iparams->u_b.thetaB = iparams->u_b.thetaA;
1822 iparams->u_b.kthetaB = iparams->u_b.kthetaA;
1823 iparams->u_b.r13B = iparams->u_b.r13A;
1824 iparams->u_b.kUBB = iparams->u_b.kUBA;
1827 case F_QUARTIC_ANGLES:
1828 serializer->doReal(&iparams->qangle.theta);
1829 serializer->doRealArray(iparams->qangle.c, 5);
1832 serializer->doReal(&iparams->bham.a);
1833 serializer->doReal(&iparams->bham.b);
1834 serializer->doReal(&iparams->bham.c);
1837 serializer->doReal(&iparams->morse.b0A);
1838 serializer->doReal(&iparams->morse.cbA);
1839 serializer->doReal(&iparams->morse.betaA);
1840 if (file_version >= 79)
1842 serializer->doReal(&iparams->morse.b0B);
1843 serializer->doReal(&iparams->morse.cbB);
1844 serializer->doReal(&iparams->morse.betaB);
1848 iparams->morse.b0B = iparams->morse.b0A;
1849 iparams->morse.cbB = iparams->morse.cbA;
1850 iparams->morse.betaB = iparams->morse.betaA;
1854 serializer->doReal(&iparams->cubic.b0);
1855 serializer->doReal(&iparams->cubic.kb);
1856 serializer->doReal(&iparams->cubic.kcub);
1858 case F_CONNBONDS: break;
1859 case F_POLARIZATION: serializer->doReal(&iparams->polarize.alpha); break;
1861 serializer->doReal(&iparams->anharm_polarize.alpha);
1862 serializer->doReal(&iparams->anharm_polarize.drcut);
1863 serializer->doReal(&iparams->anharm_polarize.khyp);
1866 serializer->doReal(&iparams->wpol.al_x);
1867 serializer->doReal(&iparams->wpol.al_y);
1868 serializer->doReal(&iparams->wpol.al_z);
1869 serializer->doReal(&iparams->wpol.rOH);
1870 serializer->doReal(&iparams->wpol.rHH);
1871 serializer->doReal(&iparams->wpol.rOD);
1874 serializer->doReal(&iparams->thole.a);
1875 serializer->doReal(&iparams->thole.alpha1);
1876 serializer->doReal(&iparams->thole.alpha2);
1877 serializer->doReal(&iparams->thole.rfac);
1880 serializer->doReal(&iparams->lj.c6);
1881 serializer->doReal(&iparams->lj.c12);
1884 serializer->doReal(&iparams->lj14.c6A);
1885 serializer->doReal(&iparams->lj14.c12A);
1886 serializer->doReal(&iparams->lj14.c6B);
1887 serializer->doReal(&iparams->lj14.c12B);
1890 serializer->doReal(&iparams->ljc14.fqq);
1891 serializer->doReal(&iparams->ljc14.qi);
1892 serializer->doReal(&iparams->ljc14.qj);
1893 serializer->doReal(&iparams->ljc14.c6);
1894 serializer->doReal(&iparams->ljc14.c12);
1896 case F_LJC_PAIRS_NB:
1897 serializer->doReal(&iparams->ljcnb.qi);
1898 serializer->doReal(&iparams->ljcnb.qj);
1899 serializer->doReal(&iparams->ljcnb.c6);
1900 serializer->doReal(&iparams->ljcnb.c12);
1906 serializer->doReal(&iparams->pdihs.phiA);
1907 serializer->doReal(&iparams->pdihs.cpA);
1908 serializer->doReal(&iparams->pdihs.phiB);
1909 serializer->doReal(&iparams->pdihs.cpB);
1910 serializer->doInt(&iparams->pdihs.mult);
1913 serializer->doReal(&iparams->pdihs.phiA);
1914 serializer->doReal(&iparams->pdihs.cpA);
1917 serializer->doInt(&iparams->disres.label);
1918 serializer->doInt(&iparams->disres.type);
1919 serializer->doReal(&iparams->disres.low);
1920 serializer->doReal(&iparams->disres.up1);
1921 serializer->doReal(&iparams->disres.up2);
1922 serializer->doReal(&iparams->disres.kfac);
1925 serializer->doInt(&iparams->orires.ex);
1926 serializer->doInt(&iparams->orires.label);
1927 serializer->doInt(&iparams->orires.power);
1928 serializer->doReal(&iparams->orires.c);
1929 serializer->doReal(&iparams->orires.obs);
1930 serializer->doReal(&iparams->orires.kfac);
1933 if (file_version < 82)
1935 serializer->doInt(&idum);
1936 serializer->doInt(&idum);
1938 serializer->doReal(&iparams->dihres.phiA);
1939 serializer->doReal(&iparams->dihres.dphiA);
1940 serializer->doReal(&iparams->dihres.kfacA);
1941 if (file_version >= 82)
1943 serializer->doReal(&iparams->dihres.phiB);
1944 serializer->doReal(&iparams->dihres.dphiB);
1945 serializer->doReal(&iparams->dihres.kfacB);
1949 iparams->dihres.phiB = iparams->dihres.phiA;
1950 iparams->dihres.dphiB = iparams->dihres.dphiA;
1951 iparams->dihres.kfacB = iparams->dihres.kfacA;
1955 serializer->doRvec(&iparams->posres.pos0A);
1956 serializer->doRvec(&iparams->posres.fcA);
1957 serializer->doRvec(&iparams->posres.pos0B);
1958 serializer->doRvec(&iparams->posres.fcB);
1961 serializer->doInt(&iparams->fbposres.geom);
1962 serializer->doRvec(&iparams->fbposres.pos0);
1963 serializer->doReal(&iparams->fbposres.r);
1964 serializer->doReal(&iparams->fbposres.k);
1966 case F_CBTDIHS: serializer->doRealArray(iparams->cbtdihs.cbtcA, NR_CBTDIHS); break;
1968 // Fall-through intended
1970 /* Fourier dihedrals are internally represented
1971 * as Ryckaert-Bellemans since those are faster to compute.
1973 serializer->doRealArray(iparams->rbdihs.rbcA, NR_RBDIHS);
1974 serializer->doRealArray(iparams->rbdihs.rbcB, NR_RBDIHS);
1978 serializer->doReal(&iparams->constr.dA);
1979 serializer->doReal(&iparams->constr.dB);
1982 serializer->doReal(&iparams->settle.doh);
1983 serializer->doReal(&iparams->settle.dhh);
1985 case F_VSITE1: break; // VSite1 has 0 parameters
1987 case F_VSITE2FD: serializer->doReal(&iparams->vsite.a); break;
1991 serializer->doReal(&iparams->vsite.a);
1992 serializer->doReal(&iparams->vsite.b);
1997 serializer->doReal(&iparams->vsite.a);
1998 serializer->doReal(&iparams->vsite.b);
1999 serializer->doReal(&iparams->vsite.c);
2002 serializer->doInt(&iparams->vsiten.n);
2003 serializer->doReal(&iparams->vsiten.a);
2005 case F_GB12_NOLONGERUSED:
2006 case F_GB13_NOLONGERUSED:
2007 case F_GB14_NOLONGERUSED:
2008 // Implicit solvent parameters can still be read, but never used
2009 if (serializer->reading())
2011 if (file_version < 68)
2013 serializer->doReal(&rdum);
2014 serializer->doReal(&rdum);
2015 serializer->doReal(&rdum);
2016 serializer->doReal(&rdum);
2018 if (file_version < tpxv_RemoveImplicitSolvation)
2020 serializer->doReal(&rdum);
2021 serializer->doReal(&rdum);
2022 serializer->doReal(&rdum);
2023 serializer->doReal(&rdum);
2024 serializer->doReal(&rdum);
2029 serializer->doInt(&iparams->cmap.cmapA);
2030 serializer->doInt(&iparams->cmap.cmapB);
2034 "unknown function type %d (%s) in %s line %d",
2036 interaction_function[ftype].name,
2042 static void do_ilist(gmx::ISerializer* serializer, InteractionList* ilist)
2044 int nr = ilist->size();
2045 serializer->doInt(&nr);
2046 if (serializer->reading())
2048 ilist->iatoms.resize(nr);
2050 serializer->doIntArray(ilist->iatoms.data(), ilist->size());
2053 static void do_ffparams(gmx::ISerializer* serializer, gmx_ffparams_t* ffparams, int file_version)
2055 serializer->doInt(&ffparams->atnr);
2056 int numTypes = ffparams->numTypes();
2057 serializer->doInt(&numTypes);
2058 if (serializer->reading())
2060 ffparams->functype.resize(numTypes);
2061 ffparams->iparams.resize(numTypes);
2063 /* Read/write all the function types */
2064 serializer->doIntArray(ffparams->functype.data(), ffparams->functype.size());
2066 if (file_version >= 66)
2068 serializer->doDouble(&ffparams->reppow);
2072 ffparams->reppow = 12.0;
2075 serializer->doReal(&ffparams->fudgeQQ);
2077 /* Check whether all these function types are supported by the code.
2078 * In practice the code is backwards compatible, which means that the
2079 * numbering may have to be altered from old numbering to new numbering
2081 for (int i = 0; i < ffparams->numTypes(); i++)
2083 if (serializer->reading())
2085 /* Loop over file versions */
2086 for (int k = 0; k < NFTUPD; k++)
2088 /* Compare the read file_version to the update table */
2089 if ((file_version < ftupd[k].fvnr) && (ffparams->functype[i] >= ftupd[k].ftype))
2091 ffparams->functype[i] += 1;
2096 do_iparams(serializer, ffparams->functype[i], &ffparams->iparams[i], file_version);
2100 static void add_settle_atoms(InteractionList* ilist)
2104 /* Settle used to only store the first atom: add the other two */
2105 ilist->iatoms.resize(2 * ilist->size());
2106 for (i = ilist->size() / 4 - 1; i >= 0; i--)
2108 ilist->iatoms[4 * i + 0] = ilist->iatoms[2 * i + 0];
2109 ilist->iatoms[4 * i + 1] = ilist->iatoms[2 * i + 1];
2110 ilist->iatoms[4 * i + 2] = ilist->iatoms[2 * i + 1] + 1;
2111 ilist->iatoms[4 * i + 3] = ilist->iatoms[2 * i + 1] + 2;
2115 static void do_ilists(gmx::ISerializer* serializer, InteractionLists* ilists, int file_version)
2117 GMX_RELEASE_ASSERT(ilists, "Need a valid ilists object");
2118 GMX_RELEASE_ASSERT(ilists->size() == F_NRE,
2119 "The code needs to be in sync with InteractionLists");
2121 for (int j = 0; j < F_NRE; j++)
2123 InteractionList& ilist = (*ilists)[j];
2124 gmx_bool bClear = FALSE;
2125 if (serializer->reading())
2127 for (int k = 0; k < NFTUPD; k++)
2129 if ((file_version < ftupd[k].fvnr) && (j == ftupd[k].ftype))
2137 ilist.iatoms.clear();
2141 do_ilist(serializer, &ilist);
2142 if (file_version < 78 && j == F_SETTLE && !ilist.empty())
2144 add_settle_atoms(&ilist);
2150 static void do_block(gmx::ISerializer* serializer, t_block* block)
2152 serializer->doInt(&block->nr);
2153 if (serializer->reading())
2155 if ((block->nalloc_index > 0) && (nullptr != block->index))
2157 sfree(block->index);
2159 block->nalloc_index = block->nr + 1;
2160 snew(block->index, block->nalloc_index);
2162 serializer->doIntArray(block->index, block->nr + 1);
2165 static void doListOfLists(gmx::ISerializer* serializer, gmx::ListOfLists<int>* listOfLists)
2167 int numLists = listOfLists->ssize();
2168 serializer->doInt(&numLists);
2169 int numElements = listOfLists->elementsView().ssize();
2170 serializer->doInt(&numElements);
2171 if (serializer->reading())
2173 std::vector<int> listRanges(numLists + 1);
2174 serializer->doIntArray(listRanges.data(), numLists + 1);
2175 std::vector<int> elements(numElements);
2176 serializer->doIntArray(elements.data(), numElements);
2177 *listOfLists = gmx::ListOfLists<int>(std::move(listRanges), std::move(elements));
2181 serializer->doIntArray(const_cast<int*>(listOfLists->listRangesView().data()), numLists + 1);
2182 serializer->doIntArray(const_cast<int*>(listOfLists->elementsView().data()), numElements);
2186 /* This is a primitive routine to make it possible to translate atomic numbers
2187 * to element names when reading TPR files, without making the Gromacs library
2188 * directory a dependency on mdrun (which is the case if we need elements.dat).
2190 static const char* atomicnumber_to_element(int atomicnumber)
2194 /* This does not have to be complete, so we only include elements likely
2195 * to occur in PDB files.
2197 switch (atomicnumber)
2199 case 1: p = "H"; break;
2200 case 5: p = "B"; break;
2201 case 6: p = "C"; break;
2202 case 7: p = "N"; break;
2203 case 8: p = "O"; break;
2204 case 9: p = "F"; break;
2205 case 11: p = "Na"; break;
2206 case 12: p = "Mg"; break;
2207 case 15: p = "P"; break;
2208 case 16: p = "S"; break;
2209 case 17: p = "Cl"; break;
2210 case 18: p = "Ar"; break;
2211 case 19: p = "K"; break;
2212 case 20: p = "Ca"; break;
2213 case 25: p = "Mn"; break;
2214 case 26: p = "Fe"; break;
2215 case 28: p = "Ni"; break;
2216 case 29: p = "Cu"; break;
2217 case 30: p = "Zn"; break;
2218 case 35: p = "Br"; break;
2219 case 47: p = "Ag"; break;
2220 default: p = ""; break;
2226 static void do_atom(gmx::ISerializer* serializer, t_atom* atom)
2228 serializer->doReal(&atom->m);
2229 serializer->doReal(&atom->q);
2230 serializer->doReal(&atom->mB);
2231 serializer->doReal(&atom->qB);
2232 serializer->doUShort(&atom->type);
2233 serializer->doUShort(&atom->typeB);
2234 serializer->doEnumAsInt(&atom->ptype);
2235 serializer->doInt(&atom->resind);
2236 serializer->doInt(&atom->atomnumber);
2237 if (serializer->reading())
2239 /* Set element string from atomic number if present.
2240 * This routine returns an empty string if the name is not found.
2242 std::strncpy(atom->elem, atomicnumber_to_element(atom->atomnumber), 4);
2243 /* avoid warnings about potentially unterminated string */
2244 atom->elem[3] = '\0';
2248 static void do_grps(gmx::ISerializer* serializer, gmx::ArrayRef<AtomGroupIndices> grps)
2250 for (auto& group : grps)
2252 int size = group.size();
2253 serializer->doInt(&size);
2254 if (serializer->reading())
2258 serializer->doIntArray(group.data(), size);
2262 static void do_symstr(gmx::ISerializer* serializer, char*** nm, t_symtab* symtab)
2266 if (serializer->reading())
2268 serializer->doInt(&ls);
2269 *nm = get_symtab_handle(symtab, ls);
2273 ls = lookup_symtab(symtab, *nm);
2274 serializer->doInt(&ls);
2278 static void do_strstr(gmx::ISerializer* serializer, int nstr, char*** nm, t_symtab* symtab)
2282 for (j = 0; (j < nstr); j++)
2284 do_symstr(serializer, &(nm[j]), symtab);
2288 static void do_resinfo(gmx::ISerializer* serializer, int n, t_resinfo* ri, t_symtab* symtab, int file_version)
2292 for (j = 0; (j < n); j++)
2294 do_symstr(serializer, &(ri[j].name), symtab);
2295 if (file_version >= 63)
2297 serializer->doInt(&ri[j].nr);
2298 serializer->doUChar(&ri[j].ic);
2308 static void do_atoms(gmx::ISerializer* serializer, t_atoms* atoms, t_symtab* symtab, int file_version)
2312 serializer->doInt(&atoms->nr);
2313 serializer->doInt(&atoms->nres);
2314 if (serializer->reading())
2316 /* Since we have always written all t_atom properties in the tpr file
2317 * (at least for all backward compatible versions), we don't store
2318 * but simple set the booleans here.
2320 atoms->haveMass = TRUE;
2321 atoms->haveCharge = TRUE;
2322 atoms->haveType = TRUE;
2323 atoms->haveBState = TRUE;
2324 atoms->havePdbInfo = FALSE;
2326 snew(atoms->atom, atoms->nr);
2327 snew(atoms->atomname, atoms->nr);
2328 snew(atoms->atomtype, atoms->nr);
2329 snew(atoms->atomtypeB, atoms->nr);
2330 snew(atoms->resinfo, atoms->nres);
2331 atoms->pdbinfo = nullptr;
2335 GMX_RELEASE_ASSERT(atoms->haveMass && atoms->haveCharge && atoms->haveType && atoms->haveBState,
2336 "Mass, charge, atomtype and B-state parameters should be present in "
2337 "t_atoms when writing a tpr file");
2339 for (i = 0; (i < atoms->nr); i++)
2341 do_atom(serializer, &atoms->atom[i]);
2343 do_strstr(serializer, atoms->nr, atoms->atomname, symtab);
2344 do_strstr(serializer, atoms->nr, atoms->atomtype, symtab);
2345 do_strstr(serializer, atoms->nr, atoms->atomtypeB, symtab);
2347 do_resinfo(serializer, atoms->nres, atoms->resinfo, symtab, file_version);
2350 static void do_groups(gmx::ISerializer* serializer, SimulationGroups* groups, t_symtab* symtab)
2352 do_grps(serializer, groups->groups);
2353 int numberOfGroupNames = groups->groupNames.size();
2354 serializer->doInt(&numberOfGroupNames);
2355 if (serializer->reading())
2357 groups->groupNames.resize(numberOfGroupNames);
2359 do_strstr(serializer, numberOfGroupNames, groups->groupNames.data(), symtab);
2360 for (auto group : gmx::keysOf(groups->groupNumbers))
2362 int numberOfGroupNumbers = groups->numberOfGroupNumbers(group);
2363 serializer->doInt(&numberOfGroupNumbers);
2364 if (numberOfGroupNumbers != 0)
2366 if (serializer->reading())
2368 groups->groupNumbers[group].resize(numberOfGroupNumbers);
2370 serializer->doUCharArray(groups->groupNumbers[group].data(), numberOfGroupNumbers);
2375 static void do_atomtypes(gmx::ISerializer* serializer, t_atomtypes* atomtypes, int file_version)
2379 serializer->doInt(&atomtypes->nr);
2381 if (serializer->reading())
2383 snew(atomtypes->atomnumber, j);
2385 if (serializer->reading() && file_version < tpxv_RemoveImplicitSolvation)
2387 std::vector<real> dummy(atomtypes->nr, 0);
2388 serializer->doRealArray(dummy.data(), dummy.size());
2389 serializer->doRealArray(dummy.data(), dummy.size());
2390 serializer->doRealArray(dummy.data(), dummy.size());
2392 serializer->doIntArray(atomtypes->atomnumber, j);
2394 if (serializer->reading() && file_version >= 60 && file_version < tpxv_RemoveImplicitSolvation)
2396 std::vector<real> dummy(atomtypes->nr, 0);
2397 serializer->doRealArray(dummy.data(), dummy.size());
2398 serializer->doRealArray(dummy.data(), dummy.size());
2402 static void do_symtab(gmx::ISerializer* serializer, t_symtab* symtab)
2407 serializer->doInt(&symtab->nr);
2409 if (serializer->reading())
2411 snew(symtab->symbuf, 1);
2412 symbuf = symtab->symbuf;
2413 symbuf->bufsize = nr;
2414 snew(symbuf->buf, nr);
2415 for (i = 0; (i < nr); i++)
2418 serializer->doString(&buf);
2419 symbuf->buf[i] = gmx_strdup(buf.c_str());
2424 symbuf = symtab->symbuf;
2425 while (symbuf != nullptr)
2427 for (i = 0; (i < symbuf->bufsize) && (i < nr); i++)
2429 std::string buf = symbuf->buf[i];
2430 serializer->doString(&buf);
2433 symbuf = symbuf->next;
2437 gmx_fatal(FARGS, "nr of symtab strings left: %d", nr);
2442 static void do_cmap(gmx::ISerializer* serializer, gmx_cmap_t* cmap_grid)
2445 int ngrid = cmap_grid->cmapdata.size();
2446 serializer->doInt(&ngrid);
2447 serializer->doInt(&cmap_grid->grid_spacing);
2449 int gs = cmap_grid->grid_spacing;
2450 int nelem = gs * gs;
2452 if (serializer->reading())
2454 cmap_grid->cmapdata.resize(ngrid);
2456 for (int i = 0; i < ngrid; i++)
2458 cmap_grid->cmapdata[i].cmap.resize(4 * nelem);
2462 for (int i = 0; i < ngrid; i++)
2464 for (int j = 0; j < nelem; j++)
2466 serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4]);
2467 serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 1]);
2468 serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 2]);
2469 serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 3]);
2475 static void do_moltype(gmx::ISerializer* serializer, gmx_moltype_t* molt, t_symtab* symtab, int file_version)
2477 do_symstr(serializer, &(molt->name), symtab);
2479 do_atoms(serializer, &molt->atoms, symtab, file_version);
2481 do_ilists(serializer, &molt->ilist, file_version);
2483 /* TODO: Remove the obsolete charge group index from the file */
2485 cgs.nr = molt->atoms.nr;
2486 cgs.nalloc_index = cgs.nr + 1;
2487 snew(cgs.index, cgs.nalloc_index);
2488 for (int i = 0; i < cgs.nr + 1; i++)
2492 do_block(serializer, &cgs);
2495 /* This used to be in the atoms struct */
2496 doListOfLists(serializer, &molt->excls);
2499 static void do_molblock(gmx::ISerializer* serializer, gmx_molblock_t* molb, int numAtomsPerMolecule)
2501 serializer->doInt(&molb->type);
2502 serializer->doInt(&molb->nmol);
2503 /* To maintain forward topology reading compatibility, we store #atoms.
2504 * TODO: Change this to conditional reading of a dummy int when we
2505 * increase tpx_generation.
2507 serializer->doInt(&numAtomsPerMolecule);
2508 /* Position restraint coordinates */
2509 int numPosres_xA = molb->posres_xA.size();
2510 serializer->doInt(&numPosres_xA);
2511 if (numPosres_xA > 0)
2513 if (serializer->reading())
2515 molb->posres_xA.resize(numPosres_xA);
2517 serializer->doRvecArray(as_rvec_array(molb->posres_xA.data()), numPosres_xA);
2519 int numPosres_xB = molb->posres_xB.size();
2520 serializer->doInt(&numPosres_xB);
2521 if (numPosres_xB > 0)
2523 if (serializer->reading())
2525 molb->posres_xB.resize(numPosres_xB);
2527 serializer->doRvecArray(as_rvec_array(molb->posres_xB.data()), numPosres_xB);
2531 static void set_disres_npair(gmx_mtop_t* mtop)
2533 gmx::ArrayRef<t_iparams> ip = mtop->ffparams.iparams;
2535 for (const auto ilist : IListRange(*mtop))
2537 const InteractionList& il = ilist.list()[F_DISRES];
2541 gmx::ArrayRef<const int> a = il.iatoms;
2543 for (int i = 0; i < il.size(); i += 3)
2546 if (i + 3 == il.size() || ip[a[i]].disres.label != ip[a[i + 3]].disres.label)
2548 ip[a[i]].disres.npair = npair;
2556 static void do_mtop(gmx::ISerializer* serializer, gmx_mtop_t* mtop, int file_version)
2558 do_symtab(serializer, &(mtop->symtab));
2560 do_symstr(serializer, &(mtop->name), &(mtop->symtab));
2562 do_ffparams(serializer, &mtop->ffparams, file_version);
2564 int nmoltype = mtop->moltype.size();
2565 serializer->doInt(&nmoltype);
2566 if (serializer->reading())
2568 mtop->moltype.resize(nmoltype);
2570 for (gmx_moltype_t& moltype : mtop->moltype)
2572 do_moltype(serializer, &moltype, &mtop->symtab, file_version);
2575 int nmolblock = mtop->molblock.size();
2576 serializer->doInt(&nmolblock);
2577 if (serializer->reading())
2579 mtop->molblock.resize(nmolblock);
2581 for (gmx_molblock_t& molblock : mtop->molblock)
2583 int numAtomsPerMolecule = (serializer->reading() ? 0 : mtop->moltype[molblock.type].atoms.nr);
2584 do_molblock(serializer, &molblock, numAtomsPerMolecule);
2586 serializer->doInt(&mtop->natoms);
2588 if (file_version >= tpxv_IntermolecularBondeds)
2590 serializer->doBool(&mtop->bIntermolecularInteractions);
2591 if (mtop->bIntermolecularInteractions)
2593 if (serializer->reading())
2595 mtop->intermolecular_ilist = std::make_unique<InteractionLists>();
2597 do_ilists(serializer, mtop->intermolecular_ilist.get(), file_version);
2602 mtop->bIntermolecularInteractions = FALSE;
2605 do_atomtypes(serializer, &(mtop->atomtypes), file_version);
2607 if (file_version >= 65)
2609 do_cmap(serializer, &mtop->ffparams.cmap_grid);
2613 mtop->ffparams.cmap_grid.grid_spacing = 0;
2614 mtop->ffparams.cmap_grid.cmapdata.clear();
2617 do_groups(serializer, &mtop->groups, &(mtop->symtab));
2618 if (file_version < tpxv_RemovedConstantAcceleration)
2620 mtop->groups.groups[SimulationAtomGroupType::AccelerationUnused].clear();
2621 mtop->groups.groupNumbers[SimulationAtomGroupType::AccelerationUnused].clear();
2624 mtop->haveMoleculeIndices = true;
2626 if (file_version >= tpxv_StoreNonBondedInteractionExclusionGroup)
2628 std::int64_t intermolecularExclusionGroupSize = gmx::ssize(mtop->intermolecularExclusionGroup);
2629 serializer->doInt64(&intermolecularExclusionGroupSize);
2630 GMX_RELEASE_ASSERT(intermolecularExclusionGroupSize >= 0,
2631 "Number of atoms with excluded intermolecular non-bonded interactions "
2633 mtop->intermolecularExclusionGroup.resize(intermolecularExclusionGroupSize); // no effect when writing
2634 serializer->doIntArray(mtop->intermolecularExclusionGroup.data(),
2635 mtop->intermolecularExclusionGroup.size());
2638 if (serializer->reading())
2640 close_symtab(&(mtop->symtab));
2645 * Read the first part of the TPR file to find general system information.
2647 * If \p TopOnlyOK is true then we can read even future versions
2648 * of tpx files, provided the \p fileGeneration hasn't changed.
2649 * If it is false, we need the \p ir too, and bail out
2650 * if the file is newer than the program.
2652 * The version and generation of the topology (see top of this file)
2653 * are returned in the two last arguments, if those arguments are non-nullptr.
2655 * If possible, we will read the \p ir even when \p TopOnlyOK is true.
2657 * \param[in,out] serializer The serializer used to handle header processing.
2658 * \param[in,out] tpx File header datastructure.
2659 * \param[in] filename The name of the file being read/written
2660 * \param[in,out] fio File handle.
2661 * \param[in] TopOnlyOK If not reading \p ir is fine or not.
2663 static void do_tpxheader(gmx::FileIOXdrSerializer* serializer,
2665 const char* filename,
2673 /* XDR binary topology file */
2674 precision = sizeof(real);
2676 std::string fileTag;
2677 if (serializer->reading())
2679 serializer->doString(&buf);
2680 if (std::strncmp(buf.c_str(), "VERSION", 7) != 0)
2684 "Can not read file %s,\n"
2685 " this file is from a GROMACS version which is older than 2.0\n"
2686 " Make a new one with grompp or use a gro or pdb file, if possible",
2689 // We need to know the precision used to write the TPR file, to match it
2690 // to the precision of the currently running binary. If the precisions match
2691 // there is no problem, but mismatching precision needs to be accounted for
2692 // by reading into temporary variables of the correct precision instead
2693 // of the desired target datastructures.
2694 serializer->doInt(&precision);
2695 tpx->isDouble = (precision == sizeof(double));
2696 if ((precision != sizeof(float)) && !tpx->isDouble)
2699 "Unknown precision in file %s: real is %d bytes "
2700 "instead of %zu or %zu",
2706 gmx_fio_setprecision(fio, tpx->isDouble);
2708 "Reading file %s, %s (%s precision)\n",
2711 tpx->isDouble ? "double" : "single");
2715 buf = gmx::formatString("VERSION %s", gmx_version());
2716 serializer->doString(&buf);
2717 gmx_fio_setprecision(fio, tpx->isDouble);
2718 serializer->doInt(&precision);
2722 /* Check versions! */
2723 serializer->doInt(&tpx->fileVersion);
2725 /* This is for backward compatibility with development versions 77-79
2726 * where the tag was, mistakenly, placed before the generation,
2727 * which would cause a segv instead of a proper error message
2728 * when reading the topology only from tpx with <77 code.
2730 if (tpx->fileVersion >= 77 && tpx->fileVersion <= 79)
2732 serializer->doString(&fileTag);
2735 serializer->doInt(&tpx->fileGeneration);
2737 if (tpx->fileVersion >= 81)
2739 serializer->doString(&fileTag);
2741 if (serializer->reading())
2743 if (tpx->fileVersion < 77)
2745 /* Versions before 77 don't have the tag, set it to release */
2746 fileTag = gmx::formatString("%s", TPX_TAG_RELEASE);
2749 if (fileTag != tpx_tag)
2751 fprintf(stderr, "Note: file tpx tag '%s', software tpx tag '%s'\n", fileTag.c_str(), tpx_tag.c_str());
2753 /* We only support reading tpx files with the same tag as the code
2754 * or tpx files with the release tag and with lower version number.
2756 if (fileTag != TPX_TAG_RELEASE && tpx->fileVersion < tpx_version)
2759 "tpx tag/version mismatch: reading tpx file (%s) version %d, tag '%s' "
2760 "with program for tpx version %d, tag '%s'",
2770 if ((tpx->fileVersion <= tpx_incompatible_version)
2771 || ((tpx->fileVersion > tpx_version) && !TopOnlyOK) || (tpx->fileGeneration > tpx_generation)
2772 || tpx_version == 80) /*80 was used by both 5.0-dev and 4.6-dev*/
2775 "reading tpx file (%s) version %d with version %d program",
2781 serializer->doInt(&tpx->natoms);
2782 serializer->doInt(&tpx->ngtc);
2784 if (tpx->fileVersion < 62)
2786 serializer->doInt(&idum);
2787 serializer->doReal(&rdum);
2789 if (tpx->fileVersion >= 79)
2791 serializer->doInt(&tpx->fep_state);
2793 serializer->doReal(&tpx->lambda);
2794 serializer->doBool(&tpx->bIr);
2795 serializer->doBool(&tpx->bTop);
2796 serializer->doBool(&tpx->bX);
2797 serializer->doBool(&tpx->bV);
2798 serializer->doBool(&tpx->bF);
2799 serializer->doBool(&tpx->bBox);
2801 if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
2803 if (!serializer->reading())
2805 GMX_RELEASE_ASSERT(tpx->sizeOfTprBody != 0,
2806 "Not possible to write new file with zero TPR body size");
2808 serializer->doInt64(&tpx->sizeOfTprBody);
2811 if ((tpx->fileGeneration > tpx_generation))
2813 /* This can only happen if TopOnlyOK=TRUE */
2818 #define do_test(serializer, b, p) \
2819 if ((serializer)->reading() && ((p) != nullptr) && !(b)) \
2820 gmx_fatal(FARGS, "No %s in input file", #p)
2823 * Process the first part of the TPR into the state datastructure.
2825 * Due to the structure of the legacy code, it is necessary
2826 * to split up the state reading into two parts, with the
2827 * box and legacy temperature coupling processed before the
2828 * topology datastructures.
2830 * See the documentation for do_tpx_body for the correct order of
2831 * the operations for reading a tpr file.
2833 * \param[in] serializer Abstract serializer used to read/write data.
2834 * \param[in] tpx The file header data.
2835 * \param[in, out] state Global state data.
2837 static void do_tpx_state_first(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state)
2839 if (serializer->reading())
2842 init_gtc_state(state, tpx->ngtc, 0, 0);
2844 do_test(serializer, tpx->bBox, state->box);
2847 serializer->doRvecArray(state->box, DIM);
2848 if (tpx->fileVersion >= 51)
2850 serializer->doRvecArray(state->box_rel, DIM);
2854 /* We initialize box_rel after reading the inputrec */
2855 clear_mat(state->box_rel);
2857 serializer->doRvecArray(state->boxv, DIM);
2858 if (tpx->fileVersion < 56)
2861 serializer->doRvecArray(mdum, DIM);
2865 if (state->ngtc > 0)
2868 snew(dumv, state->ngtc);
2869 if (tpx->fileVersion < 69)
2871 serializer->doRealArray(dumv, state->ngtc);
2873 /* These used to be the Berendsen tcoupl_lambda's */
2874 serializer->doRealArray(dumv, state->ngtc);
2880 * Process global topology data.
2882 * See the documentation for do_tpx_body for the correct order of
2883 * the operations for reading a tpr file.
2885 * \param[in] serializer Abstract serializer used to read/write data.
2886 * \param[in] tpx The file header data.
2887 * \param[in,out] mtop Global topology.
2889 static void do_tpx_mtop(gmx::ISerializer* serializer, TpxFileHeader* tpx, gmx_mtop_t* mtop)
2891 do_test(serializer, tpx->bTop, mtop);
2896 do_mtop(serializer, mtop, tpx->fileVersion);
2897 set_disres_npair(mtop);
2903 do_mtop(serializer, &dum_top, tpx->fileVersion);
2908 * Process coordinate vectors for state data.
2910 * Main part of state gets processed here.
2912 * See the documentation for do_tpx_body for the correct order of
2913 * the operations for reading a tpr file.
2915 * \param[in] serializer Abstract serializer used to read/write data.
2916 * \param[in] tpx The file header data.
2917 * \param[in,out] state Global state data.
2918 * \param[in,out] x Individual coordinates for processing, deprecated.
2919 * \param[in,out] v Individual velocities for processing, deprecated.
2921 static void do_tpx_state_second(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state, rvec* x, rvec* v)
2923 if (!serializer->reading())
2926 x == nullptr && v == nullptr,
2927 "Passing separate x and v pointers to do_tpx() is not supported when writing");
2931 GMX_RELEASE_ASSERT(!(x == nullptr && v != nullptr),
2932 "Passing x==NULL and v!=NULL is not supported");
2935 if (serializer->reading())
2939 // v is also nullptr by the above assertion, so we may
2940 // need to make memory in state for storing the contents
2944 state->flags |= enumValueToBitMask(StateEntry::X);
2948 state->flags |= enumValueToBitMask(StateEntry::V);
2950 state_change_natoms(state, tpx->natoms);
2956 x = state->x.rvec_array();
2957 v = state->v.rvec_array();
2959 do_test(serializer, tpx->bX, x);
2962 if (serializer->reading())
2964 state->flags |= enumValueToBitMask(StateEntry::X);
2966 serializer->doRvecArray(x, tpx->natoms);
2969 do_test(serializer, tpx->bV, v);
2972 if (serializer->reading())
2974 state->flags |= enumValueToBitMask(StateEntry::V);
2978 std::vector<gmx::RVec> dummyVelocities(tpx->natoms);
2979 serializer->doRvecArray(as_rvec_array(dummyVelocities.data()), tpx->natoms);
2983 serializer->doRvecArray(v, tpx->natoms);
2987 // No need to run do_test when the last argument is NULL
2990 std::vector<gmx::RVec> dummyForces(state->natoms);
2991 serializer->doRvecArray(as_rvec_array(dummyForces.data()), tpx->natoms);
2995 * Process simulation parameters.
2997 * See the documentation for do_tpx_body for the correct order of
2998 * the operations for reading a tpr file.
3000 * \param[in] serializer Abstract serializer used to read/write data.
3001 * \param[in] tpx The file header data.
3002 * \param[in,out] ir Datastructure with simulation parameters.
3004 static PbcType do_tpx_ir(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir)
3007 gmx_bool bPeriodicMols;
3009 /* Starting with tpx version 26, we have the inputrec
3010 * at the end of the file, so we can ignore it
3011 * if the file is never than the software (but still the
3012 * same generation - see comments at the top of this file.
3016 pbcType = PbcType::Unset;
3017 bPeriodicMols = FALSE;
3019 do_test(serializer, tpx->bIr, ir);
3022 if (tpx->fileVersion >= 53)
3024 /* Removed the pbc info from do_inputrec, since we always want it */
3025 if (!serializer->reading())
3027 pbcType = ir->pbcType;
3028 bPeriodicMols = ir->bPeriodicMols;
3030 serializer->doInt(reinterpret_cast<int*>(&pbcType));
3031 serializer->doBool(&bPeriodicMols);
3033 if (tpx->fileGeneration <= tpx_generation && ir)
3035 do_inputrec(serializer, ir, tpx->fileVersion);
3036 if (tpx->fileVersion < 53)
3038 pbcType = ir->pbcType;
3039 bPeriodicMols = ir->bPeriodicMols;
3042 if (serializer->reading() && ir && tpx->fileVersion >= 53)
3044 /* We need to do this after do_inputrec, since that initializes ir */
3045 ir->pbcType = pbcType;
3046 ir->bPeriodicMols = bPeriodicMols;
3053 * Correct and finalize read information.
3055 * If \p state is nullptr, skip the parts dependent on it.
3057 * See the documentation for do_tpx_body for the correct order of
3058 * the operations for reading a tpr file.
3060 * \param[in] tpx The file header used to check version numbers.
3061 * \param[out] ir Input rec that needs correction.
3062 * \param[out] state State needing correction.
3063 * \param[out] mtop Topology to finalize.
3065 static void do_tpx_finalize(TpxFileHeader* tpx, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
3067 if (tpx->fileVersion < 51 && state)
3069 set_box_rel(ir, state);
3073 if (state && state->ngtc == 0)
3075 /* Reading old version without tcoupl state data: set it */
3076 init_gtc_state(state, ir->opts.ngtc, 0, ir->opts.nhchainlength);
3078 if (tpx->bTop && mtop)
3080 if (tpx->fileVersion < 57)
3082 ir->eDisre = !mtop->moltype[0].ilist[F_DISRES].empty()
3083 ? DistanceRestraintRefinement::Simple
3084 : DistanceRestraintRefinement::None;
3091 * Process TPR data for file reading/writing.
3093 * The TPR file gets processed in in four stages due to the organization
3094 * of the data within it.
3096 * First, state data for the box is processed in do_tpx_state_first.
3097 * This is followed by processing the topology in do_tpx_mtop.
3098 * Coordinate and velocity vectors are handled next in do_tpx_state_second.
3099 * The last file information processed is the collection of simulation parameters in do_tpx_ir.
3100 * When reading, a final processing step is undertaken at the end.
3102 * \param[in] serializer Abstract serializer used to read/write data.
3103 * \param[in] tpx The file header data.
3104 * \param[in,out] ir Datastructures with simulation parameters.
3105 * \param[in,out] state Global state data.
3106 * \param[in,out] x Individual coordinates for processing, deprecated.
3107 * \param[in,out] v Individual velocities for processing, deprecated.
3108 * \param[in,out] mtop Global topology.
3110 static PbcType do_tpx_body(gmx::ISerializer* serializer,
3120 do_tpx_state_first(serializer, tpx, state);
3122 do_tpx_mtop(serializer, tpx, mtop);
3125 do_tpx_state_second(serializer, tpx, state, x, v);
3127 PbcType pbcType = do_tpx_ir(serializer, tpx, ir);
3128 if (serializer->reading())
3130 do_tpx_finalize(tpx, ir, state, mtop);
3136 * Overload for do_tpx_body that defaults to state vectors being nullptr.
3138 * \param[in] serializer Abstract serializer used to read/write data.
3139 * \param[in] tpx The file header data.
3140 * \param[in,out] ir Datastructures with simulation parameters.
3141 * \param[in,out] mtop Global topology.
3143 static PbcType do_tpx_body(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir, gmx_mtop_t* mtop)
3145 return do_tpx_body(serializer, tpx, ir, nullptr, nullptr, nullptr, mtop);
3148 static t_fileio* open_tpx(const char* fn, const char* mode)
3150 return gmx_fio_open(fn, mode);
3153 static void close_tpx(t_fileio* fio)
3159 * Fill information into the header only from state before writing.
3161 * Populating the header needs to be independent from writing the information
3162 * to file to allow things like writing the raw byte stream.
3164 * \param[in] state The current simulation state. Can't write without it.
3165 * \param[in] ir Parameter and system information.
3166 * \param[in] mtop Global topology.
3167 * \returns Fully populated header.
3169 static TpxFileHeader populateTpxHeader(const t_state& state, const t_inputrec* ir, const gmx_mtop_t* mtop)
3171 TpxFileHeader header;
3172 header.natoms = state.natoms;
3173 header.ngtc = state.ngtc;
3174 header.fep_state = state.fep_state;
3175 header.lambda = state.lambda[FreeEnergyPerturbationCouplingType::Fep];
3176 header.bIr = ir != nullptr;
3177 header.bTop = mtop != nullptr;
3178 header.bX = (state.flags & enumValueToBitMask(StateEntry::X)) != 0;
3179 header.bV = (state.flags & enumValueToBitMask(StateEntry::V)) != 0;
3182 header.fileVersion = tpx_version;
3183 header.fileGeneration = tpx_generation;
3184 header.isDouble = (sizeof(real) == sizeof(double));
3190 * Process the body of a TPR file as an opaque data buffer.
3192 * Reads/writes the information in \p buffer from/to the \p serializer
3193 * provided to the function. Does not interact with the actual
3194 * TPR datastructures but with an in memory representation of the
3195 * data, so that this data can be efficiently read or written from/to
3196 * an original source.
3198 * \param[in] serializer The abstract serializer used for reading or writing
3199 * the information in \p buffer.
3200 * \param[in,out] buffer Information from TPR file as char buffer.
3202 static void doTpxBodyBuffer(gmx::ISerializer* serializer, gmx::ArrayRef<char> buffer)
3204 serializer->doOpaque(buffer.data(), buffer.size());
3208 * Populates simulation datastructures.
3210 * Here the information from the serialization interface \p serializer
3211 * is used to first populate the datastructures containing the simulation
3212 * information. Depending on the version found in the header \p tpx,
3213 * this is done using the new reading of the data as one block from disk,
3214 * followed by complete deserialization of the information read from there.
3215 * Otherwise, the datastructures are populated as before one by one from disk.
3216 * The second version is the default for the legacy tools that read the
3217 * coordinates and velocities separate from the state.
3219 * After reading in the data, a separate buffer is populated from them
3220 * containing only \p ir and \p mtop that can be communicated directly
3221 * to nodes needing the information to set up a simulation.
3223 * \param[in] tpx The file header.
3224 * \param[in] serializer The Serialization interface used to read the TPR.
3225 * \param[out] ir Input rec to populate.
3226 * \param[out] state State vectors to populate.
3227 * \param[out] x Coordinates to populate if needed.
3228 * \param[out] v Velocities to populate if needed.
3229 * \param[out] mtop Global topology to populate.
3231 * \returns Partial de-serialized TPR used for communication to nodes.
3233 static PartialDeserializedTprFile readTpxBody(TpxFileHeader* tpx,
3234 gmx::ISerializer* serializer,
3241 PartialDeserializedTprFile partialDeserializedTpr;
3242 if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
3244 partialDeserializedTpr.body.resize(tpx->sizeOfTprBody);
3245 partialDeserializedTpr.header = *tpx;
3246 doTpxBodyBuffer(serializer, partialDeserializedTpr.body);
3248 partialDeserializedTpr.pbcType =
3249 completeTprDeserialization(&partialDeserializedTpr, ir, state, x, v, mtop);
3253 partialDeserializedTpr.pbcType = do_tpx_body(serializer, tpx, ir, state, x, v, mtop);
3255 // Update header to system info for communication to nodes.
3256 // As we only need to communicate the inputrec and mtop to other nodes,
3257 // we prepare a new char buffer with the information we have already read
3259 partialDeserializedTpr.header = populateTpxHeader(*state, ir, mtop);
3260 // Long-term we should move to use little endian in files to avoid extra byte swapping,
3261 // but since we just used the default XDR format (which is big endian) for the TPR
3262 // header it would cause third-party libraries reading our raw data to tear their hair
3263 // if we swap the endian in the middle of the file, so we stick to big endian in the
3264 // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
3265 gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
3266 do_tpx_body(&tprBodySerializer, &partialDeserializedTpr.header, ir, mtop);
3267 partialDeserializedTpr.body = tprBodySerializer.finishAndGetBuffer();
3269 return partialDeserializedTpr;
3272 /************************************************************
3274 * The following routines are the exported ones
3276 ************************************************************/
3278 TpxFileHeader readTpxHeader(const char* fileName, bool canReadTopologyOnly)
3282 fio = open_tpx(fileName, "r");
3283 gmx::FileIOXdrSerializer serializer(fio);
3286 do_tpxheader(&serializer, &tpx, fileName, fio, canReadTopologyOnly);
3291 void write_tpx_state(const char* fn, const t_inputrec* ir, const t_state* state, const gmx_mtop_t& mtop)
3293 /* To write a state, we first need to write the state information to a buffer before
3294 * we append the raw bytes to the file. For this, the header information needs to be
3295 * populated before we write the main body because it has some information that is
3296 * otherwise not available.
3301 TpxFileHeader tpx = populateTpxHeader(*state, ir, &mtop);
3302 // Long-term we should move to use little endian in files to avoid extra byte swapping,
3303 // but since we just used the default XDR format (which is big endian) for the TPR
3304 // header it would cause third-party libraries reading our raw data to tear their hair
3305 // if we swap the endian in the middle of the file, so we stick to big endian in the
3306 // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
3307 gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
3309 do_tpx_body(&tprBodySerializer,
3311 const_cast<t_inputrec*>(ir),
3312 const_cast<t_state*>(state),
3315 const_cast<gmx_mtop_t*>(&mtop));
3317 std::vector<char> tprBody = tprBodySerializer.finishAndGetBuffer();
3318 tpx.sizeOfTprBody = tprBody.size();
3320 fio = open_tpx(fn, "w");
3321 gmx::FileIOXdrSerializer serializer(fio);
3322 do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
3323 doTpxBodyBuffer(&serializer, tprBody);
3328 PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
3335 // Long-term we should move to use little endian in files to avoid extra byte swapping,
3336 // but since we just used the default XDR format (which is big endian) for the TPR
3337 // header it would cause third-party libraries reading our raw data to tear their hair
3338 // if we swap the endian in the middle of the file, so we stick to big endian in the
3339 // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
3340 gmx::InMemoryDeserializer tprBodyDeserializer(partialDeserializedTpr->body,
3341 partialDeserializedTpr->header.isDouble,
3342 gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
3343 return do_tpx_body(&tprBodyDeserializer, &partialDeserializedTpr->header, ir, state, x, v, mtop);
3346 PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
3350 return completeTprDeserialization(partialDeserializedTpr, ir, nullptr, nullptr, nullptr, mtop);
3353 PartialDeserializedTprFile read_tpx_state(const char* fn, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
3356 fio = open_tpx(fn, "r");
3357 gmx::FileIOXdrSerializer serializer(fio);
3358 PartialDeserializedTprFile partialDeserializedTpr;
3359 do_tpxheader(&serializer, &partialDeserializedTpr.header, fn, fio, ir == nullptr);
3360 partialDeserializedTpr =
3361 readTpxBody(&partialDeserializedTpr.header, &serializer, ir, state, nullptr, nullptr, mtop);
3363 return partialDeserializedTpr;
3366 PbcType read_tpx(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, gmx_mtop_t* mtop)
3372 fio = open_tpx(fn, "r");
3373 gmx::FileIOXdrSerializer serializer(fio);
3374 do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
3375 PartialDeserializedTprFile partialDeserializedTpr =
3376 readTpxBody(&tpx, &serializer, ir, &state, x, v, mtop);
3378 if (mtop != nullptr && natoms != nullptr)
3380 *natoms = mtop->natoms;
3384 copy_mat(state.box, box);
3386 return partialDeserializedTpr.pbcType;
3389 PbcType read_tpx_top(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, t_topology* top)
3394 pbcType = read_tpx(fn, ir, box, natoms, x, v, &mtop);
3396 *top = gmx_mtop_t_to_t_topology(&mtop, true);
3401 gmx_bool fn2bTPX(const char* file)
3403 return (efTPR == fn2ftp(file));
3406 void pr_tpxheader(FILE* fp, int indent, const char* title, const TpxFileHeader* sh)
3408 if (available(fp, sh, indent, title))
3410 indent = pr_title(fp, indent, title);
3411 pr_indent(fp, indent);
3412 fprintf(fp, "bIr = %spresent\n", sh->bIr ? "" : "not ");
3413 pr_indent(fp, indent);
3414 fprintf(fp, "bBox = %spresent\n", sh->bBox ? "" : "not ");
3415 pr_indent(fp, indent);
3416 fprintf(fp, "bTop = %spresent\n", sh->bTop ? "" : "not ");
3417 pr_indent(fp, indent);
3418 fprintf(fp, "bX = %spresent\n", sh->bX ? "" : "not ");
3419 pr_indent(fp, indent);
3420 fprintf(fp, "bV = %spresent\n", sh->bV ? "" : "not ");
3421 pr_indent(fp, indent);
3422 fprintf(fp, "bF = %spresent\n", sh->bF ? "" : "not ");
3424 pr_indent(fp, indent);
3425 fprintf(fp, "natoms = %d\n", sh->natoms);
3426 pr_indent(fp, indent);
3427 fprintf(fp, "lambda = %e\n", sh->lambda);
3428 pr_indent(fp, indent);
3429 fprintf(fp, "buffer size = %" PRId64 "\n", sh->sizeOfTprBody);