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