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