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