Split lines with many copyright years
[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/exceptions.h"
63 #include "gromacs/utility/fatalerror.h"
64 #include "gromacs/utility/gmxassert.h"
65 #include "gromacs/utility/path.h"
66 #include "gromacs/utility/programcontext.h"
67 #include "gromacs/utility/stringutil.h"
68
69 /* The source code in this file should be thread-safe.
70       Please keep it that way. */
71
72 int nenum(const char* const enumc[])
73 {
74     int i;
75
76     i = 1;
77     /* we *can* compare pointers directly here! */
78     while (enumc[i] && enumc[0] != enumc[i])
79     {
80         i++;
81     }
82
83     return i;
84 }
85
86 int opt2parg_int(const char* option, int nparg, t_pargs pa[])
87 {
88     int i;
89
90     for (i = 0; (i < nparg); i++)
91     {
92         if (strcmp(pa[i].option, option) == 0)
93         {
94             return *pa[i].u.i;
95         }
96     }
97
98     gmx_fatal(FARGS, "No integer option %s in pargs", option);
99 }
100
101 gmx_bool opt2parg_bool(const char* option, int nparg, t_pargs pa[])
102 {
103     int i;
104
105     for (i = 0; (i < nparg); i++)
106     {
107         if (strcmp(pa[i].option, option) == 0)
108         {
109             return *pa[i].u.b;
110         }
111     }
112
113     gmx_fatal(FARGS, "No boolean option %s in pargs", option);
114
115     return FALSE;
116 }
117
118 real opt2parg_real(const char* option, int nparg, t_pargs pa[])
119 {
120     int i;
121
122     for (i = 0; (i < nparg); i++)
123     {
124         if (strcmp(pa[i].option, option) == 0)
125         {
126             return *pa[i].u.r;
127         }
128     }
129
130     gmx_fatal(FARGS, "No real option %s in pargs", option);
131 }
132
133 const char* opt2parg_str(const char* option, int nparg, t_pargs pa[])
134 {
135     int i;
136
137     for (i = 0; (i < nparg); i++)
138     {
139         if (strcmp(pa[i].option, option) == 0)
140         {
141             return *(pa[i].u.c);
142         }
143     }
144
145     gmx_fatal(FARGS, "No string option %s in pargs", option);
146 }
147
148 gmx_bool opt2parg_bSet(const char* option, int nparg, const t_pargs* pa)
149 {
150     int i;
151
152     for (i = 0; (i < nparg); i++)
153     {
154         if (strcmp(pa[i].option, option) == 0)
155         {
156             return pa[i].bSet;
157         }
158     }
159
160     gmx_fatal(FARGS, "No such option %s in pargs", option);
161
162     return FALSE; /* Too make some compilers happy */
163 }
164
165 const char* opt2parg_enum(const char* option, int nparg, t_pargs pa[])
166 {
167     int i;
168
169     for (i = 0; (i < nparg); i++)
170     {
171         if (strcmp(pa[i].option, option) == 0)
172         {
173             return pa[i].u.c[0];
174         }
175     }
176
177     gmx_fatal(FARGS, "No such option %s in pargs", option);
178 }
179
180 /********************************************************************
181  * parse_common_args()
182  */
183
184 namespace gmx
185 {
186
187 namespace
188 {
189
190 /*! \brief
191  * Returns the index of the default xvg format.
192  *
193  * \ingroup module_commandline
194  */
195 int getDefaultXvgFormat(gmx::ArrayRef<const char* const> xvgFormats)
196 {
197     const char* const select = getenv("GMX_VIEW_XVG");
198     if (select != nullptr)
199     {
200         ArrayRef<const char* const>::const_iterator i =
201                 std::find(xvgFormats.begin(), xvgFormats.end(), std::string(select));
202         if (i != xvgFormats.end())
203         {
204             return std::distance(xvgFormats.begin(), i);
205         }
206         else
207         {
208             return exvgNONE - 1;
209         }
210     }
211     /* The default is the first option */
212     return 0;
213 }
214
215 /*! \brief
216  * Conversion helper between t_pargs/t_filenm and Options.
217  *
218  * This class holds the necessary mapping between the old C structures and
219  * the new C++ options to allow copying values back after parsing for cases
220  * where the C++ options do not directly provide the type of value required for
221  * the C structures.
222  *
223  * \ingroup module_commandline
224  */
225 class OptionsAdapter
226 {
227 public:
228     /*! \brief
229      * Initializes the adapter to convert from a specified command line.
230      *
231      * The command line is required, because t_pargs wants to return
232      * strings by reference to the original command line.
233      * OptionsAdapter creates a copy of the `argv` array (but not the
234      * strings) to make this possible, even if the parser removes
235      * options it has recognized.
236      */
237     OptionsAdapter(int argc, const char* const argv[]) : argv_(argv, argv + argc) {}
238
239     /*! \brief
240      * Converts a t_filenm option into an Options option.
241      *
242      * \param options Options object to add the new option to.
243      * \param fnm     t_filenm option to convert.
244      */
245     void filenmToOptions(Options* options, t_filenm* fnm);
246     /*! \brief
247      * Converts a t_pargs option into an Options option.
248      *
249      * \param     options Options object to add the new option to.
250      * \param     pa      t_pargs option to convert.
251      */
252     void pargsToOptions(Options* options, t_pargs* pa);
253
254     /*! \brief
255      * Copies values back from options to t_pargs/t_filenm.
256      */
257     void copyValues();
258
259 private:
260     struct FileNameData
261     {
262         //! Creates a conversion helper for a given `t_filenm` struct.
263         explicit FileNameData(t_filenm* fnm) : fnm(fnm), optionInfo(nullptr) {}
264
265         //! t_filenm structure to receive the final values.
266         t_filenm* fnm;
267         //! Option info object for the created FileNameOption.
268         FileNameOptionInfo* optionInfo;
269         //! Value storage for the created FileNameOption.
270         std::vector<std::string> values;
271     };
272     struct ProgramArgData
273     {
274         //! Creates a conversion helper for a given `t_pargs` struct.
275         explicit ProgramArgData(t_pargs* pa) :
276             pa(pa),
277             optionInfo(nullptr),
278             enumIndex(0),
279             boolValue(false)
280         {
281         }
282
283         //! t_pargs structure to receive the final values.
284         t_pargs* pa;
285         //! Option info object for the created option.
286         OptionInfo* optionInfo;
287         //! Value storage for a non-enum StringOption (unused for other types).
288         std::string stringValue;
289         //! Value storage for an enum option (unused for other types).
290         int enumIndex;
291         //! Value storage for a BooleanOption (unused for other types).
292         bool boolValue;
293     };
294
295     std::vector<const char*> argv_;
296     // These are lists instead of vectors to avoid relocating existing
297     // objects in case the container is reallocated (the Options object
298     // contains pointes to members of the objects, which would get
299     // invalidated).
300     std::list<FileNameData>   fileNameOptions_;
301     std::list<ProgramArgData> programArgs_;
302
303     GMX_DISALLOW_COPY_AND_ASSIGN(OptionsAdapter);
304 };
305
306 void OptionsAdapter::filenmToOptions(Options* options, t_filenm* fnm)
307 {
308     const bool        bRead     = ((fnm->flag & ffREAD) != 0);
309     const bool        bWrite    = ((fnm->flag & ffWRITE) != 0);
310     const bool        bOptional = ((fnm->flag & ffOPT) != 0);
311     const bool        bLibrary  = ((fnm->flag & ffLIB) != 0);
312     const bool        bMultiple = ((fnm->flag & ffMULT) != 0);
313     const bool        bMissing  = ((fnm->flag & ffALLOW_MISSING) != 0);
314     const char* const name      = (fnm->opt ? &fnm->opt[1] : &ftp2defopt(fnm->ftp)[1]);
315     const char*       defName   = fnm->fn;
316     int               defType   = -1;
317     if (defName == nullptr)
318     {
319         defName = ftp2defnm(fnm->ftp);
320     }
321     else if (Path::hasExtension(defName))
322     {
323         defType = fn2ftp(defName);
324         GMX_RELEASE_ASSERT(defType != efNR, "File name option specifies an invalid extension");
325     }
326     fileNameOptions_.emplace_back(fnm);
327     FileNameData& data = fileNameOptions_.back();
328     data.optionInfo    = options->addOption(FileNameOption(name)
329                                                  .storeVector(&data.values)
330                                                  .defaultBasename(defName)
331                                                  .defaultType(defType)
332                                                  .legacyType(fnm->ftp)
333                                                  .legacyOptionalBehavior()
334                                                  .readWriteFlags(bRead, bWrite)
335                                                  .required(!bOptional)
336                                                  .libraryFile(bLibrary)
337                                                  .multiValue(bMultiple)
338                                                  .allowMissing(bMissing)
339                                                  .description(ftp2desc(fnm->ftp)));
340 }
341
342 void OptionsAdapter::pargsToOptions(Options* options, t_pargs* pa)
343 {
344     const bool        bHidden = startsWith(pa->desc, "HIDDEN");
345     const char* const name    = &pa->option[1];
346     const char* const desc    = (bHidden ? &pa->desc[6] : pa->desc);
347     programArgs_.emplace_back(pa);
348     ProgramArgData& data = programArgs_.back();
349     switch (pa->type)
350     {
351         case etINT:
352             data.optionInfo = options->addOption(
353                     IntegerOption(name).store(pa->u.i).description(desc).hidden(bHidden));
354             return;
355         case etINT64:
356             data.optionInfo = options->addOption(
357                     Int64Option(name).store(pa->u.is).description(desc).hidden(bHidden));
358             return;
359         case etREAL:
360             data.optionInfo =
361                     options->addOption(RealOption(name).store(pa->u.r).description(desc).hidden(bHidden));
362             return;
363         case etTIME:
364             data.optionInfo = options->addOption(
365                     RealOption(name).store(pa->u.r).timeValue().description(desc).hidden(bHidden));
366             return;
367         case etSTR:
368         {
369             const char* const defValue = (*pa->u.c != nullptr ? *pa->u.c : "");
370             data.optionInfo            = options->addOption(StringOption(name)
371                                                          .store(&data.stringValue)
372                                                          .defaultValue(defValue)
373                                                          .description(desc)
374                                                          .hidden(bHidden));
375             return;
376         }
377         case etBOOL:
378             data.optionInfo = options->addOption(BooleanOption(name)
379                                                          .store(&data.boolValue)
380                                                          .defaultValue(*pa->u.b)
381                                                          .description(desc)
382                                                          .hidden(bHidden));
383             return;
384         case etRVEC:
385             data.optionInfo = options->addOption(
386                     RealOption(name).store(*pa->u.rv).vector().description(desc).hidden(bHidden));
387             return;
388         case etENUM:
389         {
390             const int defaultIndex = (pa->u.c[0] != nullptr ? nenum(pa->u.c) - 1 : 0);
391             data.optionInfo        = options->addOption(EnumIntOption(name)
392                                                          .store(&data.enumIndex)
393                                                          .defaultValue(defaultIndex)
394                                                          .enumValueFromNullTerminatedArray(pa->u.c + 1)
395                                                          .description(desc)
396                                                          .hidden(bHidden));
397             return;
398         }
399     }
400     GMX_THROW(NotImplementedError("Argument type not implemented"));
401 }
402
403 void OptionsAdapter::copyValues()
404 {
405     std::list<FileNameData>::const_iterator file;
406     for (file = fileNameOptions_.begin(); file != fileNameOptions_.end(); ++file)
407     {
408         if (file->optionInfo->isSet())
409         {
410             file->fnm->flag |= ffSET;
411         }
412         file->fnm->filenames = file->values;
413     }
414     std::list<ProgramArgData>::const_iterator arg;
415     for (arg = programArgs_.begin(); arg != programArgs_.end(); ++arg)
416     {
417         arg->pa->bSet = arg->optionInfo->isSet();
418         switch (arg->pa->type)
419         {
420             case etSTR:
421             {
422                 if (arg->pa->bSet)
423                 {
424                     std::vector<const char*>::const_iterator pos =
425                             std::find(argv_.begin(), argv_.end(), arg->stringValue);
426                     GMX_RELEASE_ASSERT(pos != argv_.end(),
427                                        "String argument got a value not in argv");
428                     *arg->pa->u.c = *pos;
429                 }
430                 break;
431             }
432             case etBOOL: *arg->pa->u.b = arg->boolValue; break;
433             case etENUM: *arg->pa->u.c = arg->pa->u.c[arg->enumIndex + 1]; break;
434             default:
435                 // For other types, there is nothing type-specific to do.
436                 break;
437         }
438     }
439 }
440
441 } // namespace
442
443 } // namespace gmx
444
445 gmx_bool parse_common_args(int*               argc,
446                            char*              argv[],
447                            unsigned long      Flags,
448                            int                nfile,
449                            t_filenm           fnm[],
450                            int                npargs,
451                            t_pargs*           pa,
452                            int                ndesc,
453                            const char**       desc,
454                            int                nbugs,
455                            const char**       bugs,
456                            gmx_output_env_t** oenv)
457 {
458     /* This array should match the order of the enum in oenv.h */
459     const char* const xvg_formats[] = { "xmgrace", "xmgr", "none" };
460
461     // Lambda function to test the (local) Flags parameter against a bit mask.
462     auto isFlagSet = [Flags](unsigned long bits) { return (Flags & bits) == bits; };
463
464     try
465     {
466         double                         tbegin = 0.0, tend = 0.0, tdelta = 0.0;
467         bool                           bBeginTimeSet = false, bEndTimeSet = false, bDtSet = false;
468         bool                           bView     = false;
469         int                            xvgFormat = 0;
470         gmx::OptionsAdapter            adapter(*argc, argv);
471         gmx::Options                   options;
472         gmx::OptionsBehaviorCollection behaviors(&options);
473         gmx::FileNameOptionManager     fileOptManager;
474
475         fileOptManager.disableInputOptionChecking(isFlagSet(PCA_DISABLE_INPUT_FILE_CHECKING));
476         options.addManager(&fileOptManager);
477
478         if (isFlagSet(PCA_CAN_SET_DEFFNM))
479         {
480             fileOptManager.addDefaultFileNameOption(&options, "deffnm");
481         }
482         if (isFlagSet(PCA_CAN_BEGIN))
483         {
484             options.addOption(
485                     gmx::DoubleOption("b").store(&tbegin).storeIsSet(&bBeginTimeSet).timeValue().description("Time of first frame to read from trajectory (default unit %t)"));
486         }
487         if (isFlagSet(PCA_CAN_END))
488         {
489             options.addOption(
490                     gmx::DoubleOption("e").store(&tend).storeIsSet(&bEndTimeSet).timeValue().description("Time of last frame to read from trajectory (default unit %t)"));
491         }
492         if (isFlagSet(PCA_CAN_DT))
493         {
494             options.addOption(gmx::DoubleOption("dt").store(&tdelta).storeIsSet(&bDtSet).timeValue().description(
495                     "Only use frame when t MOD dt = first time (default unit %t)"));
496         }
497         gmx::TimeUnit timeUnit = gmx::TimeUnit_Default;
498         if (isFlagSet(PCA_TIME_UNIT))
499         {
500             std::shared_ptr<gmx::TimeUnitBehavior> timeUnitBehavior(new gmx::TimeUnitBehavior());
501             timeUnitBehavior->setTimeUnitStore(&timeUnit);
502             timeUnitBehavior->setTimeUnitFromEnvironment();
503             timeUnitBehavior->addTimeUnitOption(&options, "tu");
504             behaviors.addBehavior(timeUnitBehavior);
505         }
506         if (isFlagSet(PCA_CAN_VIEW))
507         {
508             options.addOption(gmx::BooleanOption("w").store(&bView).description(
509                     "View output [REF].xvg[ref], [REF].xpm[ref], "
510                     "[REF].eps[ref] and [REF].pdb[ref] files"));
511         }
512
513         bool bXvgr = false;
514         for (int i = 0; i < nfile; i++)
515         {
516             bXvgr = bXvgr || (fnm[i].ftp == efXVG);
517         }
518         xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
519         if (bXvgr)
520         {
521             options.addOption(
522                     gmx::EnumIntOption("xvg").enumValue(xvg_formats).store(&xvgFormat).description("xvg plot formatting"));
523         }
524
525         /* Now append the program specific arguments */
526         for (int i = 0; i < nfile; i++)
527         {
528             adapter.filenmToOptions(&options, &fnm[i]);
529         }
530         for (int i = 0; i < npargs; i++)
531         {
532             adapter.pargsToOptions(&options, &pa[i]);
533         }
534
535         const gmx::CommandLineHelpContext* context = gmx::GlobalCommandLineHelpContext::get();
536         if (context != nullptr)
537         {
538             GMX_RELEASE_ASSERT(gmx_node_rank() == 0,
539                                "Help output should be handled higher up and "
540                                "only get called only on the master rank");
541             gmx::CommandLineHelpWriter(options)
542                     .setHelpText(gmx::constArrayRefFromArray<const char*>(desc, ndesc))
543                     .setKnownIssues(gmx::constArrayRefFromArray(bugs, nbugs))
544                     .writeHelp(*context);
545             return FALSE;
546         }
547
548         /* Now parse all the command-line options */
549         gmx::CommandLineParser(&options)
550                 .skipUnknown(isFlagSet(PCA_NOEXIT_ON_ARGS))
551                 .allowPositionalArguments(isFlagSet(PCA_NOEXIT_ON_ARGS))
552                 .parse(argc, argv);
553         behaviors.optionsFinishing();
554         options.finish();
555
556         /* set program name, command line, and default values for output options */
557         // NOLINTNEXTLINE(bugprone-misplaced-widening-cast)
558         output_env_init(oenv, gmx::getProgramContext(), static_cast<time_unit_t>(timeUnit + 1),
559                         bView, static_cast<xvg_format_t>(xvgFormat + 1), 0);
560
561         /* Extract Time info from arguments */
562         if (bBeginTimeSet)
563         {
564             setTimeValue(TBEGIN, tbegin);
565         }
566         if (bEndTimeSet)
567         {
568             setTimeValue(TEND, tend);
569         }
570         if (bDtSet)
571         {
572             setTimeValue(TDELTA, tdelta);
573         }
574
575         adapter.copyValues();
576
577         return TRUE;
578     }
579     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
580 }