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! */
40 #include "gromacs/commandline/pargs.h"
50 #include "gromacs/commandline/cmdlinehelpcontext.h"
51 #include "gromacs/commandline/cmdlinehelpwriter.h"
52 #include "gromacs/commandline/cmdlineparser.h"
53 #include "gromacs/fileio/timecontrol.h"
54 #include "gromacs/options/basicoptions.h"
55 #include "gromacs/options/filenameoption.h"
56 #include "gromacs/options/filenameoptionmanager.h"
57 #include "gromacs/options/options.h"
58 #include "gromacs/options/timeunitmanager.h"
59 #include "gromacs/utility/arrayref.h"
60 #include "gromacs/utility/basenetwork.h"
61 #include "gromacs/utility/common.h"
62 #include "gromacs/utility/cstringutil.h"
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/fatalerror.h"
65 #include "gromacs/utility/gmxassert.h"
66 #include "gromacs/utility/programcontext.h"
67 #include "gromacs/utility/smalloc.h"
68 #include "gromacs/utility/stringutil.h"
70 /* The source code in this file should be thread-safe.
71 Please keep it that way. */
73 int nenum(const char *const enumc[])
78 /* we *can* compare pointers directly here! */
79 while (enumc[i] && enumc[0] != enumc[i])
87 int opt2parg_int(const char *option, int nparg, t_pargs pa[])
91 for (i = 0; (i < nparg); i++)
93 if (strcmp(pa[i].option, option) == 0)
99 gmx_fatal(FARGS, "No integer option %s in pargs", option);
104 gmx_bool opt2parg_bool(const char *option, int nparg, t_pargs pa[])
108 for (i = 0; (i < nparg); i++)
110 if (strcmp(pa[i].option, option) == 0)
116 gmx_fatal(FARGS, "No boolean option %s in pargs", option);
121 real opt2parg_real(const char *option, int nparg, t_pargs pa[])
125 for (i = 0; (i < nparg); i++)
127 if (strcmp(pa[i].option, option) == 0)
133 gmx_fatal(FARGS, "No real option %s in pargs", option);
138 const char *opt2parg_str(const char *option, int nparg, t_pargs pa[])
142 for (i = 0; (i < nparg); i++)
144 if (strcmp(pa[i].option, option) == 0)
150 gmx_fatal(FARGS, "No string option %s in pargs", option);
155 gmx_bool opt2parg_bSet(const char *option, int nparg, t_pargs pa[])
159 for (i = 0; (i < nparg); i++)
161 if (strcmp(pa[i].option, option) == 0)
167 gmx_fatal(FARGS, "No such option %s in pargs", option);
169 return FALSE; /* Too make some compilers happy */
172 const char *opt2parg_enum(const char *option, int nparg, t_pargs pa[])
176 for (i = 0; (i < nparg); i++)
178 if (strcmp(pa[i].option, option) == 0)
184 gmx_fatal(FARGS, "No such option %s in pargs", option);
189 /********************************************************************
190 * parse_common_args()
200 * Returns the index of the default xvg format.
202 * \ingroup module_commandline
204 int getDefaultXvgFormat(gmx::ConstArrayRef<const char *> xvgFormats)
206 const char *const select = getenv("GMX_VIEW_XVG");
209 ConstArrayRef<const char *>::const_iterator i =
210 std::find(xvgFormats.begin(), xvgFormats.end(), std::string(select));
211 if (i != xvgFormats.end())
213 return i - xvgFormats.begin();
220 /* The default is the first option */
225 * Conversion helper between t_pargs/t_filenm and Options.
227 * This class holds the necessary mapping between the old C structures and
228 * the new C++ options to allow copying values back after parsing for cases
229 * where the C++ options do not directly provide the type of value required for
232 * \ingroup module_commandline
238 * Initializes the adapter to convert from a specified command line.
240 * The command line is required, because t_pargs wants to return
241 * strings by reference to the original command line.
242 * OptionsAdapter creates a copy of the `argv` array (but not the
243 * strings) to make this possible, even if the parser removes
244 * options it has recognized.
246 OptionsAdapter(int argc, const char *const argv[])
247 : argv_(argv, argv + argc)
252 * Converts a t_filenm option into an Options option.
254 * \param options Options object to add the new option to.
255 * \param fnm t_filenm option to convert.
257 void filenmToOptions(Options *options, t_filenm *fnm);
259 * Converts a t_pargs option into an Options option.
261 * \param options Options object to add the new option to.
262 * \param pa t_pargs option to convert.
264 void pargsToOptions(Options *options, t_pargs *pa);
267 * Copies values back from options to t_pargs/t_filenm.
269 void copyValues(bool bReadNode);
274 //! Creates a conversion helper for a given `t_filenm` struct.
275 explicit FileNameData(t_filenm *fnm) : fnm(fnm), optionInfo(NULL)
279 //! t_filenm structure to receive the final values.
281 //! Option info object for the created FileNameOption.
282 FileNameOptionInfo *optionInfo;
283 //! Value storage for the created FileNameOption.
284 std::vector<std::string> values;
286 struct ProgramArgData
288 //! Creates a conversion helper for a given `t_pargs` struct.
289 explicit ProgramArgData(t_pargs *pa)
290 : pa(pa), optionInfo(NULL), enumIndex(0), boolValue(false)
294 //! t_pargs structure to receive the final values.
296 //! Option info object for the created option.
297 OptionInfo *optionInfo;
298 //! Value storage for a non-enum StringOption (unused for other types).
299 std::string stringValue;
300 //! Value storage for an enum option (unused for other types).
302 //! Value storage for a BooleanOption (unused for other types).
306 std::vector<const char *> argv_;
307 // These are lists instead of vectors to avoid relocating existing
308 // objects in case the container is reallocated (the Options object
309 // contains pointes to members of the objects, which would get
311 std::list<FileNameData> fileNameOptions_;
312 std::list<ProgramArgData> programArgs_;
314 GMX_DISALLOW_COPY_AND_ASSIGN(OptionsAdapter);
317 void OptionsAdapter::filenmToOptions(Options *options, t_filenm *fnm)
319 if (fnm->opt == NULL)
321 // Existing code may use opt2fn() instead of ftp2fn() for
322 // options that use the default option name, so we need to
323 // keep the old behavior instead of fixing opt2fn().
324 // TODO: Check that this is not the case, remove this, and make
325 // opt2*() work even if fnm->opt is NULL for some options.
326 fnm->opt = ftp2defopt(fnm->ftp);
328 const bool bRead = ((fnm->flag & ffREAD) != 0);
329 const bool bWrite = ((fnm->flag & ffWRITE) != 0);
330 const bool bOptional = ((fnm->flag & ffOPT) != 0);
331 const bool bLibrary = ((fnm->flag & ffLIB) != 0);
332 const bool bMultiple = ((fnm->flag & ffMULT) != 0);
333 const char *const name = &fnm->opt[1];
334 const char * defName = fnm->fn;
337 defName = ftp2defnm(fnm->ftp);
339 fileNameOptions_.push_back(FileNameData(fnm));
340 FileNameData &data = fileNameOptions_.back();
341 data.optionInfo = options->addOption(
342 FileNameOption(name).storeVector(&data.values)
343 .defaultBasename(defName).legacyType(fnm->ftp)
344 .legacyOptionalBehavior()
345 .readWriteFlags(bRead, bWrite).required(!bOptional)
346 .libraryFile(bLibrary).multiValue(bMultiple)
347 .description(ftp2desc(fnm->ftp)));
350 void OptionsAdapter::pargsToOptions(Options *options, t_pargs *pa)
352 const bool bHidden = startsWith(pa->desc, "HIDDEN");
353 const char *const name = &pa->option[1];
354 const char *const desc = (bHidden ? &pa->desc[6] : pa->desc);
355 programArgs_.push_back(ProgramArgData(pa));
356 ProgramArgData &data = programArgs_.back();
360 data.optionInfo = options->addOption(
361 IntegerOption(name).store(pa->u.i)
362 .description(desc).hidden(bHidden));
365 data.optionInfo = options->addOption(
366 Int64Option(name).store(pa->u.is)
367 .description(desc).hidden(bHidden));
370 data.optionInfo = options->addOption(
371 RealOption(name).store(pa->u.r)
372 .description(desc).hidden(bHidden));
375 data.optionInfo = options->addOption(
376 RealOption(name).store(pa->u.r).timeValue()
377 .description(desc).hidden(bHidden));
381 const char *const defValue = (*pa->u.c != NULL ? *pa->u.c : "");
382 data.optionInfo = options->addOption(
383 StringOption(name).store(&data.stringValue)
384 .defaultValue(defValue)
385 .description(desc).hidden(bHidden));
389 data.optionInfo = options->addOption(
390 BooleanOption(name).store(&data.boolValue)
391 .defaultValue(*pa->u.b)
392 .description(desc).hidden(bHidden));
395 data.optionInfo = options->addOption(
396 RealOption(name).store(*pa->u.rv).vector()
397 .description(desc).hidden(bHidden));
401 const int defaultIndex = (pa->u.c[0] != NULL ? nenum(pa->u.c) - 1 : 0);
402 data.optionInfo = options->addOption(
403 StringOption(name).storeEnumIndex(&data.enumIndex)
404 .defaultEnumIndex(defaultIndex)
405 .enumValueFromNullTerminatedArray(pa->u.c + 1)
406 .description(desc).hidden(bHidden));
410 GMX_THROW(NotImplementedError("Argument type not implemented"));
413 void OptionsAdapter::copyValues(bool bReadNode)
415 std::list<FileNameData>::const_iterator file;
416 for (file = fileNameOptions_.begin(); file != fileNameOptions_.end(); ++file)
418 if (!bReadNode && (file->fnm->flag & ffREAD))
422 if (file->optionInfo->isSet())
424 file->fnm->flag |= ffSET;
426 file->fnm->nfiles = file->values.size();
427 snew(file->fnm->fns, file->fnm->nfiles);
428 for (int i = 0; i < file->fnm->nfiles; ++i)
430 file->fnm->fns[i] = gmx_strdup(file->values[i].c_str());
433 std::list<ProgramArgData>::const_iterator arg;
434 for (arg = programArgs_.begin(); arg != programArgs_.end(); ++arg)
436 arg->pa->bSet = arg->optionInfo->isSet();
437 switch (arg->pa->type)
443 std::vector<const char *>::const_iterator pos =
444 std::find(argv_.begin(), argv_.end(), arg->stringValue);
445 GMX_RELEASE_ASSERT(pos != argv_.end(),
446 "String argument got a value not in argv");
447 *arg->pa->u.c = *pos;
452 *arg->pa->u.b = arg->boolValue;
455 *arg->pa->u.c = arg->pa->u.c[arg->enumIndex + 1];
458 // For other types, there is nothing type-specific to do.
468 gmx_bool parse_common_args(int *argc, char *argv[], unsigned long Flags,
469 int nfile, t_filenm fnm[], int npargs, t_pargs *pa,
470 int ndesc, const char **desc,
471 int nbugs, const char **bugs,
474 /* This array should match the order of the enum in oenv.h */
475 const char *const xvg_formats[] = { "xmgrace", "xmgr", "none" };
477 // Handle the flags argument, which is a bit field
478 // The FF macro returns whether or not the bit is set
479 #define FF(arg) ((Flags & arg) == arg)
483 double tbegin = 0.0, tend = 0.0, tdelta = 0.0;
486 gmx::TimeUnitManager timeUnitManager;
487 gmx::OptionsAdapter adapter(*argc, argv);
488 gmx::Options options(NULL, NULL);
489 gmx::FileNameOptionManager fileOptManager;
491 fileOptManager.disableInputOptionChecking(
492 FF(PCA_NOT_READ_NODE) || FF(PCA_DISABLE_INPUT_FILE_CHECKING));
493 options.addManager(&fileOptManager);
494 options.setDescription(gmx::constArrayRefFromArray<const char *>(desc, ndesc));
496 if (FF(PCA_CAN_SET_DEFFNM))
498 fileOptManager.addDefaultFileNameOption(&options, "deffnm");
500 if (FF(PCA_CAN_BEGIN))
503 gmx::DoubleOption("b").store(&tbegin).timeValue()
504 .description("First frame (%t) to read from trajectory"));
509 gmx::DoubleOption("e").store(&tend).timeValue()
510 .description("Last frame (%t) to read from trajectory"));
515 gmx::DoubleOption("dt").store(&tdelta).timeValue()
516 .description("Only use frame when t MOD dt = first time (%t)"));
518 if (FF(PCA_TIME_UNIT))
520 timeUnitManager.setTimeUnitFromEnvironment();
521 timeUnitManager.addTimeUnitOption(&options, "tu");
523 if (FF(PCA_CAN_VIEW))
526 gmx::BooleanOption("w").store(&bView)
527 .description("View output [TT].xvg[tt], [TT].xpm[tt], "
528 "[TT].eps[tt] and [TT].pdb[tt] files"));
532 for (int i = 0; i < nfile; i++)
534 bXvgr = bXvgr || (fnm[i].ftp == efXVG);
536 xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
540 gmx::StringOption("xvg").enumValue(xvg_formats)
541 .storeEnumIndex(&xvgFormat)
542 .description("xvg plot formatting"));
545 /* Now append the program specific arguments */
546 for (int i = 0; i < nfile; i++)
548 adapter.filenmToOptions(&options, &fnm[i]);
550 for (int i = 0; i < npargs; i++)
552 adapter.pargsToOptions(&options, &pa[i]);
555 const gmx::CommandLineHelpContext *context =
556 gmx::GlobalCommandLineHelpContext::get();
559 GMX_RELEASE_ASSERT(gmx_node_rank() == 0,
560 "Help output should be handled higher up and "
561 "only get called only on the master rank");
562 gmx::CommandLineHelpWriter(options)
563 .setShowDescriptions(true)
564 .setTimeUnitString(timeUnitManager.timeUnitAsString())
565 .setKnownIssues(gmx::constArrayRefFromArray(bugs, nbugs))
566 .writeHelp(*context);
570 /* Now parse all the command-line options */
571 gmx::CommandLineParser(&options).skipUnknown(FF(PCA_NOEXIT_ON_ARGS))
575 /* set program name, command line, and default values for output options */
576 output_env_init(oenv, gmx::getProgramContext(),
577 (time_unit_t)(timeUnitManager.timeUnit() + 1), bView,
578 (xvg_format_t)(xvgFormat + 1), 0);
580 timeUnitManager.scaleTimeOptions(&options);
582 /* Extract Time info from arguments */
583 // TODO: Use OptionInfo objects instead of string constants
584 if (FF(PCA_CAN_BEGIN) && options.isSet("b"))
586 setTimeValue(TBEGIN, tbegin);
588 if (FF(PCA_CAN_END) && options.isSet("e"))
590 setTimeValue(TEND, tend);
592 if (FF(PCA_CAN_DT) && options.isSet("dt"))
594 setTimeValue(TDELTA, tdelta);
597 adapter.copyValues(!FF(PCA_NOT_READ_NODE));
601 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;