1b4f6a8c523a994490fca7a4e8179a6369419bf8
[alexxy/gromacs.git] / src / gromacs / commandline / pargs.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 #include "gmxpre.h"
39
40 #include "pargs.h"
41
42 #include <cstdlib>
43 #include <cstring>
44
45 #include <algorithm>
46 #include <list>
47
48 #include "gromacs/commandline/cmdlinehelpcontext.h"
49 #include "gromacs/commandline/cmdlinehelpwriter.h"
50 #include "gromacs/commandline/cmdlineparser.h"
51 #include "gromacs/fileio/oenv.h"
52 #include "gromacs/fileio/timecontrol.h"
53 #include "gromacs/options/basicoptions.h"
54 #include "gromacs/options/behaviorcollection.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/classhelpers.h"
62 #include "gromacs/utility/enumerationhelpers.h"
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/fatalerror.h"
65 #include "gromacs/utility/gmxassert.h"
66 #include "gromacs/utility/path.h"
67 #include "gromacs/utility/programcontext.h"
68 #include "gromacs/utility/stringutil.h"
69
70 /* The source code in this file should be thread-safe.
71       Please keep it that way. */
72
73 int nenum(const char* const enumc[])
74 {
75     int i;
76
77     i = 1;
78     /* we *can* compare pointers directly here! */
79     while (enumc[i] && enumc[0] != enumc[i])
80     {
81         i++;
82     }
83
84     return i;
85 }
86
87 int opt2parg_int(const char* option, int nparg, t_pargs pa[])
88 {
89     int i;
90
91     for (i = 0; (i < nparg); i++)
92     {
93         if (strcmp(pa[i].option, option) == 0)
94         {
95             return *pa[i].u.i;
96         }
97     }
98
99     gmx_fatal(FARGS, "No integer option %s in pargs", option);
100 }
101
102 gmx_bool opt2parg_bool(const char* option, int nparg, t_pargs pa[])
103 {
104     int i;
105
106     for (i = 0; (i < nparg); i++)
107     {
108         if (strcmp(pa[i].option, option) == 0)
109         {
110             return *pa[i].u.b;
111         }
112     }
113
114     gmx_fatal(FARGS, "No boolean option %s in pargs", option);
115
116     return FALSE;
117 }
118
119 real opt2parg_real(const char* option, int nparg, t_pargs pa[])
120 {
121     int i;
122
123     for (i = 0; (i < nparg); i++)
124     {
125         if (strcmp(pa[i].option, option) == 0)
126         {
127             return *pa[i].u.r;
128         }
129     }
130
131     gmx_fatal(FARGS, "No real option %s in pargs", option);
132 }
133
134 const char* opt2parg_str(const char* option, int nparg, t_pargs pa[])
135 {
136     int i;
137
138     for (i = 0; (i < nparg); i++)
139     {
140         if (strcmp(pa[i].option, option) == 0)
141         {
142             return *(pa[i].u.c);
143         }
144     }
145
146     gmx_fatal(FARGS, "No string option %s in pargs", option);
147 }
148
149 gmx_bool opt2parg_bSet(const char* option, int nparg, const t_pargs* pa)
150 {
151     int i;
152
153     for (i = 0; (i < nparg); i++)
154     {
155         if (strcmp(pa[i].option, option) == 0)
156         {
157             return pa[i].bSet;
158         }
159     }
160
161     gmx_fatal(FARGS, "No such option %s in pargs", option);
162
163     return FALSE; /* Too make some compilers happy */
164 }
165
166 const char* opt2parg_enum(const char* option, int nparg, t_pargs pa[])
167 {
168     int i;
169
170     for (i = 0; (i < nparg); i++)
171     {
172         if (strcmp(pa[i].option, option) == 0)
173         {
174             return pa[i].u.c[0];
175         }
176     }
177
178     gmx_fatal(FARGS, "No such option %s in pargs", option);
179 }
180
181 /********************************************************************
182  * parse_common_args()
183  */
184
185 namespace gmx
186 {
187
188 namespace
189 {
190
191 //! Names for XvgFormat
192 const gmx::EnumerationArray<XvgFormat, const char*> c_xvgFormatNames = { { "xmgrace", "xmgr",
193                                                                            "none" } };
194
195 /*! \brief Returns the default xvg format, as modified by GMX_VIEW_XVG
196  * if that environment variable is set.
197  *
198  * \ingroup module_commandline
199  */
200 XvgFormat getDefaultXvgFormat()
201 {
202     const char* const select = getenv("GMX_VIEW_XVG");
203     if (select != nullptr)
204     {
205         for (XvgFormat c : keysOf(c_xvgFormatNames))
206         {
207             if (std::strcmp(select, c_xvgFormatNames[c]) == 0)
208             {
209                 return c;
210             }
211         }
212         return XvgFormat::None;
213     }
214     return XvgFormat::Xmgrace;
215 }
216
217 /*! \brief
218  * Conversion helper between t_pargs/t_filenm and Options.
219  *
220  * This class holds the necessary mapping between the old C structures and
221  * the new C++ options to allow copying values back after parsing for cases
222  * where the C++ options do not directly provide the type of value required for
223  * the C structures.
224  *
225  * \ingroup module_commandline
226  */
227 class OptionsAdapter
228 {
229 public:
230     /*! \brief
231      * Initializes the adapter to convert from a specified command line.
232      *
233      * The command line is required, because t_pargs wants to return
234      * strings by reference to the original command line.
235      * OptionsAdapter creates a copy of the `argv` array (but not the
236      * strings) to make this possible, even if the parser removes
237      * options it has recognized.
238      */
239     OptionsAdapter(int argc, const char* const argv[]) : argv_(argv, argv + argc) {}
240
241     /*! \brief
242      * Converts a t_filenm option into an Options option.
243      *
244      * \param options Options object to add the new option to.
245      * \param fnm     t_filenm option to convert.
246      */
247     void filenmToOptions(Options* options, t_filenm* fnm);
248     /*! \brief
249      * Converts a t_pargs option into an Options option.
250      *
251      * \param     options Options object to add the new option to.
252      * \param     pa      t_pargs option to convert.
253      */
254     void pargsToOptions(Options* options, t_pargs* pa);
255
256     /*! \brief
257      * Copies values back from options to t_pargs/t_filenm.
258      */
259     void copyValues();
260
261 private:
262     struct FileNameData
263     {
264         //! Creates a conversion helper for a given `t_filenm` struct.
265         explicit FileNameData(t_filenm* fnm) : fnm(fnm), optionInfo(nullptr) {}
266
267         //! t_filenm structure to receive the final values.
268         t_filenm* fnm;
269         //! Option info object for the created FileNameOption.
270         FileNameOptionInfo* optionInfo;
271         //! Value storage for the created FileNameOption.
272         std::vector<std::string> values;
273     };
274     struct ProgramArgData
275     {
276         //! Creates a conversion helper for a given `t_pargs` struct.
277         explicit ProgramArgData(t_pargs* pa) :
278             pa(pa),
279             optionInfo(nullptr),
280             enumIndex(0),
281             boolValue(false)
282         {
283         }
284
285         //! t_pargs structure to receive the final values.
286         t_pargs* pa;
287         //! Option info object for the created option.
288         OptionInfo* optionInfo;
289         //! Value storage for a non-enum StringOption (unused for other types).
290         std::string stringValue;
291         //! Value storage for an enum option (unused for other types).
292         int enumIndex;
293         //! Value storage for a BooleanOption (unused for other types).
294         bool boolValue;
295     };
296
297     std::vector<const char*> argv_;
298     // These are lists instead of vectors to avoid relocating existing
299     // objects in case the container is reallocated (the Options object
300     // contains pointes to members of the objects, which would get
301     // invalidated).
302     std::list<FileNameData>   fileNameOptions_;
303     std::list<ProgramArgData> programArgs_;
304
305     GMX_DISALLOW_COPY_AND_ASSIGN(OptionsAdapter);
306 };
307
308 void OptionsAdapter::filenmToOptions(Options* options, t_filenm* fnm)
309 {
310     const bool        bRead     = ((fnm->flag & ffREAD) != 0);
311     const bool        bWrite    = ((fnm->flag & ffWRITE) != 0);
312     const bool        bOptional = ((fnm->flag & ffOPT) != 0);
313     const bool        bLibrary  = ((fnm->flag & ffLIB) != 0);
314     const bool        bMultiple = ((fnm->flag & ffMULT) != 0);
315     const bool        bMissing  = ((fnm->flag & ffALLOW_MISSING) != 0);
316     const char* const name      = (fnm->opt ? &fnm->opt[1] : &ftp2defopt(fnm->ftp)[1]);
317     const char*       defName   = fnm->fn;
318     int               defType   = -1;
319     if (defName == nullptr)
320     {
321         defName = ftp2defnm(fnm->ftp);
322     }
323     else if (Path::hasExtension(defName))
324     {
325         defType = fn2ftp(defName);
326         GMX_RELEASE_ASSERT(defType != efNR, "File name option specifies an invalid extension");
327     }
328     fileNameOptions_.emplace_back(fnm);
329     FileNameData& data = fileNameOptions_.back();
330     data.optionInfo    = options->addOption(FileNameOption(name)
331                                                  .storeVector(&data.values)
332                                                  .defaultBasename(defName)
333                                                  .defaultType(defType)
334                                                  .legacyType(fnm->ftp)
335                                                  .legacyOptionalBehavior()
336                                                  .readWriteFlags(bRead, bWrite)
337                                                  .required(!bOptional)
338                                                  .libraryFile(bLibrary)
339                                                  .multiValue(bMultiple)
340                                                  .allowMissing(bMissing)
341                                                  .description(ftp2desc(fnm->ftp)));
342 }
343
344 void OptionsAdapter::pargsToOptions(Options* options, t_pargs* pa)
345 {
346     const bool        bHidden = startsWith(pa->desc, "HIDDEN");
347     const char* const name    = &pa->option[1];
348     const char* const desc    = (bHidden ? &pa->desc[6] : pa->desc);
349     programArgs_.emplace_back(pa);
350     ProgramArgData& data = programArgs_.back();
351     switch (pa->type)
352     {
353         case etINT:
354             data.optionInfo = options->addOption(
355                     IntegerOption(name).store(pa->u.i).description(desc).hidden(bHidden));
356             return;
357         case etINT64:
358             data.optionInfo = options->addOption(
359                     Int64Option(name).store(pa->u.is).description(desc).hidden(bHidden));
360             return;
361         case etREAL:
362             data.optionInfo =
363                     options->addOption(RealOption(name).store(pa->u.r).description(desc).hidden(bHidden));
364             return;
365         case etTIME:
366             data.optionInfo = options->addOption(
367                     RealOption(name).store(pa->u.r).timeValue().description(desc).hidden(bHidden));
368             return;
369         case etSTR:
370         {
371             const char* const defValue = (*pa->u.c != nullptr ? *pa->u.c : "");
372             data.optionInfo            = options->addOption(StringOption(name)
373                                                          .store(&data.stringValue)
374                                                          .defaultValue(defValue)
375                                                          .description(desc)
376                                                          .hidden(bHidden));
377             return;
378         }
379         case etBOOL:
380             data.optionInfo = options->addOption(BooleanOption(name)
381                                                          .store(&data.boolValue)
382                                                          .defaultValue(*pa->u.b)
383                                                          .description(desc)
384                                                          .hidden(bHidden));
385             return;
386         case etRVEC:
387             data.optionInfo = options->addOption(
388                     RealOption(name).store(*pa->u.rv).vector().description(desc).hidden(bHidden));
389             return;
390         case etENUM:
391         {
392             // TODO This is the only use of LegacyEnumOption. It
393             // exists to support dozens of analysis tools use that
394             // don't make sense to fix without either test coverage or
395             // automated refactoring. No new uses of LegacyEnumOption
396             // should be made.
397             const int defaultIndex = (pa->u.c[0] != nullptr ? nenum(pa->u.c) - 1 : 0);
398             data.optionInfo        = options->addOption(LegacyEnumOption<int>(name)
399                                                          .store(&data.enumIndex)
400                                                          .defaultValue(defaultIndex)
401                                                          .enumValueFromNullTerminatedArray(pa->u.c + 1)
402                                                          .description(desc)
403                                                          .hidden(bHidden));
404             return;
405         }
406     }
407     GMX_THROW(NotImplementedError("Argument type not implemented"));
408 }
409
410 void OptionsAdapter::copyValues()
411 {
412     std::list<FileNameData>::const_iterator file;
413     for (file = fileNameOptions_.begin(); file != fileNameOptions_.end(); ++file)
414     {
415         if (file->optionInfo->isSet())
416         {
417             file->fnm->flag |= ffSET;
418         }
419         file->fnm->filenames = file->values;
420     }
421     std::list<ProgramArgData>::const_iterator arg;
422     for (arg = programArgs_.begin(); arg != programArgs_.end(); ++arg)
423     {
424         arg->pa->bSet = arg->optionInfo->isSet();
425         switch (arg->pa->type)
426         {
427             case etSTR:
428             {
429                 if (arg->pa->bSet)
430                 {
431                     std::vector<const char*>::const_iterator pos =
432                             std::find(argv_.begin(), argv_.end(), arg->stringValue);
433                     GMX_RELEASE_ASSERT(pos != argv_.end(),
434                                        "String argument got a value not in argv");
435                     *arg->pa->u.c = *pos;
436                 }
437                 break;
438             }
439             case etBOOL: *arg->pa->u.b = arg->boolValue; break;
440             case etENUM: *arg->pa->u.c = arg->pa->u.c[arg->enumIndex + 1]; break;
441             default:
442                 // For other types, there is nothing type-specific to do.
443                 break;
444         }
445     }
446 }
447
448 } // namespace
449
450 } // namespace gmx
451
452 gmx_bool parse_common_args(int*               argc,
453                            char*              argv[],
454                            unsigned long      Flags,
455                            int                nfile,
456                            t_filenm           fnm[],
457                            int                npargs,
458                            t_pargs*           pa,
459                            int                ndesc,
460                            const char**       desc,
461                            int                nbugs,
462                            const char**       bugs,
463                            gmx_output_env_t** oenv)
464 {
465     // Lambda function to test the (local) Flags parameter against a bit mask.
466     auto isFlagSet = [Flags](unsigned long bits) { return (Flags & bits) == bits; };
467
468     try
469     {
470         double                         tbegin = 0.0, tend = 0.0, tdelta = 0.0;
471         bool                           bBeginTimeSet = false, bEndTimeSet = false, bDtSet = false;
472         bool                           bView = false;
473         gmx::OptionsAdapter            adapter(*argc, argv);
474         gmx::Options                   options;
475         gmx::OptionsBehaviorCollection behaviors(&options);
476         gmx::FileNameOptionManager     fileOptManager;
477
478         fileOptManager.disableInputOptionChecking(isFlagSet(PCA_DISABLE_INPUT_FILE_CHECKING));
479         options.addManager(&fileOptManager);
480
481         if (isFlagSet(PCA_CAN_SET_DEFFNM))
482         {
483             fileOptManager.addDefaultFileNameOption(&options, "deffnm");
484         }
485         if (isFlagSet(PCA_CAN_BEGIN))
486         {
487             options.addOption(
488                     gmx::DoubleOption("b").store(&tbegin).storeIsSet(&bBeginTimeSet).timeValue().description("Time of first frame to read from trajectory (default unit %t)"));
489         }
490         if (isFlagSet(PCA_CAN_END))
491         {
492             options.addOption(
493                     gmx::DoubleOption("e").store(&tend).storeIsSet(&bEndTimeSet).timeValue().description("Time of last frame to read from trajectory (default unit %t)"));
494         }
495         if (isFlagSet(PCA_CAN_DT))
496         {
497             options.addOption(gmx::DoubleOption("dt").store(&tdelta).storeIsSet(&bDtSet).timeValue().description(
498                     "Only use frame when t MOD dt = first time (default unit %t)"));
499         }
500         gmx::TimeUnit timeUnit = gmx::TimeUnit::Default;
501         if (isFlagSet(PCA_TIME_UNIT))
502         {
503             std::shared_ptr<gmx::TimeUnitBehavior> timeUnitBehavior(new gmx::TimeUnitBehavior());
504             timeUnitBehavior->setTimeUnitStore(&timeUnit);
505             timeUnitBehavior->setTimeUnitFromEnvironment();
506             timeUnitBehavior->addTimeUnitOption(&options, "tu");
507             behaviors.addBehavior(timeUnitBehavior);
508         }
509         if (isFlagSet(PCA_CAN_VIEW))
510         {
511             options.addOption(gmx::BooleanOption("w").store(&bView).description(
512                     "View output [REF].xvg[ref], [REF].xpm[ref], "
513                     "[REF].eps[ref] and [REF].pdb[ref] files"));
514         }
515
516         bool bXvgr = false;
517         for (int i = 0; i < nfile; i++)
518         {
519             bXvgr = bXvgr || (fnm[i].ftp == efXVG);
520         }
521         XvgFormat xvgFormat = gmx::getDefaultXvgFormat();
522         if (bXvgr)
523         {
524             options.addOption(gmx::EnumOption<XvgFormat>("xvg")
525                                       .enumValue(gmx::c_xvgFormatNames)
526                                       .store(&xvgFormat)
527                                       .description("xvg plot formatting"));
528         }
529
530         /* Now append the program specific arguments */
531         for (int i = 0; i < nfile; i++)
532         {
533             adapter.filenmToOptions(&options, &fnm[i]);
534         }
535         for (int i = 0; i < npargs; i++)
536         {
537             adapter.pargsToOptions(&options, &pa[i]);
538         }
539
540         const gmx::CommandLineHelpContext* context = gmx::GlobalCommandLineHelpContext::get();
541         if (context != nullptr)
542         {
543             GMX_RELEASE_ASSERT(gmx_node_rank() == 0,
544                                "Help output should be handled higher up and "
545                                "only get called only on the master rank");
546             gmx::CommandLineHelpWriter(options)
547                     .setHelpText(gmx::constArrayRefFromArray<const char*>(desc, ndesc))
548                     .setKnownIssues(gmx::constArrayRefFromArray(bugs, nbugs))
549                     .writeHelp(*context);
550             return FALSE;
551         }
552
553         /* Now parse all the command-line options */
554         gmx::CommandLineParser(&options)
555                 .skipUnknown(isFlagSet(PCA_NOEXIT_ON_ARGS))
556                 .allowPositionalArguments(isFlagSet(PCA_NOEXIT_ON_ARGS))
557                 .parse(argc, argv);
558         behaviors.optionsFinishing();
559         options.finish();
560
561         /* set program name, command line, and default values for output options */
562         // NOLINTNEXTLINE(bugprone-misplaced-widening-cast)
563         output_env_init(oenv, gmx::getProgramContext(), timeUnit, bView, xvgFormat, 0);
564
565         /* Extract Time info from arguments */
566         if (bBeginTimeSet)
567         {
568             setTimeValue(TBEGIN, tbegin);
569         }
570         if (bEndTimeSet)
571         {
572             setTimeValue(TEND, tend);
573         }
574         if (bDtSet)
575         {
576             setTimeValue(TDELTA, tdelta);
577         }
578
579         adapter.copyValues();
580
581         return TRUE;
582     }
583     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
584 }