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