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