7b0f9ba2399765744378878f5f6b7e9a3daba218
[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, 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.
10  *
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.
15  *
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.
20  *
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.
25  *
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.
33  *
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.
36  */
37 /* This file is completely threadsafe - keep it that way! */
38 #include "gmxpre.h"
39
40 #include "gromacs/commandline/pargs.h"
41
42 #include "config.h"
43
44 #include <cstdlib>
45 #include <cstring>
46
47 #include <algorithm>
48 #include <list>
49
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"
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     return 0;
102 }
103
104 gmx_bool opt2parg_bool(const char *option, int nparg, t_pargs pa[])
105 {
106     int i;
107
108     for (i = 0; (i < nparg); i++)
109     {
110         if (strcmp(pa[i].option, option) == 0)
111         {
112             return *pa[i].u.b;
113         }
114     }
115
116     gmx_fatal(FARGS, "No boolean option %s in pargs", option);
117
118     return FALSE;
119 }
120
121 real opt2parg_real(const char *option, int nparg, t_pargs pa[])
122 {
123     int i;
124
125     for (i = 0; (i < nparg); i++)
126     {
127         if (strcmp(pa[i].option, option) == 0)
128         {
129             return *pa[i].u.r;
130         }
131     }
132
133     gmx_fatal(FARGS, "No real option %s in pargs", option);
134
135     return 0.0;
136 }
137
138 const char *opt2parg_str(const char *option, int nparg, t_pargs pa[])
139 {
140     int i;
141
142     for (i = 0; (i < nparg); i++)
143     {
144         if (strcmp(pa[i].option, option) == 0)
145         {
146             return *(pa[i].u.c);
147         }
148     }
149
150     gmx_fatal(FARGS, "No string option %s in pargs", option);
151
152     return NULL;
153 }
154
155 gmx_bool opt2parg_bSet(const char *option, int nparg, t_pargs pa[])
156 {
157     int i;
158
159     for (i = 0; (i < nparg); i++)
160     {
161         if (strcmp(pa[i].option, option) == 0)
162         {
163             return pa[i].bSet;
164         }
165     }
166
167     gmx_fatal(FARGS, "No such option %s in pargs", option);
168
169     return FALSE; /* Too make some compilers happy */
170 }
171
172 const char *opt2parg_enum(const char *option, int nparg, t_pargs pa[])
173 {
174     int i;
175
176     for (i = 0; (i < nparg); i++)
177     {
178         if (strcmp(pa[i].option, option) == 0)
179         {
180             return pa[i].u.c[0];
181         }
182     }
183
184     gmx_fatal(FARGS, "No such option %s in pargs", option);
185
186     return NULL;
187 }
188
189 /********************************************************************
190  * parse_common_args()
191  */
192
193 namespace gmx
194 {
195
196 namespace
197 {
198
199 /*! \brief
200  * Returns the index of the default xvg format.
201  *
202  * \ingroup module_commandline
203  */
204 int getDefaultXvgFormat(gmx::ConstArrayRef<const char *> xvgFormats)
205 {
206     const char *const select = getenv("GMX_VIEW_XVG");
207     if (select != NULL)
208     {
209         ConstArrayRef<const char *>::const_iterator i =
210             std::find(xvgFormats.begin(), xvgFormats.end(), std::string(select));
211         if (i != xvgFormats.end())
212         {
213             return i - xvgFormats.begin();
214         }
215         else
216         {
217             return exvgNONE - 1;
218         }
219     }
220     /* The default is the first option */
221     return 0;
222 }
223
224 /*! \brief
225  * Conversion helper between t_pargs/t_filenm and Options.
226  *
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
230  * the C structures.
231  *
232  * \ingroup module_commandline
233  */
234 class OptionsAdapter
235 {
236     public:
237         /*! \brief
238          * Initializes the adapter to convert from a specified command line.
239          *
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.
245          */
246         OptionsAdapter(int argc, const char *const argv[])
247             : argv_(argv, argv + argc)
248         {
249         }
250
251         /*! \brief
252          * Converts a t_filenm option into an Options option.
253          *
254          * \param options Options object to add the new option to.
255          * \param fnm     t_filenm option to convert.
256          */
257         void filenmToOptions(Options *options, t_filenm *fnm);
258         /*! \brief
259          * Converts a t_pargs option into an Options option.
260          *
261          * \param     options Options object to add the new option to.
262          * \param     pa      t_pargs option to convert.
263          */
264         void pargsToOptions(Options *options, t_pargs *pa);
265
266         /*! \brief
267          * Copies values back from options to t_pargs/t_filenm.
268          */
269         void copyValues(bool bReadNode);
270
271     private:
272         struct FileNameData
273         {
274             //! Creates a conversion helper for a given `t_filenm` struct.
275             explicit FileNameData(t_filenm *fnm) : fnm(fnm), optionInfo(NULL)
276             {
277             }
278
279             //! t_filenm structure to receive the final values.
280             t_filenm                 *fnm;
281             //! Option info object for the created FileNameOption.
282             FileNameOptionInfo       *optionInfo;
283             //! Value storage for the created FileNameOption.
284             std::vector<std::string>  values;
285         };
286         struct ProgramArgData
287         {
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)
291             {
292             }
293
294             //! t_pargs structure to receive the final values.
295             t_pargs                 *pa;
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).
301             int                      enumIndex;
302             //! Value storage for a BooleanOption (unused for other types).
303             bool                     boolValue;
304         };
305
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
310         // invalidated).
311         std::list<FileNameData>      fileNameOptions_;
312         std::list<ProgramArgData>    programArgs_;
313
314         GMX_DISALLOW_COPY_AND_ASSIGN(OptionsAdapter);
315 };
316
317 void OptionsAdapter::filenmToOptions(Options *options, t_filenm *fnm)
318 {
319     if (fnm->opt == NULL)
320     {
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);
327     }
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;
335     if (defName == NULL)
336     {
337         defName = ftp2defnm(fnm->ftp);
338     }
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)));
348 }
349
350 void OptionsAdapter::pargsToOptions(Options *options, t_pargs *pa)
351 {
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();
357     switch (pa->type)
358     {
359         case etINT:
360             data.optionInfo = options->addOption(
361                         IntegerOption(name).store(pa->u.i)
362                             .description(desc).hidden(bHidden));
363             return;
364         case etINT64:
365             data.optionInfo = options->addOption(
366                         Int64Option(name).store(pa->u.is)
367                             .description(desc).hidden(bHidden));
368             return;
369         case etREAL:
370             data.optionInfo = options->addOption(
371                         RealOption(name).store(pa->u.r)
372                             .description(desc).hidden(bHidden));
373             return;
374         case etTIME:
375             data.optionInfo = options->addOption(
376                         RealOption(name).store(pa->u.r).timeValue()
377                             .description(desc).hidden(bHidden));
378             return;
379         case etSTR:
380         {
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));
386             return;
387         }
388         case etBOOL:
389             data.optionInfo = options->addOption(
390                         BooleanOption(name).store(&data.boolValue)
391                             .defaultValue(*pa->u.b)
392                             .description(desc).hidden(bHidden));
393             return;
394         case etRVEC:
395             data.optionInfo = options->addOption(
396                         RealOption(name).store(*pa->u.rv).vector()
397                             .description(desc).hidden(bHidden));
398             return;
399         case etENUM:
400         {
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));
407             return;
408         }
409     }
410     GMX_THROW(NotImplementedError("Argument type not implemented"));
411 }
412
413 void OptionsAdapter::copyValues(bool bReadNode)
414 {
415     std::list<FileNameData>::const_iterator file;
416     for (file = fileNameOptions_.begin(); file != fileNameOptions_.end(); ++file)
417     {
418         if (!bReadNode && (file->fnm->flag & ffREAD))
419         {
420             continue;
421         }
422         if (file->optionInfo->isSet())
423         {
424             file->fnm->flag |= ffSET;
425         }
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)
429         {
430             file->fnm->fns[i] = gmx_strdup(file->values[i].c_str());
431         }
432     }
433     std::list<ProgramArgData>::const_iterator arg;
434     for (arg = programArgs_.begin(); arg != programArgs_.end(); ++arg)
435     {
436         arg->pa->bSet = arg->optionInfo->isSet();
437         switch (arg->pa->type)
438         {
439             case etSTR:
440             {
441                 if (arg->pa->bSet)
442                 {
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;
448                 }
449                 break;
450             }
451             case etBOOL:
452                 *arg->pa->u.b = arg->boolValue;
453                 break;
454             case etENUM:
455                 *arg->pa->u.c = arg->pa->u.c[arg->enumIndex + 1];
456                 break;
457             default:
458                 // For other types, there is nothing type-specific to do.
459                 break;
460         }
461     }
462 }
463
464 } // namespace
465
466 } // namespace gmx
467
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,
472                            output_env_t *oenv)
473 {
474     /* This array should match the order of the enum in oenv.h */
475     const char *const xvg_formats[] = { "xmgrace", "xmgr", "none" };
476
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)
480
481     try
482     {
483         double                     tbegin    = 0.0, tend = 0.0, tdelta = 0.0;
484         bool                       bView     = false;
485         int                        xvgFormat = 0;
486         gmx::TimeUnitManager       timeUnitManager;
487         gmx::OptionsAdapter        adapter(*argc, argv);
488         gmx::Options               options(NULL, NULL);
489         gmx::FileNameOptionManager fileOptManager;
490
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));
495
496         if (FF(PCA_CAN_SET_DEFFNM))
497         {
498             fileOptManager.addDefaultFileNameOption(&options, "deffnm");
499         }
500         if (FF(PCA_CAN_BEGIN))
501         {
502             options.addOption(
503                     gmx::DoubleOption("b").store(&tbegin).timeValue()
504                         .description("First frame (%t) to read from trajectory"));
505         }
506         if (FF(PCA_CAN_END))
507         {
508             options.addOption(
509                     gmx::DoubleOption("e").store(&tend).timeValue()
510                         .description("Last frame (%t) to read from trajectory"));
511         }
512         if (FF(PCA_CAN_DT))
513         {
514             options.addOption(
515                     gmx::DoubleOption("dt").store(&tdelta).timeValue()
516                         .description("Only use frame when t MOD dt = first time (%t)"));
517         }
518         if (FF(PCA_TIME_UNIT))
519         {
520             timeUnitManager.setTimeUnitFromEnvironment();
521             timeUnitManager.addTimeUnitOption(&options, "tu");
522         }
523         if (FF(PCA_CAN_VIEW))
524         {
525             options.addOption(
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"));
529         }
530
531         bool bXvgr = false;
532         for (int i = 0; i < nfile; i++)
533         {
534             bXvgr = bXvgr || (fnm[i].ftp == efXVG);
535         }
536         xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
537         if (bXvgr)
538         {
539             options.addOption(
540                     gmx::StringOption("xvg").enumValue(xvg_formats)
541                         .storeEnumIndex(&xvgFormat)
542                         .description("xvg plot formatting"));
543         }
544
545         /* Now append the program specific arguments */
546         for (int i = 0; i < nfile; i++)
547         {
548             adapter.filenmToOptions(&options, &fnm[i]);
549         }
550         for (int i = 0; i < npargs; i++)
551         {
552             adapter.pargsToOptions(&options, &pa[i]);
553         }
554
555         const gmx::CommandLineHelpContext *context =
556             gmx::GlobalCommandLineHelpContext::get();
557         if (context != NULL)
558         {
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);
567             return FALSE;
568         }
569
570         /* Now parse all the command-line options */
571         gmx::CommandLineParser(&options).skipUnknown(FF(PCA_NOEXIT_ON_ARGS))
572             .parse(argc, argv);
573         options.finish();
574
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);
579
580         timeUnitManager.scaleTimeOptions(&options);
581
582         /* Extract Time info from arguments */
583         // TODO: Use OptionInfo objects instead of string constants
584         if (FF(PCA_CAN_BEGIN) && options.isSet("b"))
585         {
586             setTimeValue(TBEGIN, tbegin);
587         }
588         if (FF(PCA_CAN_END) && options.isSet("e"))
589         {
590             setTimeValue(TEND, tend);
591         }
592         if (FF(PCA_CAN_DT) && options.isSet("dt"))
593         {
594             setTimeValue(TDELTA, tdelta);
595         }
596
597         adapter.copyValues(!FF(PCA_NOT_READ_NODE));
598
599         return TRUE;
600     }
601     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
602 #undef FF
603 }