Merge branch 'release-4-5-patches'
[alexxy/gromacs.git] / src / kernel / 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_THREADS
53 #include "thread_mpi.h"
54 #endif
55
56 /* afm stuf */
57 #include "pull.h"
58
59 int main(int argc,char *argv[])
60 {
61   const char *desc[] = {
62  #ifdef GMX_OPENMM
63     "This is an experimental release of GROMACS for accelerated",
64         "Molecular Dynamics simulations on GPU processors. Support is provided",
65         "by the OpenMM library (https://simtk.org/home/openmm).[PAR]",
66         "*Warning*[BR]",
67         "This release is targeted at developers and advanced users and",
68         "care should be taken before production use. The following should be",
69         "noted before using the program:[PAR]",
70         " * The current release runs only on modern nVidia GPU hardware with CUDA support.",
71         "Make sure that the necessary CUDA drivers and libraries for your operating system",
72         "are already installed. The CUDA SDK also should be installed in order to compile",
73         "the program from source (http://www.nvidia.com/object/cuda_home.html).[PAR]",
74         " * Multiple GPU cards are not supported.[PAR]",
75         " * Only a small subset of the GROMACS features and options are supported on the GPUs.",
76         "See below for a detailed list.[PAR]",
77         " * Consumer level GPU cards are known to often have problems with faulty memory.",
78         "It is recommended that a full memory check of the cards is done at least once",
79         "(for example, using the memtest=full option).",
80         "A partial memory check (for example, memtest=15) before and",
81         "after the simulation run would help spot",
82         "problems resulting from processor overheating.[PAR]",
83         " * The maximum size of the simulated systems depends on the available",
84         "GPU memory,for example, a GTX280 with 1GB memory has been tested with systems",
85         "of up to about 100,000 atoms.[PAR]",
86         " * In order to take a full advantage of the GPU platform features, many algorithms",
87         "have been implemented in a very different way than they are on the CPUs.",
88         "Therefore numercal correspondence between properties of the state of",
89         "simulated systems should not be expected. Moreover, the values will likely vary",
90         "when simulations are done on different GPU hardware.[PAR]",
91         " * Frequent retrieval of system state information such as",
92         "trajectory coordinates and energies can greatly influence the performance",
93         "of the program due to slow CPU<->GPU memory transfer speed.[PAR]",
94         " * MD algorithms are complex, and although the Gromacs code is highly tuned for them,",
95         "they often do not translate very well onto the streaming architetures.",
96         "Realistic expectations about the achievable speed-up from test with GTX280:",
97         "For small protein systems in implicit solvent using all-vs-all kernels the acceleration",
98         "can be as high as 20 times, but in most other setups involving cutoffs and PME the",
99         "acceleration is usually only ~4 times relative to a 3GHz CPU.[PAR]",
100         "Supported features:[PAR]",
101         " * Integrators: md/md-vv/md-vv-avek, sd/sd1 and bd.\n",
102         " * Long-range interactions (option coulombtype): Reaction-Field, Ewald, PME, and cut-off (for Implicit Solvent only)\n",
103         " * Temperature control: Supported only with the md/md-vv/md-vv-avek, sd/sd1 and bd integrators.\n",
104         " * Pressure control: Supported.\n",
105         " * Implicit solvent: Supported.\n",
106         "A detailed description can be found on the GROMACS website:\n",
107         "http://www.gromacs.org/gpu[PAR]",
108 /* From the original mdrun documentaion */
109     "The mdrun program reads the run input file ([TT]-s[tt])",
110     "and distributes the topology over nodes if needed.",
111     "mdrun produces at least four output files.",
112     "A single log file ([TT]-g[tt]) is written, unless the option",
113     "[TT]-seppot[tt] is used, in which case each node writes a log file.",
114     "The trajectory file ([TT]-o[tt]), contains coordinates, velocities and",
115     "optionally forces.",
116     "The structure file ([TT]-c[tt]) contains the coordinates and",
117     "velocities of the last step.",
118     "The energy file ([TT]-e[tt]) contains energies, the temperature,",
119     "pressure, etc, a lot of these things are also printed in the log file.",
120     "Optionally coordinates can be written to a compressed trajectory file",
121     "([TT]-x[tt]).[PAR]",
122 /* openmm specific information */
123         "Usage with OpenMM:[BR]",
124         "$ mdrun -device \"OpenMM:platform=Cuda,memtest=15,deviceid=0,force-device=no\"[PAR]",
125         "Options:[PAR]",
126         "      [TT]platform[tt] = Cuda\t\t:\tThe only available value. OpenCL support will be available in future.\n",
127         "      [TT]memtest[tt] = 15\t\t:\tRun a partial, random GPU memory test for the given amount of seconds. A full test",
128         "(recommended!) can be run with \"memtest=full\". Memory testing can be disabled with \"memtest=off\".\n",
129         "      [TT]deviceid[tt] = 0\t\t:\tSpecify the target device when multiple cards are present.",
130         "Only one card can be used at any given time though.\n",
131         "      [TT]force-device[tt] = no\t\t:\tIf set to \"yes\" mdrun  will be forced to execute on",
132         "hardware that is not officially supported. GPU acceleration can also be achieved on older",
133         "but Cuda capable cards, although the simulation might be too slow, and the memory limits too strict.",
134 #else
135     "The mdrun program is the main computational chemistry engine",
136     "within GROMACS. Obviously, it performs Molecular Dynamics simulations,",
137     "but it can also perform Stochastic Dynamics, Energy Minimization,",
138     "test particle insertion or (re)calculation of energies.",
139     "Normal mode analysis is another option. In this case mdrun",
140     "builds a Hessian matrix from single conformation.",
141     "For usual Normal Modes-like calculations, make sure that",
142     "the structure provided is properly energy-minimized.",
143     "The generated matrix can be diagonalized by g_nmeig.[PAR]",
144     "The mdrun program reads the run input file ([TT]-s[tt])",
145     "and distributes the topology over nodes if needed.",
146     "mdrun produces at least four output files.",
147     "A single log file ([TT]-g[tt]) is written, unless the option",
148     "[TT]-seppot[tt] is used, in which case each node writes a log file.",
149     "The trajectory file ([TT]-o[tt]), contains coordinates, velocities and",
150     "optionally forces.",
151     "The structure file ([TT]-c[tt]) contains the coordinates and",
152     "velocities of the last step.",
153     "The energy file ([TT]-e[tt]) contains energies, the temperature,",
154     "pressure, etc, a lot of these things are also printed in the log file.",
155     "Optionally coordinates can be written to a compressed trajectory file",
156     "([TT]-x[tt]).[PAR]",
157     "The option [TT]-dhdl[tt] is only used when free energy calculation is",
158     "turned on.[PAR]",
159     "When mdrun is started using MPI with more than 1 node, parallelization",
160     "is used. By default domain decomposition is used, unless the [TT]-pd[tt]",
161     "option is set, which selects particle decomposition.[PAR]",
162     "With domain decomposition, the spatial decomposition can be set",
163     "with option [TT]-dd[tt]. By default mdrun selects a good decomposition.",
164     "The user only needs to change this when the system is very inhomogeneous.",
165     "Dynamic load balancing is set with the option [TT]-dlb[tt],",
166     "which can give a significant performance improvement,",
167     "especially for inhomogeneous systems. The only disadvantage of",
168     "dynamic load balancing is that runs are no longer binary reproducible,",
169     "but in most cases this is not important.",
170     "By default the dynamic load balancing is automatically turned on",
171     "when the measured performance loss due to load imbalance is 5% or more.",
172     "At low parallelization these are the only important options",
173     "for domain decomposition.",
174     "At high parallelization the options in the next two sections",
175     "could be important for increasing the performace.",
176     "[PAR]",
177     "When PME is used with domain decomposition, separate nodes can",
178     "be assigned to do only the PME mesh calculation;",
179     "this is computationally more efficient starting at about 12 nodes.",
180     "The number of PME nodes is set with option [TT]-npme[tt],",
181     "this can not be more than half of the nodes.",
182     "By default mdrun makes a guess for the number of PME",
183     "nodes when the number of nodes is larger than 11 or performance wise",
184     "not compatible with the PME grid x dimension.",
185     "But the user should optimize npme. Performance statistics on this issue",
186     "are written at the end of the log file.",
187     "For good load balancing at high parallelization, the PME grid x and y",
188     "dimensions should be divisible by the number of PME nodes",
189     "(the simulation will run correctly also when this is not the case).",
190     "[PAR]",
191     "This section lists all options that affect the domain decomposition.",
192     "[BR]",
193     "Option [TT]-rdd[tt] can be used to set the required maximum distance",
194     "for inter charge-group bonded interactions.",
195     "Communication for two-body bonded interactions below the non-bonded",
196     "cut-off distance always comes for free with the non-bonded communication.",
197     "Atoms beyond the non-bonded cut-off are only communicated when they have",
198     "missing bonded interactions; this means that the extra cost is minor",
199     "and nearly indepedent of the value of [TT]-rdd[tt].",
200     "With dynamic load balancing option [TT]-rdd[tt] also sets",
201     "the lower limit for the domain decomposition cell sizes.",
202     "By default [TT]-rdd[tt] is determined by mdrun based on",
203     "the initial coordinates. The chosen value will be a balance",
204     "between interaction range and communication cost.",
205     "[BR]",
206     "When inter charge-group bonded interactions are beyond",
207     "the bonded cut-off distance, mdrun terminates with an error message.",
208     "For pair interactions and tabulated bonds",
209     "that do not generate exclusions, this check can be turned off",
210     "with the option [TT]-noddcheck[tt].",
211     "[BR]",
212     "When constraints are present, option [TT]-rcon[tt] influences",
213     "the cell size limit as well.",
214     "Atoms connected by NC constraints, where NC is the LINCS order plus 1,",
215     "should not be beyond the smallest cell size. A error message is",
216     "generated when this happens and the user should change the decomposition",
217     "or decrease the LINCS order and increase the number of LINCS iterations.",
218     "By default mdrun estimates the minimum cell size required for P-LINCS",
219     "in a conservative fashion. For high parallelization it can be useful",
220     "to set the distance required for P-LINCS with the option [TT]-rcon[tt].",
221     "[BR]",
222     "The [TT]-dds[tt] option sets the minimum allowed x, y and/or z scaling",
223     "of the cells with dynamic load balancing. mdrun will ensure that",
224     "the cells can scale down by at least this factor. This option is used",
225     "for the automated spatial decomposition (when not using [TT]-dd[tt])",
226     "as well as for determining the number of grid pulses, which in turn",
227     "sets the minimum allowed cell size. Under certain circumstances",
228     "the value of [TT]-dds[tt] might need to be adjusted to account for",
229     "high or low spatial inhomogeneity of the system.",
230     "[PAR]",
231     "The option [TT]-gcom[tt] can be used to only do global communication",
232     "every n steps.",
233     "This can improve performance for highly parallel simulations",
234     "where this global communication step becomes the bottleneck.",
235     "For a global thermostat and/or barostat the temperature",
236     "and/or pressure will also only be updated every -gcom steps.",
237     "By default it is set to the minimum of nstcalcenergy and nstlist.[PAR]",
238     "With [TT]-rerun[tt] an input trajectory can be given for which ",
239     "forces and energies will be (re)calculated. Neighbor searching will be",
240     "performed for every frame, unless [TT]nstlist[tt] is zero",
241     "(see the [TT].mdp[tt] file).[PAR]",
242     "ED (essential dynamics) sampling is switched on by using the [TT]-ei[tt]",
243     "flag followed by an [TT].edi[tt] file.",
244     "The [TT].edi[tt] file can be produced using options in the essdyn",
245     "menu of the WHAT IF program. mdrun produces a [TT].edo[tt] file that",
246     "contains projections of positions, velocities and forces onto selected",
247     "eigenvectors.[PAR]",
248     "When user-defined potential functions have been selected in the",
249     "[TT].mdp[tt] file the [TT]-table[tt] option is used to pass mdrun",
250     "a formatted table with potential functions. The file is read from",
251     "either the current directory or from the GMXLIB directory.",
252     "A number of pre-formatted tables are presented in the GMXLIB dir,",
253     "for 6-8, 6-9, 6-10, 6-11, 6-12 Lennard Jones potentials with",
254     "normal Coulomb.",
255     "When pair interactions are present a separate table for pair interaction",
256     "functions is read using the [TT]-tablep[tt] option.[PAR]",
257     "When tabulated bonded functions are present in the topology,",
258     "interaction functions are read using the [TT]-tableb[tt] option.",
259     "For each different tabulated interaction type the table file name is",
260     "modified in a different way: before the file extension an underscore is",
261     "appended, then a b for bonds, an a for angles or a d for dihedrals",
262     "and finally the table number of the interaction type.[PAR]",
263     "The options [TT]-px[tt] and [TT]-pf[tt] are used for writing pull COM",
264     "coordinates and forces when pulling is selected",
265     "in the [TT].mdp[tt] file.[PAR]",
266     "With [TT]-multi[tt] multiple systems are simulated in parallel.",
267     "As many input files are required as the number of systems.",
268     "The system number is appended to the run input and each output filename,",
269     "for instance topol.tpr becomes topol0.tpr, topol1.tpr etc.",
270     "The number of nodes per system is the total number of nodes",
271     "divided by the number of systems.",
272     "One use of this option is for NMR refinement: when distance",
273     "or orientation restraints are present these can be ensemble averaged",
274     "over all the systems.[PAR]",
275     "With [TT]-replex[tt] replica exchange is attempted every given number",
276     "of steps. The number of replicas is set with the [TT]-multi[tt] option,",
277     "see above.",
278     "All run input files should use a different coupling temperature,",
279     "the order of the files is not important. The random seed is set with",
280     "[TT]-reseed[tt]. The velocities are scaled and neighbor searching",
281     "is performed after every exchange.[PAR]",
282     "Finally some experimental algorithms can be tested when the",
283     "appropriate options have been given. Currently under",
284     "investigation are: polarizability, and X-Ray bombardments.",
285     "[PAR]",
286     "The option [TT]-membed[dd] does what used to be g_membed, i.e. embed",
287     "a protein into a membrane. The data file should contain the options",
288     "that where passed to g_membed before. The [TT]-mn[tt] and [TT]-mp[tt]",
289     "both apply to this as well.",
290     "[PAR]",
291     "The option [TT]-pforce[tt] is useful when you suspect a simulation",
292     "crashes due to too large forces. With this option coordinates and",
293     "forces of atoms with a force larger than a certain value will",
294     "be printed to stderr.",
295     "[PAR]",
296     "Checkpoints containing the complete state of the system are written",
297     "at regular intervals (option [TT]-cpt[tt]) to the file [TT]-cpo[tt],",
298     "unless option [TT]-cpt[tt] is set to -1.",
299     "The previous checkpoint is backed up to [TT]state_prev.cpt[tt] to",
300     "make sure that a recent state of the system is always available,",
301     "even when the simulation is terminated while writing a checkpoint.",
302     "With [TT]-cpnum[tt] all checkpoint files are kept and appended",
303     "with the step number.",
304     "A simulation can be continued by reading the full state from file",
305     "with option [TT]-cpi[tt]. This option is intelligent in the way that",
306     "if no checkpoint file is found, Gromacs just assumes a normal run and",
307     "starts from the first step of the tpr file. By default the output",
308     "will be appending to the existing output files. The checkpoint file",
309     "contains checksums of all output files, such that you will never",
310     "loose data when some output files are modified, corrupt or removed.",
311     "There are three scenarios with [TT]-cpi[tt]:[BR]",
312     "* no files with matching names are present: new output files are written[BR]",
313     "* all files are present with names and checksums matching those stored",
314     "in the checkpoint file: files are appended[BR]",
315     "* otherwise no files are modified and a fatal error is generated[BR]",
316     "With [TT]-noappend[tt] new output files are opened and the simulation",
317     "part number is added to all output file names.",
318     "Note that in all cases the checkpoint file itself is not renamed",
319     "and will be overwritten, unless its name does not match",
320     "the [TT]-cpo[tt] option.",
321     "[PAR]",
322     "With checkpointing the output is appended to previously written",
323     "output files, unless [TT]-noappend[tt] is used or none of the previous",
324     "output files are present (except for the checkpoint file).",
325     "The integrity of the files to be appended is verified using checksums",
326     "which are stored in the checkpoint file. This ensures that output can",
327     "not be mixed up or corrupted due to file appending. When only some",
328     "of the previous output files are present, a fatal error is generated",
329     "and no old output files are modified and no new output files are opened.",
330     "The result with appending will be the same as from a single run.",
331     "The contents will be binary identical, unless you use a different number",
332     "of nodes or dynamic load balancing or the FFT library uses optimizations",
333     "through timing.",
334     "[PAR]",
335     "With option [TT]-maxh[tt] a simulation is terminated and a checkpoint",
336     "file is written at the first neighbor search step where the run time",
337     "exceeds [TT]-maxh[tt]*0.99 hours.",
338     "[PAR]",
339     "When mdrun receives a TERM signal, it will set nsteps to the current",
340     "step plus one. When mdrun receives an INT signal (e.g. when ctrl+C is",
341     "pressed), it will stop after the next neighbor search step ",
342     "(with nstlist=0 at the next step).",
343     "In both cases all the usual output will be written to file.",
344     "When running with MPI, a signal to one of the mdrun processes",
345     "is sufficient, this signal should not be sent to mpirun or",
346     "the mdrun process that is the parent of the others.",
347     "[PAR]",
348     "When mdrun is started with MPI, it does not run niced by default."
349 #endif
350   };
351   t_commrec    *cr;
352   t_filenm fnm[] = {
353     { efTPX, NULL,      NULL,       ffREAD },
354     { efTRN, "-o",      NULL,       ffWRITE },
355     { efXTC, "-x",      NULL,       ffOPTWR },
356     { efCPT, "-cpi",    NULL,       ffOPTRD },
357     { efCPT, "-cpo",    NULL,       ffOPTWR },
358     { efSTO, "-c",      "confout",  ffWRITE },
359     { efEDR, "-e",      "ener",     ffWRITE },
360     { efLOG, "-g",      "md",       ffWRITE },
361     { efXVG, "-dhdl",   "dhdl",     ffOPTWR },
362     { efXVG, "-field",  "field",    ffOPTWR },
363     { efXVG, "-table",  "table",    ffOPTRD },
364     { efXVG, "-tablep", "tablep",   ffOPTRD },
365     { efXVG, "-tableb", "table",    ffOPTRD },
366     { efTRX, "-rerun",  "rerun",    ffOPTRD },
367     { efXVG, "-tpi",    "tpi",      ffOPTWR },
368     { efXVG, "-tpid",   "tpidist",  ffOPTWR },
369     { efEDI, "-ei",     "sam",      ffOPTRD },
370     { efEDO, "-eo",     "sam",      ffOPTWR },
371     { efGCT, "-j",      "wham",     ffOPTRD },
372     { efGCT, "-jo",     "bam",      ffOPTWR },
373     { efXVG, "-ffout",  "gct",      ffOPTWR },
374     { efXVG, "-devout", "deviatie", ffOPTWR },
375     { efXVG, "-runav",  "runaver",  ffOPTWR },
376     { efXVG, "-px",     "pullx",    ffOPTWR },
377     { efXVG, "-pf",     "pullf",    ffOPTWR },
378     { efMTX, "-mtx",    "nm",       ffOPTWR },
379     { efNDX, "-dn",     "dipole",   ffOPTWR },
380     { efDAT, "-membed", "membed",   ffOPTRD },
381     { efTOP, "-mp",     "membed",   ffOPTRD },
382     { efNDX, "-mn",     "membed",   ffOPTRD }
383   };
384 #define NFILE asize(fnm)
385
386   /* Command line options ! */
387   gmx_bool bCart        = FALSE;
388   gmx_bool bPPPME       = FALSE;
389   gmx_bool bPartDec     = FALSE;
390   gmx_bool bDDBondCheck = TRUE;
391   gmx_bool bDDBondComm  = TRUE;
392   gmx_bool bVerbose     = FALSE;
393   gmx_bool bCompact     = TRUE;
394   gmx_bool bSepPot      = FALSE;
395   gmx_bool bRerunVSite  = FALSE;
396   gmx_bool bIonize      = FALSE;
397   gmx_bool bConfout     = TRUE;
398   gmx_bool bReproducible = FALSE;
399     
400   int  npme=-1;
401   int  nmultisim=0;
402   int  nstglobalcomm=-1;
403   int  repl_ex_nst=0;
404   int  repl_ex_seed=-1;
405   int  nstepout=100;
406   int  nthreads=0; /* set to determine # of threads automatically */
407   int  resetstep=-1;
408   
409   rvec realddxyz={0,0,0};
410   const char *ddno_opt[ddnoNR+1] =
411     { NULL, "interleave", "pp_pme", "cartesian", NULL };
412     const char *dddlb_opt[] =
413     { NULL, "auto", "no", "yes", NULL };
414   real rdd=0.0,rconstr=0.0,dlb_scale=0.8,pforce=-1;
415   char *ddcsx=NULL,*ddcsy=NULL,*ddcsz=NULL;
416   real cpt_period=15.0,max_hours=-1;
417   gmx_bool bAppendFiles=TRUE;
418   gmx_bool bKeepAndNumCPT=FALSE;
419   gmx_bool bResetCountersHalfWay=FALSE;
420   output_env_t oenv=NULL;
421   const char *deviceOptions = "";
422
423   t_pargs pa[] = {
424
425     { "-pd",      FALSE, etBOOL,{&bPartDec},
426       "Use particle decompostion" },
427     { "-dd",      FALSE, etRVEC,{&realddxyz},
428       "Domain decomposition grid, 0 is optimize" },
429 #ifdef GMX_THREADS
430     { "-nt",      FALSE, etINT, {&nthreads},
431       "Number of threads to start (0 is guess)" },
432 #endif
433     { "-npme",    FALSE, etINT, {&npme},
434       "Number of separate nodes to be used for PME, -1 is guess" },
435     { "-ddorder", FALSE, etENUM, {ddno_opt},
436       "DD node order" },
437     { "-ddcheck", FALSE, etBOOL, {&bDDBondCheck},
438       "Check for all bonded interactions with DD" },
439     { "-ddbondcomm", FALSE, etBOOL, {&bDDBondComm},
440       "HIDDENUse special bonded atom communication when -rdd > cut-off" },
441     { "-rdd",     FALSE, etREAL, {&rdd},
442       "The maximum distance for bonded interactions with DD (nm), 0 is determine from initial coordinates" },
443     { "-rcon",    FALSE, etREAL, {&rconstr},
444       "Maximum distance for P-LINCS (nm), 0 is estimate" },
445     { "-dlb",     FALSE, etENUM, {dddlb_opt},
446       "Dynamic load balancing (with DD)" },
447     { "-dds",     FALSE, etREAL, {&dlb_scale},
448       "Minimum allowed dlb scaling of the DD cell size" },
449     { "-ddcsx",   FALSE, etSTR, {&ddcsx},
450       "HIDDENThe DD cell sizes in x" },
451     { "-ddcsy",   FALSE, etSTR, {&ddcsy},
452       "HIDDENThe DD cell sizes in y" },
453     { "-ddcsz",   FALSE, etSTR, {&ddcsz},
454       "HIDDENThe DD cell sizes in z" },
455     { "-gcom",    FALSE, etINT,{&nstglobalcomm},
456       "Global communication frequency" },
457     { "-v",       FALSE, etBOOL,{&bVerbose},  
458       "Be loud and noisy" },
459     { "-compact", FALSE, etBOOL,{&bCompact},  
460       "Write a compact log file" },
461     { "-seppot",  FALSE, etBOOL, {&bSepPot},
462       "Write separate V and dVdl terms for each interaction type and node to the log file(s)" },
463     { "-pforce",  FALSE, etREAL, {&pforce},
464       "Print all forces larger than this (kJ/mol nm)" },
465     { "-reprod",  FALSE, etBOOL,{&bReproducible},  
466       "Try to avoid optimizations that affect binary reproducibility" },
467     { "-cpt",     FALSE, etREAL, {&cpt_period},
468       "Checkpoint interval (minutes)" },
469     { "-cpnum",   FALSE, etBOOL, {&bKeepAndNumCPT},
470       "Keep and number checkpoint files" },
471     { "-append",  FALSE, etBOOL, {&bAppendFiles},
472       "Append to previous output files when continuing from checkpoint instead of adding the simulation part number to all file names" },
473     { "-maxh",   FALSE, etREAL, {&max_hours},
474       "Terminate after 0.99 times this time (hours)" },
475     { "-multi",   FALSE, etINT,{&nmultisim}, 
476       "Do multiple simulations in parallel" },
477     { "-replex",  FALSE, etINT, {&repl_ex_nst}, 
478       "Attempt replica exchange every # steps" },
479     { "-reseed",  FALSE, etINT, {&repl_ex_seed}, 
480       "Seed for replica exchange, -1 is generate a seed" },
481     { "-rerunvsite", FALSE, etBOOL, {&bRerunVSite},
482       "HIDDENRecalculate virtual site coordinates with -rerun" },
483     { "-ionize",  FALSE, etBOOL,{&bIonize},
484       "Do a simulation including the effect of an X-Ray bombardment on your system" },
485     { "-confout", FALSE, etBOOL, {&bConfout},
486       "HIDDENWrite the last configuration with -c and force checkpointing at the last step" },
487     { "-stepout", FALSE, etINT, {&nstepout},
488       "HIDDENFrequency of writing the remaining runtime" },
489     { "-resetstep", FALSE, etINT, {&resetstep},
490       "HIDDENReset cycle counters after these many time steps" },
491     { "-resethway", FALSE, etBOOL, {&bResetCountersHalfWay},
492       "HIDDENReset the cycle counters after half the number of steps or halfway -maxh" }
493 #ifdef GMX_OPENMM
494     ,
495     { "-device",  FALSE, etSTR, {&deviceOptions},
496       "Device option string" }
497 #endif
498   };
499   gmx_edsam_t  ed;
500   unsigned long Flags, PCA_Flags;
501   ivec     ddxyz;
502   int      dd_node_order;
503   gmx_bool     bAddPart;
504   FILE     *fplog,*fptest;
505   int      sim_part,sim_part_fn;
506   const char *part_suffix=".part";
507   char     suffix[STRLEN];
508   int      rc;
509
510
511   cr = init_par(&argc,&argv);
512
513   if (MASTER(cr))
514     CopyRight(stderr, argv[0]);
515
516   PCA_Flags = (PCA_KEEP_ARGS | PCA_NOEXIT_ON_ARGS | PCA_CAN_SET_DEFFNM
517                | (MASTER(cr) ? 0 : PCA_QUIET));
518   
519
520   /* Comment this in to do fexist calls only on master
521    * works not with rerun or tables at the moment
522    * also comment out the version of init_forcerec in md.c 
523    * with NULL instead of opt2fn
524    */
525   /*
526      if (!MASTER(cr))
527      {
528      PCA_Flags |= PCA_NOT_READ_NODE;
529      }
530      */
531
532   parse_common_args(&argc,argv,PCA_Flags, NFILE,fnm,asize(pa),pa,
533                     asize(desc),desc,0,NULL, &oenv);
534
535   /* we set these early because they might be used in init_multisystem() 
536      Note that there is the potential for npme>nnodes until the number of
537      threads is set later on, if there's thread parallelization. That shouldn't
538      lead to problems. */ 
539   dd_node_order = nenum(ddno_opt);
540   cr->npmenodes = npme;
541
542 #ifndef GMX_THREADS
543   nthreads=1;
544 #endif
545
546
547   if (repl_ex_nst != 0 && nmultisim < 2)
548       gmx_fatal(FARGS,"Need at least two replicas for replica exchange (option -multi)");
549
550   if (nmultisim > 1) {
551 #ifndef GMX_THREADS
552     init_multisystem(cr,nmultisim,NFILE,fnm,TRUE);
553 #else
554     gmx_fatal(FARGS,"mdrun -multi is not supported with the thread library.Please compile GROMACS with MPI support");
555 #endif
556   }
557
558   bAddPart = !bAppendFiles;
559
560   /* Check if there is ANY checkpoint file available */ 
561   sim_part    = 1;
562   sim_part_fn = sim_part;
563   if (opt2bSet("-cpi",NFILE,fnm))
564   {
565       bAppendFiles =
566                 read_checkpoint_simulation_part(opt2fn_master("-cpi", NFILE,
567                                                               fnm,cr),
568                                                 &sim_part_fn,NULL,cr,
569                                                 bAppendFiles,NFILE,fnm,
570                                                 part_suffix,&bAddPart);
571       if (sim_part_fn==0 && MASTER(cr))
572       {
573           fprintf(stdout,"No previous checkpoint file present, assuming this is a new run.\n");
574       }
575       else
576       {
577           sim_part = sim_part_fn + 1;
578       }
579   } 
580   else
581   {
582       bAppendFiles = FALSE;
583   }
584
585   if (!bAppendFiles)
586   {
587       sim_part_fn = sim_part;
588   }
589
590   if (bAddPart)
591   {
592       /* Rename all output files (except checkpoint files) */
593       /* create new part name first (zero-filled) */
594       sprintf(suffix,"%s%04d",part_suffix,sim_part_fn);
595
596       add_suffix_to_output_names(fnm,NFILE,suffix);
597       if (MASTER(cr))
598       {
599           fprintf(stdout,"Checkpoint file is from part %d, new output files will be suffixed '%s'.\n",sim_part-1,suffix);
600       }
601   }
602
603   Flags = opt2bSet("-rerun",NFILE,fnm) ? MD_RERUN : 0;
604   Flags = Flags | (bSepPot       ? MD_SEPPOT       : 0);
605   Flags = Flags | (bIonize       ? MD_IONIZE       : 0);
606   Flags = Flags | (bPartDec      ? MD_PARTDEC      : 0);
607   Flags = Flags | (bDDBondCheck  ? MD_DDBONDCHECK  : 0);
608   Flags = Flags | (bDDBondComm   ? MD_DDBONDCOMM   : 0);
609   Flags = Flags | (bConfout      ? MD_CONFOUT      : 0);
610   Flags = Flags | (bRerunVSite   ? MD_RERUN_VSITE  : 0);
611   Flags = Flags | (bReproducible ? MD_REPRODUCIBLE : 0);
612   Flags = Flags | (bAppendFiles  ? MD_APPENDFILES  : 0); 
613   Flags = Flags | (bKeepAndNumCPT ? MD_KEEPANDNUMCPT : 0); 
614   Flags = Flags | (sim_part>1    ? MD_STARTFROMCPT : 0); 
615   Flags = Flags | (bResetCountersHalfWay ? MD_RESETCOUNTERSHALFWAY : 0);
616
617
618   /* We postpone opening the log file if we are appending, so we can 
619      first truncate the old log file and append to the correct position 
620      there instead.  */
621   if ((MASTER(cr) || bSepPot) && !bAppendFiles) 
622   {
623       gmx_log_open(ftp2fn(efLOG,NFILE,fnm),cr,!bSepPot,Flags,&fplog);
624       CopyRight(fplog,argv[0]);
625       please_cite(fplog,"Hess2008b");
626       please_cite(fplog,"Spoel2005a");
627       please_cite(fplog,"Lindahl2001a");
628       please_cite(fplog,"Berendsen95a");
629   }
630   else if (!MASTER(cr) && bSepPot)
631   {
632       gmx_log_open(ftp2fn(efLOG,NFILE,fnm),cr,!bSepPot,Flags,&fplog);
633   }
634   else
635   {
636       fplog = NULL;
637   }
638
639   ddxyz[XX] = (int)(realddxyz[XX] + 0.5);
640   ddxyz[YY] = (int)(realddxyz[YY] + 0.5);
641   ddxyz[ZZ] = (int)(realddxyz[ZZ] + 0.5);
642
643   rc = mdrunner(nthreads, fplog,cr,NFILE,fnm,oenv,bVerbose,bCompact,
644                 nstglobalcomm, ddxyz,dd_node_order,rdd,rconstr,
645                 dddlb_opt[0],dlb_scale,ddcsx,ddcsy,ddcsz,
646                 nstepout,resetstep,nmultisim,repl_ex_nst,repl_ex_seed,
647                 pforce, cpt_period,max_hours,deviceOptions,Flags);
648
649   if (gmx_parallel_env_initialized())
650       gmx_finalize();
651
652   if (MULTIMASTER(cr)) {
653       thanx(stderr);
654   }
655
656   /* Log file has to be closed in mdrunner if we are appending to it 
657      (fplog not set here) */
658   if (MASTER(cr) && !bAppendFiles) 
659   {
660       gmx_log_close(fplog);
661   }
662
663   return rc;
664 }
665