508f6d03b6101dae7225c5298acba6dd6c497266
[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, 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 <stdio.h>
58 #include <string.h>
59
60 #include "gromacs/commandline/pargs.h"
61 #include "gromacs/fileio/filenm.h"
62 #include "gromacs/legacyheaders/checkpoint.h"
63 #include "gromacs/legacyheaders/copyrite.h"
64 #include "gromacs/legacyheaders/macros.h"
65 #include "gromacs/legacyheaders/main.h"
66 #include "gromacs/legacyheaders/mdrun.h"
67 #include "gromacs/legacyheaders/network.h"
68 #include "gromacs/legacyheaders/readinp.h"
69 #include "gromacs/legacyheaders/typedefs.h"
70 #include "gromacs/legacyheaders/types/commrec.h"
71 #include "gromacs/utility/fatalerror.h"
72
73 #include "mdrun_main.h"
74
75 /*! \brief Return whether either of the command-line parameters that
76  *  will trigger a multi-simulation is set */
77 static bool is_multisim_option_set(int argc, const char *const argv[])
78 {
79     for (int i = 0; i < argc; ++i)
80     {
81         if (strcmp(argv[i], "-multi") == 0 || strcmp(argv[i], "-multidir") == 0)
82         {
83             return true;
84         }
85     }
86     return false;
87 }
88
89 //! Implements C-style main function for mdrun
90 int gmx_mdrun(int argc, char *argv[])
91 {
92     const char   *desc[] = {
93         "[THISMODULE] is the main computational chemistry engine",
94         "within GROMACS. Obviously, it performs Molecular Dynamics simulations,",
95         "but it can also perform Stochastic Dynamics, Energy Minimization,",
96         "test particle insertion or (re)calculation of energies.",
97         "Normal mode analysis is another option. In this case [TT]mdrun[tt]",
98         "builds a Hessian matrix from single conformation.",
99         "For usual Normal Modes-like calculations, make sure that",
100         "the structure provided is properly energy-minimized.",
101         "The generated matrix can be diagonalized by [gmx-nmeig].[PAR]",
102         "The [TT]mdrun[tt] program reads the run input file ([TT]-s[tt])",
103         "and distributes the topology over ranks if needed.",
104         "[TT]mdrun[tt] produces at least four output files.",
105         "A single log file ([TT]-g[tt]) is written.",
106         "The trajectory file ([TT]-o[tt]), contains coordinates, velocities and",
107         "optionally forces.",
108         "The structure file ([TT]-c[tt]) contains the coordinates and",
109         "velocities of the last step.",
110         "The energy file ([TT]-e[tt]) contains energies, the temperature,",
111         "pressure, etc, a lot of these things are also printed in the log file.",
112         "Optionally coordinates can be written to a compressed trajectory file",
113         "([TT]-x[tt]).[PAR]",
114         "The option [TT]-dhdl[tt] is only used when free energy calculation is",
115         "turned on.[PAR]",
116         "Running mdrun efficiently in parallel is a complex topic topic,",
117         "many aspects of which are covered in the online User Guide. You",
118         "should look there for practical advice on using many of the options",
119         "available in mdrun.[PAR]",
120         "ED (essential dynamics) sampling and/or additional flooding potentials",
121         "are switched on by using the [TT]-ei[tt] flag followed by an [REF].edi[ref]",
122         "file. The [REF].edi[ref] file can be produced with the [TT]make_edi[tt] tool",
123         "or by using options in the essdyn menu of the WHAT IF program.",
124         "[TT]mdrun[tt] produces a [REF].xvg[ref] output file that",
125         "contains projections of positions, velocities and forces onto selected",
126         "eigenvectors.[PAR]",
127         "When user-defined potential functions have been selected in the",
128         "[REF].mdp[ref] file the [TT]-table[tt] option is used to pass [TT]mdrun[tt]",
129         "a formatted table with potential functions. The file is read from",
130         "either the current directory or from the [TT]GMXLIB[tt] directory.",
131         "A number of pre-formatted tables are presented in the [TT]GMXLIB[tt] dir,",
132         "for 6-8, 6-9, 6-10, 6-11, 6-12 Lennard-Jones potentials with",
133         "normal Coulomb.",
134         "When pair interactions are present, a separate table for pair interaction",
135         "functions is read using the [TT]-tablep[tt] option.[PAR]",
136         "When tabulated bonded functions are present in the topology,",
137         "interaction functions are read using the [TT]-tableb[tt] option.",
138         "For each different tabulated interaction type the table file name is",
139         "modified in a different way: before the file extension an underscore is",
140         "appended, then a 'b' for bonds, an 'a' for angles or a 'd' for dihedrals",
141         "and finally the table number of the interaction type.[PAR]",
142         "The options [TT]-px[tt] and [TT]-pf[tt] are used for writing pull COM",
143         "coordinates and forces when pulling is selected",
144         "in the [REF].mdp[ref] file.[PAR]",
145         "Finally some experimental algorithms can be tested when the",
146         "appropriate options have been given. Currently under",
147         "investigation are: polarizability.",
148         "[PAR]",
149         "The option [TT]-membed[tt] does what used to be g_membed, i.e. embed",
150         "a protein into a membrane. The data file should contain the options",
151         "that where passed to g_membed before. The [TT]-mn[tt] and [TT]-mp[tt]",
152         "both apply to this as well.",
153         "[PAR]",
154         "The option [TT]-pforce[tt] is useful when you suspect a simulation",
155         "crashes due to too large forces. With this option coordinates and",
156         "forces of atoms with a force larger than a certain value will",
157         "be printed to stderr.",
158         "[PAR]",
159         "Checkpoints containing the complete state of the system are written",
160         "at regular intervals (option [TT]-cpt[tt]) to the file [TT]-cpo[tt],",
161         "unless option [TT]-cpt[tt] is set to -1.",
162         "The previous checkpoint is backed up to [TT]state_prev.cpt[tt] to",
163         "make sure that a recent state of the system is always available,",
164         "even when the simulation is terminated while writing a checkpoint.",
165         "With [TT]-cpnum[tt] all checkpoint files are kept and appended",
166         "with the step number.",
167         "A simulation can be continued by reading the full state from file",
168         "with option [TT]-cpi[tt]. This option is intelligent in the way that",
169         "if no checkpoint file is found, GROMACS just assumes a normal run and",
170         "starts from the first step of the [REF].tpr[ref] file. By default the output",
171         "will be appending to the existing output files. The checkpoint file",
172         "contains checksums of all output files, such that you will never",
173         "loose data when some output files are modified, corrupt or removed.",
174         "There are three scenarios with [TT]-cpi[tt]:[PAR]",
175         "[TT]*[tt] no files with matching names are present: new output files are written[PAR]",
176         "[TT]*[tt] all files are present with names and checksums matching those stored",
177         "in the checkpoint file: files are appended[PAR]",
178         "[TT]*[tt] otherwise no files are modified and a fatal error is generated[PAR]",
179         "With [TT]-noappend[tt] new output files are opened and the simulation",
180         "part number is added to all output file names.",
181         "Note that in all cases the checkpoint file itself is not renamed",
182         "and will be overwritten, unless its name does not match",
183         "the [TT]-cpo[tt] option.",
184         "[PAR]",
185         "With checkpointing the output is appended to previously written",
186         "output files, unless [TT]-noappend[tt] is used or none of the previous",
187         "output files are present (except for the checkpoint file).",
188         "The integrity of the files to be appended is verified using checksums",
189         "which are stored in the checkpoint file. This ensures that output can",
190         "not be mixed up or corrupted due to file appending. When only some",
191         "of the previous output files are present, a fatal error is generated",
192         "and no old output files are modified and no new output files are opened.",
193         "The result with appending will be the same as from a single run.",
194         "The contents will be binary identical, unless you use a different number",
195         "of ranks or dynamic load balancing or the FFT library uses optimizations",
196         "through timing.",
197         "[PAR]",
198         "With option [TT]-maxh[tt] a simulation is terminated and a checkpoint",
199         "file is written at the first neighbor search step where the run time",
200         "exceeds [TT]-maxh[tt]\\*0.99 hours. This option is particularly useful in",
201         "combination with setting [TT]nsteps[tt] to -1 either in the mdp or using the",
202         "similarly named command line option. This results in an infinite run,",
203         "terminated only when the time limit set by [TT]-maxh[tt] is reached (if any)"
204         "or upon receiving a signal."
205         "[PAR]",
206         "When [TT]mdrun[tt] receives a TERM signal, it will set nsteps to the current",
207         "step plus one. When [TT]mdrun[tt] receives an INT signal (e.g. when ctrl+C is",
208         "pressed), it will stop after the next neighbor search step ",
209         "(with nstlist=0 at the next step).",
210         "In both cases all the usual output will be written to file.",
211         "When running with MPI, a signal to one of the [TT]mdrun[tt] ranks",
212         "is sufficient, this signal should not be sent to mpirun or",
213         "the [TT]mdrun[tt] process that is the parent of the others.",
214         "[PAR]",
215         "Interactive molecular dynamics (IMD) can be activated by using at least one",
216         "of the three IMD switches: The [TT]-imdterm[tt] switch allows to terminate the",
217         "simulation from the molecular viewer (e.g. VMD). With [TT]-imdwait[tt],",
218         "[TT]mdrun[tt] pauses whenever no IMD client is connected. Pulling from the",
219         "IMD remote can be turned on by [TT]-imdpull[tt].",
220         "The port [TT]mdrun[tt] listens to can be altered by [TT]-imdport[tt].The",
221         "file pointed to by [TT]-if[tt] contains atom indices and forces if IMD",
222         "pulling is used."
223         "[PAR]",
224         "When [TT]mdrun[tt] is started with MPI, it does not run niced by default."
225     };
226     t_commrec    *cr;
227     t_filenm      fnm[] = {
228         { efTPR, NULL,      NULL,       ffREAD },
229         { efTRN, "-o",      NULL,       ffWRITE },
230         { efCOMPRESSED, "-x", NULL,     ffOPTWR },
231         { efCPT, "-cpi",    NULL,       ffOPTRD | ffALLOW_MISSING },
232         { efCPT, "-cpo",    NULL,       ffOPTWR },
233         { efSTO, "-c",      "confout",  ffWRITE },
234         { efEDR, "-e",      "ener",     ffWRITE },
235         { efLOG, "-g",      "md",       ffWRITE },
236         { efXVG, "-dhdl",   "dhdl",     ffOPTWR },
237         { efXVG, "-field",  "field",    ffOPTWR },
238         { efXVG, "-table",  "table",    ffOPTRD },
239         { efXVG, "-tabletf", "tabletf",    ffOPTRD },
240         { efXVG, "-tablep", "tablep",   ffOPTRD },
241         { efXVG, "-tableb", "table",    ffOPTRD },
242         { efTRX, "-rerun",  "rerun",    ffOPTRD },
243         { efXVG, "-tpi",    "tpi",      ffOPTWR },
244         { efXVG, "-tpid",   "tpidist",  ffOPTWR },
245         { efEDI, "-ei",     "sam",      ffOPTRD },
246         { efXVG, "-eo",     "edsam",    ffOPTWR },
247         { efXVG, "-devout", "deviatie", ffOPTWR },
248         { efXVG, "-runav",  "runaver",  ffOPTWR },
249         { efXVG, "-px",     "pullx",    ffOPTWR },
250         { efXVG, "-pf",     "pullf",    ffOPTWR },
251         { efXVG, "-ro",     "rotation", ffOPTWR },
252         { efLOG, "-ra",     "rotangles", ffOPTWR },
253         { efLOG, "-rs",     "rotslabs", ffOPTWR },
254         { efLOG, "-rt",     "rottorque", ffOPTWR },
255         { efMTX, "-mtx",    "nm",       ffOPTWR },
256         { efNDX, "-dn",     "dipole",   ffOPTWR },
257         { efRND, "-multidir", NULL,      ffOPTRDMULT},
258         { efDAT, "-membed", "membed",   ffOPTRD },
259         { efTOP, "-mp",     "membed",   ffOPTRD },
260         { efNDX, "-mn",     "membed",   ffOPTRD },
261         { efXVG, "-if",     "imdforces", ffOPTWR },
262         { efXVG, "-swap",   "swapions", ffOPTWR }
263     };
264     const int     NFILE = asize(fnm);
265
266     /* Command line options ! */
267     gmx_bool        bDDBondCheck  = TRUE;
268     gmx_bool        bDDBondComm   = TRUE;
269     gmx_bool        bTunePME      = TRUE;
270     gmx_bool        bVerbose      = FALSE;
271     gmx_bool        bCompact      = TRUE;
272     gmx_bool        bRerunVSite   = FALSE;
273     gmx_bool        bConfout      = TRUE;
274     gmx_bool        bReproducible = FALSE;
275     gmx_bool        bIMDwait      = FALSE;
276     gmx_bool        bIMDterm      = FALSE;
277     gmx_bool        bIMDpull      = FALSE;
278
279     int             npme          = -1;
280     int             nstlist       = 0;
281     int             nmultisim     = 0;
282     int             nstglobalcomm = -1;
283     int             repl_ex_nst   = 0;
284     int             repl_ex_seed  = -1;
285     int             repl_ex_nex   = 0;
286     int             nstepout      = 100;
287     int             resetstep     = -1;
288     gmx_int64_t     nsteps        = -2;   /* the value -2 means that the mdp option will be used */
289     int             imdport       = 8888; /* can be almost anything, 8888 is easy to remember */
290
291     rvec            realddxyz          = {0, 0, 0};
292     const char     *ddno_opt[ddnoNR+1] =
293     { NULL, "interleave", "pp_pme", "cartesian", NULL };
294     const char     *dddlb_opt[] =
295     { NULL, "auto", "no", "yes", NULL };
296     const char     *thread_aff_opt[threadaffNR+1] =
297     { NULL, "auto", "on", "off", NULL };
298     const char     *nbpu_opt[] =
299     { NULL, "auto", "cpu", "gpu", "gpu_cpu", NULL };
300     real            rdd                   = 0.0, rconstr = 0.0, dlb_scale = 0.8, pforce = -1;
301     char           *ddcsx                 = NULL, *ddcsy = NULL, *ddcsz = NULL;
302     real            cpt_period            = 15.0, max_hours = -1;
303     gmx_bool        bAppendFiles          = TRUE;
304     gmx_bool        bKeepAndNumCPT        = FALSE;
305     gmx_bool        bResetCountersHalfWay = FALSE;
306     output_env_t    oenv                  = NULL;
307
308     /* Non transparent initialization of a complex gmx_hw_opt_t struct.
309      * But unfortunately we are not allowed to call a function here,
310      * since declarations follow below.
311      */
312     gmx_hw_opt_t    hw_opt = {
313         0, 0, 0, 0, threadaffSEL, 0, 0,
314         { NULL, FALSE, 0, NULL }
315     };
316
317     t_pargs         pa[] = {
318
319         { "-dd",      FALSE, etRVEC, {&realddxyz},
320           "Domain decomposition grid, 0 is optimize" },
321         { "-ddorder", FALSE, etENUM, {ddno_opt},
322           "DD rank order" },
323         { "-npme",    FALSE, etINT, {&npme},
324           "Number of separate ranks to be used for PME, -1 is guess" },
325         { "-nt",      FALSE, etINT, {&hw_opt.nthreads_tot},
326           "Total number of threads to start (0 is guess)" },
327         { "-ntmpi",   FALSE, etINT, {&hw_opt.nthreads_tmpi},
328           "Number of thread-MPI threads to start (0 is guess)" },
329         { "-ntomp",   FALSE, etINT, {&hw_opt.nthreads_omp},
330           "Number of OpenMP threads per MPI rank to start (0 is guess)" },
331         { "-ntomp_pme", FALSE, etINT, {&hw_opt.nthreads_omp_pme},
332           "Number of OpenMP threads per MPI rank to start (0 is -ntomp)" },
333         { "-pin",     FALSE, etENUM, {thread_aff_opt},
334           "Whether mdrun should try to set thread affinities" },
335         { "-pinoffset", FALSE, etINT, {&hw_opt.core_pinning_offset},
336           "The lowest logical core number to which mdrun should pin the first thread" },
337         { "-pinstride", FALSE, etINT, {&hw_opt.core_pinning_stride},
338           "Pinning distance in logical cores for threads, use 0 to minimize the number of threads per physical core" },
339         { "-gpu_id",  FALSE, etSTR, {&hw_opt.gpu_opt.gpu_id},
340           "List of GPU device id-s to use, specifies the per-node PP rank to GPU mapping" },
341         { "-ddcheck", FALSE, etBOOL, {&bDDBondCheck},
342           "Check for all bonded interactions with DD" },
343         { "-ddbondcomm", FALSE, etBOOL, {&bDDBondComm},
344           "HIDDENUse special bonded atom communication when [TT]-rdd[tt] > cut-off" },
345         { "-rdd",     FALSE, etREAL, {&rdd},
346           "The maximum distance for bonded interactions with DD (nm), 0 is determine from initial coordinates" },
347         { "-rcon",    FALSE, etREAL, {&rconstr},
348           "Maximum distance for P-LINCS (nm), 0 is estimate" },
349         { "-dlb",     FALSE, etENUM, {dddlb_opt},
350           "Dynamic load balancing (with DD)" },
351         { "-dds",     FALSE, etREAL, {&dlb_scale},
352           "Fraction in (0,1) by whose reciprocal the initial DD cell size will be increased in order to "
353           "provide a margin in which dynamic load balancing can act while preserving the minimum cell size." },
354         { "-ddcsx",   FALSE, etSTR, {&ddcsx},
355           "HIDDENA string containing a vector of the relative sizes in the x "
356           "direction of the corresponding DD cells. Only effective with static "
357           "load balancing." },
358         { "-ddcsy",   FALSE, etSTR, {&ddcsy},
359           "HIDDENA string containing a vector of the relative sizes in the y "
360           "direction of the corresponding DD cells. Only effective with static "
361           "load balancing." },
362         { "-ddcsz",   FALSE, etSTR, {&ddcsz},
363           "HIDDENA string containing a vector of the relative sizes in the z "
364           "direction of the corresponding DD cells. Only effective with static "
365           "load balancing." },
366         { "-gcom",    FALSE, etINT, {&nstglobalcomm},
367           "Global communication frequency" },
368         { "-nb",      FALSE, etENUM, {&nbpu_opt},
369           "Calculate non-bonded interactions on" },
370         { "-nstlist", FALSE, etINT, {&nstlist},
371           "Set nstlist when using a Verlet buffer tolerance (0 is guess)" },
372         { "-tunepme", FALSE, etBOOL, {&bTunePME},
373           "Optimize PME load between PP/PME ranks or GPU/CPU" },
374         { "-v",       FALSE, etBOOL, {&bVerbose},
375           "Be loud and noisy" },
376         { "-compact", FALSE, etBOOL, {&bCompact},
377           "Write a compact log file" },
378         { "-pforce",  FALSE, etREAL, {&pforce},
379           "Print all forces larger than this (kJ/mol nm)" },
380         { "-reprod",  FALSE, etBOOL, {&bReproducible},
381           "Try to avoid optimizations that affect binary reproducibility" },
382         { "-cpt",     FALSE, etREAL, {&cpt_period},
383           "Checkpoint interval (minutes)" },
384         { "-cpnum",   FALSE, etBOOL, {&bKeepAndNumCPT},
385           "Keep and number checkpoint files" },
386         { "-append",  FALSE, etBOOL, {&bAppendFiles},
387           "Append to previous output files when continuing from checkpoint instead of adding the simulation part number to all file names" },
388         { "-nsteps",  FALSE, etINT64, {&nsteps},
389           "Run this number of steps, overrides .mdp file option (-1 means infinite, -2 means use mdp option, smaller is invalid)" },
390         { "-maxh",   FALSE, etREAL, {&max_hours},
391           "Terminate after 0.99 times this time (hours)" },
392         { "-multi",   FALSE, etINT, {&nmultisim},
393           "Do multiple simulations in parallel" },
394         { "-replex",  FALSE, etINT, {&repl_ex_nst},
395           "Attempt replica exchange periodically with this period (steps)" },
396         { "-nex",  FALSE, etINT, {&repl_ex_nex},
397           "Number of random exchanges to carry out each exchange interval (N^3 is one suggestion).  -nex zero or not specified gives neighbor replica exchange." },
398         { "-reseed",  FALSE, etINT, {&repl_ex_seed},
399           "Seed for replica exchange, -1 is generate a seed" },
400         { "-imdport",    FALSE, etINT, {&imdport},
401           "HIDDENIMD listening port" },
402         { "-imdwait",  FALSE, etBOOL, {&bIMDwait},
403           "HIDDENPause the simulation while no IMD client is connected" },
404         { "-imdterm",  FALSE, etBOOL, {&bIMDterm},
405           "HIDDENAllow termination of the simulation from IMD client" },
406         { "-imdpull",  FALSE, etBOOL, {&bIMDpull},
407           "HIDDENAllow pulling in the simulation from IMD client" },
408         { "-rerunvsite", FALSE, etBOOL, {&bRerunVSite},
409           "HIDDENRecalculate virtual site coordinates with [TT]-rerun[tt]" },
410         { "-confout", FALSE, etBOOL, {&bConfout},
411           "HIDDENWrite the last configuration with [TT]-c[tt] and force checkpointing at the last step" },
412         { "-stepout", FALSE, etINT, {&nstepout},
413           "HIDDENFrequency of writing the remaining wall clock time for the run" },
414         { "-resetstep", FALSE, etINT, {&resetstep},
415           "HIDDENReset cycle counters after these many time steps" },
416         { "-resethway", FALSE, etBOOL, {&bResetCountersHalfWay},
417           "HIDDENReset the cycle counters after half the number of steps or halfway [TT]-maxh[tt]" }
418     };
419     unsigned long   Flags;
420     ivec            ddxyz;
421     int             dd_node_order;
422     gmx_bool        bAddPart;
423     FILE           *fplog, *fpmulti;
424     int             sim_part, sim_part_fn;
425     const char     *part_suffix = ".part";
426     char            suffix[STRLEN];
427     int             rc;
428     char          **multidir = NULL;
429
430     cr = init_commrec();
431
432     unsigned long PCA_Flags = PCA_CAN_SET_DEFFNM;
433     // With -multi or -multidir, the file names are going to get processed
434     // further (or the working directory changed), so we can't check for their
435     // existence during parsing.  It isn't useful to do any completion based on
436     // file system contents, either.
437     if (is_multisim_option_set(argc, argv))
438     {
439         PCA_Flags |= PCA_DISABLE_INPUT_FILE_CHECKING;
440     }
441
442     /* Comment this in to do fexist calls only on master
443      * works not with rerun or tables at the moment
444      * also comment out the version of init_forcerec in md.c
445      * with NULL instead of opt2fn
446      */
447     /*
448        if (!MASTER(cr))
449        {
450        PCA_Flags |= PCA_NOT_READ_NODE;
451        }
452      */
453
454     if (!parse_common_args(&argc, argv, PCA_Flags, NFILE, fnm, asize(pa), pa,
455                            asize(desc), desc, 0, NULL, &oenv))
456     {
457         return 0;
458     }
459
460
461     /* we set these early because they might be used in init_multisystem()
462        Note that there is the potential for npme>nnodes until the number of
463        threads is set later on, if there's thread parallelization. That shouldn't
464        lead to problems. */
465     dd_node_order = nenum(ddno_opt);
466     cr->npmenodes = npme;
467
468     hw_opt.thread_affinity = nenum(thread_aff_opt);
469
470     /* now check the -multi and -multidir option */
471     if (opt2bSet("-multidir", NFILE, fnm))
472     {
473         if (nmultisim > 0)
474         {
475             gmx_fatal(FARGS, "mdrun -multi and -multidir options are mutually exclusive.");
476         }
477         nmultisim = opt2fns(&multidir, "-multidir", NFILE, fnm);
478     }
479
480
481     if (repl_ex_nst != 0 && nmultisim < 2)
482     {
483         gmx_fatal(FARGS, "Need at least two replicas for replica exchange (option -multi)");
484     }
485
486     if (repl_ex_nex < 0)
487     {
488         gmx_fatal(FARGS, "Replica exchange number of exchanges needs to be positive");
489     }
490
491     if (nmultisim > 1)
492     {
493 #ifndef GMX_THREAD_MPI
494         gmx_bool bParFn = (multidir == NULL);
495         init_multisystem(cr, nmultisim, multidir, NFILE, fnm, bParFn);
496 #else
497         gmx_fatal(FARGS, "mdrun -multi is not supported with the thread library. "
498                   "Please compile GROMACS with MPI support");
499 #endif
500     }
501
502     bAddPart = !bAppendFiles;
503
504     /* Check if there is ANY checkpoint file available */
505     sim_part    = 1;
506     sim_part_fn = sim_part;
507     if (opt2bSet("-cpi", NFILE, fnm))
508     {
509         bAppendFiles =
510             read_checkpoint_simulation_part(opt2fn_master("-cpi", NFILE,
511                                                           fnm, cr),
512                                             &sim_part_fn, cr,
513                                             bAppendFiles, NFILE, fnm,
514                                             part_suffix, &bAddPart);
515         if (sim_part_fn == 0 && MULTIMASTER(cr))
516         {
517             fprintf(stdout, "No previous checkpoint file present, assuming this is a new run.\n");
518         }
519         else
520         {
521             sim_part = sim_part_fn + 1;
522         }
523
524         if (MULTISIM(cr) && MASTER(cr))
525         {
526             if (MULTIMASTER(cr))
527             {
528                 /* Log file is not yet available, so if there's a
529                  * problem we can only write to stderr. */
530                 fpmulti = stderr;
531             }
532             else
533             {
534                 fpmulti = NULL;
535             }
536             check_multi_int(fpmulti, cr->ms, sim_part, "simulation part", TRUE);
537         }
538     }
539     else
540     {
541         bAppendFiles = FALSE;
542     }
543
544     if (!bAppendFiles)
545     {
546         sim_part_fn = sim_part;
547     }
548
549     if (bAddPart)
550     {
551         /* Rename all output files (except checkpoint files) */
552         /* create new part name first (zero-filled) */
553         sprintf(suffix, "%s%04d", part_suffix, sim_part_fn);
554
555         add_suffix_to_output_names(fnm, NFILE, suffix);
556         if (MULTIMASTER(cr))
557         {
558             fprintf(stdout, "Checkpoint file is from part %d, new output files will be suffixed '%s'.\n", sim_part-1, suffix);
559         }
560     }
561
562     Flags = opt2bSet("-rerun", NFILE, fnm) ? MD_RERUN : 0;
563     Flags = Flags | (bDDBondCheck  ? MD_DDBONDCHECK  : 0);
564     Flags = Flags | (bDDBondComm   ? MD_DDBONDCOMM   : 0);
565     Flags = Flags | (bTunePME      ? MD_TUNEPME      : 0);
566     Flags = Flags | (bConfout      ? MD_CONFOUT      : 0);
567     Flags = Flags | (bRerunVSite   ? MD_RERUN_VSITE  : 0);
568     Flags = Flags | (bReproducible ? MD_REPRODUCIBLE : 0);
569     Flags = Flags | (bAppendFiles  ? MD_APPENDFILES  : 0);
570     Flags = Flags | (opt2parg_bSet("-append", asize(pa), pa) ? MD_APPENDFILESSET : 0);
571     Flags = Flags | (bKeepAndNumCPT ? MD_KEEPANDNUMCPT : 0);
572     Flags = Flags | (sim_part > 1    ? MD_STARTFROMCPT : 0);
573     Flags = Flags | (bResetCountersHalfWay ? MD_RESETCOUNTERSHALFWAY : 0);
574     Flags = Flags | (bIMDwait      ? MD_IMDWAIT      : 0);
575     Flags = Flags | (bIMDterm      ? MD_IMDTERM      : 0);
576     Flags = Flags | (bIMDpull      ? MD_IMDPULL      : 0);
577
578     /* We postpone opening the log file if we are appending, so we can
579        first truncate the old log file and append to the correct position
580        there instead.  */
581     if (MASTER(cr) && !bAppendFiles)
582     {
583         gmx_log_open(ftp2fn(efLOG, NFILE, fnm), cr,
584                      Flags & MD_APPENDFILES, &fplog);
585         please_cite(fplog, "Hess2008b");
586         please_cite(fplog, "Spoel2005a");
587         please_cite(fplog, "Lindahl2001a");
588         please_cite(fplog, "Berendsen95a");
589     }
590     else
591     {
592         fplog = NULL;
593     }
594
595     ddxyz[XX] = (int)(realddxyz[XX] + 0.5);
596     ddxyz[YY] = (int)(realddxyz[YY] + 0.5);
597     ddxyz[ZZ] = (int)(realddxyz[ZZ] + 0.5);
598
599     rc = mdrunner(&hw_opt, fplog, cr, NFILE, fnm, oenv, bVerbose, bCompact,
600                   nstglobalcomm, ddxyz, dd_node_order, rdd, rconstr,
601                   dddlb_opt[0], dlb_scale, ddcsx, ddcsy, ddcsz,
602                   nbpu_opt[0], nstlist,
603                   nsteps, nstepout, resetstep,
604                   nmultisim, repl_ex_nst, repl_ex_nex, repl_ex_seed,
605                   pforce, cpt_period, max_hours, imdport, Flags);
606
607     /* Log file has to be closed in mdrunner if we are appending to it
608        (fplog not set here) */
609     if (MASTER(cr) && !bAppendFiles)
610     {
611         gmx_log_close(fplog);
612     }
613
614     return rc;
615 }