Merge "Merge branch release-4-6 into master"
[alexxy/gromacs.git] / src / programs / mdrun / mdrun.cpp
1 /*  -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  *
3  *
4  *                This source code is part of
5  *
6  *                 G   R   O   M   A   C   S
7  *
8  *          GROningen MAchine for Chemical Simulations
9  *
10  *                        VERSION 3.2.0
11  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13  * Copyright (c) 2001-2004, The GROMACS development team,
14  * check out http://www.gromacs.org for more information.
15
16  * This program is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU General Public License
18  * as published by the Free Software Foundation; either version 2
19  * of the License, or (at your option) any later version.
20  *
21  * If you want to redistribute modifications, please consider that
22  * scientific software is very special. Version control is crucial -
23  * bugs must be traceable. We will be happy to consider code for
24  * inclusion in the official distribution, but derived work must not
25  * be called official GROMACS. Details are found in the README & COPYING
26  * files - if they are missing, get the official version at www.gromacs.org.
27  *
28  * To help us fund GROMACS development, we humbly ask that you cite
29  * the papers on the package - you can find them in the top README file.
30  *
31  * For more info, check our website at http://www.gromacs.org
32  *
33  * And Hey:
34  * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
35  */
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39
40 #include <stdio.h>
41
42 #include "gromacs/legacyheaders/checkpoint.h"
43 #include "gromacs/legacyheaders/copyrite.h"
44 #include "gromacs/legacyheaders/filenm.h"
45 #include "gromacs/legacyheaders/gmx_fatal.h"
46 #include "gromacs/legacyheaders/macros.h"
47 #include "gromacs/legacyheaders/main.h"
48 #include "gromacs/legacyheaders/mdrun.h"
49 #include "gromacs/legacyheaders/network.h"
50 #include "gromacs/legacyheaders/readinp.h"
51 #include "gromacs/legacyheaders/statutil.h"
52 #include "gromacs/legacyheaders/typedefs.h"
53
54 #include "gromacs/utility/programinfo.h"
55
56 int main(int argc, char *argv[])
57 {
58     const char   *desc[] = {
59         "The [TT]mdrun[tt] program is the main computational chemistry engine",
60         "within GROMACS. Obviously, it performs Molecular Dynamics simulations,",
61         "but it can also perform Stochastic Dynamics, Energy Minimization,",
62         "test particle insertion or (re)calculation of energies.",
63         "Normal mode analysis is another option. In this case [TT]mdrun[tt]",
64         "builds a Hessian matrix from single conformation.",
65         "For usual Normal Modes-like calculations, make sure that",
66         "the structure provided is properly energy-minimized.",
67         "The generated matrix can be diagonalized by [TT]g_nmeig[tt].[PAR]",
68         "The [TT]mdrun[tt] program reads the run input file ([TT]-s[tt])",
69         "and distributes the topology over nodes if needed.",
70         "[TT]mdrun[tt] produces at least four output files.",
71         "A single log file ([TT]-g[tt]) is written, unless the option",
72         "[TT]-seppot[tt] is used, in which case each node writes a log file.",
73         "The trajectory file ([TT]-o[tt]), contains coordinates, velocities and",
74         "optionally forces.",
75         "The structure file ([TT]-c[tt]) contains the coordinates and",
76         "velocities of the last step.",
77         "The energy file ([TT]-e[tt]) contains energies, the temperature,",
78         "pressure, etc, a lot of these things are also printed in the log file.",
79         "Optionally coordinates can be written to a compressed trajectory file",
80         "([TT]-x[tt]).[PAR]",
81         "The option [TT]-dhdl[tt] is only used when free energy calculation is",
82         "turned on.[PAR]",
83         "A simulation can be run in parallel using two different parallelization",
84         "schemes: MPI parallelization and/or OpenMP thread parallelization.",
85         "The MPI parallelization uses multiple processes when [TT]mdrun[tt] is",
86         "compiled with a normal MPI library or threads when [TT]mdrun[tt] is",
87         "compiled with the GROMACS built-in thread-MPI library. OpenMP threads",
88         "are supported when mdrun is compiled with OpenMP. Full OpenMP support",
89         "is only available with the Verlet cut-off scheme, with the (older)",
90         "group scheme only PME-only processes can use OpenMP parallelization.",
91         "In all cases [TT]mdrun[tt] will by default try to use all the available",
92         "hardware resources. With a normal MPI library only the options",
93         "[TT]-ntomp[tt] (with the Verlet cut-off scheme) and [TT]-ntomp_pme[tt],",
94         "for PME-only processes, can be used to control the number of threads.",
95         "With thread-MPI there are additional options [TT]-nt[tt], which sets",
96         "the total number of threads, and [TT]-ntmpi[tt], which sets the number",
97         "of thread-MPI threads.",
98         "Note that using combined MPI+OpenMP parallelization is almost always",
99         "slower than single parallelization, except at the scaling limit, where",
100         "especially OpenMP parallelization of PME reduces the communication cost.",
101         "OpenMP-only parallelization is much faster than MPI-only parallelization",
102         "on a single CPU(-die). Since we currently don't have proper hardware",
103         "topology detection, [TT]mdrun[tt] compiled with thread-MPI will only",
104         "automatically use OpenMP-only parallelization when you use up to 4",
105         "threads, up to 12 threads with Intel Nehalem/Westmere, or up to 16",
106         "threads with Intel Sandy Bridge or newer CPUs. Otherwise MPI-only",
107         "parallelization is used (except with GPUs, see below).",
108         "[PAR]",
109         "To quickly test the performance of the new Verlet cut-off scheme",
110         "with old [TT].tpr[tt] files, either on CPUs or CPUs+GPUs, you can use",
111         "the [TT]-testverlet[tt] option. This should not be used for production,",
112         "since it can slightly modify potentials and it will remove charge groups",
113         "making analysis difficult, as the [TT].tpr[tt] file will still contain",
114         "charge groups. For production simulations it is highly recommended",
115         "to specify [TT]cutoff-scheme = Verlet[tt] in the [TT].mdp[tt] file.",
116         "[PAR]",
117         "With GPUs (only supported with the Verlet cut-off scheme), the number",
118         "of GPUs should match the number of MPI processes or MPI threads,",
119         "excluding PME-only processes/threads. With thread-MPI the number",
120         "of MPI threads will automatically be set to the number of GPUs detected.",
121         "When you want to use a subset of the available GPUs, you can use",
122         "the [TT]-gpu_id[tt] option, where GPU id's are passed as a string,",
123         "e.g. 02 for using GPUs 0 and 2. When you want different GPU id's",
124         "on different nodes of a compute cluster, use the GMX_GPU_ID environment",
125         "variable instead. The format for GMX_GPU_ID is identical to ",
126         "[TT]-gpu_id[tt], but an environment variable can have different values",
127         "on different nodes of a cluster.",
128         "[PAR]",
129         "When using PME with separate PME nodes or with a GPU, the two major",
130         "compute tasks, the non-bonded force calculation and the PME calculation",
131         "run on different compute resources. If this load is not balanced,",
132         "some of the resources will be idle part of time. With the Verlet",
133         "cut-off scheme this load is automatically balanced when the PME load",
134         "is too high (but not when it is too low). This is done by scaling",
135         "the Coulomb cut-off and PME grid spacing by the same amount. In the first",
136         "few hundred steps different settings are tried and the fastest is chosen",
137         "for the rest of the simulation. This does not affect the accuracy of",
138         "the results, but it does affect the decomposition of the Coulomb energy",
139         "into particle and mesh contributions. The auto-tuning can be turned off",
140         "with the option [TT]-notunepme[tt].",
141         "[PAR]",
142         "[TT]mdrun[tt] pins (sets affinity of) threads to specific cores,",
143         "when all (logical) cores on a compute node are used by [TT]mdrun[tt],",
144         "even when no multi-threading is used,",
145         "as this usually results in significantly better performance.",
146         "If the queuing systems or the OpenMP library pinned threads, we honor",
147         "this and don't pin again, even though the layout may be sub-optimal.",
148         "If you want to have [TT]mdrun[tt] override an already set thread affinity",
149         "or pin threads when using less cores, use [TT]-pin on[tt].",
150         "With SMT (simultaneous multithreading), e.g. Intel Hyper-Threading,",
151         "there are multiple logical cores per physical core.",
152         "The option [TT]-pinstride[tt] sets the stride in logical cores for",
153         "pinning consecutive threads. Without SMT, 1 is usually the best choice.",
154         "With Intel Hyper-Threading 2 is best when using half or less of the",
155         "logical cores, 1 otherwise. The default value of 0 do exactly that:",
156         "it minimizes the threads per logical core, to optimize performance.",
157         "If you want to run multiple mdrun jobs on the same physical node,"
158         "you should set [TT]-pinstride[tt] to 1 when using all logical cores.",
159         "When running multiple mdrun (or other) simulations on the same physical",
160         "node, some simulations need to start pinning from a non-zero core",
161         "to avoid overloading cores; with [TT]-pinoffset[tt] you can specify",
162         "the offset in logical cores for pinning.",
163         "[PAR]",
164         "When [TT]mdrun[tt] is started using MPI with more than 1 process",
165         "or with thread-MPI with more than 1 thread, MPI parallelization is used.",
166         "By default domain decomposition is used, unless the [TT]-pd[tt]",
167         "option is set, which selects particle decomposition.",
168         "[PAR]",
169         "With domain decomposition, the spatial decomposition can be set",
170         "with option [TT]-dd[tt]. By default [TT]mdrun[tt] selects a good decomposition.",
171         "The user only needs to change this when the system is very inhomogeneous.",
172         "Dynamic load balancing is set with the option [TT]-dlb[tt],",
173         "which can give a significant performance improvement,",
174         "especially for inhomogeneous systems. The only disadvantage of",
175         "dynamic load balancing is that runs are no longer binary reproducible,",
176         "but in most cases this is not important.",
177         "By default the dynamic load balancing is automatically turned on",
178         "when the measured performance loss due to load imbalance is 5% or more.",
179         "At low parallelization these are the only important options",
180         "for domain decomposition.",
181         "At high parallelization the options in the next two sections",
182         "could be important for increasing the performace.",
183         "[PAR]",
184         "When PME is used with domain decomposition, separate nodes can",
185         "be assigned to do only the PME mesh calculation;",
186         "this is computationally more efficient starting at about 12 nodes.",
187         "The number of PME nodes is set with option [TT]-npme[tt],",
188         "this can not be more than half of the nodes.",
189         "By default [TT]mdrun[tt] makes a guess for the number of PME",
190         "nodes when the number of nodes is larger than 11 or performance wise",
191         "not compatible with the PME grid x dimension.",
192         "But the user should optimize npme. Performance statistics on this issue",
193         "are written at the end of the log file.",
194         "For good load balancing at high parallelization, the PME grid x and y",
195         "dimensions should be divisible by the number of PME nodes",
196         "(the simulation will run correctly also when this is not the case).",
197         "[PAR]",
198         "This section lists all options that affect the domain decomposition.",
199         "[PAR]",
200         "Option [TT]-rdd[tt] can be used to set the required maximum distance",
201         "for inter charge-group bonded interactions.",
202         "Communication for two-body bonded interactions below the non-bonded",
203         "cut-off distance always comes for free with the non-bonded communication.",
204         "Atoms beyond the non-bonded cut-off are only communicated when they have",
205         "missing bonded interactions; this means that the extra cost is minor",
206         "and nearly indepedent of the value of [TT]-rdd[tt].",
207         "With dynamic load balancing option [TT]-rdd[tt] also sets",
208         "the lower limit for the domain decomposition cell sizes.",
209         "By default [TT]-rdd[tt] is determined by [TT]mdrun[tt] based on",
210         "the initial coordinates. The chosen value will be a balance",
211         "between interaction range and communication cost.",
212         "[PAR]",
213         "When inter charge-group bonded interactions are beyond",
214         "the bonded cut-off distance, [TT]mdrun[tt] terminates with an error message.",
215         "For pair interactions and tabulated bonds",
216         "that do not generate exclusions, this check can be turned off",
217         "with the option [TT]-noddcheck[tt].",
218         "[PAR]",
219         "When constraints are present, option [TT]-rcon[tt] influences",
220         "the cell size limit as well.",
221         "Atoms connected by NC constraints, where NC is the LINCS order plus 1,",
222         "should not be beyond the smallest cell size. A error message is",
223         "generated when this happens and the user should change the decomposition",
224         "or decrease the LINCS order and increase the number of LINCS iterations.",
225         "By default [TT]mdrun[tt] estimates the minimum cell size required for P-LINCS",
226         "in a conservative fashion. For high parallelization it can be useful",
227         "to set the distance required for P-LINCS with the option [TT]-rcon[tt].",
228         "[PAR]",
229         "The [TT]-dds[tt] option sets the minimum allowed x, y and/or z scaling",
230         "of the cells with dynamic load balancing. [TT]mdrun[tt] will ensure that",
231         "the cells can scale down by at least this factor. This option is used",
232         "for the automated spatial decomposition (when not using [TT]-dd[tt])",
233         "as well as for determining the number of grid pulses, which in turn",
234         "sets the minimum allowed cell size. Under certain circumstances",
235         "the value of [TT]-dds[tt] might need to be adjusted to account for",
236         "high or low spatial inhomogeneity of the system.",
237         "[PAR]",
238         "The option [TT]-gcom[tt] can be used to only do global communication",
239         "every n steps.",
240         "This can improve performance for highly parallel simulations",
241         "where this global communication step becomes the bottleneck.",
242         "For a global thermostat and/or barostat the temperature",
243         "and/or pressure will also only be updated every [TT]-gcom[tt] steps.",
244         "By default it is set to the minimum of nstcalcenergy and nstlist.[PAR]",
245         "With [TT]-rerun[tt] an input trajectory can be given for which ",
246         "forces and energies will be (re)calculated. Neighbor searching will be",
247         "performed for every frame, unless [TT]nstlist[tt] is zero",
248         "(see the [TT].mdp[tt] file).[PAR]",
249         "ED (essential dynamics) sampling and/or additional flooding potentials",
250         "are switched on by using the [TT]-ei[tt] flag followed by an [TT].edi[tt]",
251         "file. The [TT].edi[tt] file can be produced with the [TT]make_edi[tt] tool",
252         "or by using options in the essdyn menu of the WHAT IF program.",
253         "[TT]mdrun[tt] produces a [TT].xvg[tt] output file that",
254         "contains projections of positions, velocities and forces onto selected",
255         "eigenvectors.[PAR]",
256         "When user-defined potential functions have been selected in the",
257         "[TT].mdp[tt] file the [TT]-table[tt] option is used to pass [TT]mdrun[tt]",
258         "a formatted table with potential functions. The file is read from",
259         "either the current directory or from the [TT]GMXLIB[tt] directory.",
260         "A number of pre-formatted tables are presented in the [TT]GMXLIB[tt] dir,",
261         "for 6-8, 6-9, 6-10, 6-11, 6-12 Lennard-Jones potentials with",
262         "normal Coulomb.",
263         "When pair interactions are present, a separate table for pair interaction",
264         "functions is read using the [TT]-tablep[tt] option.[PAR]",
265         "When tabulated bonded functions are present in the topology,",
266         "interaction functions are read using the [TT]-tableb[tt] option.",
267         "For each different tabulated interaction type the table file name is",
268         "modified in a different way: before the file extension an underscore is",
269         "appended, then a 'b' for bonds, an 'a' for angles or a 'd' for dihedrals",
270         "and finally the table number of the interaction type.[PAR]",
271         "The options [TT]-px[tt] and [TT]-pf[tt] are used for writing pull COM",
272         "coordinates and forces when pulling is selected",
273         "in the [TT].mdp[tt] file.[PAR]",
274         "With [TT]-multi[tt] or [TT]-multidir[tt], multiple systems can be ",
275         "simulated in parallel.",
276         "As many input files/directories are required as the number of systems. ",
277         "The [TT]-multidir[tt] option takes a list of directories (one for each ",
278         "system) and runs in each of them, using the input/output file names, ",
279         "such as specified by e.g. the [TT]-s[tt] option, relative to these ",
280         "directories.",
281         "With [TT]-multi[tt], the system number is appended to the run input ",
282         "and each output filename, for instance [TT]topol.tpr[tt] becomes",
283         "[TT]topol0.tpr[tt], [TT]topol1.tpr[tt] etc.",
284         "The number of nodes per system is the total number of nodes",
285         "divided by the number of systems.",
286         "One use of this option is for NMR refinement: when distance",
287         "or orientation restraints are present these can be ensemble averaged",
288         "over all the systems.[PAR]",
289         "With [TT]-replex[tt] replica exchange is attempted every given number",
290         "of steps. The number of replicas is set with the [TT]-multi[tt] or ",
291         "[TT]-multidir[tt] option, described above.",
292         "All run input files should use a different coupling temperature,",
293         "the order of the files is not important. The random seed is set with",
294         "[TT]-reseed[tt]. The velocities are scaled and neighbor searching",
295         "is performed after every exchange.[PAR]",
296         "Finally some experimental algorithms can be tested when the",
297         "appropriate options have been given. Currently under",
298         "investigation are: polarizability and X-ray bombardments.",
299         "[PAR]",
300         "The option [TT]-membed[tt] does what used to be g_membed, i.e. embed",
301         "a protein into a membrane. The data file should contain the options",
302         "that where passed to g_membed before. The [TT]-mn[tt] and [TT]-mp[tt]",
303         "both apply to this as well.",
304         "[PAR]",
305         "The option [TT]-pforce[tt] is useful when you suspect a simulation",
306         "crashes due to too large forces. With this option coordinates and",
307         "forces of atoms with a force larger than a certain value will",
308         "be printed to stderr.",
309         "[PAR]",
310         "Checkpoints containing the complete state of the system are written",
311         "at regular intervals (option [TT]-cpt[tt]) to the file [TT]-cpo[tt],",
312         "unless option [TT]-cpt[tt] is set to -1.",
313         "The previous checkpoint is backed up to [TT]state_prev.cpt[tt] to",
314         "make sure that a recent state of the system is always available,",
315         "even when the simulation is terminated while writing a checkpoint.",
316         "With [TT]-cpnum[tt] all checkpoint files are kept and appended",
317         "with the step number.",
318         "A simulation can be continued by reading the full state from file",
319         "with option [TT]-cpi[tt]. This option is intelligent in the way that",
320         "if no checkpoint file is found, Gromacs just assumes a normal run and",
321         "starts from the first step of the [TT].tpr[tt] file. By default the output",
322         "will be appending to the existing output files. The checkpoint file",
323         "contains checksums of all output files, such that you will never",
324         "loose data when some output files are modified, corrupt or removed.",
325         "There are three scenarios with [TT]-cpi[tt]:[PAR]",
326         "[TT]*[tt] no files with matching names are present: new output files are written[PAR]",
327         "[TT]*[tt] all files are present with names and checksums matching those stored",
328         "in the checkpoint file: files are appended[PAR]",
329         "[TT]*[tt] otherwise no files are modified and a fatal error is generated[PAR]",
330         "With [TT]-noappend[tt] new output files are opened and the simulation",
331         "part number is added to all output file names.",
332         "Note that in all cases the checkpoint file itself is not renamed",
333         "and will be overwritten, unless its name does not match",
334         "the [TT]-cpo[tt] option.",
335         "[PAR]",
336         "With checkpointing the output is appended to previously written",
337         "output files, unless [TT]-noappend[tt] is used or none of the previous",
338         "output files are present (except for the checkpoint file).",
339         "The integrity of the files to be appended is verified using checksums",
340         "which are stored in the checkpoint file. This ensures that output can",
341         "not be mixed up or corrupted due to file appending. When only some",
342         "of the previous output files are present, a fatal error is generated",
343         "and no old output files are modified and no new output files are opened.",
344         "The result with appending will be the same as from a single run.",
345         "The contents will be binary identical, unless you use a different number",
346         "of nodes or dynamic load balancing or the FFT library uses optimizations",
347         "through timing.",
348         "[PAR]",
349         "With option [TT]-maxh[tt] a simulation is terminated and a checkpoint",
350         "file is written at the first neighbor search step where the run time",
351         "exceeds [TT]-maxh[tt]*0.99 hours.",
352         "[PAR]",
353         "When [TT]mdrun[tt] receives a TERM signal, it will set nsteps to the current",
354         "step plus one. When [TT]mdrun[tt] receives an INT signal (e.g. when ctrl+C is",
355         "pressed), it will stop after the next neighbor search step ",
356         "(with nstlist=0 at the next step).",
357         "In both cases all the usual output will be written to file.",
358         "When running with MPI, a signal to one of the [TT]mdrun[tt] processes",
359         "is sufficient, this signal should not be sent to mpirun or",
360         "the [TT]mdrun[tt] process that is the parent of the others.",
361         "[PAR]",
362         "When [TT]mdrun[tt] is started with MPI, it does not run niced by default."
363     };
364     t_commrec    *cr;
365     t_filenm      fnm[] = {
366         { efTPX, NULL,      NULL,       ffREAD },
367         { efTRN, "-o",      NULL,       ffWRITE },
368         { efXTC, "-x",      NULL,       ffOPTWR },
369         { efCPT, "-cpi",    NULL,       ffOPTRD },
370         { efCPT, "-cpo",    NULL,       ffOPTWR },
371         { efSTO, "-c",      "confout",  ffWRITE },
372         { efEDR, "-e",      "ener",     ffWRITE },
373         { efLOG, "-g",      "md",       ffWRITE },
374         { efXVG, "-dhdl",   "dhdl",     ffOPTWR },
375         { efXVG, "-field",  "field",    ffOPTWR },
376         { efXVG, "-table",  "table",    ffOPTRD },
377         { efXVG, "-tabletf", "tabletf",    ffOPTRD },
378         { efXVG, "-tablep", "tablep",   ffOPTRD },
379         { efXVG, "-tableb", "table",    ffOPTRD },
380         { efTRX, "-rerun",  "rerun",    ffOPTRD },
381         { efXVG, "-tpi",    "tpi",      ffOPTWR },
382         { efXVG, "-tpid",   "tpidist",  ffOPTWR },
383         { efEDI, "-ei",     "sam",      ffOPTRD },
384         { efXVG, "-eo",     "edsam",    ffOPTWR },
385         { efGCT, "-j",      "wham",     ffOPTRD },
386         { efGCT, "-jo",     "bam",      ffOPTWR },
387         { efXVG, "-ffout",  "gct",      ffOPTWR },
388         { efXVG, "-devout", "deviatie", ffOPTWR },
389         { efXVG, "-runav",  "runaver",  ffOPTWR },
390         { efXVG, "-px",     "pullx",    ffOPTWR },
391         { efXVG, "-pf",     "pullf",    ffOPTWR },
392         { efXVG, "-ro",     "rotation", ffOPTWR },
393         { efLOG, "-ra",     "rotangles", ffOPTWR },
394         { efLOG, "-rs",     "rotslabs", ffOPTWR },
395         { efLOG, "-rt",     "rottorque", ffOPTWR },
396         { efMTX, "-mtx",    "nm",       ffOPTWR },
397         { efNDX, "-dn",     "dipole",   ffOPTWR },
398         { efRND, "-multidir", NULL,      ffOPTRDMULT},
399         { efDAT, "-membed", "membed",   ffOPTRD },
400         { efTOP, "-mp",     "membed",   ffOPTRD },
401         { efNDX, "-mn",     "membed",   ffOPTRD }
402     };
403 #define NFILE asize(fnm)
404
405     /* Command line options ! */
406     gmx_bool      bPartDec      = FALSE;
407     gmx_bool      bDDBondCheck  = TRUE;
408     gmx_bool      bDDBondComm   = TRUE;
409     gmx_bool      bTunePME      = TRUE;
410     gmx_bool      bTestVerlet   = FALSE;
411     gmx_bool      bVerbose      = FALSE;
412     gmx_bool      bCompact      = TRUE;
413     gmx_bool      bSepPot       = FALSE;
414     gmx_bool      bRerunVSite   = FALSE;
415     gmx_bool      bIonize       = FALSE;
416     gmx_bool      bConfout      = TRUE;
417     gmx_bool      bReproducible = FALSE;
418
419     int           npme          = -1;
420     int           nmultisim     = 0;
421     int           nstglobalcomm = -1;
422     int           repl_ex_nst   = 0;
423     int           repl_ex_seed  = -1;
424     int           repl_ex_nex   = 0;
425     int           nstepout      = 100;
426     int           resetstep     = -1;
427     gmx_large_int_t nsteps      = -2; /* the value -2 means that the mdp option will be used */
428
429     rvec          realddxyz          = {0, 0, 0};
430     const char   *ddno_opt[ddnoNR+1] =
431     { NULL, "interleave", "pp_pme", "cartesian", NULL };
432     const char   *dddlb_opt[] =
433     { NULL, "auto", "no", "yes", NULL };
434     const char   *thread_aff_opt[threadaffNR+1] =
435     { NULL, "auto", "on", "off", NULL };
436     const char   *nbpu_opt[] =
437     { NULL, "auto", "cpu", "gpu", "gpu_cpu", NULL };
438     real          rdd                   = 0.0, rconstr = 0.0, dlb_scale = 0.8, pforce = -1;
439     char         *ddcsx                 = NULL, *ddcsy = NULL, *ddcsz = NULL;
440     real          cpt_period            = 15.0, max_hours = -1;
441     gmx_bool      bAppendFiles          = TRUE;
442     gmx_bool      bKeepAndNumCPT        = FALSE;
443     gmx_bool      bResetCountersHalfWay = FALSE;
444     output_env_t  oenv                  = NULL;
445     const char   *deviceOptions         = "";
446
447     gmx_hw_opt_t  hw_opt = {0, 0, 0, 0, threadaffSEL, 0, 0, NULL};
448
449     t_pargs       pa[] = {
450
451         { "-pd",      FALSE, etBOOL, {&bPartDec},
452           "Use particle decompostion" },
453         { "-dd",      FALSE, etRVEC, {&realddxyz},
454           "Domain decomposition grid, 0 is optimize" },
455         { "-ddorder", FALSE, etENUM, {ddno_opt},
456           "DD node order" },
457         { "-npme",    FALSE, etINT, {&npme},
458           "Number of separate nodes to be used for PME, -1 is guess" },
459         { "-nt",      FALSE, etINT, {&hw_opt.nthreads_tot},
460           "Total number of threads to start (0 is guess)" },
461         { "-ntmpi",   FALSE, etINT, {&hw_opt.nthreads_tmpi},
462           "Number of thread-MPI threads to start (0 is guess)" },
463         { "-ntomp",   FALSE, etINT, {&hw_opt.nthreads_omp},
464           "Number of OpenMP threads per MPI process/thread to start (0 is guess)" },
465         { "-ntomp_pme", FALSE, etINT, {&hw_opt.nthreads_omp_pme},
466           "Number of OpenMP threads per MPI process/thread to start (0 is -ntomp)" },
467         { "-pin",     FALSE, etENUM, {thread_aff_opt},
468           "Fix threads (or processes) to specific cores" },
469         { "-pinoffset", FALSE, etINT, {&hw_opt.core_pinning_offset},
470           "The starting logical core number for pinning to cores; used to avoid pinning threads from different mdrun instances to the same core" },
471         { "-pinstride", FALSE, etINT, {&hw_opt.core_pinning_stride},
472           "Pinning distance in logical cores for threads, use 0 to minimize the number of threads per physical core" },
473         { "-gpu_id",  FALSE, etSTR, {&hw_opt.gpu_id},
474           "List of GPU id's to use" },
475         { "-ddcheck", FALSE, etBOOL, {&bDDBondCheck},
476           "Check for all bonded interactions with DD" },
477         { "-ddbondcomm", FALSE, etBOOL, {&bDDBondComm},
478           "HIDDENUse special bonded atom communication when [TT]-rdd[tt] > cut-off" },
479         { "-rdd",     FALSE, etREAL, {&rdd},
480           "The maximum distance for bonded interactions with DD (nm), 0 is determine from initial coordinates" },
481         { "-rcon",    FALSE, etREAL, {&rconstr},
482           "Maximum distance for P-LINCS (nm), 0 is estimate" },
483         { "-dlb",     FALSE, etENUM, {dddlb_opt},
484           "Dynamic load balancing (with DD)" },
485         { "-dds",     FALSE, etREAL, {&dlb_scale},
486           "Minimum allowed dlb scaling of the DD cell size" },
487         { "-ddcsx",   FALSE, etSTR, {&ddcsx},
488           "HIDDENThe DD cell sizes in x" },
489         { "-ddcsy",   FALSE, etSTR, {&ddcsy},
490           "HIDDENThe DD cell sizes in y" },
491         { "-ddcsz",   FALSE, etSTR, {&ddcsz},
492           "HIDDENThe DD cell sizes in z" },
493         { "-gcom",    FALSE, etINT, {&nstglobalcomm},
494           "Global communication frequency" },
495         { "-nb",      FALSE, etENUM, {&nbpu_opt},
496           "Calculate non-bonded interactions on" },
497         { "-tunepme", FALSE, etBOOL, {&bTunePME},
498           "Optimize PME load between PP/PME nodes or GPU/CPU" },
499         { "-testverlet", FALSE, etBOOL, {&bTestVerlet},
500           "Test the Verlet non-bonded scheme" },
501         { "-v",       FALSE, etBOOL, {&bVerbose},
502           "Be loud and noisy" },
503         { "-compact", FALSE, etBOOL, {&bCompact},
504           "Write a compact log file" },
505         { "-seppot",  FALSE, etBOOL, {&bSepPot},
506           "Write separate V and dVdl terms for each interaction type and node to the log file(s)" },
507         { "-pforce",  FALSE, etREAL, {&pforce},
508           "Print all forces larger than this (kJ/mol nm)" },
509         { "-reprod",  FALSE, etBOOL, {&bReproducible},
510           "Try to avoid optimizations that affect binary reproducibility" },
511         { "-cpt",     FALSE, etREAL, {&cpt_period},
512           "Checkpoint interval (minutes)" },
513         { "-cpnum",   FALSE, etBOOL, {&bKeepAndNumCPT},
514           "Keep and number checkpoint files" },
515         { "-append",  FALSE, etBOOL, {&bAppendFiles},
516           "Append to previous output files when continuing from checkpoint instead of adding the simulation part number to all file names" },
517         { "-nsteps",  FALSE, etGMX_LARGE_INT, {&nsteps},
518           "Run this number of steps, overrides .mdp file option" },
519         { "-maxh",   FALSE, etREAL, {&max_hours},
520           "Terminate after 0.99 times this time (hours)" },
521         { "-multi",   FALSE, etINT, {&nmultisim},
522           "Do multiple simulations in parallel" },
523         { "-replex",  FALSE, etINT, {&repl_ex_nst},
524           "Attempt replica exchange periodically with this period (steps)" },
525         { "-nex",  FALSE, etINT, {&repl_ex_nex},
526           "Number of random exchanges to carry out each exchange interval (N^3 is one suggestion).  -nex zero or not specified gives neighbor replica exchange." },
527         { "-reseed",  FALSE, etINT, {&repl_ex_seed},
528           "Seed for replica exchange, -1 is generate a seed" },
529         { "-rerunvsite", FALSE, etBOOL, {&bRerunVSite},
530           "HIDDENRecalculate virtual site coordinates with [TT]-rerun[tt]" },
531         { "-ionize",  FALSE, etBOOL, {&bIonize},
532           "Do a simulation including the effect of an X-Ray bombardment on your system" },
533         { "-confout", FALSE, etBOOL, {&bConfout},
534           "HIDDENWrite the last configuration with [TT]-c[tt] and force checkpointing at the last step" },
535         { "-stepout", FALSE, etINT, {&nstepout},
536           "HIDDENFrequency of writing the remaining runtime" },
537         { "-resetstep", FALSE, etINT, {&resetstep},
538           "HIDDENReset cycle counters after these many time steps" },
539         { "-resethway", FALSE, etBOOL, {&bResetCountersHalfWay},
540           "HIDDENReset the cycle counters after half the number of steps or halfway [TT]-maxh[tt]" }
541     };
542     unsigned long Flags, PCA_Flags;
543     ivec          ddxyz;
544     int           dd_node_order;
545     gmx_bool      bAddPart;
546     FILE         *fplog, *fpmulti;
547     int           sim_part, sim_part_fn;
548     const char   *part_suffix = ".part";
549     char          suffix[STRLEN];
550     int           rc;
551     char        **multidir = NULL;
552
553
554     cr = init_par(&argc, &argv);
555     gmx::ProgramInfo::init(argc, argv);
556
557     PCA_Flags = (PCA_CAN_SET_DEFFNM | PCA_STANDALONE | (MASTER(cr) ? 0 : PCA_QUIET));
558
559     /* Comment this in to do fexist calls only on master
560      * works not with rerun or tables at the moment
561      * also comment out the version of init_forcerec in md.c
562      * with NULL instead of opt2fn
563      */
564     /*
565        if (!MASTER(cr))
566        {
567        PCA_Flags |= PCA_NOT_READ_NODE;
568        }
569      */
570
571     parse_common_args(&argc, argv, PCA_Flags, NFILE, fnm, asize(pa), pa,
572                       asize(desc), desc, 0, NULL, &oenv);
573
574
575     /* we set these early because they might be used in init_multisystem()
576        Note that there is the potential for npme>nnodes until the number of
577        threads is set later on, if there's thread parallelization. That shouldn't
578        lead to problems. */
579     dd_node_order = nenum(ddno_opt);
580     cr->npmenodes = npme;
581
582     hw_opt.thread_affinity = nenum(thread_aff_opt);
583
584     /* now check the -multi and -multidir option */
585     if (opt2bSet("-multidir", NFILE, fnm))
586     {
587         if (nmultisim > 0)
588         {
589             gmx_fatal(FARGS, "mdrun -multi and -multidir options are mutually exclusive.");
590         }
591         nmultisim = opt2fns(&multidir, "-multidir", NFILE, fnm);
592     }
593
594
595     if (repl_ex_nst != 0 && nmultisim < 2)
596     {
597         gmx_fatal(FARGS, "Need at least two replicas for replica exchange (option -multi)");
598     }
599
600     if (repl_ex_nex < 0)
601     {
602         gmx_fatal(FARGS, "Replica exchange number of exchanges needs to be positive");
603     }
604
605     if (nmultisim > 1)
606     {
607 #ifndef GMX_THREAD_MPI
608         gmx_bool bParFn = (multidir == NULL);
609         init_multisystem(cr, nmultisim, multidir, NFILE, fnm, bParFn);
610 #else
611         gmx_fatal(FARGS, "mdrun -multi is not supported with the thread library.Please compile GROMACS with MPI support");
612 #endif
613     }
614
615     bAddPart = !bAppendFiles;
616
617     /* Check if there is ANY checkpoint file available */
618     sim_part    = 1;
619     sim_part_fn = sim_part;
620     if (opt2bSet("-cpi", NFILE, fnm))
621     {
622         if (bSepPot && bAppendFiles)
623         {
624             gmx_fatal(FARGS, "Output file appending is not supported with -seppot");
625         }
626
627         bAppendFiles =
628             read_checkpoint_simulation_part(opt2fn_master("-cpi", NFILE,
629                                                           fnm, cr),
630                                             &sim_part_fn, NULL, cr,
631                                             bAppendFiles, NFILE, fnm,
632                                             part_suffix, &bAddPart);
633         if (sim_part_fn == 0 && MULTIMASTER(cr))
634         {
635             fprintf(stdout, "No previous checkpoint file present, assuming this is a new run.\n");
636         }
637         else
638         {
639             sim_part = sim_part_fn + 1;
640         }
641
642         if (MULTISIM(cr) && MASTER(cr))
643         {
644             if (MULTIMASTER(cr))
645             {
646                 /* Log file is not yet available, so if there's a
647                  * problem we can only write to stderr. */
648                 fpmulti = stderr;
649             }
650             else
651             {
652                 fpmulti = NULL;
653             }
654             check_multi_int(fpmulti, cr->ms, sim_part, "simulation part", TRUE);
655         }
656     }
657     else
658     {
659         bAppendFiles = FALSE;
660     }
661
662     if (!bAppendFiles)
663     {
664         sim_part_fn = sim_part;
665     }
666
667     if (bAddPart)
668     {
669         /* Rename all output files (except checkpoint files) */
670         /* create new part name first (zero-filled) */
671         sprintf(suffix, "%s%04d", part_suffix, sim_part_fn);
672
673         add_suffix_to_output_names(fnm, NFILE, suffix);
674         if (MULTIMASTER(cr))
675         {
676             fprintf(stdout, "Checkpoint file is from part %d, new output files will be suffixed '%s'.\n", sim_part-1, suffix);
677         }
678     }
679
680     Flags = opt2bSet("-rerun", NFILE, fnm) ? MD_RERUN : 0;
681     Flags = Flags | (bSepPot       ? MD_SEPPOT       : 0);
682     Flags = Flags | (bIonize       ? MD_IONIZE       : 0);
683     Flags = Flags | (bPartDec      ? MD_PARTDEC      : 0);
684     Flags = Flags | (bDDBondCheck  ? MD_DDBONDCHECK  : 0);
685     Flags = Flags | (bDDBondComm   ? MD_DDBONDCOMM   : 0);
686     Flags = Flags | (bTunePME      ? MD_TUNEPME      : 0);
687     Flags = Flags | (bTestVerlet   ? MD_TESTVERLET   : 0);
688     Flags = Flags | (bConfout      ? MD_CONFOUT      : 0);
689     Flags = Flags | (bRerunVSite   ? MD_RERUN_VSITE  : 0);
690     Flags = Flags | (bReproducible ? MD_REPRODUCIBLE : 0);
691     Flags = Flags | (bAppendFiles  ? MD_APPENDFILES  : 0);
692     Flags = Flags | (opt2parg_bSet("-append", asize(pa), pa) ? MD_APPENDFILESSET : 0);
693     Flags = Flags | (bKeepAndNumCPT ? MD_KEEPANDNUMCPT : 0);
694     Flags = Flags | (sim_part > 1    ? MD_STARTFROMCPT : 0);
695     Flags = Flags | (bResetCountersHalfWay ? MD_RESETCOUNTERSHALFWAY : 0);
696
697
698     /* We postpone opening the log file if we are appending, so we can
699        first truncate the old log file and append to the correct position
700        there instead.  */
701     if ((MASTER(cr) || bSepPot) && !bAppendFiles)
702     {
703         gmx_log_open(ftp2fn(efLOG, NFILE, fnm), cr,
704                      !bSepPot, Flags & MD_APPENDFILES, &fplog);
705         please_cite(fplog, "Hess2008b");
706         please_cite(fplog, "Spoel2005a");
707         please_cite(fplog, "Lindahl2001a");
708         please_cite(fplog, "Berendsen95a");
709     }
710     else if (!MASTER(cr) && bSepPot)
711     {
712         gmx_log_open(ftp2fn(efLOG, NFILE, fnm), cr, !bSepPot, Flags, &fplog);
713     }
714     else
715     {
716         fplog = NULL;
717     }
718
719     ddxyz[XX] = (int)(realddxyz[XX] + 0.5);
720     ddxyz[YY] = (int)(realddxyz[YY] + 0.5);
721     ddxyz[ZZ] = (int)(realddxyz[ZZ] + 0.5);
722
723     rc = mdrunner(&hw_opt, fplog, cr, NFILE, fnm, oenv, bVerbose, bCompact,
724                   nstglobalcomm, ddxyz, dd_node_order, rdd, rconstr,
725                   dddlb_opt[0], dlb_scale, ddcsx, ddcsy, ddcsz,
726                   nbpu_opt[0],
727                   nsteps, nstepout, resetstep,
728                   nmultisim, repl_ex_nst, repl_ex_nex, repl_ex_seed,
729                   pforce, cpt_period, max_hours, deviceOptions, Flags);
730
731     gmx_finalize_par();
732
733     if (MULTIMASTER(cr))
734     {
735         gmx_thanx(stderr);
736     }
737
738     /* Log file has to be closed in mdrunner if we are appending to it
739        (fplog not set here) */
740     if (MASTER(cr) && !bAppendFiles)
741     {
742         gmx_log_close(fplog);
743     }
744
745     return rc;
746 }