2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2013,2014, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
37 /* This file is completely threadsafe - keep it that way! */
38 #include "gromacs/commandline/pargs.h"
54 #include "thread_mpi/threads.h"
56 #include "gromacs/commandline/cmdlinehelpcontext.h"
57 #include "gromacs/commandline/cmdlinehelpwriter.h"
58 #include "gromacs/commandline/cmdlineparser.h"
59 #include "gromacs/fileio/timecontrol.h"
60 #include "gromacs/options/basicoptions.h"
61 #include "gromacs/options/filenameoption.h"
62 #include "gromacs/options/filenameoptionmanager.h"
63 #include "gromacs/options/options.h"
64 #include "gromacs/options/timeunitmanager.h"
65 #include "gromacs/utility/arrayref.h"
66 #include "gromacs/utility/basenetwork.h"
67 #include "gromacs/utility/common.h"
68 #include "gromacs/utility/cstringutil.h"
69 #include "gromacs/utility/exceptions.h"
70 #include "gromacs/utility/fatalerror.h"
71 #include "gromacs/utility/gmxassert.h"
72 #include "gromacs/utility/programcontext.h"
73 #include "gromacs/utility/smalloc.h"
74 #include "gromacs/utility/stringutil.h"
76 /* The source code in this file should be thread-safe.
77 Please keep it that way. */
79 int nenum(const char *const enumc[])
84 /* we *can* compare pointers directly here! */
85 while (enumc[i] && enumc[0] != enumc[i])
93 int opt2parg_int(const char *option, int nparg, t_pargs pa[])
97 for (i = 0; (i < nparg); i++)
99 if (strcmp(pa[i].option, option) == 0)
105 gmx_fatal(FARGS, "No integer option %s in pargs", option);
110 gmx_bool opt2parg_bool(const char *option, int nparg, t_pargs pa[])
114 for (i = 0; (i < nparg); i++)
116 if (strcmp(pa[i].option, option) == 0)
122 gmx_fatal(FARGS, "No boolean option %s in pargs", option);
127 real opt2parg_real(const char *option, int nparg, t_pargs pa[])
131 for (i = 0; (i < nparg); i++)
133 if (strcmp(pa[i].option, option) == 0)
139 gmx_fatal(FARGS, "No real option %s in pargs", option);
144 const char *opt2parg_str(const char *option, int nparg, t_pargs pa[])
148 for (i = 0; (i < nparg); i++)
150 if (strcmp(pa[i].option, option) == 0)
156 gmx_fatal(FARGS, "No string option %s in pargs", option);
161 gmx_bool opt2parg_bSet(const char *option, int nparg, t_pargs pa[])
165 for (i = 0; (i < nparg); i++)
167 if (strcmp(pa[i].option, option) == 0)
173 gmx_fatal(FARGS, "No such option %s in pargs", option);
175 return FALSE; /* Too make some compilers happy */
178 const char *opt2parg_enum(const char *option, int nparg, t_pargs pa[])
182 for (i = 0; (i < nparg); i++)
184 if (strcmp(pa[i].option, option) == 0)
190 gmx_fatal(FARGS, "No such option %s in pargs", option);
195 /********************************************************************
196 * parse_common_args()
206 * Returns the index of the default xvg format.
208 * \ingroup module_commandline
210 int getDefaultXvgFormat(gmx::ConstArrayRef<const char *> xvgFormats)
212 const char *const select = getenv("GMX_VIEW_XVG");
215 ConstArrayRef<const char *>::const_iterator i =
216 std::find(xvgFormats.begin(), xvgFormats.end(), std::string(select));
217 if (i != xvgFormats.end())
219 return i - xvgFormats.begin();
226 /* The default is the first option */
231 * Conversion helper between t_pargs/t_filenm and Options.
233 * This class holds the necessary mapping between the old C structures and
234 * the new C++ options to allow copying values back after parsing for cases
235 * where the C++ options do not directly provide the type of value required for
238 * \ingroup module_commandline
244 * Initializes the adapter to convert from a specified command line.
246 * The command line is required, because t_pargs wants to return
247 * strings by reference to the original command line.
248 * OptionsAdapter creates a copy of the `argv` array (but not the
249 * strings) to make this possible, even if the parser removes
250 * options it has recognized.
252 OptionsAdapter(int argc, const char *const argv[])
253 : argv_(argv, argv + argc)
258 * Converts a t_filenm option into an Options option.
260 * \param options Options object to add the new option to.
261 * \param fnm t_filenm option to convert.
263 void filenmToOptions(Options *options, t_filenm *fnm);
265 * Converts a t_pargs option into an Options option.
267 * \param options Options object to add the new option to.
268 * \param pa t_pargs option to convert.
270 void pargsToOptions(Options *options, t_pargs *pa);
273 * Copies values back from options to t_pargs/t_filenm.
275 void copyValues(bool bReadNode);
280 //! Creates a conversion helper for a given `t_filenm` struct.
281 explicit FileNameData(t_filenm *fnm) : fnm(fnm), optionInfo(NULL)
285 //! t_filenm structure to receive the final values.
287 //! Option info object for the created FileNameOption.
288 FileNameOptionInfo *optionInfo;
289 //! Value storage for the created FileNameOption.
290 std::vector<std::string> values;
292 struct ProgramArgData
294 //! Creates a conversion helper for a given `t_pargs` struct.
295 explicit ProgramArgData(t_pargs *pa)
296 : pa(pa), optionInfo(NULL), enumIndex(0), boolValue(false)
300 //! t_pargs structure to receive the final values.
302 //! Option info object for the created option.
303 OptionInfo *optionInfo;
304 //! Value storage for a non-enum StringOption (unused for other types).
305 std::string stringValue;
306 //! Value storage for an enum option (unused for other types).
308 //! Value storage for a BooleanOption (unused for other types).
312 std::vector<const char *> argv_;
313 // These are lists instead of vectors to avoid relocating existing
314 // objects in case the container is reallocated (the Options object
315 // contains pointes to members of the objects, which would get
317 std::list<FileNameData> fileNameOptions_;
318 std::list<ProgramArgData> programArgs_;
320 GMX_DISALLOW_COPY_AND_ASSIGN(OptionsAdapter);
323 void OptionsAdapter::filenmToOptions(Options *options, t_filenm *fnm)
325 if (fnm->opt == NULL)
327 // Existing code may use opt2fn() instead of ftp2fn() for
328 // options that use the default option name, so we need to
329 // keep the old behavior instead of fixing opt2fn().
330 // TODO: Check that this is not the case, remove this, and make
331 // opt2*() work even if fnm->opt is NULL for some options.
332 fnm->opt = ftp2defopt(fnm->ftp);
334 const bool bRead = ((fnm->flag & ffREAD) != 0);
335 const bool bWrite = ((fnm->flag & ffWRITE) != 0);
336 const bool bOptional = ((fnm->flag & ffOPT) != 0);
337 const bool bLibrary = ((fnm->flag & ffLIB) != 0);
338 const bool bMultiple = ((fnm->flag & ffMULT) != 0);
339 const char *const name = &fnm->opt[1];
340 const char * defName = fnm->fn;
343 defName = ftp2defnm(fnm->ftp);
345 fileNameOptions_.push_back(FileNameData(fnm));
346 FileNameData &data = fileNameOptions_.back();
347 data.optionInfo = options->addOption(
348 FileNameOption(name).storeVector(&data.values)
349 .defaultBasename(defName).legacyType(fnm->ftp)
350 .legacyOptionalBehavior()
351 .readWriteFlags(bRead, bWrite).required(!bOptional)
352 .libraryFile(bLibrary).multiValue(bMultiple)
353 .description(ftp2desc(fnm->ftp)));
356 void OptionsAdapter::pargsToOptions(Options *options, t_pargs *pa)
358 const bool bHidden = startsWith(pa->desc, "HIDDEN");
359 const char *const name = &pa->option[1];
360 const char *const desc = (bHidden ? &pa->desc[6] : pa->desc);
361 programArgs_.push_back(ProgramArgData(pa));
362 ProgramArgData &data = programArgs_.back();
366 data.optionInfo = options->addOption(
367 IntegerOption(name).store(pa->u.i)
368 .description(desc).hidden(bHidden));
371 data.optionInfo = options->addOption(
372 Int64Option(name).store(pa->u.is)
373 .description(desc).hidden(bHidden));
376 data.optionInfo = options->addOption(
377 RealOption(name).store(pa->u.r)
378 .description(desc).hidden(bHidden));
381 data.optionInfo = options->addOption(
382 RealOption(name).store(pa->u.r).timeValue()
383 .description(desc).hidden(bHidden));
387 const char *const defValue = (*pa->u.c != NULL ? *pa->u.c : "");
388 data.optionInfo = options->addOption(
389 StringOption(name).store(&data.stringValue)
390 .defaultValue(defValue)
391 .description(desc).hidden(bHidden));
395 data.optionInfo = options->addOption(
396 BooleanOption(name).store(&data.boolValue)
397 .defaultValue(*pa->u.b)
398 .description(desc).hidden(bHidden));
401 data.optionInfo = options->addOption(
402 RealOption(name).store(*pa->u.rv).vector()
403 .description(desc).hidden(bHidden));
407 const int defaultIndex = (pa->u.c[0] != NULL ? nenum(pa->u.c) - 1 : 0);
408 data.optionInfo = options->addOption(
409 StringOption(name).storeEnumIndex(&data.enumIndex)
410 .defaultEnumIndex(defaultIndex)
411 .enumValueFromNullTerminatedArray(pa->u.c + 1)
412 .description(desc).hidden(bHidden));
416 GMX_THROW(NotImplementedError("Argument type not implemented"));
419 void OptionsAdapter::copyValues(bool bReadNode)
421 std::list<FileNameData>::const_iterator file;
422 for (file = fileNameOptions_.begin(); file != fileNameOptions_.end(); ++file)
424 if (!bReadNode && (file->fnm->flag & ffREAD))
428 if (file->optionInfo->isSet())
430 file->fnm->flag |= ffSET;
432 file->fnm->nfiles = file->values.size();
433 snew(file->fnm->fns, file->fnm->nfiles);
434 for (int i = 0; i < file->fnm->nfiles; ++i)
436 // TODO: Check for out-of-memory.
437 file->fnm->fns[i] = strdup(file->values[i].c_str());
440 std::list<ProgramArgData>::const_iterator arg;
441 for (arg = programArgs_.begin(); arg != programArgs_.end(); ++arg)
443 arg->pa->bSet = arg->optionInfo->isSet();
444 switch (arg->pa->type)
450 std::vector<const char *>::const_iterator pos =
451 std::find(argv_.begin(), argv_.end(), arg->stringValue);
452 GMX_RELEASE_ASSERT(pos != argv_.end(),
453 "String argument got a value not in argv");
454 *arg->pa->u.c = *pos;
459 *arg->pa->u.b = arg->boolValue;
462 *arg->pa->u.c = arg->pa->u.c[arg->enumIndex + 1];
465 // For other types, there is nothing type-specific to do.
475 gmx_bool parse_common_args(int *argc, char *argv[], unsigned long Flags,
476 int nfile, t_filenm fnm[], int npargs, t_pargs *pa,
477 int ndesc, const char **desc,
478 int nbugs, const char **bugs,
481 /* This array should match the order of the enum in oenv.h */
482 const char *const xvg_formats[] = { "xmgrace", "xmgr", "none" };
484 // Handle the flags argument, which is a bit field
485 // The FF macro returns whether or not the bit is set
486 #define FF(arg) ((Flags & arg) == arg)
491 double tbegin = 0.0, tend = 0.0, tdelta = 0.0;
494 gmx::TimeUnitManager timeUnitManager;
495 gmx::OptionsAdapter adapter(*argc, argv);
496 gmx::Options options(NULL, NULL);
497 gmx::FileNameOptionManager fileOptManager;
499 fileOptManager.disableInputOptionChecking(
500 FF(PCA_NOT_READ_NODE) || FF(PCA_DISABLE_INPUT_FILE_CHECKING));
501 options.addManager(&fileOptManager);
502 options.setDescription(gmx::ConstArrayRef<const char *>(desc, ndesc));
505 gmx::IntegerOption("nice").store(&nicelevel)
506 .defaultValue(FF(PCA_BE_NICE) ? 19 : 0)
507 .description("Set the nicelevel"));
509 if (FF(PCA_CAN_SET_DEFFNM))
511 fileOptManager.addDefaultFileNameOption(&options, "deffnm");
513 if (FF(PCA_CAN_BEGIN))
516 gmx::DoubleOption("b").store(&tbegin).timeValue()
517 .description("First frame (%t) to read from trajectory"));
522 gmx::DoubleOption("e").store(&tend).timeValue()
523 .description("Last frame (%t) to read from trajectory"));
528 gmx::DoubleOption("dt").store(&tdelta).timeValue()
529 .description("Only use frame when t MOD dt = first time (%t)"));
531 if (FF(PCA_TIME_UNIT))
533 timeUnitManager.setTimeUnitFromEnvironment();
534 timeUnitManager.addTimeUnitOption(&options, "tu");
536 if (FF(PCA_CAN_VIEW))
539 gmx::BooleanOption("w").store(&bView)
540 .description("View output [TT].xvg[tt], [TT].xpm[tt], "
541 "[TT].eps[tt] and [TT].pdb[tt] files"));
545 for (int i = 0; i < nfile; i++)
547 bXvgr = bXvgr || (fnm[i].ftp == efXVG);
549 xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
553 gmx::StringOption("xvg").enumValue(xvg_formats)
554 .storeEnumIndex(&xvgFormat)
555 .description("xvg plot formatting"));
558 /* Now append the program specific arguments */
559 for (int i = 0; i < nfile; i++)
561 adapter.filenmToOptions(&options, &fnm[i]);
563 for (int i = 0; i < npargs; i++)
565 adapter.pargsToOptions(&options, &pa[i]);
568 const gmx::CommandLineHelpContext *context =
569 gmx::GlobalCommandLineHelpContext::get();
572 // TODO: The first check should not be necessary, but with
573 // thread-MPI it is...
574 GMX_RELEASE_ASSERT(!gmx_mpi_initialized() || gmx_node_rank() == 0,
575 "Help output should be handled higher up and "
576 "only get called only on the master rank");
577 gmx::CommandLineHelpWriter(options)
578 .setShowDescriptions(true)
579 .setTimeUnitString(timeUnitManager.timeUnitAsString())
580 .setKnownIssues(gmx::ConstArrayRef<const char *>(bugs, nbugs))
581 .writeHelp(*context);
585 /* Now parse all the command-line options */
586 gmx::CommandLineParser(&options).skipUnknown(FF(PCA_NOEXIT_ON_ARGS))
590 /* set program name, command line, and default values for output options */
591 output_env_init(oenv, gmx::getProgramContext(),
592 (time_unit_t)(timeUnitManager.timeUnit() + 1), bView,
593 (xvg_format_t)(xvgFormat + 1), 0);
595 /* Set the nice level */
598 /* The some system, e.g. the catamount kernel on cray xt3 do not have nice(2). */
601 static gmx_bool nice_set = FALSE; /* only set it once */
602 static tMPI_Thread_mutex_t init_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
603 tMPI_Thread_mutex_lock(&init_mutex);
606 if (nice(nicelevel) == -1)
608 /* Do nothing, but use the return value to avoid warnings. */
612 tMPI_Thread_mutex_unlock(&init_mutex);
617 timeUnitManager.scaleTimeOptions(&options);
619 /* Extract Time info from arguments */
620 // TODO: Use OptionInfo objects instead of string constants
621 if (FF(PCA_CAN_BEGIN) && options.isSet("b"))
623 setTimeValue(TBEGIN, tbegin);
625 if (FF(PCA_CAN_END) && options.isSet("e"))
627 setTimeValue(TEND, tend);
629 if (FF(PCA_CAN_DT) && options.isSet("dt"))
631 setTimeValue(TDELTA, tdelta);
634 adapter.copyValues(!FF(PCA_NOT_READ_NODE));
638 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;