1d56da89b96de64c5a7acc62cbf95f49981fbdf5
[alexxy/gromacs.git] / src / programs / mdrun / mdrun.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) 2011,2012,2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 /*! \defgroup module_mdrun Implementation of mdrun
38  * \ingroup group_mdrun
39  *
40  * \brief This module contains code that implements mdrun.
41  */
42 /*! \internal \file
43  *
44  * \brief This file implements mdrun
45  *
46  * \author Berk Hess <hess@kth.se>
47  * \author David van der Spoel <david.vanderspoel@icm.uu.se>
48  * \author Erik Lindahl <erik@kth.se>
49  * \author Mark Abraham <mark.j.abraham@gmail.com>
50  *
51  * \ingroup module_mdrun
52  */
53 #include "gmxpre.h"
54
55 #include "config.h"
56
57 #include <cstdio>
58 #include <cstdlib>
59 #include <cstring>
60
61 #include "gromacs/commandline/filenm.h"
62 #include "gromacs/commandline/pargs.h"
63 #include "gromacs/domdec/domdec.h"
64 #include "gromacs/gmxlib/network.h"
65 #include "gromacs/mdlib/main.h"
66 #include "gromacs/mdlib/mdrun.h"
67 #include "gromacs/mdlib/repl_ex.h"
68 #include "gromacs/mdrun/runner.h"
69 #include "gromacs/mdrunutility/handlerestart.h"
70 #include "gromacs/mdtypes/commrec.h"
71 #include "gromacs/utility/arraysize.h"
72 #include "gromacs/utility/fatalerror.h"
73 #include "gromacs/utility/smalloc.h"
74
75 #include "mdrun_main.h"
76
77 /*! \brief Return whether the command-line parameter that
78  *  will trigger a multi-simulation is set */
79 static bool is_multisim_option_set(int argc, const char *const argv[])
80 {
81     for (int i = 0; i < argc; ++i)
82     {
83         if (strcmp(argv[i], "-multidir") == 0)
84         {
85             return true;
86         }
87     }
88     return false;
89 }
90
91 //! Implements C-style main function for mdrun
92 int gmx_mdrun(int argc, char *argv[])
93 {
94     gmx::Mdrunner runner;
95     return runner.mainFunction(argc, argv);
96 }
97
98 namespace gmx
99 {
100
101 int Mdrunner::mainFunction(int argc, char *argv[])
102 {
103     const char   *desc[] = {
104         "[THISMODULE] is the main computational chemistry engine",
105         "within GROMACS. Obviously, it performs Molecular Dynamics simulations,",
106         "but it can also perform Stochastic Dynamics, Energy Minimization,",
107         "test particle insertion or (re)calculation of energies.",
108         "Normal mode analysis is another option. In this case [TT]mdrun[tt]",
109         "builds a Hessian matrix from single conformation.",
110         "For usual Normal Modes-like calculations, make sure that",
111         "the structure provided is properly energy-minimized.",
112         "The generated matrix can be diagonalized by [gmx-nmeig].[PAR]",
113         "The [TT]mdrun[tt] program reads the run input file ([TT]-s[tt])",
114         "and distributes the topology over ranks if needed.",
115         "[TT]mdrun[tt] produces at least four output files.",
116         "A single log file ([TT]-g[tt]) is written.",
117         "The trajectory file ([TT]-o[tt]), contains coordinates, velocities and",
118         "optionally forces.",
119         "The structure file ([TT]-c[tt]) contains the coordinates and",
120         "velocities of the last step.",
121         "The energy file ([TT]-e[tt]) contains energies, the temperature,",
122         "pressure, etc, a lot of these things are also printed in the log file.",
123         "Optionally coordinates can be written to a compressed trajectory file",
124         "([TT]-x[tt]).[PAR]",
125         "The option [TT]-dhdl[tt] is only used when free energy calculation is",
126         "turned on.[PAR]",
127         "Running mdrun efficiently in parallel is a complex topic topic,",
128         "many aspects of which are covered in the online User Guide. You",
129         "should look there for practical advice on using many of the options",
130         "available in mdrun.[PAR]",
131         "ED (essential dynamics) sampling and/or additional flooding potentials",
132         "are switched on by using the [TT]-ei[tt] flag followed by an [REF].edi[ref]",
133         "file. The [REF].edi[ref] file can be produced with the [TT]make_edi[tt] tool",
134         "or by using options in the essdyn menu of the WHAT IF program.",
135         "[TT]mdrun[tt] produces a [REF].xvg[ref] output file that",
136         "contains projections of positions, velocities and forces onto selected",
137         "eigenvectors.[PAR]",
138         "When user-defined potential functions have been selected in the",
139         "[REF].mdp[ref] file the [TT]-table[tt] option is used to pass [TT]mdrun[tt]",
140         "a formatted table with potential functions. The file is read from",
141         "either the current directory or from the [TT]GMXLIB[tt] directory.",
142         "A number of pre-formatted tables are presented in the [TT]GMXLIB[tt] dir,",
143         "for 6-8, 6-9, 6-10, 6-11, 6-12 Lennard-Jones potentials with",
144         "normal Coulomb.",
145         "When pair interactions are present, a separate table for pair interaction",
146         "functions is read using the [TT]-tablep[tt] option.[PAR]",
147         "When tabulated bonded functions are present in the topology,",
148         "interaction functions are read using the [TT]-tableb[tt] option.",
149         "For each different tabulated interaction type used, a table file name must",
150         "be given. For the topology to work, a file name given here must match a",
151         "character sequence before the file extension. That sequence is: an underscore,",
152         "then a 'b' for bonds, an 'a' for angles or a 'd' for dihedrals,",
153         "and finally the matching table number index used in the topology.[PAR]",
154         "The options [TT]-px[tt] and [TT]-pf[tt] are used for writing pull COM",
155         "coordinates and forces when pulling is selected",
156         "in the [REF].mdp[ref] file.[PAR]",
157         "Finally some experimental algorithms can be tested when the",
158         "appropriate options have been given. Currently under",
159         "investigation are: polarizability.",
160         "[PAR]",
161         "The option [TT]-membed[tt] does what used to be g_membed, i.e. embed",
162         "a protein into a membrane. This module requires a number of settings",
163         "that are provided in a data file that is the argument of this option.",
164         "For more details in membrane embedding, see the documentation in the",
165         "user guide. The options [TT]-mn[tt] and [TT]-mp[tt] are used to provide",
166         "the index and topology files used for the embedding.",
167         "[PAR]",
168         "The option [TT]-pforce[tt] is useful when you suspect a simulation",
169         "crashes due to too large forces. With this option coordinates and",
170         "forces of atoms with a force larger than a certain value will",
171         "be printed to stderr. It will also terminate the run when non-finite",
172         "forces are present.",
173         "[PAR]",
174         "Checkpoints containing the complete state of the system are written",
175         "at regular intervals (option [TT]-cpt[tt]) to the file [TT]-cpo[tt],",
176         "unless option [TT]-cpt[tt] is set to -1.",
177         "The previous checkpoint is backed up to [TT]state_prev.cpt[tt] to",
178         "make sure that a recent state of the system is always available,",
179         "even when the simulation is terminated while writing a checkpoint.",
180         "With [TT]-cpnum[tt] all checkpoint files are kept and appended",
181         "with the step number.",
182         "A simulation can be continued by reading the full state from file",
183         "with option [TT]-cpi[tt]. This option is intelligent in the way that",
184         "if no checkpoint file is found, GROMACS just assumes a normal run and",
185         "starts from the first step of the [REF].tpr[ref] file. By default the output",
186         "will be appending to the existing output files. The checkpoint file",
187         "contains checksums of all output files, such that you will never",
188         "loose data when some output files are modified, corrupt or removed.",
189         "There are three scenarios with [TT]-cpi[tt]:[PAR]",
190         "[TT]*[tt] no files with matching names are present: new output files are written[PAR]",
191         "[TT]*[tt] all files are present with names and checksums matching those stored",
192         "in the checkpoint file: files are appended[PAR]",
193         "[TT]*[tt] otherwise no files are modified and a fatal error is generated[PAR]",
194         "With [TT]-noappend[tt] new output files are opened and the simulation",
195         "part number is added to all output file names.",
196         "Note that in all cases the checkpoint file itself is not renamed",
197         "and will be overwritten, unless its name does not match",
198         "the [TT]-cpo[tt] option.",
199         "[PAR]",
200         "With checkpointing the output is appended to previously written",
201         "output files, unless [TT]-noappend[tt] is used or none of the previous",
202         "output files are present (except for the checkpoint file).",
203         "The integrity of the files to be appended is verified using checksums",
204         "which are stored in the checkpoint file. This ensures that output can",
205         "not be mixed up or corrupted due to file appending. When only some",
206         "of the previous output files are present, a fatal error is generated",
207         "and no old output files are modified and no new output files are opened.",
208         "The result with appending will be the same as from a single run.",
209         "The contents will be binary identical, unless you use a different number",
210         "of ranks or dynamic load balancing or the FFT library uses optimizations",
211         "through timing.",
212         "[PAR]",
213         "With option [TT]-maxh[tt] a simulation is terminated and a checkpoint",
214         "file is written at the first neighbor search step where the run time",
215         "exceeds [TT]-maxh[tt]\\*0.99 hours. This option is particularly useful in",
216         "combination with setting [TT]nsteps[tt] to -1 either in the mdp or using the",
217         "similarly named command line option. This results in an infinite run,",
218         "terminated only when the time limit set by [TT]-maxh[tt] is reached (if any)",
219         "or upon receiving a signal.",
220         "[PAR]",
221         "When [TT]mdrun[tt] receives a TERM or INT signal (e.g. when ctrl+C is",
222         "pressed), it will stop at the next neighbor search step or at the",
223         "second global communication step, whichever happens later.",
224         "When [TT]mdrun[tt] receives a second TERM or INT signal and",
225         "reproducibility is not requested, it will stop at the first global",
226         "communication step.",
227         "In both cases all the usual output will be written to file and",
228         "a checkpoint file is written at the last step.",
229         "When [TT]mdrun[tt] receives an ABRT signal or the third TERM or INT signal,",
230         "it will abort directly without writing a new checkpoint file.",
231         "When running with MPI, a signal to one of the [TT]mdrun[tt] ranks",
232         "is sufficient, this signal should not be sent to mpirun or",
233         "the [TT]mdrun[tt] process that is the parent of the others.",
234         "[PAR]",
235         "Interactive molecular dynamics (IMD) can be activated by using at least one",
236         "of the three IMD switches: The [TT]-imdterm[tt] switch allows one to terminate",
237         "the simulation from the molecular viewer (e.g. VMD). With [TT]-imdwait[tt],",
238         "[TT]mdrun[tt] pauses whenever no IMD client is connected. Pulling from the",
239         "IMD remote can be turned on by [TT]-imdpull[tt].",
240         "The port [TT]mdrun[tt] listens to can be altered by [TT]-imdport[tt].The",
241         "file pointed to by [TT]-if[tt] contains atom indices and forces if IMD",
242         "pulling is used.",
243         "[PAR]",
244         "When [TT]mdrun[tt] is started with MPI, it does not run niced by default."
245     };
246
247     /* Command line options */
248     rvec              realddxyz                                               = {0, 0, 0};
249     const char       *ddrank_opt_choices[static_cast<int>(DdRankOrder::nr)+1] =
250     { nullptr, "interleave", "pp_pme", "cartesian", nullptr };
251     const char       *dddlb_opt_choices[static_cast<int>(DlbOption::nr)+1] =
252     { nullptr, "auto", "no", "yes", nullptr };
253     const char       *thread_aff_opt_choices[threadaffNR+1] =
254     { nullptr, "auto", "on", "off", nullptr };
255     const char       *nbpu_opt_choices[] =
256     { nullptr, "auto", "cpu", "gpu", nullptr };
257     const char       *pme_opt_choices[] =
258     { nullptr, "auto", "cpu", "gpu", nullptr };
259     const char       *pme_fft_opt_choices[] =
260     { nullptr, "auto", "cpu", "gpu", nullptr };
261     gmx_bool          bTryToAppendFiles     = TRUE;
262     const char       *gpuIdsAvailable       = "";
263     const char       *userGpuTaskAssignment = "";
264
265     ImdOptions       &imdOptions = mdrunOptions.imdOptions;
266
267     t_pargs           pa[] = {
268
269         { "-dd",      FALSE, etRVEC, {&realddxyz},
270           "Domain decomposition grid, 0 is optimize" },
271         { "-ddorder", FALSE, etENUM, {ddrank_opt_choices},
272           "DD rank order" },
273         { "-npme",    FALSE, etINT, {&domdecOptions.numPmeRanks},
274           "Number of separate ranks to be used for PME, -1 is guess" },
275         { "-nt",      FALSE, etINT, {&hw_opt.nthreads_tot},
276           "Total number of threads to start (0 is guess)" },
277         { "-ntmpi",   FALSE, etINT, {&hw_opt.nthreads_tmpi},
278           "Number of thread-MPI ranks to start (0 is guess)" },
279         { "-ntomp",   FALSE, etINT, {&hw_opt.nthreads_omp},
280           "Number of OpenMP threads per MPI rank to start (0 is guess)" },
281         { "-ntomp_pme", FALSE, etINT, {&hw_opt.nthreads_omp_pme},
282           "Number of OpenMP threads per MPI rank to start (0 is -ntomp)" },
283         { "-pin",     FALSE, etENUM, {thread_aff_opt_choices},
284           "Whether mdrun should try to set thread affinities" },
285         { "-pinoffset", FALSE, etINT, {&hw_opt.core_pinning_offset},
286           "The lowest logical core number to which mdrun should pin the first thread" },
287         { "-pinstride", FALSE, etINT, {&hw_opt.core_pinning_stride},
288           "Pinning distance in logical cores for threads, use 0 to minimize the number of threads per physical core" },
289         { "-gpu_id",  FALSE, etSTR, {&gpuIdsAvailable},
290           "List of unique GPU device IDs available to use" },
291         { "-gputasks",  FALSE, etSTR, {&userGpuTaskAssignment},
292           "List of GPU device IDs, mapping each PP task on each node to a device" },
293         { "-ddcheck", FALSE, etBOOL, {&domdecOptions.checkBondedInteractions},
294           "Check for all bonded interactions with DD" },
295         { "-ddbondcomm", FALSE, etBOOL, {&domdecOptions.useBondedCommunication},
296           "HIDDENUse special bonded atom communication when [TT]-rdd[tt] > cut-off" },
297         { "-rdd",     FALSE, etREAL, {&domdecOptions.minimumCommunicationRange},
298           "The maximum distance for bonded interactions with DD (nm), 0 is determine from initial coordinates" },
299         { "-rcon",    FALSE, etREAL, {&domdecOptions.constraintCommunicationRange},
300           "Maximum distance for P-LINCS (nm), 0 is estimate" },
301         { "-dlb",     FALSE, etENUM, {dddlb_opt_choices},
302           "Dynamic load balancing (with DD)" },
303         { "-dds",     FALSE, etREAL, {&domdecOptions.dlbScaling},
304           "Fraction in (0,1) by whose reciprocal the initial DD cell size will be increased in order to "
305           "provide a margin in which dynamic load balancing can act while preserving the minimum cell size." },
306         { "-ddcsx",   FALSE, etSTR, {&domdecOptions.cellSizeX},
307           "HIDDENA string containing a vector of the relative sizes in the x "
308           "direction of the corresponding DD cells. Only effective with static "
309           "load balancing." },
310         { "-ddcsy",   FALSE, etSTR, {&domdecOptions.cellSizeY},
311           "HIDDENA string containing a vector of the relative sizes in the y "
312           "direction of the corresponding DD cells. Only effective with static "
313           "load balancing." },
314         { "-ddcsz",   FALSE, etSTR, {&domdecOptions.cellSizeZ},
315           "HIDDENA string containing a vector of the relative sizes in the z "
316           "direction of the corresponding DD cells. Only effective with static "
317           "load balancing." },
318         { "-gcom",    FALSE, etINT, {&mdrunOptions.globalCommunicationInterval},
319           "Global communication frequency" },
320         { "-nb",      FALSE, etENUM, {nbpu_opt_choices},
321           "Calculate non-bonded interactions on" },
322         { "-nstlist", FALSE, etINT, {&nstlist_cmdline},
323           "Set nstlist when using a Verlet buffer tolerance (0 is guess)" },
324         { "-tunepme", FALSE, etBOOL, {&mdrunOptions.tunePme},
325           "Optimize PME load between PP/PME ranks or GPU/CPU (only with the Verlet cut-off scheme)" },
326         { "-pme",     FALSE, etENUM, {pme_opt_choices},
327           "Perform PME calculations on" },
328         { "-pmefft", FALSE, etENUM, {pme_fft_opt_choices},
329           "Perform PME FFT calculations on" },
330         { "-v",       FALSE, etBOOL, {&mdrunOptions.verbose},
331           "Be loud and noisy" },
332         { "-pforce",  FALSE, etREAL, {&pforce},
333           "Print all forces larger than this (kJ/mol nm)" },
334         { "-reprod",  FALSE, etBOOL, {&mdrunOptions.reproducible},
335           "Try to avoid optimizations that affect binary reproducibility" },
336         { "-cpt",     FALSE, etREAL, {&mdrunOptions.checkpointOptions.period},
337           "Checkpoint interval (minutes)" },
338         { "-cpnum",   FALSE, etBOOL, {&mdrunOptions.checkpointOptions.keepAndNumberCheckpointFiles},
339           "Keep and number checkpoint files" },
340         { "-append",  FALSE, etBOOL, {&bTryToAppendFiles},
341           "Append to previous output files when continuing from checkpoint instead of adding the simulation part number to all file names" },
342         { "-nsteps",  FALSE, etINT64, {&mdrunOptions.numStepsCommandline},
343           "Run this number of steps, overrides .mdp file option (-1 means infinite, -2 means use mdp option, smaller is invalid)" },
344         { "-maxh",   FALSE, etREAL, {&mdrunOptions.maximumHoursToRun},
345           "Terminate after 0.99 times this time (hours)" },
346         { "-replex",  FALSE, etINT, {&replExParams.exchangeInterval},
347           "Attempt replica exchange periodically with this period (steps)" },
348         { "-nex",  FALSE, etINT, {&replExParams.numExchanges},
349           "Number of random exchanges to carry out each exchange interval (N^3 is one suggestion).  -nex zero or not specified gives neighbor replica exchange." },
350         { "-reseed",  FALSE, etINT, {&replExParams.randomSeed},
351           "Seed for replica exchange, -1 is generate a seed" },
352         { "-imdport",    FALSE, etINT, {&imdOptions.port},
353           "HIDDENIMD listening port" },
354         { "-imdwait",  FALSE, etBOOL, {&imdOptions.wait},
355           "HIDDENPause the simulation while no IMD client is connected" },
356         { "-imdterm",  FALSE, etBOOL, {&imdOptions.terminatable},
357           "HIDDENAllow termination of the simulation from IMD client" },
358         { "-imdpull",  FALSE, etBOOL, {&imdOptions.pull},
359           "HIDDENAllow pulling in the simulation from IMD client" },
360         { "-rerunvsite", FALSE, etBOOL, {&mdrunOptions.rerunConstructVsites},
361           "HIDDENRecalculate virtual site coordinates with [TT]-rerun[tt]" },
362         { "-confout", FALSE, etBOOL, {&mdrunOptions.writeConfout},
363           "HIDDENWrite the last configuration with [TT]-c[tt] and force checkpointing at the last step" },
364         { "-stepout", FALSE, etINT, {&mdrunOptions.verboseStepPrintInterval},
365           "HIDDENFrequency of writing the remaining wall clock time for the run" },
366         { "-resetstep", FALSE, etINT, {&mdrunOptions.timingOptions.resetStep},
367           "HIDDENReset cycle counters after these many time steps" },
368         { "-resethway", FALSE, etBOOL, {&mdrunOptions.timingOptions.resetHalfway},
369           "HIDDENReset the cycle counters after half the number of steps or halfway [TT]-maxh[tt]" }
370     };
371     int               rc;
372
373     cr = init_commrec();
374
375     unsigned long PCA_Flags = PCA_CAN_SET_DEFFNM;
376     // With -multidir, the working directory still needs to be
377     // changed, so we can't check for the existence of files during
378     // parsing.  It isn't useful to do any completion based on file
379     // system contents, either.
380     if (is_multisim_option_set(argc, argv))
381     {
382         PCA_Flags |= PCA_DISABLE_INPUT_FILE_CHECKING;
383     }
384
385     if (!parse_common_args(&argc, argv, PCA_Flags, nfile, fnm, asize(pa), pa,
386                            asize(desc), desc, 0, nullptr, &oenv))
387     {
388         sfree(cr);
389         return 0;
390     }
391
392     // Handle the options that permits the user to either declare
393     // which compatible GPUs are availble for use, or to select a GPU
394     // task assignment. Either could be in an environment variable (so
395     // that there is a way to customize it, when using MPI in
396     // heterogeneous contexts).
397     {
398         // TODO Argument parsing can't handle std::string. We should
399         // fix that by changing the parsing, once more of the roles of
400         // handling, validating and implementing defaults for user
401         // command-line options have been seperated.
402         hw_opt.gpuIdsAvailable       = gpuIdsAvailable;
403         hw_opt.userGpuTaskAssignment = userGpuTaskAssignment;
404
405         const char *env = getenv("GMX_GPU_ID");
406         if (env != nullptr)
407         {
408             if (!hw_opt.gpuIdsAvailable.empty())
409             {
410                 gmx_fatal(FARGS, "GMX_GPU_ID and -gpu_id can not be used at the same time");
411             }
412             hw_opt.gpuIdsAvailable = env;
413         }
414
415         env = getenv("GMX_GPUTASKS");
416         if (env != nullptr)
417         {
418             if (!hw_opt.userGpuTaskAssignment.empty())
419             {
420                 gmx_fatal(FARGS, "GMX_GPUTASKS and -gputasks can not be used at the same time");
421             }
422             hw_opt.userGpuTaskAssignment = env;
423         }
424
425         if (!hw_opt.gpuIdsAvailable.empty() && !hw_opt.userGpuTaskAssignment.empty())
426         {
427             gmx_fatal(FARGS, "-gpu_id and -gputasks cannot be used at the same time");
428         }
429     }
430
431     hw_opt.thread_affinity = nenum(thread_aff_opt_choices);
432
433     // now check for a multi-simulation
434     gmx::ArrayRef<const std::string> multidir = opt2fnsIfOptionSet("-multidir", nfile, fnm);
435
436     if (replExParams.exchangeInterval != 0 && multidir.size() < 2)
437     {
438         gmx_fatal(FARGS, "Need at least two replicas for replica exchange (use option -multidir)");
439     }
440
441     if (replExParams.numExchanges < 0)
442     {
443         gmx_fatal(FARGS, "Replica exchange number of exchanges needs to be positive");
444     }
445
446     ms = init_multisystem(MPI_COMM_WORLD, multidir);
447
448     /* Prepare the intra-simulation communication */
449     // TODO consolidate this with init_commrec, after changing the
450     // relative ordering of init_commrec and init_multisystem
451 #if GMX_MPI
452     if (ms != nullptr)
453     {
454         cr->nnodes = cr->nnodes / ms->nsim;
455         MPI_Comm_split(MPI_COMM_WORLD, ms->sim, cr->sim_nodeid, &cr->mpi_comm_mysim);
456         cr->mpi_comm_mygroup = cr->mpi_comm_mysim;
457         MPI_Comm_rank(cr->mpi_comm_mysim, &cr->sim_nodeid);
458         MPI_Comm_rank(cr->mpi_comm_mygroup, &cr->nodeid);
459     }
460 #endif
461
462     if (!opt2bSet("-cpi", nfile, fnm))
463     {
464         // If we are not starting from a checkpoint we never allow files to be appended
465         // to, since that has caused a ton of strange behaviour and bugs in the past.
466         if (opt2parg_bSet("-append", asize(pa), pa))
467         {
468             // If the user explicitly used the -append option, explain that it is not possible.
469             gmx_fatal(FARGS, "GROMACS can only append to files when restarting from a checkpoint.");
470         }
471         else
472         {
473             // If the user did not say anything explicit, just disable appending.
474             bTryToAppendFiles = FALSE;
475         }
476     }
477
478     ContinuationOptions &continuationOptions = mdrunOptions.continuationOptions;
479
480     continuationOptions.appendFilesOptionSet = opt2parg_bSet("-append", asize(pa), pa);
481
482     handleRestart(cr, ms, bTryToAppendFiles, nfile, fnm, &continuationOptions.appendFiles, &continuationOptions.startedFromCheckpoint);
483
484     mdrunOptions.rerun            = opt2bSet("-rerun", nfile, fnm);
485     mdrunOptions.ntompOptionIsSet = opt2parg_bSet("-ntomp", asize(pa), pa);
486
487     /* We postpone opening the log file if we are appending, so we can
488        first truncate the old log file and append to the correct position
489        there instead.  */
490     if (MASTER(cr) && !continuationOptions.appendFiles)
491     {
492         gmx_log_open(ftp2fn(efLOG, nfile, fnm), cr,
493                      continuationOptions.appendFiles, &fplog);
494     }
495     else
496     {
497         fplog = nullptr;
498     }
499
500     domdecOptions.rankOrder    = static_cast<DdRankOrder>(nenum(ddrank_opt_choices));
501     domdecOptions.dlbOption    = static_cast<DlbOption>(nenum(dddlb_opt_choices));
502     domdecOptions.numCells[XX] = static_cast<int>(realddxyz[XX] + 0.5);
503     domdecOptions.numCells[YY] = static_cast<int>(realddxyz[YY] + 0.5);
504     domdecOptions.numCells[ZZ] = static_cast<int>(realddxyz[ZZ] + 0.5);
505
506     nbpu_opt    = nbpu_opt_choices[0];
507     pme_opt     = pme_opt_choices[0];
508     pme_fft_opt = pme_fft_opt_choices[0];
509
510
511     rc = mdrunner();
512
513     /* Log file has to be closed in mdrunner if we are appending to it
514        (fplog not set here) */
515     if (fplog != nullptr)
516     {
517         gmx_log_close(fplog);
518     }
519
520     if (GMX_LIB_MPI)
521     {
522         done_commrec(cr);
523     }
524     done_multisim(ms);
525     return rc;
526 }
527
528 } // namespace