ba2c6b9783f7a140a91bd28095e892b40cabeb28
[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 char* 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 /* Needed for backward compatibility */
251 #define MAXNODES 256
252
253 /**************************************************************
254  *
255  * Now the higer level routines that do io of the structures and arrays
256  *
257  **************************************************************/
258 static void do_pullgrp_tpx_pre95(gmx::ISerializer* serializer, t_pull_group* pgrp, t_pull_coord* pcrd)
259 {
260     rvec tmp;
261
262     int numAtoms = pgrp->ind.size();
263     serializer->doInt(&numAtoms);
264     pgrp->ind.resize(numAtoms);
265     serializer->doIntArray(pgrp->ind.data(), numAtoms);
266     int numWeights = pgrp->weight.size();
267     serializer->doInt(&numWeights);
268     pgrp->weight.resize(numWeights);
269     serializer->doRealArray(pgrp->weight.data(), numWeights);
270     serializer->doInt(&pgrp->pbcatom);
271     serializer->doRvec(&pcrd->vec.as_vec());
272     clear_rvec(pcrd->origin);
273     serializer->doRvec(&tmp);
274     pcrd->init = tmp[0];
275     serializer->doReal(&pcrd->rate);
276     serializer->doReal(&pcrd->k);
277     serializer->doReal(&pcrd->kB);
278 }
279
280 static void do_pull_group(gmx::ISerializer* serializer, t_pull_group* pgrp)
281 {
282     int numAtoms = pgrp->ind.size();
283     serializer->doInt(&numAtoms);
284     pgrp->ind.resize(numAtoms);
285     serializer->doIntArray(pgrp->ind.data(), numAtoms);
286     int numWeights = pgrp->weight.size();
287     serializer->doInt(&numWeights);
288     pgrp->weight.resize(numWeights);
289     serializer->doRealArray(pgrp->weight.data(), numWeights);
290     serializer->doInt(&pgrp->pbcatom);
291 }
292
293 static void do_pull_coord(gmx::ISerializer* serializer,
294                           t_pull_coord*     pcrd,
295                           int               file_version,
296                           PullingAlgorithm  ePullOld,
297                           PullGroupGeometry eGeomOld,
298                           ivec              dimOld)
299 {
300     if (file_version >= tpxv_PullCoordNGroup)
301     {
302         serializer->doEnumAsInt(&pcrd->eType);
303         if (file_version >= tpxv_PullExternalPotential)
304         {
305             if (pcrd->eType == PullingAlgorithm::External)
306             {
307                 std::string buf;
308                 if (serializer->reading())
309                 {
310                     serializer->doString(&buf);
311                     pcrd->externalPotentialProvider = gmx_strdup(buf.c_str());
312                 }
313                 else
314                 {
315                     buf = pcrd->externalPotentialProvider;
316                     serializer->doString(&buf);
317                 }
318             }
319             else
320             {
321                 pcrd->externalPotentialProvider.clear();
322             }
323         }
324         else
325         {
326             if (serializer->reading())
327             {
328                 pcrd->externalPotentialProvider.clear();
329             }
330         }
331         /* Note that we try to support adding new geometries without
332          * changing the tpx version. This requires checks when printing the
333          * geometry string and a check and fatal_error in init_pull.
334          */
335         serializer->doEnumAsInt(&pcrd->eGeom);
336         serializer->doInt(&pcrd->ngroup);
337         if (pcrd->ngroup <= c_pullCoordNgroupMax)
338         {
339             serializer->doIntArray(pcrd->group.data(), pcrd->ngroup);
340         }
341         else
342         {
343             /* More groups in file than supported, this must be a new geometry
344              * that is not supported by our current code. Since we will not
345              * use the groups for this coord (checks in the pull and WHAM code
346              * ensure this), we can ignore the groups and set ngroup=0.
347              */
348             int* dum;
349             snew(dum, pcrd->ngroup);
350             serializer->doIntArray(dum, pcrd->ngroup);
351             sfree(dum);
352
353             pcrd->ngroup = 0;
354         }
355         serializer->doIvec(&pcrd->dim.as_vec());
356     }
357     else
358     {
359         pcrd->ngroup = 2;
360         serializer->doInt(&pcrd->group[0]);
361         serializer->doInt(&pcrd->group[1]);
362         if (file_version >= tpxv_PullCoordTypeGeom)
363         {
364             pcrd->ngroup = (pcrd->eGeom == PullGroupGeometry::DirectionRelative ? 4 : 2);
365             serializer->doEnumAsInt(&pcrd->eType);
366             serializer->doEnumAsInt(&pcrd->eGeom);
367             if (pcrd->ngroup == 4)
368             {
369                 serializer->doInt(&pcrd->group[2]);
370                 serializer->doInt(&pcrd->group[3]);
371             }
372             serializer->doIvec(&pcrd->dim.as_vec());
373         }
374         else
375         {
376             pcrd->eType = ePullOld;
377             pcrd->eGeom = eGeomOld;
378             copy_ivec(dimOld, pcrd->dim);
379         }
380     }
381     serializer->doRvec(&pcrd->origin.as_vec());
382     serializer->doRvec(&pcrd->vec.as_vec());
383     if (file_version >= tpxv_PullCoordTypeGeom)
384     {
385         serializer->doBool(&pcrd->bStart);
386     }
387     else
388     {
389         /* This parameter is only printed, but not actually used by mdrun */
390         pcrd->bStart = FALSE;
391     }
392     serializer->doReal(&pcrd->init);
393     serializer->doReal(&pcrd->rate);
394     serializer->doReal(&pcrd->k);
395     serializer->doReal(&pcrd->kB);
396 }
397
398 static void do_expandedvals(gmx::ISerializer* serializer, t_expanded* expand, t_lambda* fepvals, int file_version)
399 {
400     int n_lambda = fepvals->n_lambda;
401
402     /* reset the lambda calculation window */
403     fepvals->lambda_start_n = 0;
404     fepvals->lambda_stop_n  = n_lambda;
405     if (file_version >= 79)
406     {
407         if (n_lambda > 0)
408         {
409             expand->init_lambda_weights.resize(n_lambda);
410             serializer->doRealArray(expand->init_lambda_weights.data(), n_lambda);
411             serializer->doBool(&expand->bInit_weights);
412         }
413
414         serializer->doInt(&expand->nstexpanded);
415         serializer->doEnumAsInt(&expand->elmcmove);
416         serializer->doEnumAsInt(&expand->elamstats);
417         serializer->doInt(&expand->lmc_repeats);
418         serializer->doInt(&expand->gibbsdeltalam);
419         serializer->doInt(&expand->lmc_forced_nstart);
420         serializer->doInt(&expand->lmc_seed);
421         serializer->doReal(&expand->mc_temp);
422         serializer->doBool(&expand->bSymmetrizedTMatrix);
423         serializer->doInt(&expand->nstTij);
424         serializer->doInt(&expand->minvarmin);
425         serializer->doInt(&expand->c_range);
426         serializer->doReal(&expand->wl_scale);
427         serializer->doReal(&expand->wl_ratio);
428         serializer->doReal(&expand->init_wl_delta);
429         serializer->doBool(&expand->bWLoneovert);
430         serializer->doEnumAsInt(&expand->elmceq);
431         serializer->doInt(&expand->equil_steps);
432         serializer->doInt(&expand->equil_samples);
433         serializer->doInt(&expand->equil_n_at_lam);
434         serializer->doReal(&expand->equil_wl_delta);
435         serializer->doReal(&expand->equil_ratio);
436     }
437 }
438
439 static void do_simtempvals(gmx::ISerializer* serializer, t_simtemp* simtemp, int n_lambda, int file_version)
440 {
441     if (file_version >= 79)
442     {
443         serializer->doEnumAsInt(&simtemp->eSimTempScale);
444         serializer->doReal(&simtemp->simtemp_high);
445         serializer->doReal(&simtemp->simtemp_low);
446         if (n_lambda > 0)
447         {
448             if (serializer->reading())
449             {
450                 simtemp->temperatures.resize(n_lambda);
451             }
452             serializer->doRealArray(simtemp->temperatures.data(), n_lambda);
453         }
454     }
455 }
456
457 static void do_imd(gmx::ISerializer* serializer, t_IMD* imd)
458 {
459     serializer->doInt(&imd->nat);
460     if (serializer->reading())
461     {
462         snew(imd->ind, imd->nat);
463     }
464     serializer->doIntArray(imd->ind, imd->nat);
465 }
466
467 static void do_fepvals(gmx::ISerializer* serializer, t_lambda* fepvals, int file_version)
468 {
469     /* i is defined in the ndo_double macro; use g to iterate. */
470     real rdum;
471
472     /* free energy values */
473
474     if (file_version >= 79)
475     {
476         serializer->doInt(&fepvals->init_fep_state);
477         serializer->doDouble(&fepvals->init_lambda);
478         serializer->doDouble(&fepvals->delta_lambda);
479     }
480     else if (file_version >= 59)
481     {
482         serializer->doDouble(&fepvals->init_lambda);
483         serializer->doDouble(&fepvals->delta_lambda);
484     }
485     else
486     {
487         serializer->doReal(&rdum);
488         fepvals->init_lambda = rdum;
489         serializer->doReal(&rdum);
490         fepvals->delta_lambda = rdum;
491     }
492     if (file_version >= 79)
493     {
494         serializer->doInt(&fepvals->n_lambda);
495         for (auto g : keysOf(fepvals->all_lambda))
496         {
497             if (fepvals->n_lambda > 0)
498             {
499                 fepvals->all_lambda[g].resize(fepvals->n_lambda);
500                 serializer->doDoubleArray(fepvals->all_lambda[g].data(), fepvals->n_lambda);
501                 serializer->doBoolArray(
502                         fepvals->separate_dvdl.begin(),
503                         gmx::EnumerationArray<FreeEnergyPerturbationCouplingType, real>::size());
504             }
505             else if (fepvals->init_lambda >= 0)
506             {
507                 fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
508             }
509         }
510     }
511     else if (file_version >= 64)
512     {
513         serializer->doInt(&fepvals->n_lambda);
514         if (serializer->reading())
515         {
516             /* still allocate the all_lambda array's contents. */
517             for (auto g : keysOf(fepvals->all_lambda))
518             {
519                 if (fepvals->n_lambda > 0)
520                 {
521                     fepvals->all_lambda[g].resize(fepvals->n_lambda);
522                 }
523             }
524         }
525         serializer->doDoubleArray(fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep].data(),
526                                   fepvals->n_lambda);
527         if (fepvals->init_lambda >= 0)
528         {
529             fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
530
531             if (serializer->reading())
532             {
533                 /* copy the contents of the efptFEP lambda component to all
534                    the other components */
535                 for (auto g : keysOf(fepvals->all_lambda))
536                 {
537                     for (int h = 0; h < fepvals->n_lambda; h++)
538                     {
539                         if (g != FreeEnergyPerturbationCouplingType::Fep)
540                         {
541                             fepvals->all_lambda[g][h] =
542                                     fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep][h];
543                         }
544                     }
545                 }
546             }
547         }
548     }
549     else
550     {
551         fepvals->n_lambda = 0;
552         if (fepvals->init_lambda >= 0)
553         {
554             fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
555         }
556     }
557     serializer->doReal(&fepvals->sc_alpha);
558     serializer->doInt(&fepvals->sc_power);
559     if (file_version >= 79)
560     {
561         serializer->doReal(&fepvals->sc_r_power);
562     }
563     else
564     {
565         fepvals->sc_r_power = 6.0;
566     }
567     if (fepvals->sc_r_power != 6.0)
568     {
569         gmx_fatal(FARGS, "sc-r-power=48 is no longer supported");
570     }
571     serializer->doReal(&fepvals->sc_sigma);
572     if (serializer->reading())
573     {
574         if (file_version >= 71)
575         {
576             fepvals->sc_sigma_min = fepvals->sc_sigma;
577         }
578         else
579         {
580             fepvals->sc_sigma_min = 0;
581         }
582     }
583     if (file_version >= 79)
584     {
585         serializer->doBool(&fepvals->bScCoul);
586     }
587     else
588     {
589         fepvals->bScCoul = TRUE;
590     }
591     if (file_version >= 64)
592     {
593         serializer->doInt(&fepvals->nstdhdl);
594     }
595     else
596     {
597         fepvals->nstdhdl = 1;
598     }
599
600     if (file_version >= 73)
601     {
602         serializer->doEnumAsInt(&fepvals->separate_dhdl_file);
603         serializer->doEnumAsInt(&fepvals->dhdl_derivatives);
604     }
605     else
606     {
607         fepvals->separate_dhdl_file = SeparateDhdlFile::Yes;
608         fepvals->dhdl_derivatives   = DhDlDerivativeCalculation::Yes;
609     }
610     if (file_version >= 71)
611     {
612         serializer->doInt(&fepvals->dh_hist_size);
613         serializer->doDouble(&fepvals->dh_hist_spacing);
614     }
615     else
616     {
617         fepvals->dh_hist_size    = 0;
618         fepvals->dh_hist_spacing = 0.1;
619     }
620     if (file_version >= 79)
621     {
622         serializer->doEnumAsInt(&fepvals->edHdLPrintEnergy);
623     }
624     else
625     {
626         fepvals->edHdLPrintEnergy = FreeEnergyPrintEnergy::No;
627     }
628
629     /* handle lambda_neighbors */
630     if ((file_version >= 83 && file_version < 90) || file_version >= 92)
631     {
632         serializer->doInt(&fepvals->lambda_neighbors);
633         if ((fepvals->lambda_neighbors >= 0) && (fepvals->init_fep_state >= 0)
634             && (fepvals->init_lambda < 0))
635         {
636             fepvals->lambda_start_n = (fepvals->init_fep_state - fepvals->lambda_neighbors);
637             fepvals->lambda_stop_n  = (fepvals->init_fep_state + fepvals->lambda_neighbors + 1);
638             if (fepvals->lambda_start_n < 0)
639             {
640                 fepvals->lambda_start_n = 0;
641             }
642             if (fepvals->lambda_stop_n >= fepvals->n_lambda)
643             {
644                 fepvals->lambda_stop_n = fepvals->n_lambda;
645             }
646         }
647         else
648         {
649             fepvals->lambda_start_n = 0;
650             fepvals->lambda_stop_n  = fepvals->n_lambda;
651         }
652     }
653     else
654     {
655         fepvals->lambda_start_n = 0;
656         fepvals->lambda_stop_n  = fepvals->n_lambda;
657     }
658 }
659
660 static void do_pull(gmx::ISerializer* serializer, pull_params_t* pull, int file_version, PullingAlgorithm ePullOld)
661 {
662     PullGroupGeometry eGeomOld = PullGroupGeometry::Count;
663     ivec              dimOld;
664     int               g;
665
666     if (file_version >= 95)
667     {
668         serializer->doInt(&pull->ngroup);
669     }
670     serializer->doInt(&pull->ncoord);
671     if (file_version < 95)
672     {
673         pull->ngroup = pull->ncoord + 1;
674     }
675     if (file_version < tpxv_PullCoordTypeGeom)
676     {
677         real dum;
678
679         serializer->doEnumAsInt(&eGeomOld);
680         serializer->doIvec(&dimOld);
681         /* The inner cylinder radius, now removed */
682         serializer->doReal(&dum);
683     }
684     serializer->doReal(&pull->cylinder_r);
685     serializer->doReal(&pull->constr_tol);
686     if (file_version >= 95)
687     {
688         serializer->doBool(&pull->bPrintCOM);
689         /* With file_version < 95 this value is set below */
690     }
691     if (file_version >= tpxv_ReplacePullPrintCOM12)
692     {
693         serializer->doBool(&pull->bPrintRefValue);
694         serializer->doBool(&pull->bPrintComp);
695     }
696     else if (file_version >= tpxv_PullCoordTypeGeom)
697     {
698         int idum;
699         serializer->doInt(&idum); /* used to be bPrintCOM2 */
700         serializer->doBool(&pull->bPrintRefValue);
701         serializer->doBool(&pull->bPrintComp);
702     }
703     else
704     {
705         pull->bPrintRefValue = FALSE;
706         pull->bPrintComp     = TRUE;
707     }
708     serializer->doInt(&pull->nstxout);
709     serializer->doInt(&pull->nstfout);
710     if (file_version >= tpxv_PullPrevStepCOMAsReference)
711     {
712         serializer->doBool(&pull->bSetPbcRefToPrevStepCOM);
713     }
714     else
715     {
716         pull->bSetPbcRefToPrevStepCOM = FALSE;
717     }
718     pull->group.resize(pull->ngroup);
719     pull->coord.resize(pull->ncoord);
720     if (file_version < 95)
721     {
722         /* epullgPOS for position pulling, before epullgDIRPBC was removed */
723         if (eGeomOld == PullGroupGeometry::DirectionPBC)
724         {
725             gmx_fatal(FARGS, "pull-geometry=position is no longer supported");
726         }
727         if (eGeomOld > PullGroupGeometry::DirectionPBC)
728         {
729             switch (eGeomOld)
730             {
731                 case (PullGroupGeometry::DirectionRelative):
732                     eGeomOld = PullGroupGeometry::DirectionPBC;
733                     break;
734                 case (PullGroupGeometry::Angle):
735                     eGeomOld = PullGroupGeometry::DirectionRelative;
736                     break;
737                 case (PullGroupGeometry::Dihedral): eGeomOld = PullGroupGeometry::Angle; break;
738                 case (PullGroupGeometry::AngleAxis): eGeomOld = PullGroupGeometry::Dihedral; break;
739                 case (PullGroupGeometry::Count): eGeomOld = PullGroupGeometry::AngleAxis; break;
740                 default: GMX_RELEASE_ASSERT(false, "Unhandled old pull type");
741             }
742         }
743
744         for (g = 0; g < pull->ngroup; g++)
745         {
746             /* We read and ignore a pull coordinate for group 0 */
747             do_pullgrp_tpx_pre95(serializer, &pull->group[g], &pull->coord[std::max(g - 1, 0)]);
748             if (g > 0)
749             {
750                 pull->coord[g - 1].group[0] = 0;
751                 pull->coord[g - 1].group[1] = g;
752             }
753         }
754
755         pull->bPrintCOM = (!pull->group[0].ind.empty());
756     }
757     else
758     {
759         for (g = 0; g < pull->ngroup; g++)
760         {
761             do_pull_group(serializer, &pull->group[g]);
762         }
763         for (g = 0; g < pull->ncoord; g++)
764         {
765             do_pull_coord(serializer, &pull->coord[g], file_version, ePullOld, eGeomOld, dimOld);
766         }
767     }
768     if (file_version >= tpxv_PullAverage)
769     {
770         gmx_bool v;
771
772         v = pull->bXOutAverage;
773         serializer->doBool(&v);
774         pull->bXOutAverage = v;
775         v                  = pull->bFOutAverage;
776         serializer->doBool(&v);
777         pull->bFOutAverage = v;
778     }
779 }
780
781
782 static void do_rotgrp(gmx::ISerializer* serializer, t_rotgrp* rotg)
783 {
784     serializer->doEnumAsInt(&rotg->eType);
785     if (serializer->reading())
786     {
787         int temp = 0;
788         serializer->doInt(&temp);
789         rotg->bMassW = static_cast<bool>(temp);
790     }
791     else
792     {
793         int temp = static_cast<int>(rotg->bMassW);
794         serializer->doInt(&temp);
795     }
796     serializer->doInt(&rotg->nat);
797     if (serializer->reading())
798     {
799         snew(rotg->ind, rotg->nat);
800     }
801     serializer->doIntArray(rotg->ind, rotg->nat);
802     if (serializer->reading())
803     {
804         snew(rotg->x_ref, rotg->nat);
805     }
806     serializer->doRvecArray(rotg->x_ref, rotg->nat);
807     serializer->doRvec(&rotg->inputVec);
808     serializer->doRvec(&rotg->pivot);
809     serializer->doReal(&rotg->rate);
810     serializer->doReal(&rotg->k);
811     serializer->doReal(&rotg->slab_dist);
812     serializer->doReal(&rotg->min_gaussian);
813     serializer->doReal(&rotg->eps);
814     serializer->doEnumAsInt(&rotg->eFittype);
815     serializer->doInt(&rotg->PotAngle_nstep);
816     serializer->doReal(&rotg->PotAngle_step);
817 }
818
819 static void do_rot(gmx::ISerializer* serializer, t_rot* rot)
820 {
821     int g;
822
823     serializer->doInt(&rot->ngrp);
824     serializer->doInt(&rot->nstrout);
825     serializer->doInt(&rot->nstsout);
826     if (serializer->reading())
827     {
828         snew(rot->grp, rot->ngrp);
829     }
830     for (g = 0; g < rot->ngrp; g++)
831     {
832         do_rotgrp(serializer, &rot->grp[g]);
833     }
834 }
835
836
837 static void do_swapgroup(gmx::ISerializer* serializer, t_swapGroup* g)
838 {
839
840     /* Name of the group or molecule */
841     std::string buf;
842     if (serializer->reading())
843     {
844         serializer->doString(&buf);
845         g->molname = gmx_strdup(buf.c_str());
846     }
847     else
848     {
849         buf = g->molname;
850         serializer->doString(&buf);
851     }
852
853     /* Number of atoms in the group */
854     serializer->doInt(&g->nat);
855
856     /* The group's atom indices */
857     if (serializer->reading())
858     {
859         snew(g->ind, g->nat);
860     }
861     serializer->doIntArray(g->ind, g->nat);
862
863     /* Requested counts for compartments A and B */
864     serializer->doIntArray(g->nmolReq, eCompNR);
865 }
866
867 static void do_swapcoords_tpx(gmx::ISerializer* serializer, t_swapcoords* swap, int file_version)
868 {
869     /* Enums for better readability of the code */
870     enum
871     {
872         eCompA = 0,
873         eCompB
874     };
875     enum
876     {
877         eChannel0 = 0,
878         eChannel1
879     };
880
881
882     if (file_version >= tpxv_CompElPolyatomicIonsAndMultipleIonTypes)
883     {
884         /* The total number of swap groups is the sum of the fixed groups
885          * (split0, split1, solvent), and the user-defined groups (2+ types of ions)
886          */
887         serializer->doInt(&swap->ngrp);
888         if (serializer->reading())
889         {
890             snew(swap->grp, swap->ngrp);
891         }
892         for (int ig = 0; ig < swap->ngrp; ig++)
893         {
894             do_swapgroup(serializer, &swap->grp[ig]);
895         }
896         serializer->doBool(&swap->massw_split[eChannel0]);
897         serializer->doBool(&swap->massw_split[eChannel1]);
898         serializer->doInt(&swap->nstswap);
899         serializer->doInt(&swap->nAverage);
900         serializer->doReal(&swap->threshold);
901         serializer->doReal(&swap->cyl0r);
902         serializer->doReal(&swap->cyl0u);
903         serializer->doReal(&swap->cyl0l);
904         serializer->doReal(&swap->cyl1r);
905         serializer->doReal(&swap->cyl1u);
906         serializer->doReal(&swap->cyl1l);
907     }
908     else
909     {
910         /*** Support reading older CompEl .tpr files ***/
911
912         /* In the original CompEl .tpr files, we always have 5 groups: */
913         swap->ngrp = 5;
914         snew(swap->grp, swap->ngrp);
915
916         swap->grp[static_cast<int>(SwapGroupSplittingType::Split0)].molname = gmx_strdup("split0"); // group 0: split0
917         swap->grp[static_cast<int>(SwapGroupSplittingType::Split1)].molname = gmx_strdup("split1"); // group 1: split1
918         swap->grp[static_cast<int>(SwapGroupSplittingType::Solvent)].molname =
919                 gmx_strdup("solvent");                // group 2: solvent
920         swap->grp[3].molname = gmx_strdup("anions");  // group 3: anions
921         swap->grp[4].molname = gmx_strdup("cations"); // group 4: cations
922
923         serializer->doInt(&swap->grp[3].nat);
924         serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Solvent)].nat);
925         serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Split0)].nat);
926         serializer->doBool(&swap->massw_split[eChannel0]);
927         serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Split1)].nat);
928         serializer->doBool(&swap->massw_split[eChannel1]);
929         serializer->doInt(&swap->nstswap);
930         serializer->doInt(&swap->nAverage);
931         serializer->doReal(&swap->threshold);
932         serializer->doReal(&swap->cyl0r);
933         serializer->doReal(&swap->cyl0u);
934         serializer->doReal(&swap->cyl0l);
935         serializer->doReal(&swap->cyl1r);
936         serializer->doReal(&swap->cyl1u);
937         serializer->doReal(&swap->cyl1l);
938
939         // The order[] array keeps compatibility with older .tpr files
940         // by reading in the groups in the classic order
941         {
942             const int order[4] = { 3,
943                                    static_cast<int>(SwapGroupSplittingType::Solvent),
944                                    static_cast<int>(SwapGroupSplittingType::Split0),
945                                    static_cast<int>(SwapGroupSplittingType::Split1) };
946
947             for (int ig = 0; ig < 4; ig++)
948             {
949                 int g = order[ig];
950                 snew(swap->grp[g].ind, swap->grp[g].nat);
951                 serializer->doIntArray(swap->grp[g].ind, swap->grp[g].nat);
952             }
953         }
954
955         for (int j = eCompA; j <= eCompB; j++)
956         {
957             serializer->doInt(&swap->grp[3].nmolReq[j]); // group 3 = anions
958             serializer->doInt(&swap->grp[4].nmolReq[j]); // group 4 = cations
959         }
960     } /* End support reading older CompEl .tpr files */
961
962     if (file_version >= tpxv_CompElWithSwapLayerOffset)
963     {
964         serializer->doReal(&swap->bulkOffset[eCompA]);
965         serializer->doReal(&swap->bulkOffset[eCompB]);
966     }
967 }
968
969 static void do_legacy_efield(gmx::ISerializer* serializer, gmx::KeyValueTreeObjectBuilder* root)
970 {
971     const char* const dimName[] = { "x", "y", "z" };
972
973     auto appliedForcesObj = root->addObject("applied-forces");
974     auto efieldObj        = appliedForcesObj.addObject("electric-field");
975     // The content of the tpr file for this feature has
976     // been the same since gromacs 4.0 that was used for
977     // developing.
978     for (int j = 0; j < DIM; ++j)
979     {
980         int n, nt;
981         serializer->doInt(&n);
982         serializer->doInt(&nt);
983         std::vector<real> aa(n + 1), phi(nt + 1), at(nt + 1), phit(nt + 1);
984         serializer->doRealArray(aa.data(), n);
985         serializer->doRealArray(phi.data(), n);
986         serializer->doRealArray(at.data(), nt);
987         serializer->doRealArray(phit.data(), nt);
988         if (n > 0)
989         {
990             if (n > 1 || nt > 1)
991             {
992                 gmx_fatal(FARGS,
993                           "Can not handle tpr files with more than one electric field term per "
994                           "direction.");
995             }
996             auto dimObj = efieldObj.addObject(dimName[j]);
997             dimObj.addValue<real>("E0", aa[0]);
998             dimObj.addValue<real>("omega", at[0]);
999             dimObj.addValue<real>("t0", phi[0]);
1000             dimObj.addValue<real>("sigma", phit[0]);
1001         }
1002     }
1003 }
1004
1005
1006 static void do_inputrec(gmx::ISerializer* serializer, t_inputrec* ir, int file_version)
1007 {
1008     int      i, j, k, idum = 0;
1009     real     rdum;
1010     gmx_bool bdum = false;
1011
1012     if (file_version != tpx_version)
1013     {
1014         /* Give a warning about features that are not accessible */
1015         fprintf(stderr, "Note: file tpx version %d, software tpx version %d\n", file_version, tpx_version);
1016     }
1017
1018     if (file_version == 0)
1019     {
1020         return;
1021     }
1022
1023     gmx::KeyValueTreeBuilder       paramsBuilder;
1024     gmx::KeyValueTreeObjectBuilder paramsObj = paramsBuilder.rootObject();
1025
1026     /* Basic inputrec stuff */
1027     serializer->doEnumAsInt(&ir->eI);
1028     if (file_version >= 62)
1029     {
1030         serializer->doInt64(&ir->nsteps);
1031     }
1032     else
1033     {
1034         serializer->doInt(&idum);
1035         ir->nsteps = idum;
1036     }
1037
1038     if (file_version >= 62)
1039     {
1040         serializer->doInt64(&ir->init_step);
1041     }
1042     else
1043     {
1044         serializer->doInt(&idum);
1045         ir->init_step = idum;
1046     }
1047
1048     serializer->doInt(&ir->simulation_part);
1049
1050     if (file_version >= tpxv_MTS)
1051     {
1052         serializer->doBool(&ir->useMts);
1053         int numLevels = ir->mtsLevels.size();
1054         if (ir->useMts)
1055         {
1056             serializer->doInt(&numLevels);
1057         }
1058         ir->mtsLevels.resize(numLevels);
1059         for (auto& mtsLevel : ir->mtsLevels)
1060         {
1061             int forceGroups = mtsLevel.forceGroups.to_ulong();
1062             serializer->doInt(&forceGroups);
1063             mtsLevel.forceGroups = std::bitset<static_cast<int>(gmx::MtsForceGroups::Count)>(forceGroups);
1064             serializer->doInt(&mtsLevel.stepFactor);
1065         }
1066     }
1067     else
1068     {
1069         ir->useMts = false;
1070         ir->mtsLevels.clear();
1071     }
1072
1073     if (file_version >= 67)
1074     {
1075         serializer->doInt(&ir->nstcalcenergy);
1076     }
1077     else
1078     {
1079         ir->nstcalcenergy = 1;
1080     }
1081     if (file_version >= 81)
1082     {
1083         serializer->doEnumAsInt(&ir->cutoff_scheme);
1084         if (file_version < 94)
1085         {
1086             // Need to invert the scheme order
1087             switch (ir->cutoff_scheme)
1088             {
1089                 case (CutoffScheme::Group): ir->cutoff_scheme = CutoffScheme::Verlet; break;
1090                 case (CutoffScheme::Verlet): ir->cutoff_scheme = CutoffScheme::Group; break;
1091                 default: GMX_RELEASE_ASSERT(false, "Unhandled cutoff scheme type");
1092             }
1093         }
1094     }
1095     else
1096     {
1097         ir->cutoff_scheme = CutoffScheme::Group;
1098     }
1099     serializer->doInt(&idum); /* used to be ns_type; not used anymore */
1100     serializer->doInt(&ir->nstlist);
1101     serializer->doInt(&idum); /* used to be ndelta; not used anymore */
1102
1103     serializer->doReal(&ir->rtpi);
1104
1105     serializer->doInt(&ir->nstcomm);
1106     serializer->doEnumAsInt(&ir->comm_mode);
1107
1108     /* ignore nstcheckpoint */
1109     if (file_version < tpxv_RemoveObsoleteParameters1)
1110     {
1111         serializer->doInt(&idum);
1112     }
1113
1114     serializer->doInt(&ir->nstcgsteep);
1115
1116     serializer->doInt(&ir->nbfgscorr);
1117
1118     serializer->doInt(&ir->nstlog);
1119     serializer->doInt(&ir->nstxout);
1120     serializer->doInt(&ir->nstvout);
1121     serializer->doInt(&ir->nstfout);
1122     serializer->doInt(&ir->nstenergy);
1123     serializer->doInt(&ir->nstxout_compressed);
1124     if (file_version >= 59)
1125     {
1126         serializer->doDouble(&ir->init_t);
1127         serializer->doDouble(&ir->delta_t);
1128     }
1129     else
1130     {
1131         serializer->doReal(&rdum);
1132         ir->init_t = rdum;
1133         serializer->doReal(&rdum);
1134         ir->delta_t = rdum;
1135     }
1136     serializer->doReal(&ir->x_compression_precision);
1137     if (file_version >= 81)
1138     {
1139         serializer->doReal(&ir->verletbuf_tol);
1140     }
1141     else
1142     {
1143         ir->verletbuf_tol = 0;
1144     }
1145     serializer->doReal(&ir->rlist);
1146     if (file_version >= 67 && file_version < tpxv_RemoveTwinRange)
1147     {
1148         if (serializer->reading())
1149         {
1150             // Reading such a file version could invoke the twin-range
1151             // scheme, about which mdrun should give a fatal error.
1152             real dummy_rlistlong = -1;
1153             serializer->doReal(&dummy_rlistlong);
1154
1155             ir->useTwinRange = (ir->rlist > 0 && (dummy_rlistlong == 0 || dummy_rlistlong > ir->rlist));
1156             // When true, this forces mdrun to issue an error (regardless of
1157             // ir->cutoff_scheme).
1158             //
1159             // Otherwise, grompp used to set rlistlong actively. Users
1160             // were probably also confused and set rlistlong == rlist.
1161             // However, in all remaining cases, it is safe to let
1162             // mdrun proceed normally.
1163         }
1164     }
1165     else
1166     {
1167         // No need to read or write anything
1168         ir->useTwinRange = false;
1169     }
1170     if (file_version >= 82 && file_version != 90)
1171     {
1172         // Multiple time-stepping is no longer enabled, but the old
1173         // support required the twin-range scheme, for which mdrun
1174         // already emits a fatal error.
1175         int dummy_nstcalclr = -1;
1176         serializer->doInt(&dummy_nstcalclr);
1177     }
1178     serializer->doEnumAsInt(&ir->coulombtype);
1179     if (file_version >= 81)
1180     {
1181         serializer->doEnumAsInt(&ir->coulomb_modifier);
1182     }
1183     else
1184     {
1185         ir->coulomb_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
1186                                                                           : InteractionModifiers::None);
1187     }
1188     serializer->doReal(&ir->rcoulomb_switch);
1189     serializer->doReal(&ir->rcoulomb);
1190     serializer->doEnumAsInt(&ir->vdwtype);
1191     if (file_version >= 81)
1192     {
1193         serializer->doEnumAsInt(&ir->vdw_modifier);
1194     }
1195     else
1196     {
1197         ir->vdw_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
1198                                                                       : InteractionModifiers::None);
1199     }
1200     serializer->doReal(&ir->rvdw_switch);
1201     serializer->doReal(&ir->rvdw);
1202     serializer->doEnumAsInt(&ir->eDispCorr);
1203     serializer->doReal(&ir->epsilon_r);
1204     serializer->doReal(&ir->epsilon_rf);
1205     serializer->doReal(&ir->tabext);
1206
1207     // This permits reading a .tpr file that used implicit solvent,
1208     // and later permitting mdrun to refuse to run it.
1209     if (serializer->reading())
1210     {
1211         if (file_version < tpxv_RemoveImplicitSolvation)
1212         {
1213             serializer->doInt(&idum);
1214             serializer->doInt(&idum);
1215             serializer->doReal(&rdum);
1216             serializer->doReal(&rdum);
1217             serializer->doInt(&idum);
1218             ir->implicit_solvent = (idum > 0);
1219         }
1220         else
1221         {
1222             ir->implicit_solvent = false;
1223         }
1224         if (file_version < tpxv_RemoveImplicitSolvation)
1225         {
1226             serializer->doReal(&rdum);
1227             serializer->doReal(&rdum);
1228             serializer->doReal(&rdum);
1229             serializer->doReal(&rdum);
1230             if (file_version >= 60)
1231             {
1232                 serializer->doReal(&rdum);
1233                 serializer->doInt(&idum);
1234             }
1235             serializer->doReal(&rdum);
1236         }
1237     }
1238
1239     if (file_version >= 81)
1240     {
1241         serializer->doReal(&ir->fourier_spacing);
1242     }
1243     else
1244     {
1245         ir->fourier_spacing = 0.0;
1246     }
1247     serializer->doInt(&ir->nkx);
1248     serializer->doInt(&ir->nky);
1249     serializer->doInt(&ir->nkz);
1250     serializer->doInt(&ir->pme_order);
1251     serializer->doReal(&ir->ewald_rtol);
1252
1253     if (file_version >= 93)
1254     {
1255         serializer->doReal(&ir->ewald_rtol_lj);
1256     }
1257     else
1258     {
1259         ir->ewald_rtol_lj = ir->ewald_rtol;
1260     }
1261     serializer->doEnumAsInt(&ir->ewald_geometry);
1262     serializer->doReal(&ir->epsilon_surface);
1263
1264     /* ignore bOptFFT */
1265     if (file_version < tpxv_RemoveObsoleteParameters1)
1266     {
1267         serializer->doBool(&bdum);
1268     }
1269
1270     if (file_version >= 93)
1271     {
1272         serializer->doEnumAsInt(&ir->ljpme_combination_rule);
1273     }
1274     serializer->doBool(&ir->bContinuation);
1275     serializer->doEnumAsInt(&ir->etc);
1276     /* before version 18, ir->etc was a gmx_bool (ir->btc),
1277      * but the values 0 and 1 still mean no and
1278      * berendsen temperature coupling, respectively.
1279      */
1280     if (file_version >= 79)
1281     {
1282         serializer->doBool(&ir->bPrintNHChains);
1283     }
1284     if (file_version >= 71)
1285     {
1286         serializer->doInt(&ir->nsttcouple);
1287     }
1288     else
1289     {
1290         ir->nsttcouple = ir->nstcalcenergy;
1291     }
1292     serializer->doEnumAsInt(&ir->epc);
1293     serializer->doEnumAsInt(&ir->epct);
1294     if (file_version >= 71)
1295     {
1296         serializer->doInt(&ir->nstpcouple);
1297     }
1298     else
1299     {
1300         ir->nstpcouple = ir->nstcalcenergy;
1301     }
1302     serializer->doReal(&ir->tau_p);
1303     serializer->doRvec(&ir->ref_p[XX]);
1304     serializer->doRvec(&ir->ref_p[YY]);
1305     serializer->doRvec(&ir->ref_p[ZZ]);
1306     serializer->doRvec(&ir->compress[XX]);
1307     serializer->doRvec(&ir->compress[YY]);
1308     serializer->doRvec(&ir->compress[ZZ]);
1309     serializer->doEnumAsInt(&ir->refcoord_scaling);
1310     serializer->doRvec(&ir->posres_com);
1311     serializer->doRvec(&ir->posres_comB);
1312
1313     if (file_version < 79)
1314     {
1315         serializer->doInt(&ir->andersen_seed);
1316     }
1317     else
1318     {
1319         ir->andersen_seed = 0;
1320     }
1321
1322     serializer->doReal(&ir->shake_tol);
1323
1324     serializer->doEnumAsInt(&ir->efep);
1325     if (serializer->reading())
1326     {
1327         ir->fepvals = std::make_unique<t_lambda>();
1328     }
1329     do_fepvals(serializer, ir->fepvals.get(), file_version);
1330
1331     if (file_version >= 79)
1332     {
1333         serializer->doBool(&ir->bSimTemp);
1334         if (ir->bSimTemp)
1335         {
1336             ir->bSimTemp = TRUE;
1337         }
1338     }
1339     else
1340     {
1341         ir->bSimTemp = FALSE;
1342     }
1343     if (ir->bSimTemp)
1344     {
1345         if (serializer->reading())
1346         {
1347             ir->simtempvals = std::make_unique<t_simtemp>();
1348         }
1349         do_simtempvals(serializer, ir->simtempvals.get(), ir->fepvals->n_lambda, file_version);
1350     }
1351
1352     if (file_version >= 79)
1353     {
1354         serializer->doBool(&ir->bExpanded);
1355     }
1356     if (ir->bExpanded)
1357     {
1358         if (serializer->reading())
1359         {
1360             ir->expandedvals = std::make_unique<t_expanded>();
1361         }
1362         do_expandedvals(serializer, ir->expandedvals.get(), ir->fepvals.get(), file_version);
1363     }
1364
1365     serializer->doEnumAsInt(&ir->eDisre);
1366     serializer->doEnumAsInt(&ir->eDisreWeighting);
1367     serializer->doBool(&ir->bDisreMixed);
1368     serializer->doReal(&ir->dr_fc);
1369     serializer->doReal(&ir->dr_tau);
1370     serializer->doInt(&ir->nstdisreout);
1371     serializer->doReal(&ir->orires_fc);
1372     serializer->doReal(&ir->orires_tau);
1373     serializer->doInt(&ir->nstorireout);
1374
1375     /* ignore dihre_fc */
1376     if (file_version < 79)
1377     {
1378         serializer->doReal(&rdum);
1379     }
1380
1381     serializer->doReal(&ir->em_stepsize);
1382     serializer->doReal(&ir->em_tol);
1383     serializer->doBool(&ir->bShakeSOR);
1384     serializer->doInt(&ir->niter);
1385     serializer->doReal(&ir->fc_stepsize);
1386     serializer->doEnumAsInt(&ir->eConstrAlg);
1387     serializer->doInt(&ir->nProjOrder);
1388     serializer->doReal(&ir->LincsWarnAngle);
1389     serializer->doInt(&ir->nLincsIter);
1390     serializer->doReal(&ir->bd_fric);
1391     if (file_version >= tpxv_Use64BitRandomSeed)
1392     {
1393         serializer->doInt64(&ir->ld_seed);
1394     }
1395     else
1396     {
1397         serializer->doInt(&idum);
1398         ir->ld_seed = idum;
1399     }
1400
1401     for (i = 0; i < DIM; i++)
1402     {
1403         serializer->doRvec(&ir->deform[i]);
1404     }
1405     serializer->doReal(&ir->cos_accel);
1406
1407     serializer->doInt(&ir->userint1);
1408     serializer->doInt(&ir->userint2);
1409     serializer->doInt(&ir->userint3);
1410     serializer->doInt(&ir->userint4);
1411     serializer->doReal(&ir->userreal1);
1412     serializer->doReal(&ir->userreal2);
1413     serializer->doReal(&ir->userreal3);
1414     serializer->doReal(&ir->userreal4);
1415
1416     /* AdResS is removed, but we need to be able to read old files,
1417        and let mdrun refuse to run them */
1418     if (file_version >= 77 && file_version < tpxv_RemoveAdress)
1419     {
1420         serializer->doBool(&ir->bAdress);
1421         if (ir->bAdress)
1422         {
1423             int  idum, numThermoForceGroups, numEnergyGroups;
1424             real rdum;
1425             rvec rvecdum;
1426             serializer->doInt(&idum);
1427             serializer->doReal(&rdum);
1428             serializer->doReal(&rdum);
1429             serializer->doReal(&rdum);
1430             serializer->doInt(&idum);
1431             serializer->doInt(&idum);
1432             serializer->doRvec(&rvecdum);
1433             serializer->doInt(&numThermoForceGroups);
1434             serializer->doReal(&rdum);
1435             serializer->doInt(&numEnergyGroups);
1436             serializer->doInt(&idum);
1437
1438             if (numThermoForceGroups > 0)
1439             {
1440                 std::vector<int> idumn(numThermoForceGroups);
1441                 serializer->doIntArray(idumn.data(), idumn.size());
1442             }
1443             if (numEnergyGroups > 0)
1444             {
1445                 std::vector<int> idumn(numEnergyGroups);
1446                 serializer->doIntArray(idumn.data(), idumn.size());
1447             }
1448         }
1449     }
1450     else
1451     {
1452         ir->bAdress = FALSE;
1453     }
1454
1455     /* pull stuff */
1456     {
1457         PullingAlgorithm ePullOld = PullingAlgorithm::Umbrella;
1458
1459         if (file_version >= tpxv_PullCoordTypeGeom)
1460         {
1461             serializer->doBool(&ir->bPull);
1462         }
1463         else
1464         {
1465             serializer->doEnumAsInt(&ePullOld);
1466             ir->bPull = (ePullOld != PullingAlgorithm::Umbrella);
1467             /* We removed the first ePull=ePullNo for the enum */
1468             switch (ePullOld)
1469             {
1470                 case (PullingAlgorithm::Umbrella): break; // this is equal to not using pulling
1471                 case (PullingAlgorithm::Constraint): ePullOld = PullingAlgorithm::Umbrella; break;
1472                 case (PullingAlgorithm::ConstantForce):
1473                     ePullOld = PullingAlgorithm::Constraint;
1474                     break;
1475                 case (PullingAlgorithm::FlatBottom):
1476                     ePullOld = PullingAlgorithm::ConstantForce;
1477                     break;
1478                 case (PullingAlgorithm::FlatBottomHigh):
1479                     ePullOld = PullingAlgorithm::FlatBottom;
1480                     break;
1481                 case (PullingAlgorithm::External):
1482                     ePullOld = PullingAlgorithm::FlatBottomHigh;
1483                     break;
1484                 case (PullingAlgorithm::Count): ePullOld = PullingAlgorithm::External; break;
1485                 default: GMX_RELEASE_ASSERT(false, "Unhandled old pull algorithm");
1486             }
1487         }
1488         if (ir->bPull)
1489         {
1490             if (serializer->reading())
1491             {
1492                 ir->pull = std::make_unique<pull_params_t>();
1493             }
1494             do_pull(serializer, ir->pull.get(), file_version, ePullOld);
1495         }
1496     }
1497
1498     if (file_version >= tpxv_AcceleratedWeightHistogram)
1499     {
1500         serializer->doBool(&ir->bDoAwh);
1501
1502         if (ir->bDoAwh)
1503         {
1504             if (serializer->reading())
1505             {
1506                 ir->awhParams = std::make_unique<gmx::AwhParams>(serializer);
1507             }
1508             else
1509             {
1510                 ir->awhParams->serialize(serializer);
1511             }
1512         }
1513     }
1514     else
1515     {
1516         ir->bDoAwh = FALSE;
1517     }
1518
1519     /* Enforced rotation */
1520     if (file_version >= 74)
1521     {
1522         serializer->doBool(&ir->bRot);
1523         if (ir->bRot)
1524         {
1525             if (serializer->reading())
1526             {
1527                 snew(ir->rot, 1);
1528             }
1529             do_rot(serializer, ir->rot);
1530         }
1531     }
1532     else
1533     {
1534         ir->bRot = FALSE;
1535     }
1536
1537     /* Interactive molecular dynamics */
1538     if (file_version >= tpxv_InteractiveMolecularDynamics)
1539     {
1540         serializer->doBool(&ir->bIMD);
1541         if (ir->bIMD)
1542         {
1543             if (serializer->reading())
1544             {
1545                 snew(ir->imd, 1);
1546             }
1547             do_imd(serializer, ir->imd);
1548         }
1549     }
1550     else
1551     {
1552         /* We don't support IMD sessions for old .tpr files */
1553         ir->bIMD = FALSE;
1554     }
1555
1556     /* grpopts stuff */
1557     serializer->doInt(&ir->opts.ngtc);
1558     if (file_version >= 69)
1559     {
1560         serializer->doInt(&ir->opts.nhchainlength);
1561     }
1562     else
1563     {
1564         ir->opts.nhchainlength = 1;
1565     }
1566     int removedOptsNgacc = 0;
1567     if (serializer->reading() && file_version < tpxv_RemovedConstantAcceleration)
1568     {
1569         serializer->doInt(&removedOptsNgacc);
1570     }
1571     serializer->doInt(&ir->opts.ngfrz);
1572     serializer->doInt(&ir->opts.ngener);
1573
1574     if (serializer->reading())
1575     {
1576         snew(ir->opts.nrdf, ir->opts.ngtc);
1577         snew(ir->opts.ref_t, ir->opts.ngtc);
1578         snew(ir->opts.annealing, ir->opts.ngtc);
1579         snew(ir->opts.anneal_npoints, ir->opts.ngtc);
1580         snew(ir->opts.anneal_time, ir->opts.ngtc);
1581         snew(ir->opts.anneal_temp, ir->opts.ngtc);
1582         snew(ir->opts.tau_t, ir->opts.ngtc);
1583         snew(ir->opts.nFreeze, ir->opts.ngfrz);
1584         snew(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
1585     }
1586     if (ir->opts.ngtc > 0)
1587     {
1588         serializer->doRealArray(ir->opts.nrdf, ir->opts.ngtc);
1589         serializer->doRealArray(ir->opts.ref_t, ir->opts.ngtc);
1590         serializer->doRealArray(ir->opts.tau_t, ir->opts.ngtc);
1591     }
1592     if (ir->opts.ngfrz > 0)
1593     {
1594         serializer->doIvecArray(ir->opts.nFreeze, ir->opts.ngfrz);
1595     }
1596     if (serializer->reading() && file_version < tpxv_RemovedConstantAcceleration && removedOptsNgacc > 0)
1597     {
1598         std::vector<gmx::RVec> dummy;
1599         dummy.resize(removedOptsNgacc);
1600         serializer->doRvecArray(reinterpret_cast<rvec*>(dummy.data()), removedOptsNgacc);
1601         ir->useConstantAcceleration = std::any_of(dummy.begin(), dummy.end(), [](const gmx::RVec& vec) {
1602             return vec[XX] != 0.0 || vec[YY] != 0.0 || vec[ZZ] != 0.0;
1603         });
1604     }
1605     else
1606     {
1607         ir->useConstantAcceleration = false;
1608     }
1609     serializer->doIntArray(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
1610
1611     /* First read the lists with annealing and npoints for each group */
1612     serializer->doEnumArrayAsInt(ir->opts.annealing, ir->opts.ngtc);
1613     serializer->doIntArray(ir->opts.anneal_npoints, ir->opts.ngtc);
1614     for (j = 0; j < (ir->opts.ngtc); j++)
1615     {
1616         k = ir->opts.anneal_npoints[j];
1617         if (serializer->reading())
1618         {
1619             snew(ir->opts.anneal_time[j], k);
1620             snew(ir->opts.anneal_temp[j], k);
1621         }
1622         serializer->doRealArray(ir->opts.anneal_time[j], k);
1623         serializer->doRealArray(ir->opts.anneal_temp[j], k);
1624     }
1625     /* Walls */
1626     {
1627         serializer->doInt(&ir->nwall);
1628         serializer->doEnumAsInt(&ir->wall_type);
1629         serializer->doReal(&ir->wall_r_linpot);
1630         serializer->doInt(&ir->wall_atomtype[0]);
1631         serializer->doInt(&ir->wall_atomtype[1]);
1632         serializer->doReal(&ir->wall_density[0]);
1633         serializer->doReal(&ir->wall_density[1]);
1634         serializer->doReal(&ir->wall_ewald_zfac);
1635     }
1636
1637     /* Cosine stuff for electric fields */
1638     if (file_version < tpxv_GenericParamsForElectricField)
1639     {
1640         do_legacy_efield(serializer, &paramsObj);
1641     }
1642
1643     /* Swap ions */
1644     if (file_version >= tpxv_ComputationalElectrophysiology)
1645     {
1646         serializer->doEnumAsInt(&ir->eSwapCoords);
1647         if (ir->eSwapCoords != SwapType::No)
1648         {
1649             if (serializer->reading())
1650             {
1651                 snew(ir->swap, 1);
1652             }
1653             do_swapcoords_tpx(serializer, ir->swap, file_version);
1654         }
1655     }
1656
1657     /* QMMM reading - despite defunct we require reading for backwards
1658      * compability and correct serialization
1659      */
1660     {
1661         serializer->doBool(&ir->bQMMM);
1662         int qmmmScheme;
1663         serializer->doInt(&qmmmScheme);
1664         real unusedScalefactor;
1665         serializer->doReal(&unusedScalefactor);
1666
1667         // this is still used in Mimic
1668         serializer->doInt(&ir->opts.ngQM);
1669         if (ir->opts.ngQM > 0 && ir->bQMMM)
1670         {
1671             /* We leave in dummy i/o for removed parameters to avoid
1672              * changing the tpr format.
1673              */
1674             std::vector<int> dummyIntVec(4 * ir->opts.ngQM, 0);
1675             serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1676             dummyIntVec.clear();
1677
1678             // std::vector<bool> has no data()
1679             std::vector<char> dummyBoolVec(ir->opts.ngQM * sizeof(bool) / sizeof(char));
1680             serializer->doBoolArray(reinterpret_cast<bool*>(dummyBoolVec.data()), dummyBoolVec.size());
1681             dummyBoolVec.clear();
1682
1683             dummyIntVec.resize(2 * ir->opts.ngQM, 0);
1684             serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1685             dummyIntVec.clear();
1686
1687             std::vector<real> dummyRealVec(2 * ir->opts.ngQM, 0);
1688             serializer->doRealArray(dummyRealVec.data(), dummyRealVec.size());
1689             dummyRealVec.clear();
1690
1691             dummyIntVec.resize(3 * ir->opts.ngQM, 0);
1692             serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
1693             dummyIntVec.clear();
1694         }
1695         /* end of QMMM stuff */
1696     }
1697
1698     if (file_version >= tpxv_GenericParamsForElectricField)
1699     {
1700         if (serializer->reading())
1701         {
1702             paramsObj.mergeObject(gmx::deserializeKeyValueTree(serializer));
1703         }
1704         else
1705         {
1706             GMX_RELEASE_ASSERT(ir->params != nullptr,
1707                                "Parameters should be present when writing inputrec");
1708             gmx::serializeKeyValueTree(*ir->params, serializer);
1709         }
1710     }
1711     if (serializer->reading())
1712     {
1713         ir->params = new gmx::KeyValueTreeObject(paramsBuilder.build());
1714         // Initialize internal parameters to an empty kvt for all tpr versions
1715         ir->internalParameters = std::make_unique<gmx::KeyValueTreeObject>();
1716     }
1717
1718     if (file_version >= tpxv_GenericInternalParameters)
1719     {
1720         if (serializer->reading())
1721         {
1722             ir->internalParameters =
1723                     std::make_unique<gmx::KeyValueTreeObject>(gmx::deserializeKeyValueTree(serializer));
1724         }
1725         else
1726         {
1727             GMX_RELEASE_ASSERT(ir->internalParameters != nullptr,
1728                                "Parameters should be present when writing inputrec");
1729             gmx::serializeKeyValueTree(*ir->internalParameters, serializer);
1730         }
1731     }
1732 }
1733
1734
1735 static void do_harm(gmx::ISerializer* serializer, t_iparams* iparams)
1736 {
1737     serializer->doReal(&iparams->harmonic.rA);
1738     serializer->doReal(&iparams->harmonic.krA);
1739     serializer->doReal(&iparams->harmonic.rB);
1740     serializer->doReal(&iparams->harmonic.krB);
1741 }
1742
1743 static void do_iparams(gmx::ISerializer* serializer, t_functype ftype, t_iparams* iparams, int file_version)
1744 {
1745     int  idum;
1746     real rdum;
1747
1748     switch (ftype)
1749     {
1750         case F_ANGLES:
1751         case F_G96ANGLES:
1752         case F_BONDS:
1753         case F_G96BONDS:
1754         case F_HARMONIC:
1755         case F_IDIHS:
1756             do_harm(serializer, iparams);
1757             if ((ftype == F_ANGRES || ftype == F_ANGRESZ) && serializer->reading())
1758             {
1759                 /* Correct incorrect storage of parameters */
1760                 iparams->pdihs.phiB = iparams->pdihs.phiA;
1761                 iparams->pdihs.cpB  = iparams->pdihs.cpA;
1762             }
1763             break;
1764         case F_RESTRANGLES:
1765             serializer->doReal(&iparams->harmonic.rA);
1766             serializer->doReal(&iparams->harmonic.krA);
1767             break;
1768         case F_LINEAR_ANGLES:
1769             serializer->doReal(&iparams->linangle.klinA);
1770             serializer->doReal(&iparams->linangle.aA);
1771             serializer->doReal(&iparams->linangle.klinB);
1772             serializer->doReal(&iparams->linangle.aB);
1773             break;
1774         case F_FENEBONDS:
1775             serializer->doReal(&iparams->fene.bm);
1776             serializer->doReal(&iparams->fene.kb);
1777             break;
1778
1779         case F_RESTRBONDS:
1780             serializer->doReal(&iparams->restraint.lowA);
1781             serializer->doReal(&iparams->restraint.up1A);
1782             serializer->doReal(&iparams->restraint.up2A);
1783             serializer->doReal(&iparams->restraint.kA);
1784             serializer->doReal(&iparams->restraint.lowB);
1785             serializer->doReal(&iparams->restraint.up1B);
1786             serializer->doReal(&iparams->restraint.up2B);
1787             serializer->doReal(&iparams->restraint.kB);
1788             break;
1789         case F_TABBONDS:
1790         case F_TABBONDSNC:
1791         case F_TABANGLES:
1792         case F_TABDIHS:
1793             serializer->doReal(&iparams->tab.kA);
1794             serializer->doInt(&iparams->tab.table);
1795             serializer->doReal(&iparams->tab.kB);
1796             break;
1797         case F_CROSS_BOND_BONDS:
1798             serializer->doReal(&iparams->cross_bb.r1e);
1799             serializer->doReal(&iparams->cross_bb.r2e);
1800             serializer->doReal(&iparams->cross_bb.krr);
1801             break;
1802         case F_CROSS_BOND_ANGLES:
1803             serializer->doReal(&iparams->cross_ba.r1e);
1804             serializer->doReal(&iparams->cross_ba.r2e);
1805             serializer->doReal(&iparams->cross_ba.r3e);
1806             serializer->doReal(&iparams->cross_ba.krt);
1807             break;
1808         case F_UREY_BRADLEY:
1809             serializer->doReal(&iparams->u_b.thetaA);
1810             serializer->doReal(&iparams->u_b.kthetaA);
1811             serializer->doReal(&iparams->u_b.r13A);
1812             serializer->doReal(&iparams->u_b.kUBA);
1813             if (file_version >= 79)
1814             {
1815                 serializer->doReal(&iparams->u_b.thetaB);
1816                 serializer->doReal(&iparams->u_b.kthetaB);
1817                 serializer->doReal(&iparams->u_b.r13B);
1818                 serializer->doReal(&iparams->u_b.kUBB);
1819             }
1820             else
1821             {
1822                 iparams->u_b.thetaB  = iparams->u_b.thetaA;
1823                 iparams->u_b.kthetaB = iparams->u_b.kthetaA;
1824                 iparams->u_b.r13B    = iparams->u_b.r13A;
1825                 iparams->u_b.kUBB    = iparams->u_b.kUBA;
1826             }
1827             break;
1828         case F_QUARTIC_ANGLES:
1829             serializer->doReal(&iparams->qangle.theta);
1830             serializer->doRealArray(iparams->qangle.c, 5);
1831             break;
1832         case F_BHAM:
1833             serializer->doReal(&iparams->bham.a);
1834             serializer->doReal(&iparams->bham.b);
1835             serializer->doReal(&iparams->bham.c);
1836             break;
1837         case F_MORSE:
1838             serializer->doReal(&iparams->morse.b0A);
1839             serializer->doReal(&iparams->morse.cbA);
1840             serializer->doReal(&iparams->morse.betaA);
1841             if (file_version >= 79)
1842             {
1843                 serializer->doReal(&iparams->morse.b0B);
1844                 serializer->doReal(&iparams->morse.cbB);
1845                 serializer->doReal(&iparams->morse.betaB);
1846             }
1847             else
1848             {
1849                 iparams->morse.b0B   = iparams->morse.b0A;
1850                 iparams->morse.cbB   = iparams->morse.cbA;
1851                 iparams->morse.betaB = iparams->morse.betaA;
1852             }
1853             break;
1854         case F_CUBICBONDS:
1855             serializer->doReal(&iparams->cubic.b0);
1856             serializer->doReal(&iparams->cubic.kb);
1857             serializer->doReal(&iparams->cubic.kcub);
1858             break;
1859         case F_CONNBONDS: break;
1860         case F_POLARIZATION: serializer->doReal(&iparams->polarize.alpha); break;
1861         case F_ANHARM_POL:
1862             serializer->doReal(&iparams->anharm_polarize.alpha);
1863             serializer->doReal(&iparams->anharm_polarize.drcut);
1864             serializer->doReal(&iparams->anharm_polarize.khyp);
1865             break;
1866         case F_WATER_POL:
1867             serializer->doReal(&iparams->wpol.al_x);
1868             serializer->doReal(&iparams->wpol.al_y);
1869             serializer->doReal(&iparams->wpol.al_z);
1870             serializer->doReal(&iparams->wpol.rOH);
1871             serializer->doReal(&iparams->wpol.rHH);
1872             serializer->doReal(&iparams->wpol.rOD);
1873             break;
1874         case F_THOLE_POL:
1875             serializer->doReal(&iparams->thole.a);
1876             serializer->doReal(&iparams->thole.alpha1);
1877             serializer->doReal(&iparams->thole.alpha2);
1878             serializer->doReal(&iparams->thole.rfac);
1879             break;
1880         case F_LJ:
1881             serializer->doReal(&iparams->lj.c6);
1882             serializer->doReal(&iparams->lj.c12);
1883             break;
1884         case F_LJ14:
1885             serializer->doReal(&iparams->lj14.c6A);
1886             serializer->doReal(&iparams->lj14.c12A);
1887             serializer->doReal(&iparams->lj14.c6B);
1888             serializer->doReal(&iparams->lj14.c12B);
1889             break;
1890         case F_LJC14_Q:
1891             serializer->doReal(&iparams->ljc14.fqq);
1892             serializer->doReal(&iparams->ljc14.qi);
1893             serializer->doReal(&iparams->ljc14.qj);
1894             serializer->doReal(&iparams->ljc14.c6);
1895             serializer->doReal(&iparams->ljc14.c12);
1896             break;
1897         case F_LJC_PAIRS_NB:
1898             serializer->doReal(&iparams->ljcnb.qi);
1899             serializer->doReal(&iparams->ljcnb.qj);
1900             serializer->doReal(&iparams->ljcnb.c6);
1901             serializer->doReal(&iparams->ljcnb.c12);
1902             break;
1903         case F_PDIHS:
1904         case F_PIDIHS:
1905         case F_ANGRES:
1906         case F_ANGRESZ:
1907             serializer->doReal(&iparams->pdihs.phiA);
1908             serializer->doReal(&iparams->pdihs.cpA);
1909             serializer->doReal(&iparams->pdihs.phiB);
1910             serializer->doReal(&iparams->pdihs.cpB);
1911             serializer->doInt(&iparams->pdihs.mult);
1912             break;
1913         case F_RESTRDIHS:
1914             serializer->doReal(&iparams->pdihs.phiA);
1915             serializer->doReal(&iparams->pdihs.cpA);
1916             break;
1917         case F_DISRES:
1918             serializer->doInt(&iparams->disres.label);
1919             serializer->doInt(&iparams->disres.type);
1920             serializer->doReal(&iparams->disres.low);
1921             serializer->doReal(&iparams->disres.up1);
1922             serializer->doReal(&iparams->disres.up2);
1923             serializer->doReal(&iparams->disres.kfac);
1924             break;
1925         case F_ORIRES:
1926             serializer->doInt(&iparams->orires.ex);
1927             serializer->doInt(&iparams->orires.label);
1928             serializer->doInt(&iparams->orires.power);
1929             serializer->doReal(&iparams->orires.c);
1930             serializer->doReal(&iparams->orires.obs);
1931             serializer->doReal(&iparams->orires.kfac);
1932             break;
1933         case F_DIHRES:
1934             if (file_version < 82)
1935             {
1936                 serializer->doInt(&idum);
1937                 serializer->doInt(&idum);
1938             }
1939             serializer->doReal(&iparams->dihres.phiA);
1940             serializer->doReal(&iparams->dihres.dphiA);
1941             serializer->doReal(&iparams->dihres.kfacA);
1942             if (file_version >= 82)
1943             {
1944                 serializer->doReal(&iparams->dihres.phiB);
1945                 serializer->doReal(&iparams->dihres.dphiB);
1946                 serializer->doReal(&iparams->dihres.kfacB);
1947             }
1948             else
1949             {
1950                 iparams->dihres.phiB  = iparams->dihres.phiA;
1951                 iparams->dihres.dphiB = iparams->dihres.dphiA;
1952                 iparams->dihres.kfacB = iparams->dihres.kfacA;
1953             }
1954             break;
1955         case F_POSRES:
1956             serializer->doRvec(&iparams->posres.pos0A);
1957             serializer->doRvec(&iparams->posres.fcA);
1958             serializer->doRvec(&iparams->posres.pos0B);
1959             serializer->doRvec(&iparams->posres.fcB);
1960             break;
1961         case F_FBPOSRES:
1962             serializer->doInt(&iparams->fbposres.geom);
1963             serializer->doRvec(&iparams->fbposres.pos0);
1964             serializer->doReal(&iparams->fbposres.r);
1965             serializer->doReal(&iparams->fbposres.k);
1966             break;
1967         case F_CBTDIHS: serializer->doRealArray(iparams->cbtdihs.cbtcA, NR_CBTDIHS); break;
1968         case F_RBDIHS:
1969             // Fall-through intended
1970         case F_FOURDIHS:
1971             /* Fourier dihedrals are internally represented
1972              * as Ryckaert-Bellemans since those are faster to compute.
1973              */
1974             serializer->doRealArray(iparams->rbdihs.rbcA, NR_RBDIHS);
1975             serializer->doRealArray(iparams->rbdihs.rbcB, NR_RBDIHS);
1976             break;
1977         case F_CONSTR:
1978         case F_CONSTRNC:
1979             serializer->doReal(&iparams->constr.dA);
1980             serializer->doReal(&iparams->constr.dB);
1981             break;
1982         case F_SETTLE:
1983             serializer->doReal(&iparams->settle.doh);
1984             serializer->doReal(&iparams->settle.dhh);
1985             break;
1986         case F_VSITE1: break; // VSite1 has 0 parameters
1987         case F_VSITE2:
1988         case F_VSITE2FD: serializer->doReal(&iparams->vsite.a); break;
1989         case F_VSITE3:
1990         case F_VSITE3FD:
1991         case F_VSITE3FAD:
1992             serializer->doReal(&iparams->vsite.a);
1993             serializer->doReal(&iparams->vsite.b);
1994             break;
1995         case F_VSITE3OUT:
1996         case F_VSITE4FD:
1997         case F_VSITE4FDN:
1998             serializer->doReal(&iparams->vsite.a);
1999             serializer->doReal(&iparams->vsite.b);
2000             serializer->doReal(&iparams->vsite.c);
2001             break;
2002         case F_VSITEN:
2003             serializer->doInt(&iparams->vsiten.n);
2004             serializer->doReal(&iparams->vsiten.a);
2005             break;
2006         case F_GB12_NOLONGERUSED:
2007         case F_GB13_NOLONGERUSED:
2008         case F_GB14_NOLONGERUSED:
2009             // Implicit solvent parameters can still be read, but never used
2010             if (serializer->reading())
2011             {
2012                 if (file_version < 68)
2013                 {
2014                     serializer->doReal(&rdum);
2015                     serializer->doReal(&rdum);
2016                     serializer->doReal(&rdum);
2017                     serializer->doReal(&rdum);
2018                 }
2019                 if (file_version < tpxv_RemoveImplicitSolvation)
2020                 {
2021                     serializer->doReal(&rdum);
2022                     serializer->doReal(&rdum);
2023                     serializer->doReal(&rdum);
2024                     serializer->doReal(&rdum);
2025                     serializer->doReal(&rdum);
2026                 }
2027             }
2028             break;
2029         case F_CMAP:
2030             serializer->doInt(&iparams->cmap.cmapA);
2031             serializer->doInt(&iparams->cmap.cmapB);
2032             break;
2033         default:
2034             gmx_fatal(FARGS,
2035                       "unknown function type %d (%s) in %s line %d",
2036                       ftype,
2037                       interaction_function[ftype].name,
2038                       __FILE__,
2039                       __LINE__);
2040     }
2041 }
2042
2043 static void do_ilist(gmx::ISerializer* serializer, InteractionList* ilist)
2044 {
2045     int nr = ilist->size();
2046     serializer->doInt(&nr);
2047     if (serializer->reading())
2048     {
2049         ilist->iatoms.resize(nr);
2050     }
2051     serializer->doIntArray(ilist->iatoms.data(), ilist->size());
2052 }
2053
2054 static void do_ffparams(gmx::ISerializer* serializer, gmx_ffparams_t* ffparams, int file_version)
2055 {
2056     serializer->doInt(&ffparams->atnr);
2057     int numTypes = ffparams->numTypes();
2058     serializer->doInt(&numTypes);
2059     if (serializer->reading())
2060     {
2061         ffparams->functype.resize(numTypes);
2062         ffparams->iparams.resize(numTypes);
2063     }
2064     /* Read/write all the function types */
2065     serializer->doIntArray(ffparams->functype.data(), ffparams->functype.size());
2066
2067     if (file_version >= 66)
2068     {
2069         serializer->doDouble(&ffparams->reppow);
2070     }
2071     else
2072     {
2073         ffparams->reppow = 12.0;
2074     }
2075
2076     serializer->doReal(&ffparams->fudgeQQ);
2077
2078     /* Check whether all these function types are supported by the code.
2079      * In practice the code is backwards compatible, which means that the
2080      * numbering may have to be altered from old numbering to new numbering
2081      */
2082     for (int i = 0; i < ffparams->numTypes(); i++)
2083     {
2084         if (serializer->reading())
2085         {
2086             /* Loop over file versions */
2087             for (int k = 0; k < NFTUPD; k++)
2088             {
2089                 /* Compare the read file_version to the update table */
2090                 if ((file_version < ftupd[k].fvnr) && (ffparams->functype[i] >= ftupd[k].ftype))
2091                 {
2092                     ffparams->functype[i] += 1;
2093                 }
2094             }
2095         }
2096
2097         do_iparams(serializer, ffparams->functype[i], &ffparams->iparams[i], file_version);
2098     }
2099 }
2100
2101 static void add_settle_atoms(InteractionList* ilist)
2102 {
2103     int i;
2104
2105     /* Settle used to only store the first atom: add the other two */
2106     ilist->iatoms.resize(2 * ilist->size());
2107     for (i = ilist->size() / 4 - 1; i >= 0; i--)
2108     {
2109         ilist->iatoms[4 * i + 0] = ilist->iatoms[2 * i + 0];
2110         ilist->iatoms[4 * i + 1] = ilist->iatoms[2 * i + 1];
2111         ilist->iatoms[4 * i + 2] = ilist->iatoms[2 * i + 1] + 1;
2112         ilist->iatoms[4 * i + 3] = ilist->iatoms[2 * i + 1] + 2;
2113     }
2114 }
2115
2116 static void do_ilists(gmx::ISerializer* serializer, InteractionLists* ilists, int file_version)
2117 {
2118     GMX_RELEASE_ASSERT(ilists, "Need a valid ilists object");
2119     GMX_RELEASE_ASSERT(ilists->size() == F_NRE,
2120                        "The code needs to be in sync with InteractionLists");
2121
2122     for (int j = 0; j < F_NRE; j++)
2123     {
2124         InteractionList& ilist  = (*ilists)[j];
2125         gmx_bool         bClear = FALSE;
2126         if (serializer->reading())
2127         {
2128             for (int k = 0; k < NFTUPD; k++)
2129             {
2130                 if ((file_version < ftupd[k].fvnr) && (j == ftupd[k].ftype))
2131                 {
2132                     bClear = TRUE;
2133                 }
2134             }
2135         }
2136         if (bClear)
2137         {
2138             ilist.iatoms.clear();
2139         }
2140         else
2141         {
2142             do_ilist(serializer, &ilist);
2143             if (file_version < 78 && j == F_SETTLE && !ilist.empty())
2144             {
2145                 add_settle_atoms(&ilist);
2146             }
2147         }
2148     }
2149 }
2150
2151 static void do_block(gmx::ISerializer* serializer, t_block* block)
2152 {
2153     serializer->doInt(&block->nr);
2154     if (serializer->reading())
2155     {
2156         if ((block->nalloc_index > 0) && (nullptr != block->index))
2157         {
2158             sfree(block->index);
2159         }
2160         block->nalloc_index = block->nr + 1;
2161         snew(block->index, block->nalloc_index);
2162     }
2163     serializer->doIntArray(block->index, block->nr + 1);
2164 }
2165
2166 static void doListOfLists(gmx::ISerializer* serializer, gmx::ListOfLists<int>* listOfLists)
2167 {
2168     int numLists = listOfLists->ssize();
2169     serializer->doInt(&numLists);
2170     int numElements = listOfLists->elementsView().ssize();
2171     serializer->doInt(&numElements);
2172     if (serializer->reading())
2173     {
2174         std::vector<int> listRanges(numLists + 1);
2175         serializer->doIntArray(listRanges.data(), numLists + 1);
2176         std::vector<int> elements(numElements);
2177         serializer->doIntArray(elements.data(), numElements);
2178         *listOfLists = gmx::ListOfLists<int>(std::move(listRanges), std::move(elements));
2179     }
2180     else
2181     {
2182         serializer->doIntArray(const_cast<int*>(listOfLists->listRangesView().data()), numLists + 1);
2183         serializer->doIntArray(const_cast<int*>(listOfLists->elementsView().data()), numElements);
2184     }
2185 }
2186
2187 /* This is a primitive routine to make it possible to translate atomic numbers
2188  * to element names when reading TPR files, without making the Gromacs library
2189  * directory a dependency on mdrun (which is the case if we need elements.dat).
2190  */
2191 static const char* atomicnumber_to_element(int atomicnumber)
2192 {
2193     const char* p;
2194
2195     /* This does not have to be complete, so we only include elements likely
2196      * to occur in PDB files.
2197      */
2198     switch (atomicnumber)
2199     {
2200         case 1: p = "H"; break;
2201         case 5: p = "B"; break;
2202         case 6: p = "C"; break;
2203         case 7: p = "N"; break;
2204         case 8: p = "O"; break;
2205         case 9: p = "F"; break;
2206         case 11: p = "Na"; break;
2207         case 12: p = "Mg"; break;
2208         case 15: p = "P"; break;
2209         case 16: p = "S"; break;
2210         case 17: p = "Cl"; break;
2211         case 18: p = "Ar"; break;
2212         case 19: p = "K"; break;
2213         case 20: p = "Ca"; break;
2214         case 25: p = "Mn"; break;
2215         case 26: p = "Fe"; break;
2216         case 28: p = "Ni"; break;
2217         case 29: p = "Cu"; break;
2218         case 30: p = "Zn"; break;
2219         case 35: p = "Br"; break;
2220         case 47: p = "Ag"; break;
2221         default: p = ""; break;
2222     }
2223     return p;
2224 }
2225
2226
2227 static void do_atom(gmx::ISerializer* serializer, t_atom* atom)
2228 {
2229     serializer->doReal(&atom->m);
2230     serializer->doReal(&atom->q);
2231     serializer->doReal(&atom->mB);
2232     serializer->doReal(&atom->qB);
2233     serializer->doUShort(&atom->type);
2234     serializer->doUShort(&atom->typeB);
2235     serializer->doEnumAsInt(&atom->ptype);
2236     serializer->doInt(&atom->resind);
2237     serializer->doInt(&atom->atomnumber);
2238     if (serializer->reading())
2239     {
2240         /* Set element string from atomic number if present.
2241          * This routine returns an empty string if the name is not found.
2242          */
2243         std::strncpy(atom->elem, atomicnumber_to_element(atom->atomnumber), 4);
2244         /* avoid warnings about potentially unterminated string */
2245         atom->elem[3] = '\0';
2246     }
2247 }
2248
2249 static void do_grps(gmx::ISerializer* serializer, gmx::ArrayRef<AtomGroupIndices> grps)
2250 {
2251     for (auto& group : grps)
2252     {
2253         int size = group.size();
2254         serializer->doInt(&size);
2255         if (serializer->reading())
2256         {
2257             group.resize(size);
2258         }
2259         serializer->doIntArray(group.data(), size);
2260     }
2261 }
2262
2263 static void do_symstr(gmx::ISerializer* serializer, char*** nm, t_symtab* symtab)
2264 {
2265     int ls;
2266
2267     if (serializer->reading())
2268     {
2269         serializer->doInt(&ls);
2270         *nm = get_symtab_handle(symtab, ls);
2271     }
2272     else
2273     {
2274         ls = lookup_symtab(symtab, *nm);
2275         serializer->doInt(&ls);
2276     }
2277 }
2278
2279 static void do_strstr(gmx::ISerializer* serializer, int nstr, char*** nm, t_symtab* symtab)
2280 {
2281     int j;
2282
2283     for (j = 0; (j < nstr); j++)
2284     {
2285         do_symstr(serializer, &(nm[j]), symtab);
2286     }
2287 }
2288
2289 static void do_resinfo(gmx::ISerializer* serializer, int n, t_resinfo* ri, t_symtab* symtab, int file_version)
2290 {
2291     int j;
2292
2293     for (j = 0; (j < n); j++)
2294     {
2295         do_symstr(serializer, &(ri[j].name), symtab);
2296         if (file_version >= 63)
2297         {
2298             serializer->doInt(&ri[j].nr);
2299             serializer->doUChar(&ri[j].ic);
2300         }
2301         else
2302         {
2303             ri[j].nr = j + 1;
2304             ri[j].ic = ' ';
2305         }
2306     }
2307 }
2308
2309 static void do_atoms(gmx::ISerializer* serializer, t_atoms* atoms, t_symtab* symtab, int file_version)
2310 {
2311     int i;
2312
2313     serializer->doInt(&atoms->nr);
2314     serializer->doInt(&atoms->nres);
2315     if (serializer->reading())
2316     {
2317         /* Since we have always written all t_atom properties in the tpr file
2318          * (at least for all backward compatible versions), we don't store
2319          * but simple set the booleans here.
2320          */
2321         atoms->haveMass    = TRUE;
2322         atoms->haveCharge  = TRUE;
2323         atoms->haveType    = TRUE;
2324         atoms->haveBState  = TRUE;
2325         atoms->havePdbInfo = FALSE;
2326
2327         snew(atoms->atom, atoms->nr);
2328         snew(atoms->atomname, atoms->nr);
2329         snew(atoms->atomtype, atoms->nr);
2330         snew(atoms->atomtypeB, atoms->nr);
2331         snew(atoms->resinfo, atoms->nres);
2332         atoms->pdbinfo = nullptr;
2333     }
2334     else
2335     {
2336         GMX_RELEASE_ASSERT(atoms->haveMass && atoms->haveCharge && atoms->haveType && atoms->haveBState,
2337                            "Mass, charge, atomtype and B-state parameters should be present in "
2338                            "t_atoms when writing a tpr file");
2339     }
2340     for (i = 0; (i < atoms->nr); i++)
2341     {
2342         do_atom(serializer, &atoms->atom[i]);
2343     }
2344     do_strstr(serializer, atoms->nr, atoms->atomname, symtab);
2345     do_strstr(serializer, atoms->nr, atoms->atomtype, symtab);
2346     do_strstr(serializer, atoms->nr, atoms->atomtypeB, symtab);
2347
2348     do_resinfo(serializer, atoms->nres, atoms->resinfo, symtab, file_version);
2349 }
2350
2351 static void do_groups(gmx::ISerializer* serializer, SimulationGroups* groups, t_symtab* symtab)
2352 {
2353     do_grps(serializer, groups->groups);
2354     int numberOfGroupNames = groups->groupNames.size();
2355     serializer->doInt(&numberOfGroupNames);
2356     if (serializer->reading())
2357     {
2358         groups->groupNames.resize(numberOfGroupNames);
2359     }
2360     do_strstr(serializer, numberOfGroupNames, groups->groupNames.data(), symtab);
2361     for (auto group : gmx::keysOf(groups->groupNumbers))
2362     {
2363         int numberOfGroupNumbers = groups->numberOfGroupNumbers(group);
2364         serializer->doInt(&numberOfGroupNumbers);
2365         if (numberOfGroupNumbers != 0)
2366         {
2367             if (serializer->reading())
2368             {
2369                 groups->groupNumbers[group].resize(numberOfGroupNumbers);
2370             }
2371             serializer->doUCharArray(groups->groupNumbers[group].data(), numberOfGroupNumbers);
2372         }
2373     }
2374 }
2375
2376 static void do_atomtypes(gmx::ISerializer* serializer, t_atomtypes* atomtypes, int file_version)
2377 {
2378     int j;
2379
2380     serializer->doInt(&atomtypes->nr);
2381     j = atomtypes->nr;
2382     if (serializer->reading())
2383     {
2384         snew(atomtypes->atomnumber, j);
2385     }
2386     if (serializer->reading() && file_version < tpxv_RemoveImplicitSolvation)
2387     {
2388         std::vector<real> dummy(atomtypes->nr, 0);
2389         serializer->doRealArray(dummy.data(), dummy.size());
2390         serializer->doRealArray(dummy.data(), dummy.size());
2391         serializer->doRealArray(dummy.data(), dummy.size());
2392     }
2393     serializer->doIntArray(atomtypes->atomnumber, j);
2394
2395     if (serializer->reading() && file_version >= 60 && file_version < tpxv_RemoveImplicitSolvation)
2396     {
2397         std::vector<real> dummy(atomtypes->nr, 0);
2398         serializer->doRealArray(dummy.data(), dummy.size());
2399         serializer->doRealArray(dummy.data(), dummy.size());
2400     }
2401 }
2402
2403 static void do_symtab(gmx::ISerializer* serializer, t_symtab* symtab)
2404 {
2405     int       i, nr;
2406     t_symbuf* symbuf;
2407
2408     serializer->doInt(&symtab->nr);
2409     nr = symtab->nr;
2410     if (serializer->reading())
2411     {
2412         snew(symtab->symbuf, 1);
2413         symbuf          = symtab->symbuf;
2414         symbuf->bufsize = nr;
2415         snew(symbuf->buf, nr);
2416         for (i = 0; (i < nr); i++)
2417         {
2418             std::string buf;
2419             serializer->doString(&buf);
2420             symbuf->buf[i] = gmx_strdup(buf.c_str());
2421         }
2422     }
2423     else
2424     {
2425         symbuf = symtab->symbuf;
2426         while (symbuf != nullptr)
2427         {
2428             for (i = 0; (i < symbuf->bufsize) && (i < nr); i++)
2429             {
2430                 std::string buf = symbuf->buf[i];
2431                 serializer->doString(&buf);
2432             }
2433             nr -= i;
2434             symbuf = symbuf->next;
2435         }
2436         if (nr != 0)
2437         {
2438             gmx_fatal(FARGS, "nr of symtab strings left: %d", nr);
2439         }
2440     }
2441 }
2442
2443 static void do_cmap(gmx::ISerializer* serializer, gmx_cmap_t* cmap_grid)
2444 {
2445
2446     int ngrid = cmap_grid->cmapdata.size();
2447     serializer->doInt(&ngrid);
2448     serializer->doInt(&cmap_grid->grid_spacing);
2449
2450     int gs    = cmap_grid->grid_spacing;
2451     int nelem = gs * gs;
2452
2453     if (serializer->reading())
2454     {
2455         cmap_grid->cmapdata.resize(ngrid);
2456
2457         for (int i = 0; i < ngrid; i++)
2458         {
2459             cmap_grid->cmapdata[i].cmap.resize(4 * nelem);
2460         }
2461     }
2462
2463     for (int i = 0; i < ngrid; i++)
2464     {
2465         for (int j = 0; j < nelem; j++)
2466         {
2467             serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4]);
2468             serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 1]);
2469             serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 2]);
2470             serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 3]);
2471         }
2472     }
2473 }
2474
2475
2476 static void do_moltype(gmx::ISerializer* serializer, gmx_moltype_t* molt, t_symtab* symtab, int file_version)
2477 {
2478     do_symstr(serializer, &(molt->name), symtab);
2479
2480     do_atoms(serializer, &molt->atoms, symtab, file_version);
2481
2482     do_ilists(serializer, &molt->ilist, file_version);
2483
2484     /* TODO: Remove the obsolete charge group index from the file */
2485     t_block cgs;
2486     cgs.nr           = molt->atoms.nr;
2487     cgs.nalloc_index = cgs.nr + 1;
2488     snew(cgs.index, cgs.nalloc_index);
2489     for (int i = 0; i < cgs.nr + 1; i++)
2490     {
2491         cgs.index[i] = i;
2492     }
2493     do_block(serializer, &cgs);
2494     sfree(cgs.index);
2495
2496     /* This used to be in the atoms struct */
2497     doListOfLists(serializer, &molt->excls);
2498 }
2499
2500 static void do_molblock(gmx::ISerializer* serializer, gmx_molblock_t* molb, int numAtomsPerMolecule)
2501 {
2502     serializer->doInt(&molb->type);
2503     serializer->doInt(&molb->nmol);
2504     /* To maintain forward topology reading compatibility, we store #atoms.
2505      * TODO: Change this to conditional reading of a dummy int when we
2506      *       increase tpx_generation.
2507      */
2508     serializer->doInt(&numAtomsPerMolecule);
2509     /* Position restraint coordinates */
2510     int numPosres_xA = molb->posres_xA.size();
2511     serializer->doInt(&numPosres_xA);
2512     if (numPosres_xA > 0)
2513     {
2514         if (serializer->reading())
2515         {
2516             molb->posres_xA.resize(numPosres_xA);
2517         }
2518         serializer->doRvecArray(as_rvec_array(molb->posres_xA.data()), numPosres_xA);
2519     }
2520     int numPosres_xB = molb->posres_xB.size();
2521     serializer->doInt(&numPosres_xB);
2522     if (numPosres_xB > 0)
2523     {
2524         if (serializer->reading())
2525         {
2526             molb->posres_xB.resize(numPosres_xB);
2527         }
2528         serializer->doRvecArray(as_rvec_array(molb->posres_xB.data()), numPosres_xB);
2529     }
2530 }
2531
2532 static void set_disres_npair(gmx_mtop_t* mtop)
2533 {
2534     gmx_mtop_ilistloop_t iloop;
2535     int                  nmol;
2536
2537     gmx::ArrayRef<t_iparams> ip = mtop->ffparams.iparams;
2538
2539     iloop = gmx_mtop_ilistloop_init(*mtop);
2540     while (const InteractionLists* ilist = gmx_mtop_ilistloop_next(iloop, &nmol))
2541     {
2542         const InteractionList& il = (*ilist)[F_DISRES];
2543
2544         if (!il.empty())
2545         {
2546             gmx::ArrayRef<const int> a     = il.iatoms;
2547             int                      npair = 0;
2548             for (int i = 0; i < il.size(); i += 3)
2549             {
2550                 npair++;
2551                 if (i + 3 == il.size() || ip[a[i]].disres.label != ip[a[i + 3]].disres.label)
2552                 {
2553                     ip[a[i]].disres.npair = npair;
2554                     npair                 = 0;
2555                 }
2556             }
2557         }
2558     }
2559 }
2560
2561 static void do_mtop(gmx::ISerializer* serializer, gmx_mtop_t* mtop, int file_version)
2562 {
2563     do_symtab(serializer, &(mtop->symtab));
2564
2565     do_symstr(serializer, &(mtop->name), &(mtop->symtab));
2566
2567     do_ffparams(serializer, &mtop->ffparams, file_version);
2568
2569     int nmoltype = mtop->moltype.size();
2570     serializer->doInt(&nmoltype);
2571     if (serializer->reading())
2572     {
2573         mtop->moltype.resize(nmoltype);
2574     }
2575     for (gmx_moltype_t& moltype : mtop->moltype)
2576     {
2577         do_moltype(serializer, &moltype, &mtop->symtab, file_version);
2578     }
2579
2580     int nmolblock = mtop->molblock.size();
2581     serializer->doInt(&nmolblock);
2582     if (serializer->reading())
2583     {
2584         mtop->molblock.resize(nmolblock);
2585     }
2586     for (gmx_molblock_t& molblock : mtop->molblock)
2587     {
2588         int numAtomsPerMolecule = (serializer->reading() ? 0 : mtop->moltype[molblock.type].atoms.nr);
2589         do_molblock(serializer, &molblock, numAtomsPerMolecule);
2590     }
2591     serializer->doInt(&mtop->natoms);
2592
2593     if (file_version >= tpxv_IntermolecularBondeds)
2594     {
2595         serializer->doBool(&mtop->bIntermolecularInteractions);
2596         if (mtop->bIntermolecularInteractions)
2597         {
2598             if (serializer->reading())
2599             {
2600                 mtop->intermolecular_ilist = std::make_unique<InteractionLists>();
2601             }
2602             do_ilists(serializer, mtop->intermolecular_ilist.get(), file_version);
2603         }
2604     }
2605     else
2606     {
2607         mtop->bIntermolecularInteractions = FALSE;
2608     }
2609
2610     do_atomtypes(serializer, &(mtop->atomtypes), file_version);
2611
2612     if (file_version >= 65)
2613     {
2614         do_cmap(serializer, &mtop->ffparams.cmap_grid);
2615     }
2616     else
2617     {
2618         mtop->ffparams.cmap_grid.grid_spacing = 0;
2619         mtop->ffparams.cmap_grid.cmapdata.clear();
2620     }
2621
2622     do_groups(serializer, &mtop->groups, &(mtop->symtab));
2623     if (file_version < tpxv_RemovedConstantAcceleration)
2624     {
2625         mtop->groups.groups[SimulationAtomGroupType::AccelerationUnused].clear();
2626         mtop->groups.groupNumbers[SimulationAtomGroupType::AccelerationUnused].clear();
2627     }
2628
2629     mtop->haveMoleculeIndices = true;
2630
2631     if (file_version >= tpxv_StoreNonBondedInteractionExclusionGroup)
2632     {
2633         std::int64_t intermolecularExclusionGroupSize = gmx::ssize(mtop->intermolecularExclusionGroup);
2634         serializer->doInt64(&intermolecularExclusionGroupSize);
2635         GMX_RELEASE_ASSERT(intermolecularExclusionGroupSize >= 0,
2636                            "Number of atoms with excluded intermolecular non-bonded interactions "
2637                            "is negative.");
2638         mtop->intermolecularExclusionGroup.resize(intermolecularExclusionGroupSize); // no effect when writing
2639         serializer->doIntArray(mtop->intermolecularExclusionGroup.data(),
2640                                mtop->intermolecularExclusionGroup.size());
2641     }
2642
2643     if (serializer->reading())
2644     {
2645         close_symtab(&(mtop->symtab));
2646     }
2647 }
2648
2649 /*! \brief
2650  * Read the first part of the TPR file to find general system information.
2651  *
2652  * If \p TopOnlyOK is true then we can read even future versions
2653  * of tpx files, provided the \p fileGeneration hasn't changed.
2654  * If it is false, we need the \p ir too, and bail out
2655  * if the file is newer than the program.
2656  *
2657  * The version and generation of the topology (see top of this file)
2658  * are returned in the two last arguments, if those arguments are non-nullptr.
2659  *
2660  * If possible, we will read the \p ir even when \p TopOnlyOK is true.
2661  *
2662  * \param[in,out] serializer The serializer used to handle header processing.
2663  * \param[in,out] tpx File header datastructure.
2664  * \param[in]     filename The name of the file being read/written
2665  * \param[in,out] fio File handle.
2666  * \param[in] TopOnlyOK If not reading \p ir is fine or not.
2667  */
2668 static void do_tpxheader(gmx::FileIOXdrSerializer* serializer,
2669                          TpxFileHeader*            tpx,
2670                          const char*               filename,
2671                          t_fileio*                 fio,
2672                          bool                      TopOnlyOK)
2673 {
2674     int  precision;
2675     int  idum = 0;
2676     real rdum = 0;
2677
2678     /* XDR binary topology file */
2679     precision = sizeof(real);
2680     std::string buf;
2681     std::string fileTag;
2682     if (serializer->reading())
2683     {
2684         serializer->doString(&buf);
2685         if (std::strncmp(buf.c_str(), "VERSION", 7) != 0)
2686         {
2687             gmx_fatal(
2688                     FARGS,
2689                     "Can not read file %s,\n"
2690                     "             this file is from a GROMACS version which is older than 2.0\n"
2691                     "             Make a new one with grompp or use a gro or pdb file, if possible",
2692                     filename);
2693         }
2694         // We need to know the precision used to write the TPR file, to match it
2695         // to the precision of the currently running binary. If the precisions match
2696         // there is no problem, but mismatching precision needs to be accounted for
2697         // by reading into temporary variables of the correct precision instead
2698         // of the desired target datastructures.
2699         serializer->doInt(&precision);
2700         tpx->isDouble = (precision == sizeof(double));
2701         if ((precision != sizeof(float)) && !tpx->isDouble)
2702         {
2703             gmx_fatal(FARGS,
2704                       "Unknown precision in file %s: real is %d bytes "
2705                       "instead of %zu or %zu",
2706                       filename,
2707                       precision,
2708                       sizeof(float),
2709                       sizeof(double));
2710         }
2711         gmx_fio_setprecision(fio, tpx->isDouble);
2712         fprintf(stderr,
2713                 "Reading file %s, %s (%s precision)\n",
2714                 filename,
2715                 buf.c_str(),
2716                 tpx->isDouble ? "double" : "single");
2717     }
2718     else
2719     {
2720         buf = gmx::formatString("VERSION %s", gmx_version());
2721         serializer->doString(&buf);
2722         gmx_fio_setprecision(fio, tpx->isDouble);
2723         serializer->doInt(&precision);
2724         fileTag = gmx::formatString("%s", tpx_tag);
2725     }
2726
2727     /* Check versions! */
2728     serializer->doInt(&tpx->fileVersion);
2729
2730     /* This is for backward compatibility with development versions 77-79
2731      * where the tag was, mistakenly, placed before the generation,
2732      * which would cause a segv instead of a proper error message
2733      * when reading the topology only from tpx with <77 code.
2734      */
2735     if (tpx->fileVersion >= 77 && tpx->fileVersion <= 79)
2736     {
2737         serializer->doString(&fileTag);
2738     }
2739
2740     serializer->doInt(&tpx->fileGeneration);
2741
2742     if (tpx->fileVersion >= 81)
2743     {
2744         serializer->doString(&fileTag);
2745     }
2746     if (serializer->reading())
2747     {
2748         if (tpx->fileVersion < 77)
2749         {
2750             /* Versions before 77 don't have the tag, set it to release */
2751             fileTag = gmx::formatString("%s", TPX_TAG_RELEASE);
2752         }
2753
2754         if (fileTag != tpx_tag)
2755         {
2756             fprintf(stderr, "Note: file tpx tag '%s', software tpx tag '%s'\n", fileTag.c_str(), tpx_tag);
2757
2758             /* We only support reading tpx files with the same tag as the code
2759              * or tpx files with the release tag and with lower version number.
2760              */
2761             if (fileTag != TPX_TAG_RELEASE && tpx->fileVersion < tpx_version)
2762             {
2763                 gmx_fatal(FARGS,
2764                           "tpx tag/version mismatch: reading tpx file (%s) version %d, tag '%s' "
2765                           "with program for tpx version %d, tag '%s'",
2766                           filename,
2767                           tpx->fileVersion,
2768                           fileTag.c_str(),
2769                           tpx_version,
2770                           tpx_tag);
2771             }
2772         }
2773     }
2774
2775     if ((tpx->fileVersion <= tpx_incompatible_version)
2776         || ((tpx->fileVersion > tpx_version) && !TopOnlyOK) || (tpx->fileGeneration > tpx_generation)
2777         || tpx_version == 80) /*80 was used by both 5.0-dev and 4.6-dev*/
2778     {
2779         gmx_fatal(FARGS,
2780                   "reading tpx file (%s) version %d with version %d program",
2781                   filename,
2782                   tpx->fileVersion,
2783                   tpx_version);
2784     }
2785
2786     serializer->doInt(&tpx->natoms);
2787     serializer->doInt(&tpx->ngtc);
2788
2789     if (tpx->fileVersion < 62)
2790     {
2791         serializer->doInt(&idum);
2792         serializer->doReal(&rdum);
2793     }
2794     if (tpx->fileVersion >= 79)
2795     {
2796         serializer->doInt(&tpx->fep_state);
2797     }
2798     serializer->doReal(&tpx->lambda);
2799     serializer->doBool(&tpx->bIr);
2800     serializer->doBool(&tpx->bTop);
2801     serializer->doBool(&tpx->bX);
2802     serializer->doBool(&tpx->bV);
2803     serializer->doBool(&tpx->bF);
2804     serializer->doBool(&tpx->bBox);
2805
2806     if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
2807     {
2808         if (!serializer->reading())
2809         {
2810             GMX_RELEASE_ASSERT(tpx->sizeOfTprBody != 0,
2811                                "Not possible to write new file with zero TPR body size");
2812         }
2813         serializer->doInt64(&tpx->sizeOfTprBody);
2814     }
2815
2816     if ((tpx->fileGeneration > tpx_generation))
2817     {
2818         /* This can only happen if TopOnlyOK=TRUE */
2819         tpx->bIr = FALSE;
2820     }
2821 }
2822
2823 #define do_test(serializer, b, p)                            \
2824     if ((serializer)->reading() && ((p) != nullptr) && !(b)) \
2825     gmx_fatal(FARGS, "No %s in input file", #p)
2826
2827 /*! \brief
2828  * Process the first part of the TPR into the state datastructure.
2829  *
2830  * Due to the structure of the legacy code, it is necessary
2831  * to split up the state reading into two parts, with the
2832  * box and legacy temperature coupling processed before the
2833  * topology datastructures.
2834  *
2835  * See the documentation for do_tpx_body for the correct order of
2836  * the operations for reading a tpr file.
2837  *
2838  * \param[in] serializer Abstract serializer used to read/write data.
2839  * \param[in] tpx The file header data.
2840  * \param[in, out] state Global state data.
2841  */
2842 static void do_tpx_state_first(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state)
2843 {
2844     if (serializer->reading())
2845     {
2846         state->flags = 0;
2847         init_gtc_state(state, tpx->ngtc, 0, 0);
2848     }
2849     do_test(serializer, tpx->bBox, state->box);
2850     if (tpx->bBox)
2851     {
2852         serializer->doRvecArray(state->box, DIM);
2853         if (tpx->fileVersion >= 51)
2854         {
2855             serializer->doRvecArray(state->box_rel, DIM);
2856         }
2857         else
2858         {
2859             /* We initialize box_rel after reading the inputrec */
2860             clear_mat(state->box_rel);
2861         }
2862         serializer->doRvecArray(state->boxv, DIM);
2863         if (tpx->fileVersion < 56)
2864         {
2865             matrix mdum;
2866             serializer->doRvecArray(mdum, DIM);
2867         }
2868     }
2869
2870     if (state->ngtc > 0)
2871     {
2872         real* dumv;
2873         snew(dumv, state->ngtc);
2874         if (tpx->fileVersion < 69)
2875         {
2876             serializer->doRealArray(dumv, state->ngtc);
2877         }
2878         /* These used to be the Berendsen tcoupl_lambda's */
2879         serializer->doRealArray(dumv, state->ngtc);
2880         sfree(dumv);
2881     }
2882 }
2883
2884 /*! \brief
2885  * Process global topology data.
2886  *
2887  * See the documentation for do_tpx_body for the correct order of
2888  * the operations for reading a tpr file.
2889  *
2890  * \param[in] serializer Abstract serializer  used to read/write data.
2891  * \param[in] tpx The file header data.
2892  * \param[in,out] mtop Global topology.
2893  */
2894 static void do_tpx_mtop(gmx::ISerializer* serializer, TpxFileHeader* tpx, gmx_mtop_t* mtop)
2895 {
2896     do_test(serializer, tpx->bTop, mtop);
2897     if (tpx->bTop)
2898     {
2899         if (mtop)
2900         {
2901             do_mtop(serializer, mtop, tpx->fileVersion);
2902             set_disres_npair(mtop);
2903             mtop->finalize();
2904         }
2905         else
2906         {
2907             gmx_mtop_t dum_top;
2908             do_mtop(serializer, &dum_top, tpx->fileVersion);
2909         }
2910     }
2911 }
2912 /*! \brief
2913  * Process coordinate vectors for state data.
2914  *
2915  * Main part of state gets processed here.
2916  *
2917  * See the documentation for do_tpx_body for the correct order of
2918  * the operations for reading a tpr file.
2919  *
2920  * \param[in] serializer Abstract serializer used to read/write data.
2921  * \param[in] tpx The file header data.
2922  * \param[in,out] state Global state data.
2923  * \param[in,out] x Individual coordinates for processing, deprecated.
2924  * \param[in,out] v Individual velocities for processing, deprecated.
2925  */
2926 static void do_tpx_state_second(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state, rvec* x, rvec* v)
2927 {
2928     if (!serializer->reading())
2929     {
2930         GMX_RELEASE_ASSERT(
2931                 x == nullptr && v == nullptr,
2932                 "Passing separate x and v pointers to do_tpx() is not supported when writing");
2933     }
2934     else
2935     {
2936         GMX_RELEASE_ASSERT(!(x == nullptr && v != nullptr),
2937                            "Passing x==NULL and v!=NULL is not supported");
2938     }
2939
2940     if (serializer->reading())
2941     {
2942         if (x == nullptr)
2943         {
2944             // v is also nullptr by the above assertion, so we may
2945             // need to make memory in state for storing the contents
2946             // of the tpx file.
2947             if (tpx->bX)
2948             {
2949                 state->flags |= enumValueToBitMask(StateEntry::X);
2950             }
2951             if (tpx->bV)
2952             {
2953                 state->flags |= enumValueToBitMask(StateEntry::V);
2954             }
2955             state_change_natoms(state, tpx->natoms);
2956         }
2957     }
2958
2959     if (x == nullptr)
2960     {
2961         x = state->x.rvec_array();
2962         v = state->v.rvec_array();
2963     }
2964     do_test(serializer, tpx->bX, x);
2965     if (tpx->bX)
2966     {
2967         if (serializer->reading())
2968         {
2969             state->flags |= enumValueToBitMask(StateEntry::X);
2970         }
2971         serializer->doRvecArray(x, tpx->natoms);
2972     }
2973
2974     do_test(serializer, tpx->bV, v);
2975     if (tpx->bV)
2976     {
2977         if (serializer->reading())
2978         {
2979             state->flags |= enumValueToBitMask(StateEntry::V);
2980         }
2981         if (!v)
2982         {
2983             std::vector<gmx::RVec> dummyVelocities(tpx->natoms);
2984             serializer->doRvecArray(as_rvec_array(dummyVelocities.data()), tpx->natoms);
2985         }
2986         else
2987         {
2988             serializer->doRvecArray(v, tpx->natoms);
2989         }
2990     }
2991
2992     // No need to run do_test when the last argument is NULL
2993     if (tpx->bF)
2994     {
2995         std::vector<gmx::RVec> dummyForces(state->natoms);
2996         serializer->doRvecArray(as_rvec_array(dummyForces.data()), tpx->natoms);
2997     }
2998 }
2999 /*! \brief
3000  * Process simulation parameters.
3001  *
3002  * See the documentation for do_tpx_body for the correct order of
3003  * the operations for reading a tpr file.
3004  *
3005  * \param[in] serializer Abstract serializer used to read/write data.
3006  * \param[in] tpx The file header data.
3007  * \param[in,out] ir Datastructure with simulation parameters.
3008  */
3009 static PbcType do_tpx_ir(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir)
3010 {
3011     PbcType  pbcType;
3012     gmx_bool bPeriodicMols;
3013
3014     /* Starting with tpx version 26, we have the inputrec
3015      * at the end of the file, so we can ignore it
3016      * if the file is never than the software (but still the
3017      * same generation - see comments at the top of this file.
3018      *
3019      *
3020      */
3021     pbcType       = PbcType::Unset;
3022     bPeriodicMols = FALSE;
3023
3024     do_test(serializer, tpx->bIr, ir);
3025     if (tpx->bIr)
3026     {
3027         if (tpx->fileVersion >= 53)
3028         {
3029             /* Removed the pbc info from do_inputrec, since we always want it */
3030             if (!serializer->reading())
3031             {
3032                 pbcType       = ir->pbcType;
3033                 bPeriodicMols = ir->bPeriodicMols;
3034             }
3035             serializer->doInt(reinterpret_cast<int*>(&pbcType));
3036             serializer->doBool(&bPeriodicMols);
3037         }
3038         if (tpx->fileGeneration <= tpx_generation && ir)
3039         {
3040             do_inputrec(serializer, ir, tpx->fileVersion);
3041             if (tpx->fileVersion < 53)
3042             {
3043                 pbcType       = ir->pbcType;
3044                 bPeriodicMols = ir->bPeriodicMols;
3045             }
3046         }
3047         if (serializer->reading() && ir && tpx->fileVersion >= 53)
3048         {
3049             /* We need to do this after do_inputrec, since that initializes ir */
3050             ir->pbcType       = pbcType;
3051             ir->bPeriodicMols = bPeriodicMols;
3052         }
3053     }
3054     return pbcType;
3055 }
3056
3057 /*! \brief
3058  * Correct and finalize read information.
3059  *
3060  * If \p state is nullptr, skip the parts dependent on it.
3061  *
3062  * See the documentation for do_tpx_body for the correct order of
3063  * the operations for reading a tpr file.
3064  *
3065  * \param[in] tpx The file header used to check version numbers.
3066  * \param[out] ir Input rec that needs correction.
3067  * \param[out] state State needing correction.
3068  * \param[out] mtop Topology to finalize.
3069  */
3070 static void do_tpx_finalize(TpxFileHeader* tpx, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
3071 {
3072     if (tpx->fileVersion < 51 && state)
3073     {
3074         set_box_rel(ir, state);
3075     }
3076     if (tpx->bIr && ir)
3077     {
3078         if (state && state->ngtc == 0)
3079         {
3080             /* Reading old version without tcoupl state data: set it */
3081             init_gtc_state(state, ir->opts.ngtc, 0, ir->opts.nhchainlength);
3082         }
3083         if (tpx->bTop && mtop)
3084         {
3085             if (tpx->fileVersion < 57)
3086             {
3087                 ir->eDisre = !mtop->moltype[0].ilist[F_DISRES].empty()
3088                                      ? DistanceRestraintRefinement::Simple
3089                                      : DistanceRestraintRefinement::None;
3090             }
3091         }
3092     }
3093 }
3094
3095 /*! \brief
3096  * Process TPR data for file reading/writing.
3097  *
3098  * The TPR file gets processed in in four stages due to the organization
3099  * of the data within it.
3100  *
3101  * First, state data for the box is processed in do_tpx_state_first.
3102  * This is followed by processing the topology in do_tpx_mtop.
3103  * Coordinate and velocity vectors are handled next in do_tpx_state_second.
3104  * The last file information processed is the collection of simulation parameters in do_tpx_ir.
3105  * When reading, a final processing step is undertaken at the end.
3106  *
3107  * \param[in] serializer Abstract serializer used to read/write data.
3108  * \param[in] tpx The file header data.
3109  * \param[in,out] ir Datastructures with simulation parameters.
3110  * \param[in,out] state Global state data.
3111  * \param[in,out] x Individual coordinates for processing, deprecated.
3112  * \param[in,out] v Individual velocities for processing, deprecated.
3113  * \param[in,out] mtop Global topology.
3114  */
3115 static PbcType do_tpx_body(gmx::ISerializer* serializer,
3116                            TpxFileHeader*    tpx,
3117                            t_inputrec*       ir,
3118                            t_state*          state,
3119                            rvec*             x,
3120                            rvec*             v,
3121                            gmx_mtop_t*       mtop)
3122 {
3123     if (state)
3124     {
3125         do_tpx_state_first(serializer, tpx, state);
3126     }
3127     do_tpx_mtop(serializer, tpx, mtop);
3128     if (state)
3129     {
3130         do_tpx_state_second(serializer, tpx, state, x, v);
3131     }
3132     PbcType pbcType = do_tpx_ir(serializer, tpx, ir);
3133     if (serializer->reading())
3134     {
3135         do_tpx_finalize(tpx, ir, state, mtop);
3136     }
3137     return pbcType;
3138 }
3139
3140 /*! \brief
3141  * Overload for do_tpx_body that defaults to state vectors being nullptr.
3142  *
3143  * \param[in] serializer Abstract serializer used to read/write data.
3144  * \param[in] tpx The file header data.
3145  * \param[in,out] ir Datastructures with simulation parameters.
3146  * \param[in,out] mtop Global topology.
3147  */
3148 static PbcType do_tpx_body(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir, gmx_mtop_t* mtop)
3149 {
3150     return do_tpx_body(serializer, tpx, ir, nullptr, nullptr, nullptr, mtop);
3151 }
3152
3153 static t_fileio* open_tpx(const char* fn, const char* mode)
3154 {
3155     return gmx_fio_open(fn, mode);
3156 }
3157
3158 static void close_tpx(t_fileio* fio)
3159 {
3160     gmx_fio_close(fio);
3161 }
3162
3163 /*! \brief
3164  * Fill information into the header only from state before writing.
3165  *
3166  * Populating the header needs to be independent from writing the information
3167  * to file to allow things like writing the raw byte stream.
3168  *
3169  * \param[in] state The current simulation state. Can't write without it.
3170  * \param[in] ir Parameter and system information.
3171  * \param[in] mtop Global topology.
3172  * \returns Fully populated header.
3173  */
3174 static TpxFileHeader populateTpxHeader(const t_state& state, const t_inputrec* ir, const gmx_mtop_t* mtop)
3175 {
3176     TpxFileHeader header;
3177     header.natoms         = state.natoms;
3178     header.ngtc           = state.ngtc;
3179     header.fep_state      = state.fep_state;
3180     header.lambda         = state.lambda[FreeEnergyPerturbationCouplingType::Fep];
3181     header.bIr            = ir != nullptr;
3182     header.bTop           = mtop != nullptr;
3183     header.bX             = (state.flags & enumValueToBitMask(StateEntry::X)) != 0;
3184     header.bV             = (state.flags & enumValueToBitMask(StateEntry::V)) != 0;
3185     header.bF             = false;
3186     header.bBox           = true;
3187     header.fileVersion    = tpx_version;
3188     header.fileGeneration = tpx_generation;
3189     header.isDouble       = (sizeof(real) == sizeof(double));
3190
3191     return header;
3192 }
3193
3194 /*! \brief
3195  * Process the body of a TPR file as an opaque data buffer.
3196  *
3197  * Reads/writes the information in \p buffer from/to the \p serializer
3198  * provided to the function. Does not interact with the actual
3199  * TPR datastructures but with an in memory representation of the
3200  * data, so that this data can be efficiently read or written from/to
3201  * an original source.
3202  *
3203  * \param[in] serializer The abstract serializer used for reading or writing
3204  *                       the information in \p buffer.
3205  * \param[in,out] buffer Information from TPR file as char buffer.
3206  */
3207 static void doTpxBodyBuffer(gmx::ISerializer* serializer, gmx::ArrayRef<char> buffer)
3208 {
3209     serializer->doOpaque(buffer.data(), buffer.size());
3210 }
3211
3212 /*! \brief
3213  * Populates simulation datastructures.
3214  *
3215  * Here the information from the serialization interface \p serializer
3216  * is used to first populate the datastructures containing the simulation
3217  * information. Depending on the version found in the header \p tpx,
3218  * this is done using the new reading of the data as one block from disk,
3219  * followed by complete deserialization of the information read from there.
3220  * Otherwise, the datastructures are populated as before one by one from disk.
3221  * The second version is the default for the legacy tools that read the
3222  * coordinates and velocities separate from the state.
3223  *
3224  * After reading in the data, a separate buffer is populated from them
3225  * containing only \p ir and \p mtop that can be communicated directly
3226  * to nodes needing the information to set up a simulation.
3227  *
3228  * \param[in] tpx The file header.
3229  * \param[in] serializer The Serialization interface used to read the TPR.
3230  * \param[out] ir Input rec to populate.
3231  * \param[out] state State vectors to populate.
3232  * \param[out] x Coordinates to populate if needed.
3233  * \param[out] v Velocities to populate if needed.
3234  * \param[out] mtop Global topology to populate.
3235  *
3236  * \returns Partial de-serialized TPR used for communication to nodes.
3237  */
3238 static PartialDeserializedTprFile readTpxBody(TpxFileHeader*    tpx,
3239                                               gmx::ISerializer* serializer,
3240                                               t_inputrec*       ir,
3241                                               t_state*          state,
3242                                               rvec*             x,
3243                                               rvec*             v,
3244                                               gmx_mtop_t*       mtop)
3245 {
3246     PartialDeserializedTprFile partialDeserializedTpr;
3247     if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
3248     {
3249         partialDeserializedTpr.body.resize(tpx->sizeOfTprBody);
3250         partialDeserializedTpr.header = *tpx;
3251         doTpxBodyBuffer(serializer, partialDeserializedTpr.body);
3252
3253         partialDeserializedTpr.pbcType =
3254                 completeTprDeserialization(&partialDeserializedTpr, ir, state, x, v, mtop);
3255     }
3256     else
3257     {
3258         partialDeserializedTpr.pbcType = do_tpx_body(serializer, tpx, ir, state, x, v, mtop);
3259     }
3260     // Update header to system info for communication to nodes.
3261     // As we only need to communicate the inputrec and mtop to other nodes,
3262     // we prepare a new char buffer with the information we have already read
3263     // in on master.
3264     partialDeserializedTpr.header = populateTpxHeader(*state, ir, mtop);
3265     // Long-term we should move to use little endian in files to avoid extra byte swapping,
3266     // but since we just used the default XDR format (which is big endian) for the TPR
3267     // header it would cause third-party libraries reading our raw data to tear their hair
3268     // if we swap the endian in the middle of the file, so we stick to big endian in the
3269     // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
3270     gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
3271     do_tpx_body(&tprBodySerializer, &partialDeserializedTpr.header, ir, mtop);
3272     partialDeserializedTpr.body = tprBodySerializer.finishAndGetBuffer();
3273
3274     return partialDeserializedTpr;
3275 }
3276
3277 /************************************************************
3278  *
3279  *  The following routines are the exported ones
3280  *
3281  ************************************************************/
3282
3283 TpxFileHeader readTpxHeader(const char* fileName, bool canReadTopologyOnly)
3284 {
3285     t_fileio* fio;
3286
3287     fio = open_tpx(fileName, "r");
3288     gmx::FileIOXdrSerializer serializer(fio);
3289
3290     TpxFileHeader tpx;
3291     do_tpxheader(&serializer, &tpx, fileName, fio, canReadTopologyOnly);
3292     close_tpx(fio);
3293     return tpx;
3294 }
3295
3296 void write_tpx_state(const char* fn, const t_inputrec* ir, const t_state* state, const gmx_mtop_t& mtop)
3297 {
3298     /* To write a state, we first need to write the state information to a buffer before
3299      * we append the raw bytes to the file. For this, the header information needs to be
3300      * populated before we write the main body because it has some information that is
3301      * otherwise not available.
3302      */
3303
3304     t_fileio* fio;
3305
3306     TpxFileHeader tpx = populateTpxHeader(*state, ir, &mtop);
3307     // Long-term we should move to use little endian in files to avoid extra byte swapping,
3308     // but since we just used the default XDR format (which is big endian) for the TPR
3309     // header it would cause third-party libraries reading our raw data to tear their hair
3310     // if we swap the endian in the middle of the file, so we stick to big endian in the
3311     // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
3312     gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
3313
3314     do_tpx_body(&tprBodySerializer,
3315                 &tpx,
3316                 const_cast<t_inputrec*>(ir),
3317                 const_cast<t_state*>(state),
3318                 nullptr,
3319                 nullptr,
3320                 const_cast<gmx_mtop_t*>(&mtop));
3321
3322     std::vector<char> tprBody = tprBodySerializer.finishAndGetBuffer();
3323     tpx.sizeOfTprBody         = tprBody.size();
3324
3325     fio = open_tpx(fn, "w");
3326     gmx::FileIOXdrSerializer serializer(fio);
3327     do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
3328     doTpxBodyBuffer(&serializer, tprBody);
3329
3330     close_tpx(fio);
3331 }
3332
3333 PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
3334                                    t_inputrec*                 ir,
3335                                    t_state*                    state,
3336                                    rvec*                       x,
3337                                    rvec*                       v,
3338                                    gmx_mtop_t*                 mtop)
3339 {
3340     // Long-term we should move to use little endian in files to avoid extra byte swapping,
3341     // but since we just used the default XDR format (which is big endian) for the TPR
3342     // header it would cause third-party libraries reading our raw data to tear their hair
3343     // if we swap the endian in the middle of the file, so we stick to big endian in the
3344     // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
3345     gmx::InMemoryDeserializer tprBodyDeserializer(partialDeserializedTpr->body,
3346                                                   partialDeserializedTpr->header.isDouble,
3347                                                   gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
3348     return do_tpx_body(&tprBodyDeserializer, &partialDeserializedTpr->header, ir, state, x, v, mtop);
3349 }
3350
3351 PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
3352                                    t_inputrec*                 ir,
3353                                    gmx_mtop_t*                 mtop)
3354 {
3355     return completeTprDeserialization(partialDeserializedTpr, ir, nullptr, nullptr, nullptr, mtop);
3356 }
3357
3358 PartialDeserializedTprFile read_tpx_state(const char* fn, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
3359 {
3360     t_fileio* fio;
3361     fio = open_tpx(fn, "r");
3362     gmx::FileIOXdrSerializer   serializer(fio);
3363     PartialDeserializedTprFile partialDeserializedTpr;
3364     do_tpxheader(&serializer, &partialDeserializedTpr.header, fn, fio, ir == nullptr);
3365     partialDeserializedTpr =
3366             readTpxBody(&partialDeserializedTpr.header, &serializer, ir, state, nullptr, nullptr, mtop);
3367     close_tpx(fio);
3368     return partialDeserializedTpr;
3369 }
3370
3371 PbcType read_tpx(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, gmx_mtop_t* mtop)
3372 {
3373     t_fileio* fio;
3374     t_state   state;
3375
3376     TpxFileHeader tpx;
3377     fio = open_tpx(fn, "r");
3378     gmx::FileIOXdrSerializer serializer(fio);
3379     do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
3380     PartialDeserializedTprFile partialDeserializedTpr =
3381             readTpxBody(&tpx, &serializer, ir, &state, x, v, mtop);
3382     close_tpx(fio);
3383     if (mtop != nullptr && natoms != nullptr)
3384     {
3385         *natoms = mtop->natoms;
3386     }
3387     if (box)
3388     {
3389         copy_mat(state.box, box);
3390     }
3391     return partialDeserializedTpr.pbcType;
3392 }
3393
3394 PbcType read_tpx_top(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, t_topology* top)
3395 {
3396     gmx_mtop_t mtop;
3397     PbcType    pbcType;
3398
3399     pbcType = read_tpx(fn, ir, box, natoms, x, v, &mtop);
3400
3401     *top = gmx_mtop_t_to_t_topology(&mtop, true);
3402
3403     return pbcType;
3404 }
3405
3406 gmx_bool fn2bTPX(const char* file)
3407 {
3408     return (efTPR == fn2ftp(file));
3409 }
3410
3411 void pr_tpxheader(FILE* fp, int indent, const char* title, const TpxFileHeader* sh)
3412 {
3413     if (available(fp, sh, indent, title))
3414     {
3415         indent = pr_title(fp, indent, title);
3416         pr_indent(fp, indent);
3417         fprintf(fp, "bIr    = %spresent\n", sh->bIr ? "" : "not ");
3418         pr_indent(fp, indent);
3419         fprintf(fp, "bBox   = %spresent\n", sh->bBox ? "" : "not ");
3420         pr_indent(fp, indent);
3421         fprintf(fp, "bTop   = %spresent\n", sh->bTop ? "" : "not ");
3422         pr_indent(fp, indent);
3423         fprintf(fp, "bX     = %spresent\n", sh->bX ? "" : "not ");
3424         pr_indent(fp, indent);
3425         fprintf(fp, "bV     = %spresent\n", sh->bV ? "" : "not ");
3426         pr_indent(fp, indent);
3427         fprintf(fp, "bF     = %spresent\n", sh->bF ? "" : "not ");
3428
3429         pr_indent(fp, indent);
3430         fprintf(fp, "natoms = %d\n", sh->natoms);
3431         pr_indent(fp, indent);
3432         fprintf(fp, "lambda = %e\n", sh->lambda);
3433         pr_indent(fp, indent);
3434         fprintf(fp, "buffer size = %" PRId64 "\n", sh->sizeOfTprBody);
3435     }
3436 }