Merge branch release-2021 into master
[alexxy/gromacs.git] / src / gromacs / fileio / tpxio.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
11  *
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.
16  *
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.
21  *
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.
26  *
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.
34  *
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.
37  */
38 #include "gmxpre.h"
39
40 /* This file is completely threadsafe - keep it that way! */
41
42 #include "gromacs/fileio/tpxio.h"
43
44 #include <cstdio>
45 #include <cstdlib>
46 #include <cstring>
47
48 #include <algorithm>
49 #include <memory>
50 #include <vector>
51
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"
85
86 #define TPX_TAG_RELEASE "release"
87
88 /*! \brief Tag string for the file format written to run input files
89  * written by this version of the code.
90  *
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.
97  */
98 static const std::string tpx_tag = TPX_TAG_RELEASE;
99
100 /*! \brief Enum of values that describe the contents of a tpr file
101  * whose format matches a version number
102  *
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.
108  */
109 enum tpxv
110 {
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 */
141 };
142
143 /*! \brief Version number of the file format written to run input
144  * files by this version of the code.
145  *
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.
151  *
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;
155
156
157 /*! \brief
158  * Enum keeping track of incompatible changes for older TPR versions.
159  *
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.
163  *
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.
167  *
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
170  * want the topology.
171  *
172  * In particular, it must be increased when adding new elements to
173  * ftupd, so that old code can read new .tpr files.
174  */
175 enum class TpxGeneration : int
176 {
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.
181 };
182
183 //! Value of Current TPR generation.
184 static const int tpx_generation = static_cast<int>(TpxGeneration::Count) - 1;
185
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.
188  */
189 static const int tpx_incompatible_version = 57; // GMX4.0 has version 58
190
191
192 /* Struct used to maintain tpx compatibility when function types are added */
193 typedef struct
194 {
195     int fvnr;  /* file version number in which the function type first appeared */
196     int ftype; /* function type */
197 } t_ftupd;
198
199 /*
200  * TODO The following three lines make little sense, please clarify if
201  * you've had to work out how ftupd works.
202  *
203  * The entries should be ordered in:
204  * 1. ascending function type number
205  * 2. ascending file version number
206  *
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.
212  *
213  * When adding to or making breaking changes to reading this struct,
214  * update TpxGeneration.
215  */
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 },
222     { 65, F_CMAP },
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 },
228     { 93, F_LJ_RECIP },
229     { 76, F_ANHARM_POL },
230     { 90, F_FBPOSRES },
231     { tpxv_VSite1, F_VSITE1 },
232     { tpxv_VSite2FD, F_VSITE2FD },
233     { tpxv_GenericInternalParameters, F_DENSITYFITTING },
234     { 69, F_VTEMP_NOLONGERUSED },
235     { 66, F_PDISPCORR },
236     { 79, F_DVDL_COUL },
237     {
238             79,
239             F_DVDL_VDW,
240     },
241     {
242             79,
243             F_DVDL_BONDED,
244     },
245     { 79, F_DVDL_RESTRAINT },
246     { 79, F_DVDL_TEMPERATURE },
247 };
248 #define NFTUPD asize(ftupd)
249
250 /**************************************************************
251  *
252  * Now the higer level routines that do io of the structures and arrays
253  *
254  **************************************************************/
255 static void do_pullgrp_tpx_pre95(gmx::ISerializer* serializer, t_pull_group* pgrp, t_pull_coord* pcrd)
256 {
257     rvec tmp;
258
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);
271     pcrd->init = tmp[0];
272     serializer->doReal(&pcrd->rate);
273     serializer->doReal(&pcrd->k);
274     serializer->doReal(&pcrd->kB);
275 }
276
277 static void do_pull_group(gmx::ISerializer* serializer, t_pull_group* pgrp)
278 {
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);
288 }
289
290 static void do_pull_coord(gmx::ISerializer* serializer,
291                           t_pull_coord*     pcrd,
292                           int               file_version,
293                           PullingAlgorithm  ePullOld,
294                           PullGroupGeometry eGeomOld,
295                           ivec              dimOld)
296 {
297     if (file_version >= tpxv_PullCoordNGroup)
298     {
299         serializer->doEnumAsInt(&pcrd->eType);
300         if (file_version >= tpxv_PullExternalPotential)
301         {
302             if (pcrd->eType == PullingAlgorithm::External)
303             {
304                 std::string buf;
305                 if (serializer->reading())
306                 {
307                     serializer->doString(&buf);
308                     pcrd->externalPotentialProvider = gmx_strdup(buf.c_str());
309                 }
310                 else
311                 {
312                     buf = pcrd->externalPotentialProvider;
313                     serializer->doString(&buf);
314                 }
315             }
316             else
317             {
318                 pcrd->externalPotentialProvider.clear();
319             }
320         }
321         else
322         {
323             if (serializer->reading())
324             {
325                 pcrd->externalPotentialProvider.clear();
326             }
327         }
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.
331          */
332         serializer->doEnumAsInt(&pcrd->eGeom);
333         serializer->doInt(&pcrd->ngroup);
334         if (pcrd->ngroup <= c_pullCoordNgroupMax)
335         {
336             serializer->doIntArray(pcrd->group.data(), pcrd->ngroup);
337         }
338         else
339         {
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.
344              */
345             int* dum;
346             snew(dum, pcrd->ngroup);
347             serializer->doIntArray(dum, pcrd->ngroup);
348             sfree(dum);
349
350             pcrd->ngroup = 0;
351         }
352         serializer->doIvec(&pcrd->dim.as_vec());
353     }
354     else
355     {
356         pcrd->ngroup = 2;
357         serializer->doInt(&pcrd->group[0]);
358         serializer->doInt(&pcrd->group[1]);
359         if (file_version >= tpxv_PullCoordTypeGeom)
360         {
361             pcrd->ngroup = (pcrd->eGeom == PullGroupGeometry::DirectionRelative ? 4 : 2);
362             serializer->doEnumAsInt(&pcrd->eType);
363             serializer->doEnumAsInt(&pcrd->eGeom);
364             if (pcrd->ngroup == 4)
365             {
366                 serializer->doInt(&pcrd->group[2]);
367                 serializer->doInt(&pcrd->group[3]);
368             }
369             serializer->doIvec(&pcrd->dim.as_vec());
370         }
371         else
372         {
373             pcrd->eType = ePullOld;
374             pcrd->eGeom = eGeomOld;
375             copy_ivec(dimOld, pcrd->dim);
376         }
377     }
378     serializer->doRvec(&pcrd->origin.as_vec());
379     serializer->doRvec(&pcrd->vec.as_vec());
380     if (file_version >= tpxv_PullCoordTypeGeom)
381     {
382         serializer->doBool(&pcrd->bStart);
383     }
384     else
385     {
386         /* This parameter is only printed, but not actually used by mdrun */
387         pcrd->bStart = FALSE;
388     }
389     serializer->doReal(&pcrd->init);
390     serializer->doReal(&pcrd->rate);
391     serializer->doReal(&pcrd->k);
392     serializer->doReal(&pcrd->kB);
393 }
394
395 static void do_expandedvals(gmx::ISerializer* serializer, t_expanded* expand, t_lambda* fepvals, int file_version)
396 {
397     int n_lambda = fepvals->n_lambda;
398
399     /* reset the lambda calculation window */
400     fepvals->lambda_start_n = 0;
401     fepvals->lambda_stop_n  = n_lambda;
402     if (file_version >= 79)
403     {
404         if (n_lambda > 0)
405         {
406             expand->init_lambda_weights.resize(n_lambda);
407             serializer->doRealArray(expand->init_lambda_weights.data(), n_lambda);
408             serializer->doBool(&expand->bInit_weights);
409         }
410
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);
433     }
434 }
435
436 static void do_simtempvals(gmx::ISerializer* serializer, t_simtemp* simtemp, int n_lambda, int file_version)
437 {
438     if (file_version >= 79)
439     {
440         serializer->doEnumAsInt(&simtemp->eSimTempScale);
441         serializer->doReal(&simtemp->simtemp_high);
442         serializer->doReal(&simtemp->simtemp_low);
443         if (n_lambda > 0)
444         {
445             if (serializer->reading())
446             {
447                 simtemp->temperatures.resize(n_lambda);
448             }
449             serializer->doRealArray(simtemp->temperatures.data(), n_lambda);
450         }
451     }
452 }
453
454 static void do_imd(gmx::ISerializer* serializer, t_IMD* imd)
455 {
456     serializer->doInt(&imd->nat);
457     if (serializer->reading())
458     {
459         snew(imd->ind, imd->nat);
460     }
461     serializer->doIntArray(imd->ind, imd->nat);
462 }
463
464 static void do_fepvals(gmx::ISerializer* serializer, t_lambda* fepvals, int file_version)
465 {
466     /* i is defined in the ndo_double macro; use g to iterate. */
467     real rdum;
468
469     /* free energy values */
470
471     if (file_version >= 79)
472     {
473         serializer->doInt(&fepvals->init_fep_state);
474         serializer->doDouble(&fepvals->init_lambda);
475         serializer->doDouble(&fepvals->delta_lambda);
476     }
477     else if (file_version >= 59)
478     {
479         serializer->doDouble(&fepvals->init_lambda);
480         serializer->doDouble(&fepvals->delta_lambda);
481     }
482     else
483     {
484         serializer->doReal(&rdum);
485         fepvals->init_lambda = rdum;
486         serializer->doReal(&rdum);
487         fepvals->delta_lambda = rdum;
488     }
489     if (file_version >= 79)
490     {
491         serializer->doInt(&fepvals->n_lambda);
492         for (auto g : keysOf(fepvals->all_lambda))
493         {
494             if (fepvals->n_lambda > 0)
495             {
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());
499             }
500             else if (fepvals->init_lambda >= 0)
501             {
502                 fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
503             }
504         }
505     }
506     else if (file_version >= 64)
507     {
508         serializer->doInt(&fepvals->n_lambda);
509         if (serializer->reading())
510         {
511             /* still allocate the all_lambda array's contents. */
512             for (auto g : keysOf(fepvals->all_lambda))
513             {
514                 if (fepvals->n_lambda > 0)
515                 {
516                     fepvals->all_lambda[g].resize(fepvals->n_lambda);
517                 }
518             }
519         }
520         serializer->doDoubleArray(fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep].data(),
521                                   fepvals->n_lambda);
522         if (fepvals->init_lambda >= 0)
523         {
524             fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
525
526             if (serializer->reading())
527             {
528                 /* copy the contents of the efptFEP lambda component to all
529                    the other components */
530                 for (auto g : keysOf(fepvals->all_lambda))
531                 {
532                     for (int h = 0; h < fepvals->n_lambda; h++)
533                     {
534                         if (g != FreeEnergyPerturbationCouplingType::Fep)
535                         {
536                             fepvals->all_lambda[g][h] =
537                                     fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep][h];
538                         }
539                     }
540                 }
541             }
542         }
543     }
544     else
545     {
546         fepvals->n_lambda = 0;
547         if (fepvals->init_lambda >= 0)
548         {
549             fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
550         }
551     }
552     serializer->doReal(&fepvals->sc_alpha);
553     serializer->doInt(&fepvals->sc_power);
554     if (file_version >= 79)
555     {
556         serializer->doReal(&fepvals->sc_r_power);
557     }
558     else
559     {
560         fepvals->sc_r_power = 6.0;
561     }
562     if (fepvals->sc_r_power != 6.0)
563     {
564         gmx_fatal(FARGS, "sc-r-power=48 is no longer supported");
565     }
566     serializer->doReal(&fepvals->sc_sigma);
567     if (serializer->reading())
568     {
569         if (file_version >= 71)
570         {
571             fepvals->sc_sigma_min = fepvals->sc_sigma;
572         }
573         else
574         {
575             fepvals->sc_sigma_min = 0;
576         }
577     }
578     if (file_version >= 79)
579     {
580         serializer->doBool(&fepvals->bScCoul);
581     }
582     else
583     {
584         fepvals->bScCoul = TRUE;
585     }
586     if (file_version >= 64)
587     {
588         serializer->doInt(&fepvals->nstdhdl);
589     }
590     else
591     {
592         fepvals->nstdhdl = 1;
593     }
594
595     if (file_version >= 73)
596     {
597         serializer->doEnumAsInt(&fepvals->separate_dhdl_file);
598         serializer->doEnumAsInt(&fepvals->dhdl_derivatives);
599     }
600     else
601     {
602         fepvals->separate_dhdl_file = SeparateDhdlFile::Yes;
603         fepvals->dhdl_derivatives   = DhDlDerivativeCalculation::Yes;
604     }
605     if (file_version >= 71)
606     {
607         serializer->doInt(&fepvals->dh_hist_size);
608         serializer->doDouble(&fepvals->dh_hist_spacing);
609     }
610     else
611     {
612         fepvals->dh_hist_size    = 0;
613         fepvals->dh_hist_spacing = 0.1;
614     }
615     if (file_version >= 79)
616     {
617         serializer->doEnumAsInt(&fepvals->edHdLPrintEnergy);
618     }
619     else
620     {
621         fepvals->edHdLPrintEnergy = FreeEnergyPrintEnergy::No;
622     }
623
624     /* handle lambda_neighbors */
625     if ((file_version >= 83 && file_version < 90) || file_version >= 92)
626     {
627         serializer->doInt(&fepvals->lambda_neighbors);
628         if ((fepvals->lambda_neighbors >= 0) && (fepvals->init_fep_state >= 0)
629             && (fepvals->init_lambda < 0))
630         {
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)
634             {
635                 fepvals->lambda_start_n = 0;
636             }
637             if (fepvals->lambda_stop_n >= fepvals->n_lambda)
638             {
639                 fepvals->lambda_stop_n = fepvals->n_lambda;
640             }
641         }
642         else
643         {
644             fepvals->lambda_start_n = 0;
645             fepvals->lambda_stop_n  = fepvals->n_lambda;
646         }
647     }
648     else
649     {
650         fepvals->lambda_start_n = 0;
651         fepvals->lambda_stop_n  = fepvals->n_lambda;
652     }
653 }
654
655 static void do_pull(gmx::ISerializer* serializer, pull_params_t* pull, int file_version, PullingAlgorithm ePullOld)
656 {
657     PullGroupGeometry eGeomOld = PullGroupGeometry::Count;
658     ivec              dimOld;
659     int               g;
660
661     if (file_version >= 95)
662     {
663         serializer->doInt(&pull->ngroup);
664     }
665     serializer->doInt(&pull->ncoord);
666     if (file_version < 95)
667     {
668         pull->ngroup = pull->ncoord + 1;
669     }
670     if (file_version < tpxv_PullCoordTypeGeom)
671     {
672         real dum;
673
674         serializer->doEnumAsInt(&eGeomOld);
675         serializer->doIvec(&dimOld);
676         /* The inner cylinder radius, now removed */
677         serializer->doReal(&dum);
678     }
679     serializer->doReal(&pull->cylinder_r);
680     serializer->doReal(&pull->constr_tol);
681     if (file_version >= 95)
682     {
683         serializer->doBool(&pull->bPrintCOM);
684         /* With file_version < 95 this value is set below */
685     }
686     if (file_version >= tpxv_ReplacePullPrintCOM12)
687     {
688         serializer->doBool(&pull->bPrintRefValue);
689         serializer->doBool(&pull->bPrintComp);
690     }
691     else if (file_version >= tpxv_PullCoordTypeGeom)
692     {
693         int idum;
694         serializer->doInt(&idum); /* used to be bPrintCOM2 */
695         serializer->doBool(&pull->bPrintRefValue);
696         serializer->doBool(&pull->bPrintComp);
697     }
698     else
699     {
700         pull->bPrintRefValue = FALSE;
701         pull->bPrintComp     = TRUE;
702     }
703     serializer->doInt(&pull->nstxout);
704     serializer->doInt(&pull->nstfout);
705     if (file_version >= tpxv_PullPrevStepCOMAsReference)
706     {
707         serializer->doBool(&pull->bSetPbcRefToPrevStepCOM);
708     }
709     else
710     {
711         pull->bSetPbcRefToPrevStepCOM = FALSE;
712     }
713     pull->group.resize(pull->ngroup);
714     pull->coord.resize(pull->ncoord);
715     if (file_version < 95)
716     {
717         /* epullgPOS for position pulling, before epullgDIRPBC was removed */
718         if (eGeomOld == PullGroupGeometry::DirectionPBC)
719         {
720             gmx_fatal(FARGS, "pull-geometry=position is no longer supported");
721         }
722         if (eGeomOld > PullGroupGeometry::DirectionPBC)
723         {
724             switch (eGeomOld)
725             {
726                 case (PullGroupGeometry::DirectionRelative):
727                     eGeomOld = PullGroupGeometry::DirectionPBC;
728                     break;
729                 case (PullGroupGeometry::Angle):
730                     eGeomOld = PullGroupGeometry::DirectionRelative;
731                     break;
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");
736             }
737         }
738
739         for (g = 0; g < pull->ngroup; g++)
740         {
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)]);
743             if (g > 0)
744             {
745                 pull->coord[g - 1].group[0] = 0;
746                 pull->coord[g - 1].group[1] = g;
747             }
748         }
749
750         pull->bPrintCOM = (!pull->group[0].ind.empty());
751     }
752     else
753     {
754         for (g = 0; g < pull->ngroup; g++)
755         {
756             do_pull_group(serializer, &pull->group[g]);
757         }
758         for (g = 0; g < pull->ncoord; g++)
759         {
760             do_pull_coord(serializer, &pull->coord[g], file_version, ePullOld, eGeomOld, dimOld);
761             if (serializer->reading())
762             {
763                 pull->coord[g].coordIndex = g;
764             }
765         }
766     }
767     if (file_version >= tpxv_PullAverage)
768     {
769         gmx_bool v;
770
771         v = pull->bXOutAverage;
772         serializer->doBool(&v);
773         pull->bXOutAverage = v;
774         v                  = pull->bFOutAverage;
775         serializer->doBool(&v);
776         pull->bFOutAverage = v;
777     }
778 }
779
780
781 static void do_rotgrp(gmx::ISerializer* serializer, t_rotgrp* rotg)
782 {
783     serializer->doEnumAsInt(&rotg->eType);
784     if (serializer->reading())
785     {
786         int temp = 0;
787         serializer->doInt(&temp);
788         rotg->bMassW = static_cast<bool>(temp);
789     }
790     else
791     {
792         int temp = static_cast<int>(rotg->bMassW);
793         serializer->doInt(&temp);
794     }
795     serializer->doInt(&rotg->nat);
796     if (serializer->reading())
797     {
798         snew(rotg->ind, rotg->nat);
799     }
800     serializer->doIntArray(rotg->ind, rotg->nat);
801     if (serializer->reading())
802     {
803         snew(rotg->x_ref, rotg->nat);
804     }
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);
816 }
817
818 static void do_rot(gmx::ISerializer* serializer, t_rot* rot)
819 {
820     int g;
821
822     serializer->doInt(&rot->ngrp);
823     serializer->doInt(&rot->nstrout);
824     serializer->doInt(&rot->nstsout);
825     if (serializer->reading())
826     {
827         snew(rot->grp, rot->ngrp);
828     }
829     for (g = 0; g < rot->ngrp; g++)
830     {
831         do_rotgrp(serializer, &rot->grp[g]);
832     }
833 }
834
835
836 static void do_swapgroup(gmx::ISerializer* serializer, t_swapGroup* g)
837 {
838
839     /* Name of the group or molecule */
840     std::string buf;
841     if (serializer->reading())
842     {
843         serializer->doString(&buf);
844         g->molname = gmx_strdup(buf.c_str());
845     }
846     else
847     {
848         buf = g->molname;
849         serializer->doString(&buf);
850     }
851
852     /* Number of atoms in the group */
853     serializer->doInt(&g->nat);
854
855     /* The group's atom indices */
856     if (serializer->reading())
857     {
858         snew(g->ind, g->nat);
859     }
860     serializer->doIntArray(g->ind, g->nat);
861
862     /* Requested counts for compartments A and B */
863     serializer->doIntArray(g->nmolReq.data(), static_cast<int>(Compartment::Count));
864 }
865
866 static void do_swapcoords_tpx(gmx::ISerializer* serializer, t_swapcoords* swap, int file_version)
867 {
868     /* Enums for better readability of the code */
869     enum
870     {
871         eCompA = 0,
872         eCompB
873     };
874     enum
875     {
876         eChannel0 = 0,
877         eChannel1
878     };
879
880
881     if (file_version >= tpxv_CompElPolyatomicIonsAndMultipleIonTypes)
882     {
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)
885          */
886         serializer->doInt(&swap->ngrp);
887         if (serializer->reading())
888         {
889             snew(swap->grp, swap->ngrp);
890         }
891         for (int ig = 0; ig < swap->ngrp; ig++)
892         {
893             do_swapgroup(serializer, &swap->grp[ig]);
894         }
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);
906     }
907     else
908     {
909         /*** Support reading older CompEl .tpr files ***/
910
911         /* In the original CompEl .tpr files, we always have 5 groups: */
912         swap->ngrp = 5;
913         snew(swap->grp, swap->ngrp);
914
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
921
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);
937
938         // The order[] array keeps compatibility with older .tpr files
939         // by reading in the groups in the classic order
940         {
941             const int order[4] = { 3,
942                                    static_cast<int>(SwapGroupSplittingType::Solvent),
943                                    static_cast<int>(SwapGroupSplittingType::Split0),
944                                    static_cast<int>(SwapGroupSplittingType::Split1) };
945
946             for (int ig = 0; ig < 4; ig++)
947             {
948                 int g = order[ig];
949                 snew(swap->grp[g].ind, swap->grp[g].nat);
950                 serializer->doIntArray(swap->grp[g].ind, swap->grp[g].nat);
951             }
952         }
953
954         for (int j = eCompA; j <= eCompB; j++)
955         {
956             serializer->doInt(&swap->grp[3].nmolReq[j]); // group 3 = anions
957             serializer->doInt(&swap->grp[4].nmolReq[j]); // group 4 = cations
958         }
959     } /* End support reading older CompEl .tpr files */
960
961     if (file_version >= tpxv_CompElWithSwapLayerOffset)
962     {
963         serializer->doReal(&swap->bulkOffset[eCompA]);
964         serializer->doReal(&swap->bulkOffset[eCompB]);
965     }
966 }
967
968 static void do_legacy_efield(gmx::ISerializer* serializer, gmx::KeyValueTreeObjectBuilder* root)
969 {
970     const char* const dimName[] = { "x", "y", "z" };
971
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
976     // developing.
977     for (int j = 0; j < DIM; ++j)
978     {
979         int n, nt;
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);
987         if (n > 0)
988         {
989             if (n > 1 || nt > 1)
990             {
991                 gmx_fatal(FARGS,
992                           "Can not handle tpr files with more than one electric field term per "
993                           "direction.");
994             }
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]);
1000         }
1001     }
1002 }
1003
1004
1005 static void do_inputrec(gmx::ISerializer* serializer, t_inputrec* ir, int file_version)
1006 {
1007     int      i, j, k, idum = 0;
1008     real     rdum;
1009     gmx_bool bdum = false;
1010
1011     if (file_version != tpx_version)
1012     {
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);
1015     }
1016
1017     if (file_version == 0)
1018     {
1019         return;
1020     }
1021
1022     gmx::KeyValueTreeBuilder       paramsBuilder;
1023     gmx::KeyValueTreeObjectBuilder paramsObj = paramsBuilder.rootObject();
1024
1025     /* Basic inputrec stuff */
1026     serializer->doEnumAsInt(&ir->eI);
1027     if (file_version >= 62)
1028     {
1029         serializer->doInt64(&ir->nsteps);
1030     }
1031     else
1032     {
1033         serializer->doInt(&idum);
1034         ir->nsteps = idum;
1035     }
1036
1037     if (file_version >= 62)
1038     {
1039         serializer->doInt64(&ir->init_step);
1040     }
1041     else
1042     {
1043         serializer->doInt(&idum);
1044         ir->init_step = idum;
1045     }
1046
1047     serializer->doInt(&ir->simulation_part);
1048
1049     if (file_version >= tpxv_MTS)
1050     {
1051         serializer->doBool(&ir->useMts);
1052         int numLevels = ir->mtsLevels.size();
1053         if (ir->useMts)
1054         {
1055             serializer->doInt(&numLevels);
1056         }
1057         ir->mtsLevels.resize(numLevels);
1058         for (auto& mtsLevel : ir->mtsLevels)
1059         {
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);
1064         }
1065     }
1066     else
1067     {
1068         ir->useMts = false;
1069         ir->mtsLevels.clear();
1070     }
1071
1072     if (file_version >= 67)
1073     {
1074         serializer->doInt(&ir->nstcalcenergy);
1075     }
1076     else
1077     {
1078         ir->nstcalcenergy = 1;
1079     }
1080     if (file_version >= 81)
1081     {
1082         serializer->doEnumAsInt(&ir->cutoff_scheme);
1083         if (file_version < 94)
1084         {
1085             // Need to invert the scheme order
1086             switch (ir->cutoff_scheme)
1087             {
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");
1091             }
1092         }
1093     }
1094     else
1095     {
1096         ir->cutoff_scheme = CutoffScheme::Group;
1097     }
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 */
1101
1102     serializer->doReal(&ir->rtpi);
1103
1104     serializer->doInt(&ir->nstcomm);
1105     serializer->doEnumAsInt(&ir->comm_mode);
1106
1107     /* ignore nstcheckpoint */
1108     if (file_version < tpxv_RemoveObsoleteParameters1)
1109     {
1110         serializer->doInt(&idum);
1111     }
1112
1113     serializer->doInt(&ir->nstcgsteep);
1114
1115     serializer->doInt(&ir->nbfgscorr);
1116
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)
1124     {
1125         serializer->doDouble(&ir->init_t);
1126         serializer->doDouble(&ir->delta_t);
1127     }
1128     else
1129     {
1130         serializer->doReal(&rdum);
1131         ir->init_t = rdum;
1132         serializer->doReal(&rdum);
1133         ir->delta_t = rdum;
1134     }
1135     serializer->doReal(&ir->x_compression_precision);
1136     if (file_version >= 81)
1137     {
1138         serializer->doReal(&ir->verletbuf_tol);
1139     }
1140     else
1141     {
1142         ir->verletbuf_tol = 0;
1143     }
1144     serializer->doReal(&ir->rlist);
1145     if (file_version >= 67 && file_version < tpxv_RemoveTwinRange)
1146     {
1147         if (serializer->reading())
1148         {
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);
1153
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).
1157             //
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.
1162         }
1163     }
1164     else
1165     {
1166         // No need to read or write anything
1167         ir->useTwinRange = false;
1168     }
1169     if (file_version >= 82 && file_version != 90)
1170     {
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);
1176     }
1177     serializer->doEnumAsInt(&ir->coulombtype);
1178     if (file_version >= 81)
1179     {
1180         serializer->doEnumAsInt(&ir->coulomb_modifier);
1181     }
1182     else
1183     {
1184         ir->coulomb_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
1185                                                                           : InteractionModifiers::None);
1186     }
1187     serializer->doReal(&ir->rcoulomb_switch);
1188     serializer->doReal(&ir->rcoulomb);
1189     serializer->doEnumAsInt(&ir->vdwtype);
1190     if (file_version >= 81)
1191     {
1192         serializer->doEnumAsInt(&ir->vdw_modifier);
1193     }
1194     else
1195     {
1196         ir->vdw_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
1197                                                                       : InteractionModifiers::None);
1198     }
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);
1205
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())
1209     {
1210         if (file_version < tpxv_RemoveImplicitSolvation)
1211         {
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);
1218         }
1219         else
1220         {
1221             ir->implicit_solvent = false;
1222         }
1223         if (file_version < tpxv_RemoveImplicitSolvation)
1224         {
1225             serializer->doReal(&rdum);
1226             serializer->doReal(&rdum);
1227             serializer->doReal(&rdum);
1228             serializer->doReal(&rdum);
1229             if (file_version >= 60)
1230             {
1231                 serializer->doReal(&rdum);
1232                 serializer->doInt(&idum);
1233             }
1234             serializer->doReal(&rdum);
1235         }
1236     }
1237
1238     if (file_version >= 81)
1239     {
1240         serializer->doReal(&ir->fourier_spacing);
1241     }
1242     else
1243     {
1244         ir->fourier_spacing = 0.0;
1245     }
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);
1251
1252     if (file_version >= 93)
1253     {
1254         serializer->doReal(&ir->ewald_rtol_lj);
1255     }
1256     else
1257     {
1258         ir->ewald_rtol_lj = ir->ewald_rtol;
1259     }
1260     serializer->doEnumAsInt(&ir->ewald_geometry);
1261     serializer->doReal(&ir->epsilon_surface);
1262
1263     /* ignore bOptFFT */
1264     if (file_version < tpxv_RemoveObsoleteParameters1)
1265     {
1266         serializer->doBool(&bdum);
1267     }
1268
1269     if (file_version >= 93)
1270     {
1271         serializer->doEnumAsInt(&ir->ljpme_combination_rule);
1272     }
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.
1278      */
1279     if (file_version >= 79)
1280     {
1281         serializer->doBool(&ir->bPrintNHChains);
1282     }
1283     if (file_version >= 71)
1284     {
1285         serializer->doInt(&ir->nsttcouple);
1286     }
1287     else
1288     {
1289         ir->nsttcouple = ir->nstcalcenergy;
1290     }
1291     serializer->doEnumAsInt(&ir->epc);
1292     serializer->doEnumAsInt(&ir->epct);
1293     if (file_version >= 71)
1294     {
1295         serializer->doInt(&ir->nstpcouple);
1296     }
1297     else
1298     {
1299         ir->nstpcouple = ir->nstcalcenergy;
1300     }
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);
1311
1312     if (file_version < 79)
1313     {
1314         serializer->doInt(&ir->andersen_seed);
1315     }
1316     else
1317     {
1318         ir->andersen_seed = 0;
1319     }
1320
1321     serializer->doReal(&ir->shake_tol);
1322
1323     serializer->doEnumAsInt(&ir->efep);
1324     if (serializer->reading())
1325     {
1326         ir->fepvals = std::make_unique<t_lambda>();
1327     }
1328     do_fepvals(serializer, ir->fepvals.get(), file_version);
1329
1330     if (file_version >= 79)
1331     {
1332         serializer->doBool(&ir->bSimTemp);
1333         if (ir->bSimTemp)
1334         {
1335             ir->bSimTemp = TRUE;
1336         }
1337     }
1338     else
1339     {
1340         ir->bSimTemp = FALSE;
1341     }
1342     if (ir->bSimTemp)
1343     {
1344         if (serializer->reading())
1345         {
1346             ir->simtempvals = std::make_unique<t_simtemp>();
1347         }
1348         do_simtempvals(serializer, ir->simtempvals.get(), ir->fepvals->n_lambda, file_version);
1349     }
1350
1351     if (file_version >= 79)
1352     {
1353         serializer->doBool(&ir->bExpanded);
1354     }
1355     if (ir->bExpanded)
1356     {
1357         if (serializer->reading())
1358         {
1359             ir->expandedvals = std::make_unique<t_expanded>();
1360         }
1361         do_expandedvals(serializer, ir->expandedvals.get(), ir->fepvals.get(), file_version);
1362     }
1363
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);
1373
1374     /* ignore dihre_fc */
1375     if (file_version < 79)
1376     {
1377         serializer->doReal(&rdum);
1378     }
1379
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)
1391     {
1392         serializer->doInt64(&ir->ld_seed);
1393     }
1394     else
1395     {
1396         serializer->doInt(&idum);
1397         ir->ld_seed = idum;
1398     }
1399
1400     for (i = 0; i < DIM; i++)
1401     {
1402         serializer->doRvec(&ir->deform[i]);
1403     }
1404     serializer->doReal(&ir->cos_accel);
1405
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);
1414
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)
1418     {
1419         serializer->doBool(&ir->bAdress);
1420         if (ir->bAdress)
1421         {
1422             int  idum, numThermoForceGroups, numEnergyGroups;
1423             real rdum;
1424             rvec rvecdum;
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);
1436
1437             if (numThermoForceGroups > 0)
1438             {
1439                 std::vector<int> idumn(numThermoForceGroups);
1440                 serializer->doIntArray(idumn.data(), idumn.size());
1441             }
1442             if (numEnergyGroups > 0)
1443             {
1444                 std::vector<int> idumn(numEnergyGroups);
1445                 serializer->doIntArray(idumn.data(), idumn.size());
1446             }
1447         }
1448     }
1449     else
1450     {
1451         ir->bAdress = FALSE;
1452     }
1453
1454     /* pull stuff */
1455     {
1456         PullingAlgorithm ePullOld = PullingAlgorithm::Umbrella;
1457
1458         if (file_version >= tpxv_PullCoordTypeGeom)
1459         {
1460             serializer->doBool(&ir->bPull);
1461         }
1462         else
1463         {
1464             serializer->doEnumAsInt(&ePullOld);
1465             ir->bPull = (ePullOld != PullingAlgorithm::Umbrella);
1466             /* We removed the first ePull=ePullNo for the enum */
1467             switch (ePullOld)
1468             {
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;
1473                     break;
1474                 case (PullingAlgorithm::FlatBottom):
1475                     ePullOld = PullingAlgorithm::ConstantForce;
1476                     break;
1477                 case (PullingAlgorithm::FlatBottomHigh):
1478                     ePullOld = PullingAlgorithm::FlatBottom;
1479                     break;
1480                 case (PullingAlgorithm::External):
1481                     ePullOld = PullingAlgorithm::FlatBottomHigh;
1482                     break;
1483                 case (PullingAlgorithm::Count): ePullOld = PullingAlgorithm::External; break;
1484                 default: GMX_RELEASE_ASSERT(false, "Unhandled old pull algorithm");
1485             }
1486         }
1487         if (ir->bPull)
1488         {
1489             if (serializer->reading())
1490             {
1491                 ir->pull = std::make_unique<pull_params_t>();
1492             }
1493             do_pull(serializer, ir->pull.get(), file_version, ePullOld);
1494         }
1495     }
1496
1497     if (file_version >= tpxv_AcceleratedWeightHistogram)
1498     {
1499         serializer->doBool(&ir->bDoAwh);
1500
1501         if (ir->bDoAwh)
1502         {
1503             if (serializer->reading())
1504             {
1505                 ir->awhParams = std::make_unique<gmx::AwhParams>(serializer);
1506             }
1507             else
1508             {
1509                 ir->awhParams->serialize(serializer);
1510             }
1511         }
1512     }
1513     else
1514     {
1515         ir->bDoAwh = FALSE;
1516     }
1517
1518     /* Enforced rotation */
1519     if (file_version >= 74)
1520     {
1521         serializer->doBool(&ir->bRot);
1522         if (ir->bRot)
1523         {
1524             if (serializer->reading())
1525             {
1526                 snew(ir->rot, 1);
1527             }
1528             do_rot(serializer, ir->rot);
1529         }
1530     }
1531     else
1532     {
1533         ir->bRot = FALSE;
1534     }
1535
1536     /* Interactive molecular dynamics */
1537     if (file_version >= tpxv_InteractiveMolecularDynamics)
1538     {
1539         serializer->doBool(&ir->bIMD);
1540         if (ir->bIMD)
1541         {
1542             if (serializer->reading())
1543             {
1544                 snew(ir->imd, 1);
1545             }
1546             do_imd(serializer, ir->imd);
1547         }
1548     }
1549     else
1550     {
1551         /* We don't support IMD sessions for old .tpr files */
1552         ir->bIMD = FALSE;
1553     }
1554
1555     /* grpopts stuff */
1556     serializer->doInt(&ir->opts.ngtc);
1557     if (file_version >= 69)
1558     {
1559         serializer->doInt(&ir->opts.nhchainlength);
1560     }
1561     else
1562     {
1563         ir->opts.nhchainlength = 1;
1564     }
1565     int removedOptsNgacc = 0;
1566     if (serializer->reading() && file_version < tpxv_RemovedConstantAcceleration)
1567     {
1568         serializer->doInt(&removedOptsNgacc);
1569     }
1570     serializer->doInt(&ir->opts.ngfrz);
1571     serializer->doInt(&ir->opts.ngener);
1572
1573     if (serializer->reading())
1574     {
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);
1584     }
1585     if (ir->opts.ngtc > 0)
1586     {
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);
1590     }
1591     if (ir->opts.ngfrz > 0)
1592     {
1593         serializer->doIvecArray(ir->opts.nFreeze, ir->opts.ngfrz);
1594     }
1595     if (serializer->reading() && file_version < tpxv_RemovedConstantAcceleration && removedOptsNgacc > 0)
1596     {
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;
1602         });
1603     }
1604     else
1605     {
1606         ir->useConstantAcceleration = false;
1607     }
1608     serializer->doIntArray(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
1609
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++)
1614     {
1615         k = ir->opts.anneal_npoints[j];
1616         if (serializer->reading())
1617         {
1618             snew(ir->opts.anneal_time[j], k);
1619             snew(ir->opts.anneal_temp[j], k);
1620         }
1621         serializer->doRealArray(ir->opts.anneal_time[j], k);
1622         serializer->doRealArray(ir->opts.anneal_temp[j], k);
1623     }
1624     /* Walls */
1625     {
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);
1634     }
1635
1636     /* Cosine stuff for electric fields */
1637     if (file_version < tpxv_GenericParamsForElectricField)
1638     {
1639         do_legacy_efield(serializer, &paramsObj);
1640     }
1641
1642     /* Swap ions */
1643     if (file_version >= tpxv_ComputationalElectrophysiology)
1644     {
1645         serializer->doEnumAsInt(&ir->eSwapCoords);
1646         if (ir->eSwapCoords != SwapType::No)
1647         {
1648             if (serializer->reading())
1649             {
1650                 snew(ir->swap, 1);
1651             }
1652             do_swapcoords_tpx(serializer, ir->swap, file_version);
1653         }
1654     }
1655
1656     /* QMMM reading - despite defunct we require reading for backwards
1657      * compability and correct serialization
1658      */
1659     {
1660         serializer->doBool(&ir->bQMMM);
1661         int qmmmScheme;
1662         serializer->doInt(&qmmmScheme);
1663         real unusedScalefactor;
1664         serializer->doReal(&unusedScalefactor);
1665
1666         // this is still used in Mimic
1667         serializer->doInt(&ir->opts.ngQM);
1668         if (ir->opts.ngQM > 0 && ir->bQMMM)
1669         {
1670             /* We leave in dummy i/o for removed parameters to avoid
1671              * changing the tpr format.
1672              */
1673             std::vector<int> dummyIntVec(4 * ir->opts.ngQM, 0);
1674             serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1675             dummyIntVec.clear();
1676
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();
1681
1682             dummyIntVec.resize(2 * ir->opts.ngQM, 0);
1683             serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1684             dummyIntVec.clear();
1685
1686             std::vector<real> dummyRealVec(2 * ir->opts.ngQM, 0);
1687             serializer->doRealArray(dummyRealVec.data(), dummyRealVec.size());
1688             dummyRealVec.clear();
1689
1690             dummyIntVec.resize(3 * ir->opts.ngQM, 0);
1691             serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1692             dummyIntVec.clear();
1693         }
1694         /* end of QMMM stuff */
1695     }
1696
1697     if (file_version >= tpxv_GenericParamsForElectricField)
1698     {
1699         if (serializer->reading())
1700         {
1701             paramsObj.mergeObject(gmx::deserializeKeyValueTree(serializer));
1702         }
1703         else
1704         {
1705             GMX_RELEASE_ASSERT(ir->params != nullptr,
1706                                "Parameters should be present when writing inputrec");
1707             gmx::serializeKeyValueTree(*ir->params, serializer);
1708         }
1709     }
1710     if (serializer->reading())
1711     {
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>();
1715     }
1716
1717     if (file_version >= tpxv_GenericInternalParameters)
1718     {
1719         if (serializer->reading())
1720         {
1721             ir->internalParameters =
1722                     std::make_unique<gmx::KeyValueTreeObject>(gmx::deserializeKeyValueTree(serializer));
1723         }
1724         else
1725         {
1726             GMX_RELEASE_ASSERT(ir->internalParameters != nullptr,
1727                                "Parameters should be present when writing inputrec");
1728             gmx::serializeKeyValueTree(*ir->internalParameters, serializer);
1729         }
1730     }
1731 }
1732
1733
1734 static void do_harm(gmx::ISerializer* serializer, t_iparams* iparams)
1735 {
1736     serializer->doReal(&iparams->harmonic.rA);
1737     serializer->doReal(&iparams->harmonic.krA);
1738     serializer->doReal(&iparams->harmonic.rB);
1739     serializer->doReal(&iparams->harmonic.krB);
1740 }
1741
1742 static void do_iparams(gmx::ISerializer* serializer, t_functype ftype, t_iparams* iparams, int file_version)
1743 {
1744     int  idum;
1745     real rdum;
1746
1747     switch (ftype)
1748     {
1749         case F_ANGLES:
1750         case F_G96ANGLES:
1751         case F_BONDS:
1752         case F_G96BONDS:
1753         case F_HARMONIC:
1754         case F_IDIHS:
1755             do_harm(serializer, iparams);
1756             if ((ftype == F_ANGRES || ftype == F_ANGRESZ) && serializer->reading())
1757             {
1758                 /* Correct incorrect storage of parameters */
1759                 iparams->pdihs.phiB = iparams->pdihs.phiA;
1760                 iparams->pdihs.cpB  = iparams->pdihs.cpA;
1761             }
1762             break;
1763         case F_RESTRANGLES:
1764             serializer->doReal(&iparams->harmonic.rA);
1765             serializer->doReal(&iparams->harmonic.krA);
1766             break;
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);
1772             break;
1773         case F_FENEBONDS:
1774             serializer->doReal(&iparams->fene.bm);
1775             serializer->doReal(&iparams->fene.kb);
1776             break;
1777
1778         case F_RESTRBONDS:
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);
1787             break;
1788         case F_TABBONDS:
1789         case F_TABBONDSNC:
1790         case F_TABANGLES:
1791         case F_TABDIHS:
1792             serializer->doReal(&iparams->tab.kA);
1793             serializer->doInt(&iparams->tab.table);
1794             serializer->doReal(&iparams->tab.kB);
1795             break;
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);
1800             break;
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);
1806             break;
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)
1813             {
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);
1818             }
1819             else
1820             {
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;
1825             }
1826             break;
1827         case F_QUARTIC_ANGLES:
1828             serializer->doReal(&iparams->qangle.theta);
1829             serializer->doRealArray(iparams->qangle.c, 5);
1830             break;
1831         case F_BHAM:
1832             serializer->doReal(&iparams->bham.a);
1833             serializer->doReal(&iparams->bham.b);
1834             serializer->doReal(&iparams->bham.c);
1835             break;
1836         case F_MORSE:
1837             serializer->doReal(&iparams->morse.b0A);
1838             serializer->doReal(&iparams->morse.cbA);
1839             serializer->doReal(&iparams->morse.betaA);
1840             if (file_version >= 79)
1841             {
1842                 serializer->doReal(&iparams->morse.b0B);
1843                 serializer->doReal(&iparams->morse.cbB);
1844                 serializer->doReal(&iparams->morse.betaB);
1845             }
1846             else
1847             {
1848                 iparams->morse.b0B   = iparams->morse.b0A;
1849                 iparams->morse.cbB   = iparams->morse.cbA;
1850                 iparams->morse.betaB = iparams->morse.betaA;
1851             }
1852             break;
1853         case F_CUBICBONDS:
1854             serializer->doReal(&iparams->cubic.b0);
1855             serializer->doReal(&iparams->cubic.kb);
1856             serializer->doReal(&iparams->cubic.kcub);
1857             break;
1858         case F_CONNBONDS: break;
1859         case F_POLARIZATION: serializer->doReal(&iparams->polarize.alpha); break;
1860         case F_ANHARM_POL:
1861             serializer->doReal(&iparams->anharm_polarize.alpha);
1862             serializer->doReal(&iparams->anharm_polarize.drcut);
1863             serializer->doReal(&iparams->anharm_polarize.khyp);
1864             break;
1865         case F_WATER_POL:
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);
1872             break;
1873         case F_THOLE_POL:
1874             serializer->doReal(&iparams->thole.a);
1875             serializer->doReal(&iparams->thole.alpha1);
1876             serializer->doReal(&iparams->thole.alpha2);
1877             serializer->doReal(&iparams->thole.rfac);
1878             break;
1879         case F_LJ:
1880             serializer->doReal(&iparams->lj.c6);
1881             serializer->doReal(&iparams->lj.c12);
1882             break;
1883         case F_LJ14:
1884             serializer->doReal(&iparams->lj14.c6A);
1885             serializer->doReal(&iparams->lj14.c12A);
1886             serializer->doReal(&iparams->lj14.c6B);
1887             serializer->doReal(&iparams->lj14.c12B);
1888             break;
1889         case F_LJC14_Q:
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);
1895             break;
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);
1901             break;
1902         case F_PDIHS:
1903         case F_PIDIHS:
1904         case F_ANGRES:
1905         case F_ANGRESZ:
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);
1911             break;
1912         case F_RESTRDIHS:
1913             serializer->doReal(&iparams->pdihs.phiA);
1914             serializer->doReal(&iparams->pdihs.cpA);
1915             break;
1916         case F_DISRES:
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);
1923             break;
1924         case F_ORIRES:
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);
1931             break;
1932         case F_DIHRES:
1933             if (file_version < 82)
1934             {
1935                 serializer->doInt(&idum);
1936                 serializer->doInt(&idum);
1937             }
1938             serializer->doReal(&iparams->dihres.phiA);
1939             serializer->doReal(&iparams->dihres.dphiA);
1940             serializer->doReal(&iparams->dihres.kfacA);
1941             if (file_version >= 82)
1942             {
1943                 serializer->doReal(&iparams->dihres.phiB);
1944                 serializer->doReal(&iparams->dihres.dphiB);
1945                 serializer->doReal(&iparams->dihres.kfacB);
1946             }
1947             else
1948             {
1949                 iparams->dihres.phiB  = iparams->dihres.phiA;
1950                 iparams->dihres.dphiB = iparams->dihres.dphiA;
1951                 iparams->dihres.kfacB = iparams->dihres.kfacA;
1952             }
1953             break;
1954         case F_POSRES:
1955             serializer->doRvec(&iparams->posres.pos0A);
1956             serializer->doRvec(&iparams->posres.fcA);
1957             serializer->doRvec(&iparams->posres.pos0B);
1958             serializer->doRvec(&iparams->posres.fcB);
1959             break;
1960         case F_FBPOSRES:
1961             serializer->doInt(&iparams->fbposres.geom);
1962             serializer->doRvec(&iparams->fbposres.pos0);
1963             serializer->doReal(&iparams->fbposres.r);
1964             serializer->doReal(&iparams->fbposres.k);
1965             break;
1966         case F_CBTDIHS: serializer->doRealArray(iparams->cbtdihs.cbtcA, NR_CBTDIHS); break;
1967         case F_RBDIHS:
1968             // Fall-through intended
1969         case F_FOURDIHS:
1970             /* Fourier dihedrals are internally represented
1971              * as Ryckaert-Bellemans since those are faster to compute.
1972              */
1973             serializer->doRealArray(iparams->rbdihs.rbcA, NR_RBDIHS);
1974             serializer->doRealArray(iparams->rbdihs.rbcB, NR_RBDIHS);
1975             break;
1976         case F_CONSTR:
1977         case F_CONSTRNC:
1978             serializer->doReal(&iparams->constr.dA);
1979             serializer->doReal(&iparams->constr.dB);
1980             break;
1981         case F_SETTLE:
1982             serializer->doReal(&iparams->settle.doh);
1983             serializer->doReal(&iparams->settle.dhh);
1984             break;
1985         case F_VSITE1: break; // VSite1 has 0 parameters
1986         case F_VSITE2:
1987         case F_VSITE2FD: serializer->doReal(&iparams->vsite.a); break;
1988         case F_VSITE3:
1989         case F_VSITE3FD:
1990         case F_VSITE3FAD:
1991             serializer->doReal(&iparams->vsite.a);
1992             serializer->doReal(&iparams->vsite.b);
1993             break;
1994         case F_VSITE3OUT:
1995         case F_VSITE4FD:
1996         case F_VSITE4FDN:
1997             serializer->doReal(&iparams->vsite.a);
1998             serializer->doReal(&iparams->vsite.b);
1999             serializer->doReal(&iparams->vsite.c);
2000             break;
2001         case F_VSITEN:
2002             serializer->doInt(&iparams->vsiten.n);
2003             serializer->doReal(&iparams->vsiten.a);
2004             break;
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())
2010             {
2011                 if (file_version < 68)
2012                 {
2013                     serializer->doReal(&rdum);
2014                     serializer->doReal(&rdum);
2015                     serializer->doReal(&rdum);
2016                     serializer->doReal(&rdum);
2017                 }
2018                 if (file_version < tpxv_RemoveImplicitSolvation)
2019                 {
2020                     serializer->doReal(&rdum);
2021                     serializer->doReal(&rdum);
2022                     serializer->doReal(&rdum);
2023                     serializer->doReal(&rdum);
2024                     serializer->doReal(&rdum);
2025                 }
2026             }
2027             break;
2028         case F_CMAP:
2029             serializer->doInt(&iparams->cmap.cmapA);
2030             serializer->doInt(&iparams->cmap.cmapB);
2031             break;
2032         default:
2033             gmx_fatal(FARGS,
2034                       "unknown function type %d (%s) in %s line %d",
2035                       ftype,
2036                       interaction_function[ftype].name,
2037                       __FILE__,
2038                       __LINE__);
2039     }
2040 }
2041
2042 static void do_ilist(gmx::ISerializer* serializer, InteractionList* ilist)
2043 {
2044     int nr = ilist->size();
2045     serializer->doInt(&nr);
2046     if (serializer->reading())
2047     {
2048         ilist->iatoms.resize(nr);
2049     }
2050     serializer->doIntArray(ilist->iatoms.data(), ilist->size());
2051 }
2052
2053 static void do_ffparams(gmx::ISerializer* serializer, gmx_ffparams_t* ffparams, int file_version)
2054 {
2055     serializer->doInt(&ffparams->atnr);
2056     int numTypes = ffparams->numTypes();
2057     serializer->doInt(&numTypes);
2058     if (serializer->reading())
2059     {
2060         ffparams->functype.resize(numTypes);
2061         ffparams->iparams.resize(numTypes);
2062     }
2063     /* Read/write all the function types */
2064     serializer->doIntArray(ffparams->functype.data(), ffparams->functype.size());
2065
2066     if (file_version >= 66)
2067     {
2068         serializer->doDouble(&ffparams->reppow);
2069     }
2070     else
2071     {
2072         ffparams->reppow = 12.0;
2073     }
2074
2075     serializer->doReal(&ffparams->fudgeQQ);
2076
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
2080      */
2081     for (int i = 0; i < ffparams->numTypes(); i++)
2082     {
2083         if (serializer->reading())
2084         {
2085             /* Loop over file versions */
2086             for (int k = 0; k < NFTUPD; k++)
2087             {
2088                 /* Compare the read file_version to the update table */
2089                 if ((file_version < ftupd[k].fvnr) && (ffparams->functype[i] >= ftupd[k].ftype))
2090                 {
2091                     ffparams->functype[i] += 1;
2092                 }
2093             }
2094         }
2095
2096         do_iparams(serializer, ffparams->functype[i], &ffparams->iparams[i], file_version);
2097     }
2098 }
2099
2100 static void add_settle_atoms(InteractionList* ilist)
2101 {
2102     int i;
2103
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--)
2107     {
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;
2112     }
2113 }
2114
2115 static void do_ilists(gmx::ISerializer* serializer, InteractionLists* ilists, int file_version)
2116 {
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");
2120
2121     for (int j = 0; j < F_NRE; j++)
2122     {
2123         InteractionList& ilist  = (*ilists)[j];
2124         gmx_bool         bClear = FALSE;
2125         if (serializer->reading())
2126         {
2127             for (int k = 0; k < NFTUPD; k++)
2128             {
2129                 if ((file_version < ftupd[k].fvnr) && (j == ftupd[k].ftype))
2130                 {
2131                     bClear = TRUE;
2132                 }
2133             }
2134         }
2135         if (bClear)
2136         {
2137             ilist.iatoms.clear();
2138         }
2139         else
2140         {
2141             do_ilist(serializer, &ilist);
2142             if (file_version < 78 && j == F_SETTLE && !ilist.empty())
2143             {
2144                 add_settle_atoms(&ilist);
2145             }
2146         }
2147     }
2148 }
2149
2150 static void do_block(gmx::ISerializer* serializer, t_block* block)
2151 {
2152     serializer->doInt(&block->nr);
2153     if (serializer->reading())
2154     {
2155         if ((block->nalloc_index > 0) && (nullptr != block->index))
2156         {
2157             sfree(block->index);
2158         }
2159         block->nalloc_index = block->nr + 1;
2160         snew(block->index, block->nalloc_index);
2161     }
2162     serializer->doIntArray(block->index, block->nr + 1);
2163 }
2164
2165 static void doListOfLists(gmx::ISerializer* serializer, gmx::ListOfLists<int>* listOfLists)
2166 {
2167     int numLists = listOfLists->ssize();
2168     serializer->doInt(&numLists);
2169     int numElements = listOfLists->elementsView().ssize();
2170     serializer->doInt(&numElements);
2171     if (serializer->reading())
2172     {
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));
2178     }
2179     else
2180     {
2181         serializer->doIntArray(const_cast<int*>(listOfLists->listRangesView().data()), numLists + 1);
2182         serializer->doIntArray(const_cast<int*>(listOfLists->elementsView().data()), numElements);
2183     }
2184 }
2185
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).
2189  */
2190 static const char* atomicnumber_to_element(int atomicnumber)
2191 {
2192     const char* p;
2193
2194     /* This does not have to be complete, so we only include elements likely
2195      * to occur in PDB files.
2196      */
2197     switch (atomicnumber)
2198     {
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;
2221     }
2222     return p;
2223 }
2224
2225
2226 static void do_atom(gmx::ISerializer* serializer, t_atom* atom)
2227 {
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())
2238     {
2239         /* Set element string from atomic number if present.
2240          * This routine returns an empty string if the name is not found.
2241          */
2242         std::strncpy(atom->elem, atomicnumber_to_element(atom->atomnumber), 4);
2243         /* avoid warnings about potentially unterminated string */
2244         atom->elem[3] = '\0';
2245     }
2246 }
2247
2248 static void do_grps(gmx::ISerializer* serializer, gmx::ArrayRef<AtomGroupIndices> grps)
2249 {
2250     for (auto& group : grps)
2251     {
2252         int size = group.size();
2253         serializer->doInt(&size);
2254         if (serializer->reading())
2255         {
2256             group.resize(size);
2257         }
2258         serializer->doIntArray(group.data(), size);
2259     }
2260 }
2261
2262 static void do_symstr(gmx::ISerializer* serializer, char*** nm, t_symtab* symtab)
2263 {
2264     int ls;
2265
2266     if (serializer->reading())
2267     {
2268         serializer->doInt(&ls);
2269         *nm = get_symtab_handle(symtab, ls);
2270     }
2271     else
2272     {
2273         ls = lookup_symtab(symtab, *nm);
2274         serializer->doInt(&ls);
2275     }
2276 }
2277
2278 static void do_strstr(gmx::ISerializer* serializer, int nstr, char*** nm, t_symtab* symtab)
2279 {
2280     int j;
2281
2282     for (j = 0; (j < nstr); j++)
2283     {
2284         do_symstr(serializer, &(nm[j]), symtab);
2285     }
2286 }
2287
2288 static void do_resinfo(gmx::ISerializer* serializer, int n, t_resinfo* ri, t_symtab* symtab, int file_version)
2289 {
2290     int j;
2291
2292     for (j = 0; (j < n); j++)
2293     {
2294         do_symstr(serializer, &(ri[j].name), symtab);
2295         if (file_version >= 63)
2296         {
2297             serializer->doInt(&ri[j].nr);
2298             serializer->doUChar(&ri[j].ic);
2299         }
2300         else
2301         {
2302             ri[j].nr = j + 1;
2303             ri[j].ic = ' ';
2304         }
2305     }
2306 }
2307
2308 static void do_atoms(gmx::ISerializer* serializer, t_atoms* atoms, t_symtab* symtab, int file_version)
2309 {
2310     int i;
2311
2312     serializer->doInt(&atoms->nr);
2313     serializer->doInt(&atoms->nres);
2314     if (serializer->reading())
2315     {
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.
2319          */
2320         atoms->haveMass    = TRUE;
2321         atoms->haveCharge  = TRUE;
2322         atoms->haveType    = TRUE;
2323         atoms->haveBState  = TRUE;
2324         atoms->havePdbInfo = FALSE;
2325
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;
2332     }
2333     else
2334     {
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");
2338     }
2339     for (i = 0; (i < atoms->nr); i++)
2340     {
2341         do_atom(serializer, &atoms->atom[i]);
2342     }
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);
2346
2347     do_resinfo(serializer, atoms->nres, atoms->resinfo, symtab, file_version);
2348 }
2349
2350 static void do_groups(gmx::ISerializer* serializer, SimulationGroups* groups, t_symtab* symtab)
2351 {
2352     do_grps(serializer, groups->groups);
2353     int numberOfGroupNames = groups->groupNames.size();
2354     serializer->doInt(&numberOfGroupNames);
2355     if (serializer->reading())
2356     {
2357         groups->groupNames.resize(numberOfGroupNames);
2358     }
2359     do_strstr(serializer, numberOfGroupNames, groups->groupNames.data(), symtab);
2360     for (auto group : gmx::keysOf(groups->groupNumbers))
2361     {
2362         int numberOfGroupNumbers = groups->numberOfGroupNumbers(group);
2363         serializer->doInt(&numberOfGroupNumbers);
2364         if (numberOfGroupNumbers != 0)
2365         {
2366             if (serializer->reading())
2367             {
2368                 groups->groupNumbers[group].resize(numberOfGroupNumbers);
2369             }
2370             serializer->doUCharArray(groups->groupNumbers[group].data(), numberOfGroupNumbers);
2371         }
2372     }
2373 }
2374
2375 static void do_atomtypes(gmx::ISerializer* serializer, t_atomtypes* atomtypes, int file_version)
2376 {
2377     int j;
2378
2379     serializer->doInt(&atomtypes->nr);
2380     j = atomtypes->nr;
2381     if (serializer->reading())
2382     {
2383         snew(atomtypes->atomnumber, j);
2384     }
2385     if (serializer->reading() && file_version < tpxv_RemoveImplicitSolvation)
2386     {
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());
2391     }
2392     serializer->doIntArray(atomtypes->atomnumber, j);
2393
2394     if (serializer->reading() && file_version >= 60 && file_version < tpxv_RemoveImplicitSolvation)
2395     {
2396         std::vector<real> dummy(atomtypes->nr, 0);
2397         serializer->doRealArray(dummy.data(), dummy.size());
2398         serializer->doRealArray(dummy.data(), dummy.size());
2399     }
2400 }
2401
2402 static void do_symtab(gmx::ISerializer* serializer, t_symtab* symtab)
2403 {
2404     int       i, nr;
2405     t_symbuf* symbuf;
2406
2407     serializer->doInt(&symtab->nr);
2408     nr = symtab->nr;
2409     if (serializer->reading())
2410     {
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++)
2416         {
2417             std::string buf;
2418             serializer->doString(&buf);
2419             symbuf->buf[i] = gmx_strdup(buf.c_str());
2420         }
2421     }
2422     else
2423     {
2424         symbuf = symtab->symbuf;
2425         while (symbuf != nullptr)
2426         {
2427             for (i = 0; (i < symbuf->bufsize) && (i < nr); i++)
2428             {
2429                 std::string buf = symbuf->buf[i];
2430                 serializer->doString(&buf);
2431             }
2432             nr -= i;
2433             symbuf = symbuf->next;
2434         }
2435         if (nr != 0)
2436         {
2437             gmx_fatal(FARGS, "nr of symtab strings left: %d", nr);
2438         }
2439     }
2440 }
2441
2442 static void do_cmap(gmx::ISerializer* serializer, gmx_cmap_t* cmap_grid)
2443 {
2444
2445     int ngrid = cmap_grid->cmapdata.size();
2446     serializer->doInt(&ngrid);
2447     serializer->doInt(&cmap_grid->grid_spacing);
2448
2449     int gs    = cmap_grid->grid_spacing;
2450     int nelem = gs * gs;
2451
2452     if (serializer->reading())
2453     {
2454         cmap_grid->cmapdata.resize(ngrid);
2455
2456         for (int i = 0; i < ngrid; i++)
2457         {
2458             cmap_grid->cmapdata[i].cmap.resize(4 * nelem);
2459         }
2460     }
2461
2462     for (int i = 0; i < ngrid; i++)
2463     {
2464         for (int j = 0; j < nelem; j++)
2465         {
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]);
2470         }
2471     }
2472 }
2473
2474
2475 static void do_moltype(gmx::ISerializer* serializer, gmx_moltype_t* molt, t_symtab* symtab, int file_version)
2476 {
2477     do_symstr(serializer, &(molt->name), symtab);
2478
2479     do_atoms(serializer, &molt->atoms, symtab, file_version);
2480
2481     do_ilists(serializer, &molt->ilist, file_version);
2482
2483     /* TODO: Remove the obsolete charge group index from the file */
2484     t_block cgs;
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++)
2489     {
2490         cgs.index[i] = i;
2491     }
2492     do_block(serializer, &cgs);
2493     sfree(cgs.index);
2494
2495     /* This used to be in the atoms struct */
2496     doListOfLists(serializer, &molt->excls);
2497 }
2498
2499 static void do_molblock(gmx::ISerializer* serializer, gmx_molblock_t* molb, int numAtomsPerMolecule)
2500 {
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.
2506      */
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)
2512     {
2513         if (serializer->reading())
2514         {
2515             molb->posres_xA.resize(numPosres_xA);
2516         }
2517         serializer->doRvecArray(as_rvec_array(molb->posres_xA.data()), numPosres_xA);
2518     }
2519     int numPosres_xB = molb->posres_xB.size();
2520     serializer->doInt(&numPosres_xB);
2521     if (numPosres_xB > 0)
2522     {
2523         if (serializer->reading())
2524         {
2525             molb->posres_xB.resize(numPosres_xB);
2526         }
2527         serializer->doRvecArray(as_rvec_array(molb->posres_xB.data()), numPosres_xB);
2528     }
2529 }
2530
2531 static void set_disres_npair(gmx_mtop_t* mtop)
2532 {
2533     gmx::ArrayRef<t_iparams> ip = mtop->ffparams.iparams;
2534
2535     for (const auto ilist : IListRange(*mtop))
2536     {
2537         const InteractionList& il = ilist.list()[F_DISRES];
2538
2539         if (!il.empty())
2540         {
2541             gmx::ArrayRef<const int> a     = il.iatoms;
2542             int                      npair = 0;
2543             for (int i = 0; i < il.size(); i += 3)
2544             {
2545                 npair++;
2546                 if (i + 3 == il.size() || ip[a[i]].disres.label != ip[a[i + 3]].disres.label)
2547                 {
2548                     ip[a[i]].disres.npair = npair;
2549                     npair                 = 0;
2550                 }
2551             }
2552         }
2553     }
2554 }
2555
2556 static void do_mtop(gmx::ISerializer* serializer, gmx_mtop_t* mtop, int file_version)
2557 {
2558     do_symtab(serializer, &(mtop->symtab));
2559
2560     do_symstr(serializer, &(mtop->name), &(mtop->symtab));
2561
2562     do_ffparams(serializer, &mtop->ffparams, file_version);
2563
2564     int nmoltype = mtop->moltype.size();
2565     serializer->doInt(&nmoltype);
2566     if (serializer->reading())
2567     {
2568         mtop->moltype.resize(nmoltype);
2569     }
2570     for (gmx_moltype_t& moltype : mtop->moltype)
2571     {
2572         do_moltype(serializer, &moltype, &mtop->symtab, file_version);
2573     }
2574
2575     int nmolblock = mtop->molblock.size();
2576     serializer->doInt(&nmolblock);
2577     if (serializer->reading())
2578     {
2579         mtop->molblock.resize(nmolblock);
2580     }
2581     for (gmx_molblock_t& molblock : mtop->molblock)
2582     {
2583         int numAtomsPerMolecule = (serializer->reading() ? 0 : mtop->moltype[molblock.type].atoms.nr);
2584         do_molblock(serializer, &molblock, numAtomsPerMolecule);
2585     }
2586     serializer->doInt(&mtop->natoms);
2587
2588     if (file_version >= tpxv_IntermolecularBondeds)
2589     {
2590         serializer->doBool(&mtop->bIntermolecularInteractions);
2591         if (mtop->bIntermolecularInteractions)
2592         {
2593             if (serializer->reading())
2594             {
2595                 mtop->intermolecular_ilist = std::make_unique<InteractionLists>();
2596             }
2597             do_ilists(serializer, mtop->intermolecular_ilist.get(), file_version);
2598         }
2599     }
2600     else
2601     {
2602         mtop->bIntermolecularInteractions = FALSE;
2603     }
2604
2605     do_atomtypes(serializer, &(mtop->atomtypes), file_version);
2606
2607     if (file_version >= 65)
2608     {
2609         do_cmap(serializer, &mtop->ffparams.cmap_grid);
2610     }
2611     else
2612     {
2613         mtop->ffparams.cmap_grid.grid_spacing = 0;
2614         mtop->ffparams.cmap_grid.cmapdata.clear();
2615     }
2616
2617     do_groups(serializer, &mtop->groups, &(mtop->symtab));
2618     if (file_version < tpxv_RemovedConstantAcceleration)
2619     {
2620         mtop->groups.groups[SimulationAtomGroupType::AccelerationUnused].clear();
2621         mtop->groups.groupNumbers[SimulationAtomGroupType::AccelerationUnused].clear();
2622     }
2623
2624     mtop->haveMoleculeIndices = true;
2625
2626     if (file_version >= tpxv_StoreNonBondedInteractionExclusionGroup)
2627     {
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 "
2632                            "is negative.");
2633         mtop->intermolecularExclusionGroup.resize(intermolecularExclusionGroupSize); // no effect when writing
2634         serializer->doIntArray(mtop->intermolecularExclusionGroup.data(),
2635                                mtop->intermolecularExclusionGroup.size());
2636     }
2637
2638     if (serializer->reading())
2639     {
2640         close_symtab(&(mtop->symtab));
2641     }
2642 }
2643
2644 /*! \brief
2645  * Read the first part of the TPR file to find general system information.
2646  *
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.
2651  *
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.
2654  *
2655  * If possible, we will read the \p ir even when \p TopOnlyOK is true.
2656  *
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.
2662  */
2663 static void do_tpxheader(gmx::FileIOXdrSerializer* serializer,
2664                          TpxFileHeader*            tpx,
2665                          const char*               filename,
2666                          t_fileio*                 fio,
2667                          bool                      TopOnlyOK)
2668 {
2669     int  precision;
2670     int  idum = 0;
2671     real rdum = 0;
2672
2673     /* XDR binary topology file */
2674     precision = sizeof(real);
2675     std::string buf;
2676     std::string fileTag;
2677     if (serializer->reading())
2678     {
2679         serializer->doString(&buf);
2680         if (std::strncmp(buf.c_str(), "VERSION", 7) != 0)
2681         {
2682             gmx_fatal(
2683                     FARGS,
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",
2687                     filename);
2688         }
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)
2697         {
2698             gmx_fatal(FARGS,
2699                       "Unknown precision in file %s: real is %d bytes "
2700                       "instead of %zu or %zu",
2701                       filename,
2702                       precision,
2703                       sizeof(float),
2704                       sizeof(double));
2705         }
2706         gmx_fio_setprecision(fio, tpx->isDouble);
2707         fprintf(stderr,
2708                 "Reading file %s, %s (%s precision)\n",
2709                 filename,
2710                 buf.c_str(),
2711                 tpx->isDouble ? "double" : "single");
2712     }
2713     else
2714     {
2715         buf = gmx::formatString("VERSION %s", gmx_version());
2716         serializer->doString(&buf);
2717         gmx_fio_setprecision(fio, tpx->isDouble);
2718         serializer->doInt(&precision);
2719         fileTag = tpx_tag;
2720     }
2721
2722     /* Check versions! */
2723     serializer->doInt(&tpx->fileVersion);
2724
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.
2729      */
2730     if (tpx->fileVersion >= 77 && tpx->fileVersion <= 79)
2731     {
2732         serializer->doString(&fileTag);
2733     }
2734
2735     serializer->doInt(&tpx->fileGeneration);
2736
2737     if (tpx->fileVersion >= 81)
2738     {
2739         serializer->doString(&fileTag);
2740     }
2741     if (serializer->reading())
2742     {
2743         if (tpx->fileVersion < 77)
2744         {
2745             /* Versions before 77 don't have the tag, set it to release */
2746             fileTag = gmx::formatString("%s", TPX_TAG_RELEASE);
2747         }
2748
2749         if (fileTag != tpx_tag)
2750         {
2751             fprintf(stderr, "Note: file tpx tag '%s', software tpx tag '%s'\n", fileTag.c_str(), tpx_tag.c_str());
2752
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.
2755              */
2756             if (fileTag != TPX_TAG_RELEASE && tpx->fileVersion < tpx_version)
2757             {
2758                 gmx_fatal(FARGS,
2759                           "tpx tag/version mismatch: reading tpx file (%s) version %d, tag '%s' "
2760                           "with program for tpx version %d, tag '%s'",
2761                           filename,
2762                           tpx->fileVersion,
2763                           fileTag.c_str(),
2764                           tpx_version,
2765                           tpx_tag.c_str());
2766             }
2767         }
2768     }
2769
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*/
2773     {
2774         gmx_fatal(FARGS,
2775                   "reading tpx file (%s) version %d with version %d program",
2776                   filename,
2777                   tpx->fileVersion,
2778                   tpx_version);
2779     }
2780
2781     serializer->doInt(&tpx->natoms);
2782     serializer->doInt(&tpx->ngtc);
2783
2784     if (tpx->fileVersion < 62)
2785     {
2786         serializer->doInt(&idum);
2787         serializer->doReal(&rdum);
2788     }
2789     if (tpx->fileVersion >= 79)
2790     {
2791         serializer->doInt(&tpx->fep_state);
2792     }
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);
2800
2801     if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
2802     {
2803         if (!serializer->reading())
2804         {
2805             GMX_RELEASE_ASSERT(tpx->sizeOfTprBody != 0,
2806                                "Not possible to write new file with zero TPR body size");
2807         }
2808         serializer->doInt64(&tpx->sizeOfTprBody);
2809     }
2810
2811     if ((tpx->fileGeneration > tpx_generation))
2812     {
2813         /* This can only happen if TopOnlyOK=TRUE */
2814         tpx->bIr = FALSE;
2815     }
2816 }
2817
2818 #define do_test(serializer, b, p)                            \
2819     if ((serializer)->reading() && ((p) != nullptr) && !(b)) \
2820     gmx_fatal(FARGS, "No %s in input file", #p)
2821
2822 /*! \brief
2823  * Process the first part of the TPR into the state datastructure.
2824  *
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.
2829  *
2830  * See the documentation for do_tpx_body for the correct order of
2831  * the operations for reading a tpr file.
2832  *
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.
2836  */
2837 static void do_tpx_state_first(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state)
2838 {
2839     if (serializer->reading())
2840     {
2841         state->flags = 0;
2842         init_gtc_state(state, tpx->ngtc, 0, 0);
2843     }
2844     do_test(serializer, tpx->bBox, state->box);
2845     if (tpx->bBox)
2846     {
2847         serializer->doRvecArray(state->box, DIM);
2848         if (tpx->fileVersion >= 51)
2849         {
2850             serializer->doRvecArray(state->box_rel, DIM);
2851         }
2852         else
2853         {
2854             /* We initialize box_rel after reading the inputrec */
2855             clear_mat(state->box_rel);
2856         }
2857         serializer->doRvecArray(state->boxv, DIM);
2858         if (tpx->fileVersion < 56)
2859         {
2860             matrix mdum;
2861             serializer->doRvecArray(mdum, DIM);
2862         }
2863     }
2864
2865     if (state->ngtc > 0)
2866     {
2867         real* dumv;
2868         snew(dumv, state->ngtc);
2869         if (tpx->fileVersion < 69)
2870         {
2871             serializer->doRealArray(dumv, state->ngtc);
2872         }
2873         /* These used to be the Berendsen tcoupl_lambda's */
2874         serializer->doRealArray(dumv, state->ngtc);
2875         sfree(dumv);
2876     }
2877 }
2878
2879 /*! \brief
2880  * Process global topology data.
2881  *
2882  * See the documentation for do_tpx_body for the correct order of
2883  * the operations for reading a tpr file.
2884  *
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.
2888  */
2889 static void do_tpx_mtop(gmx::ISerializer* serializer, TpxFileHeader* tpx, gmx_mtop_t* mtop)
2890 {
2891     do_test(serializer, tpx->bTop, mtop);
2892     if (tpx->bTop)
2893     {
2894         if (mtop)
2895         {
2896             do_mtop(serializer, mtop, tpx->fileVersion);
2897             set_disres_npair(mtop);
2898             mtop->finalize();
2899         }
2900         else
2901         {
2902             gmx_mtop_t dum_top;
2903             do_mtop(serializer, &dum_top, tpx->fileVersion);
2904         }
2905     }
2906 }
2907 /*! \brief
2908  * Process coordinate vectors for state data.
2909  *
2910  * Main part of state gets processed here.
2911  *
2912  * See the documentation for do_tpx_body for the correct order of
2913  * the operations for reading a tpr file.
2914  *
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.
2920  */
2921 static void do_tpx_state_second(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state, rvec* x, rvec* v)
2922 {
2923     if (!serializer->reading())
2924     {
2925         GMX_RELEASE_ASSERT(
2926                 x == nullptr && v == nullptr,
2927                 "Passing separate x and v pointers to do_tpx() is not supported when writing");
2928     }
2929     else
2930     {
2931         GMX_RELEASE_ASSERT(!(x == nullptr && v != nullptr),
2932                            "Passing x==NULL and v!=NULL is not supported");
2933     }
2934
2935     if (serializer->reading())
2936     {
2937         if (x == nullptr)
2938         {
2939             // v is also nullptr by the above assertion, so we may
2940             // need to make memory in state for storing the contents
2941             // of the tpx file.
2942             if (tpx->bX)
2943             {
2944                 state->flags |= enumValueToBitMask(StateEntry::X);
2945             }
2946             if (tpx->bV)
2947             {
2948                 state->flags |= enumValueToBitMask(StateEntry::V);
2949             }
2950             state_change_natoms(state, tpx->natoms);
2951         }
2952     }
2953
2954     if (x == nullptr)
2955     {
2956         x = state->x.rvec_array();
2957         v = state->v.rvec_array();
2958     }
2959     do_test(serializer, tpx->bX, x);
2960     if (tpx->bX)
2961     {
2962         if (serializer->reading())
2963         {
2964             state->flags |= enumValueToBitMask(StateEntry::X);
2965         }
2966         serializer->doRvecArray(x, tpx->natoms);
2967     }
2968
2969     do_test(serializer, tpx->bV, v);
2970     if (tpx->bV)
2971     {
2972         if (serializer->reading())
2973         {
2974             state->flags |= enumValueToBitMask(StateEntry::V);
2975         }
2976         if (!v)
2977         {
2978             std::vector<gmx::RVec> dummyVelocities(tpx->natoms);
2979             serializer->doRvecArray(as_rvec_array(dummyVelocities.data()), tpx->natoms);
2980         }
2981         else
2982         {
2983             serializer->doRvecArray(v, tpx->natoms);
2984         }
2985     }
2986
2987     // No need to run do_test when the last argument is NULL
2988     if (tpx->bF)
2989     {
2990         std::vector<gmx::RVec> dummyForces(state->natoms);
2991         serializer->doRvecArray(as_rvec_array(dummyForces.data()), tpx->natoms);
2992     }
2993 }
2994 /*! \brief
2995  * Process simulation parameters.
2996  *
2997  * See the documentation for do_tpx_body for the correct order of
2998  * the operations for reading a tpr file.
2999  *
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.
3003  */
3004 static PbcType do_tpx_ir(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir)
3005 {
3006     PbcType  pbcType;
3007     gmx_bool bPeriodicMols;
3008
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.
3013      *
3014      *
3015      */
3016     pbcType       = PbcType::Unset;
3017     bPeriodicMols = FALSE;
3018
3019     do_test(serializer, tpx->bIr, ir);
3020     if (tpx->bIr)
3021     {
3022         if (tpx->fileVersion >= 53)
3023         {
3024             /* Removed the pbc info from do_inputrec, since we always want it */
3025             if (!serializer->reading())
3026             {
3027                 pbcType       = ir->pbcType;
3028                 bPeriodicMols = ir->bPeriodicMols;
3029             }
3030             serializer->doInt(reinterpret_cast<int*>(&pbcType));
3031             serializer->doBool(&bPeriodicMols);
3032         }
3033         if (tpx->fileGeneration <= tpx_generation && ir)
3034         {
3035             do_inputrec(serializer, ir, tpx->fileVersion);
3036             if (tpx->fileVersion < 53)
3037             {
3038                 pbcType       = ir->pbcType;
3039                 bPeriodicMols = ir->bPeriodicMols;
3040             }
3041         }
3042         if (serializer->reading() && ir && tpx->fileVersion >= 53)
3043         {
3044             /* We need to do this after do_inputrec, since that initializes ir */
3045             ir->pbcType       = pbcType;
3046             ir->bPeriodicMols = bPeriodicMols;
3047         }
3048     }
3049     return pbcType;
3050 }
3051
3052 /*! \brief
3053  * Correct and finalize read information.
3054  *
3055  * If \p state is nullptr, skip the parts dependent on it.
3056  *
3057  * See the documentation for do_tpx_body for the correct order of
3058  * the operations for reading a tpr file.
3059  *
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.
3064  */
3065 static void do_tpx_finalize(TpxFileHeader* tpx, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
3066 {
3067     if (tpx->fileVersion < 51 && state)
3068     {
3069         set_box_rel(ir, state);
3070     }
3071     if (tpx->bIr && ir)
3072     {
3073         if (state && state->ngtc == 0)
3074         {
3075             /* Reading old version without tcoupl state data: set it */
3076             init_gtc_state(state, ir->opts.ngtc, 0, ir->opts.nhchainlength);
3077         }
3078         if (tpx->bTop && mtop)
3079         {
3080             if (tpx->fileVersion < 57)
3081             {
3082                 ir->eDisre = !mtop->moltype[0].ilist[F_DISRES].empty()
3083                                      ? DistanceRestraintRefinement::Simple
3084                                      : DistanceRestraintRefinement::None;
3085             }
3086         }
3087     }
3088 }
3089
3090 /*! \brief
3091  * Process TPR data for file reading/writing.
3092  *
3093  * The TPR file gets processed in in four stages due to the organization
3094  * of the data within it.
3095  *
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.
3101  *
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.
3109  */
3110 static PbcType do_tpx_body(gmx::ISerializer* serializer,
3111                            TpxFileHeader*    tpx,
3112                            t_inputrec*       ir,
3113                            t_state*          state,
3114                            rvec*             x,
3115                            rvec*             v,
3116                            gmx_mtop_t*       mtop)
3117 {
3118     if (state)
3119     {
3120         do_tpx_state_first(serializer, tpx, state);
3121     }
3122     do_tpx_mtop(serializer, tpx, mtop);
3123     if (state)
3124     {
3125         do_tpx_state_second(serializer, tpx, state, x, v);
3126     }
3127     PbcType pbcType = do_tpx_ir(serializer, tpx, ir);
3128     if (serializer->reading())
3129     {
3130         do_tpx_finalize(tpx, ir, state, mtop);
3131     }
3132     return pbcType;
3133 }
3134
3135 /*! \brief
3136  * Overload for do_tpx_body that defaults to state vectors being nullptr.
3137  *
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.
3142  */
3143 static PbcType do_tpx_body(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir, gmx_mtop_t* mtop)
3144 {
3145     return do_tpx_body(serializer, tpx, ir, nullptr, nullptr, nullptr, mtop);
3146 }
3147
3148 static t_fileio* open_tpx(const char* fn, const char* mode)
3149 {
3150     return gmx_fio_open(fn, mode);
3151 }
3152
3153 static void close_tpx(t_fileio* fio)
3154 {
3155     gmx_fio_close(fio);
3156 }
3157
3158 /*! \brief
3159  * Fill information into the header only from state before writing.
3160  *
3161  * Populating the header needs to be independent from writing the information
3162  * to file to allow things like writing the raw byte stream.
3163  *
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.
3168  */
3169 static TpxFileHeader populateTpxHeader(const t_state& state, const t_inputrec* ir, const gmx_mtop_t* mtop)
3170 {
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;
3180     header.bF             = false;
3181     header.bBox           = true;
3182     header.fileVersion    = tpx_version;
3183     header.fileGeneration = tpx_generation;
3184     header.isDouble       = (sizeof(real) == sizeof(double));
3185
3186     return header;
3187 }
3188
3189 /*! \brief
3190  * Process the body of a TPR file as an opaque data buffer.
3191  *
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.
3197  *
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.
3201  */
3202 static void doTpxBodyBuffer(gmx::ISerializer* serializer, gmx::ArrayRef<char> buffer)
3203 {
3204     serializer->doOpaque(buffer.data(), buffer.size());
3205 }
3206
3207 /*! \brief
3208  * Populates simulation datastructures.
3209  *
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.
3218  *
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.
3222  *
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.
3230  *
3231  * \returns Partial de-serialized TPR used for communication to nodes.
3232  */
3233 static PartialDeserializedTprFile readTpxBody(TpxFileHeader*    tpx,
3234                                               gmx::ISerializer* serializer,
3235                                               t_inputrec*       ir,
3236                                               t_state*          state,
3237                                               rvec*             x,
3238                                               rvec*             v,
3239                                               gmx_mtop_t*       mtop)
3240 {
3241     PartialDeserializedTprFile partialDeserializedTpr;
3242     if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
3243     {
3244         partialDeserializedTpr.body.resize(tpx->sizeOfTprBody);
3245         partialDeserializedTpr.header = *tpx;
3246         doTpxBodyBuffer(serializer, partialDeserializedTpr.body);
3247
3248         partialDeserializedTpr.pbcType =
3249                 completeTprDeserialization(&partialDeserializedTpr, ir, state, x, v, mtop);
3250     }
3251     else
3252     {
3253         partialDeserializedTpr.pbcType = do_tpx_body(serializer, tpx, ir, state, x, v, mtop);
3254     }
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
3258     // in on master.
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();
3268
3269     return partialDeserializedTpr;
3270 }
3271
3272 /************************************************************
3273  *
3274  *  The following routines are the exported ones
3275  *
3276  ************************************************************/
3277
3278 TpxFileHeader readTpxHeader(const char* fileName, bool canReadTopologyOnly)
3279 {
3280     t_fileio* fio;
3281
3282     fio = open_tpx(fileName, "r");
3283     gmx::FileIOXdrSerializer serializer(fio);
3284
3285     TpxFileHeader tpx;
3286     do_tpxheader(&serializer, &tpx, fileName, fio, canReadTopologyOnly);
3287     close_tpx(fio);
3288     return tpx;
3289 }
3290
3291 void write_tpx_state(const char* fn, const t_inputrec* ir, const t_state* state, const gmx_mtop_t& mtop)
3292 {
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.
3297      */
3298
3299     t_fileio* fio;
3300
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);
3308
3309     do_tpx_body(&tprBodySerializer,
3310                 &tpx,
3311                 const_cast<t_inputrec*>(ir),
3312                 const_cast<t_state*>(state),
3313                 nullptr,
3314                 nullptr,
3315                 const_cast<gmx_mtop_t*>(&mtop));
3316
3317     std::vector<char> tprBody = tprBodySerializer.finishAndGetBuffer();
3318     tpx.sizeOfTprBody         = tprBody.size();
3319
3320     fio = open_tpx(fn, "w");
3321     gmx::FileIOXdrSerializer serializer(fio);
3322     do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
3323     doTpxBodyBuffer(&serializer, tprBody);
3324
3325     close_tpx(fio);
3326 }
3327
3328 PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
3329                                    t_inputrec*                 ir,
3330                                    t_state*                    state,
3331                                    rvec*                       x,
3332                                    rvec*                       v,
3333                                    gmx_mtop_t*                 mtop)
3334 {
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);
3344 }
3345
3346 PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
3347                                    t_inputrec*                 ir,
3348                                    gmx_mtop_t*                 mtop)
3349 {
3350     return completeTprDeserialization(partialDeserializedTpr, ir, nullptr, nullptr, nullptr, mtop);
3351 }
3352
3353 PartialDeserializedTprFile read_tpx_state(const char* fn, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
3354 {
3355     t_fileio* fio;
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);
3362     close_tpx(fio);
3363     return partialDeserializedTpr;
3364 }
3365
3366 PbcType read_tpx(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, gmx_mtop_t* mtop)
3367 {
3368     t_fileio* fio;
3369     t_state   state;
3370
3371     TpxFileHeader tpx;
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);
3377     close_tpx(fio);
3378     if (mtop != nullptr && natoms != nullptr)
3379     {
3380         *natoms = mtop->natoms;
3381     }
3382     if (box)
3383     {
3384         copy_mat(state.box, box);
3385     }
3386     return partialDeserializedTpr.pbcType;
3387 }
3388
3389 PbcType read_tpx_top(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, t_topology* top)
3390 {
3391     gmx_mtop_t mtop;
3392     PbcType    pbcType;
3393
3394     pbcType = read_tpx(fn, ir, box, natoms, x, v, &mtop);
3395
3396     *top = gmx_mtop_t_to_t_topology(&mtop, true);
3397
3398     return pbcType;
3399 }
3400
3401 gmx_bool fn2bTPX(const char* file)
3402 {
3403     return (efTPR == fn2ftp(file));
3404 }
3405
3406 void pr_tpxheader(FILE* fp, int indent, const char* title, const TpxFileHeader* sh)
3407 {
3408     if (available(fp, sh, indent, title))
3409     {
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 ");
3423
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);
3430     }
3431 }