Extend task assignment code
[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, 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/mdrunutility/handlerestart.h"
68 #include "gromacs/mdtypes/commrec.h"
69 #include "gromacs/utility/arraysize.h"
70 #include "gromacs/utility/fatalerror.h"
71 #include "gromacs/utility/smalloc.h"
72
73 #include "mdrun_main.h"
74 #include "repl_ex.h"
75 #include "runner.h"
76
77 /*! \brief Return whether either of the command-line parameters 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], "-multi") == 0 || 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 signal, it will stop as soon as",
222         "checkpoint file can be written, i.e. after the next global communication step.",
223         "When [TT]mdrun[tt] receives an INT signal (e.g. when ctrl+C is",
224         "pressed), it will stop at the next neighbor search step or at the",
225         "second global communication step, whichever happens later.",
226         "In both cases all the usual output will be written to file.",
227         "When running with MPI, a signal to one of the [TT]mdrun[tt] ranks",
228         "is sufficient, this signal should not be sent to mpirun or",
229         "the [TT]mdrun[tt] process that is the parent of the others.",
230         "[PAR]",
231         "Interactive molecular dynamics (IMD) can be activated by using at least one",
232         "of the three IMD switches: The [TT]-imdterm[tt] switch allows one to terminate",
233         "the simulation from the molecular viewer (e.g. VMD). With [TT]-imdwait[tt],",
234         "[TT]mdrun[tt] pauses whenever no IMD client is connected. Pulling from the",
235         "IMD remote can be turned on by [TT]-imdpull[tt].",
236         "The port [TT]mdrun[tt] listens to can be altered by [TT]-imdport[tt].The",
237         "file pointed to by [TT]-if[tt] contains atom indices and forces if IMD",
238         "pulling is used."
239         "[PAR]",
240         "When [TT]mdrun[tt] is started with MPI, it does not run niced by default."
241     };
242
243     /* Command line options */
244     rvec              realddxyz                                               = {0, 0, 0};
245     const char       *ddrank_opt_choices[static_cast<int>(DdRankOrder::nr)+1] =
246     { nullptr, "interleave", "pp_pme", "cartesian", nullptr };
247     const char       *dddlb_opt_choices[static_cast<int>(DlbOption::nr)+1] =
248     { nullptr, "auto", "no", "yes", nullptr };
249     const char       *thread_aff_opt_choices[threadaffNR+1] =
250     { nullptr, "auto", "on", "off", nullptr };
251     const char       *nbpu_opt_choices[] =
252     { nullptr, "auto", "cpu", "gpu", nullptr };
253     gmx_bool          bTryToAppendFiles     = TRUE;
254     const char       *gpuIdsAvailable       = "";
255     const char       *userGpuTaskAssignment = "";
256
257     ImdOptions       &imdOptions = mdrunOptions.imdOptions;
258
259     t_pargs           pa[] = {
260
261         { "-dd",      FALSE, etRVEC, {&realddxyz},
262           "Domain decomposition grid, 0 is optimize" },
263         { "-ddorder", FALSE, etENUM, {ddrank_opt_choices},
264           "DD rank order" },
265         { "-npme",    FALSE, etINT, {&domdecOptions.numPmeRanks},
266           "Number of separate ranks to be used for PME, -1 is guess" },
267         { "-nt",      FALSE, etINT, {&hw_opt.nthreads_tot},
268           "Total number of threads to start (0 is guess)" },
269         { "-ntmpi",   FALSE, etINT, {&hw_opt.nthreads_tmpi},
270           "Number of thread-MPI threads to start (0 is guess)" },
271         { "-ntomp",   FALSE, etINT, {&hw_opt.nthreads_omp},
272           "Number of OpenMP threads per MPI rank to start (0 is guess)" },
273         { "-ntomp_pme", FALSE, etINT, {&hw_opt.nthreads_omp_pme},
274           "Number of OpenMP threads per MPI rank to start (0 is -ntomp)" },
275         { "-pin",     FALSE, etENUM, {thread_aff_opt_choices},
276           "Whether mdrun should try to set thread affinities" },
277         { "-pinoffset", FALSE, etINT, {&hw_opt.core_pinning_offset},
278           "The lowest logical core number to which mdrun should pin the first thread" },
279         { "-pinstride", FALSE, etINT, {&hw_opt.core_pinning_stride},
280           "Pinning distance in logical cores for threads, use 0 to minimize the number of threads per physical core" },
281         { "-gpu_id",  FALSE, etSTR, {&gpuIdsAvailable},
282           "List of unique GPU device IDs available to use" },
283         { "-gputasks",  FALSE, etSTR, {&userGpuTaskAssignment},
284           "List of GPU device IDs, mapping each PP task on each node to a device" },
285         { "-ddcheck", FALSE, etBOOL, {&domdecOptions.checkBondedInteractions},
286           "Check for all bonded interactions with DD" },
287         { "-ddbondcomm", FALSE, etBOOL, {&domdecOptions.useBondedCommunication},
288           "HIDDENUse special bonded atom communication when [TT]-rdd[tt] > cut-off" },
289         { "-rdd",     FALSE, etREAL, {&domdecOptions.minimumCommunicationRange},
290           "The maximum distance for bonded interactions with DD (nm), 0 is determine from initial coordinates" },
291         { "-rcon",    FALSE, etREAL, {&domdecOptions.constraintCommunicationRange},
292           "Maximum distance for P-LINCS (nm), 0 is estimate" },
293         { "-dlb",     FALSE, etENUM, {dddlb_opt_choices},
294           "Dynamic load balancing (with DD)" },
295         { "-dds",     FALSE, etREAL, {&domdecOptions.dlbScaling},
296           "Fraction in (0,1) by whose reciprocal the initial DD cell size will be increased in order to "
297           "provide a margin in which dynamic load balancing can act while preserving the minimum cell size." },
298         { "-ddcsx",   FALSE, etSTR, {&domdecOptions.cellSizeX},
299           "HIDDENA string containing a vector of the relative sizes in the x "
300           "direction of the corresponding DD cells. Only effective with static "
301           "load balancing." },
302         { "-ddcsy",   FALSE, etSTR, {&domdecOptions.cellSizeY},
303           "HIDDENA string containing a vector of the relative sizes in the y "
304           "direction of the corresponding DD cells. Only effective with static "
305           "load balancing." },
306         { "-ddcsz",   FALSE, etSTR, {&domdecOptions.cellSizeZ},
307           "HIDDENA string containing a vector of the relative sizes in the z "
308           "direction of the corresponding DD cells. Only effective with static "
309           "load balancing." },
310         { "-gcom",    FALSE, etINT, {&mdrunOptions.globalCommunicationInterval},
311           "Global communication frequency" },
312         { "-nb",      FALSE, etENUM, {nbpu_opt_choices},
313           "Calculate non-bonded interactions on" },
314         { "-nstlist", FALSE, etINT, {&nstlist_cmdline},
315           "Set nstlist when using a Verlet buffer tolerance (0 is guess)" },
316         { "-tunepme", FALSE, etBOOL, {&mdrunOptions.tunePme},
317           "Optimize PME load between PP/PME ranks or GPU/CPU (only with the Verlet cut-off scheme)" },
318         { "-v",       FALSE, etBOOL, {&mdrunOptions.verbose},
319           "Be loud and noisy" },
320         { "-pforce",  FALSE, etREAL, {&pforce},
321           "Print all forces larger than this (kJ/mol nm)" },
322         { "-reprod",  FALSE, etBOOL, {&mdrunOptions.reproducible},
323           "Try to avoid optimizations that affect binary reproducibility" },
324         { "-cpt",     FALSE, etREAL, {&mdrunOptions.checkpointOptions.period},
325           "Checkpoint interval (minutes)" },
326         { "-cpnum",   FALSE, etBOOL, {&mdrunOptions.checkpointOptions.keepAndNumberCheckpointFiles},
327           "Keep and number checkpoint files" },
328         { "-append",  FALSE, etBOOL, {&bTryToAppendFiles},
329           "Append to previous output files when continuing from checkpoint instead of adding the simulation part number to all file names" },
330         { "-nsteps",  FALSE, etINT64, {&mdrunOptions.numStepsCommandline},
331           "Run this number of steps, overrides .mdp file option (-1 means infinite, -2 means use mdp option, smaller is invalid)" },
332         { "-maxh",   FALSE, etREAL, {&mdrunOptions.maximumHoursToRun},
333           "Terminate after 0.99 times this time (hours)" },
334         { "-multi",   FALSE, etINT, {&nmultisim},
335           "Do multiple simulations in parallel" },
336         { "-replex",  FALSE, etINT, {&replExParams.exchangeInterval},
337           "Attempt replica exchange periodically with this period (steps)" },
338         { "-nex",  FALSE, etINT, {&replExParams.numExchanges},
339           "Number of random exchanges to carry out each exchange interval (N^3 is one suggestion).  -nex zero or not specified gives neighbor replica exchange." },
340         { "-reseed",  FALSE, etINT, {&replExParams.randomSeed},
341           "Seed for replica exchange, -1 is generate a seed" },
342         { "-imdport",    FALSE, etINT, {&imdOptions.port},
343           "HIDDENIMD listening port" },
344         { "-imdwait",  FALSE, etBOOL, {&imdOptions.wait},
345           "HIDDENPause the simulation while no IMD client is connected" },
346         { "-imdterm",  FALSE, etBOOL, {&imdOptions.terminatable},
347           "HIDDENAllow termination of the simulation from IMD client" },
348         { "-imdpull",  FALSE, etBOOL, {&imdOptions.pull},
349           "HIDDENAllow pulling in the simulation from IMD client" },
350         { "-rerunvsite", FALSE, etBOOL, {&mdrunOptions.rerunConstructVsites},
351           "HIDDENRecalculate virtual site coordinates with [TT]-rerun[tt]" },
352         { "-confout", FALSE, etBOOL, {&mdrunOptions.writeConfout},
353           "HIDDENWrite the last configuration with [TT]-c[tt] and force checkpointing at the last step" },
354         { "-stepout", FALSE, etINT, {&mdrunOptions.verboseStepPrintInterval},
355           "HIDDENFrequency of writing the remaining wall clock time for the run" },
356         { "-resetstep", FALSE, etINT, {&mdrunOptions.timingOptions.resetStep},
357           "HIDDENReset cycle counters after these many time steps" },
358         { "-resethway", FALSE, etBOOL, {&mdrunOptions.timingOptions.resetHalfway},
359           "HIDDENReset the cycle counters after half the number of steps or halfway [TT]-maxh[tt]" }
360     };
361     int               rc;
362     char            **multidir = nullptr;
363
364     cr = init_commrec();
365
366     unsigned long PCA_Flags = PCA_CAN_SET_DEFFNM;
367     // With -multi or -multidir, the file names are going to get processed
368     // further (or the working directory changed), so we can't check for their
369     // existence during parsing.  It isn't useful to do any completion based on
370     // file system contents, either.
371     if (is_multisim_option_set(argc, argv))
372     {
373         PCA_Flags |= PCA_DISABLE_INPUT_FILE_CHECKING;
374     }
375
376     /* Comment this in to do fexist calls only on master
377      * works not with rerun or tables at the moment
378      * also comment out the version of init_forcerec in md.c
379      * with NULL instead of opt2fn
380      */
381     /*
382        if (!MASTER(cr))
383        {
384        PCA_Flags |= PCA_NOT_READ_NODE;
385        }
386      */
387
388     if (!parse_common_args(&argc, argv, PCA_Flags, nfile, fnm, asize(pa), pa,
389                            asize(desc), desc, 0, nullptr, &oenv))
390     {
391         sfree(cr);
392         return 0;
393     }
394
395     // Handle the options that permits the user to either declare
396     // which compatible GPUs are availble for use, or to select a GPU
397     // task assignment. Either could be in an environment variable (so
398     // that there is a way to customize it, when using MPI in
399     // heterogeneous contexts).
400     {
401         // TODO Argument parsing can't handle std::string. We should
402         // fix that by changing the parsing, once more of the roles of
403         // handling, validating and implementing defaults for user
404         // command-line options have been seperated.
405         hw_opt.gpuIdsAvailable       = gpuIdsAvailable;
406         hw_opt.userGpuTaskAssignment = userGpuTaskAssignment;
407
408         const char *env = getenv("GMX_GPU_ID");
409         if (env != nullptr)
410         {
411             if (!hw_opt.gpuIdsAvailable.empty())
412             {
413                 gmx_fatal(FARGS, "GMX_GPU_ID and -gpu_id can not be used at the same time");
414             }
415             hw_opt.gpuIdsAvailable = env;
416         }
417
418         env = getenv("GMX_GPUTASKS");
419         if (env != nullptr)
420         {
421             if (!hw_opt.userGpuTaskAssignment.empty())
422             {
423                 gmx_fatal(FARGS, "GMX_GPUTASKS and -gputasks can not be used at the same time");
424             }
425             hw_opt.userGpuTaskAssignment = env;
426         }
427
428         if (!hw_opt.gpuIdsAvailable.empty() && !hw_opt.userGpuTaskAssignment.empty())
429         {
430             gmx_fatal(FARGS, "-gpu_id and -gputasks cannot be used at the same time");
431         }
432     }
433
434     hw_opt.thread_affinity = nenum(thread_aff_opt_choices);
435
436     /* now check the -multi and -multidir option */
437     if (opt2bSet("-multidir", nfile, fnm))
438     {
439         if (nmultisim > 0)
440         {
441             gmx_fatal(FARGS, "mdrun -multi and -multidir options are mutually exclusive.");
442         }
443         nmultisim = opt2fns(&multidir, "-multidir", nfile, fnm);
444     }
445
446
447     if (replExParams.exchangeInterval != 0 && nmultisim < 2)
448     {
449         gmx_fatal(FARGS, "Need at least two replicas for replica exchange (option -multi)");
450     }
451
452     if (replExParams.numExchanges < 0)
453     {
454         gmx_fatal(FARGS, "Replica exchange number of exchanges needs to be positive");
455     }
456
457     if (nmultisim >= 1)
458     {
459 #if !GMX_THREAD_MPI
460         init_multisystem(cr, nmultisim, multidir, nfile, fnm);
461 #else
462         gmx_fatal(FARGS, "mdrun -multi or -multidir are not supported with the thread-MPI library. "
463                   "Please compile GROMACS with a proper external MPI library.");
464 #endif
465     }
466
467     if (!opt2bSet("-cpi", nfile, fnm))
468     {
469         // If we are not starting from a checkpoint we never allow files to be appended
470         // to, since that has caused a ton of strange behaviour and bugs in the past.
471         if (opt2parg_bSet("-append", asize(pa), pa))
472         {
473             // If the user explicitly used the -append option, explain that it is not possible.
474             gmx_fatal(FARGS, "GROMACS can only append to files when restarting from a checkpoint.");
475         }
476         else
477         {
478             // If the user did not say anything explicit, just disable appending.
479             bTryToAppendFiles = FALSE;
480         }
481     }
482
483     ContinuationOptions &continuationOptions = mdrunOptions.continuationOptions;
484
485     continuationOptions.appendFilesOptionSet = opt2parg_bSet("-append", asize(pa), pa);
486
487     handleRestart(cr, bTryToAppendFiles, nfile, fnm, &continuationOptions.appendFiles, &continuationOptions.startedFromCheckpoint);
488
489     mdrunOptions.rerun            = opt2bSet("-rerun", nfile, fnm);
490     mdrunOptions.ntompOptionIsSet = opt2parg_bSet("-ntomp", asize(pa), pa);
491
492     /* We postpone opening the log file if we are appending, so we can
493        first truncate the old log file and append to the correct position
494        there instead.  */
495     if (MASTER(cr) && !continuationOptions.appendFiles)
496     {
497         gmx_log_open(ftp2fn(efLOG, nfile, fnm), cr,
498                      continuationOptions.appendFiles, &fplog);
499     }
500     else
501     {
502         fplog = nullptr;
503     }
504
505     domdecOptions.rankOrder    = static_cast<DdRankOrder>(nenum(ddrank_opt_choices));
506     domdecOptions.dlbOption    = static_cast<DlbOption>(nenum(dddlb_opt_choices));
507     domdecOptions.numCells[XX] = (int)(realddxyz[XX] + 0.5);
508     domdecOptions.numCells[YY] = (int)(realddxyz[YY] + 0.5);
509     domdecOptions.numCells[ZZ] = (int)(realddxyz[ZZ] + 0.5);
510
511     nbpu_opt  = nbpu_opt_choices[0];
512     rc        = mdrunner();
513
514     /* Log file has to be closed in mdrunner if we are appending to it
515        (fplog not set here) */
516     if (MASTER(cr) && !continuationOptions.appendFiles)
517     {
518         gmx_log_close(fplog);
519     }
520
521     return rc;
522 }
523
524 } // namespace