Move parse_common_args() into commandline/pargs.*
[alexxy/gromacs.git] / src / gromacs / trajectoryanalysis / cmdlinerunner.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2012,2013, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::TrajectoryAnalysisCommandLineRunner.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_trajectoryanalysis
41  */
42 #include "cmdlinerunner.h"
43
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif
47
48 #include "gromacs/legacyheaders/pbc.h"
49 #include "gromacs/legacyheaders/rmpbc.h"
50
51 #include "gromacs/analysisdata/paralleloptions.h"
52 #include "gromacs/commandline/cmdlinehelpcontext.h"
53 #include "gromacs/commandline/cmdlinehelpwriter.h"
54 #include "gromacs/commandline/cmdlinemodule.h"
55 #include "gromacs/commandline/cmdlinemodulemanager.h"
56 #include "gromacs/commandline/cmdlineparser.h"
57 #include "gromacs/options/options.h"
58 #include "gromacs/selection/selectioncollection.h"
59 #include "gromacs/selection/selectionoptionmanager.h"
60 #include "gromacs/trajectoryanalysis/analysismodule.h"
61 #include "gromacs/trajectoryanalysis/analysissettings.h"
62 #include "gromacs/trajectoryanalysis/runnercommon.h"
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/file.h"
65 #include "gromacs/utility/gmxassert.h"
66 #include "gromacs/utility/programinfo.h"
67
68 namespace gmx
69 {
70
71 /********************************************************************
72  * TrajectoryAnalysisCommandLineRunner::Impl
73  */
74
75 class TrajectoryAnalysisCommandLineRunner::Impl
76 {
77     public:
78         class RunnerCommandLineModule;
79
80         Impl(TrajectoryAnalysisModule *module);
81         ~Impl();
82
83         bool parseOptions(TrajectoryAnalysisSettings *settings,
84                           TrajectoryAnalysisRunnerCommon *common,
85                           SelectionCollection *selections,
86                           int *argc, char *argv[]);
87
88         TrajectoryAnalysisModule *module_;
89         int                       debugLevel_;
90 };
91
92
93 TrajectoryAnalysisCommandLineRunner::Impl::Impl(
94         TrajectoryAnalysisModule *module)
95     : module_(module), debugLevel_(0)
96 {
97 }
98
99
100 TrajectoryAnalysisCommandLineRunner::Impl::~Impl()
101 {
102 }
103
104
105 bool
106 TrajectoryAnalysisCommandLineRunner::Impl::parseOptions(
107         TrajectoryAnalysisSettings *settings,
108         TrajectoryAnalysisRunnerCommon *common,
109         SelectionCollection *selections,
110         int *argc, char *argv[])
111 {
112     Options options(NULL, NULL);
113     Options moduleOptions(module_->name(), module_->description());
114     Options commonOptions("common", "Common analysis control");
115     Options selectionOptions("selection", "Common selection control");
116     module_->initOptions(&moduleOptions, settings);
117     common->initOptions(&commonOptions);
118     selections->initOptions(&selectionOptions);
119
120     options.addSubSection(&commonOptions);
121     options.addSubSection(&selectionOptions);
122     options.addSubSection(&moduleOptions);
123
124     SelectionOptionManager seloptManager(selections);
125     setManagerForSelectionOptions(&options, &seloptManager);
126
127     {
128         CommandLineParser  parser(&options);
129         // TODO: Print the help if user provides an invalid option?
130         // Or just add a message advising the user to invoke the help?
131         parser.parse(argc, argv);
132         common->scaleTimeOptions(&options);
133         options.finish();
134     }
135
136     common->optionsFinished(&commonOptions);
137     module_->optionsFinished(&moduleOptions, settings);
138
139     common->initIndexGroups(selections);
140
141     // TODO: Check whether the input is a pipe.
142     bool bInteractive = true;
143     seloptManager.parseRequestedFromStdin(bInteractive);
144     common->doneIndexGroups(selections);
145
146     return true;
147 }
148
149
150 /********************************************************************
151  * TrajectoryAnalysisCommandLineRunner
152  */
153
154 TrajectoryAnalysisCommandLineRunner::TrajectoryAnalysisCommandLineRunner(
155         TrajectoryAnalysisModule *module)
156     : impl_(new Impl(module))
157 {
158 }
159
160
161 TrajectoryAnalysisCommandLineRunner::~TrajectoryAnalysisCommandLineRunner()
162 {
163 }
164
165
166 void
167 TrajectoryAnalysisCommandLineRunner::setSelectionDebugLevel(int debuglevel)
168 {
169     impl_->debugLevel_ = debuglevel;
170 }
171
172
173 int
174 TrajectoryAnalysisCommandLineRunner::run(int argc, char *argv[])
175 {
176     TrajectoryAnalysisModule *module = impl_->module_;
177
178     SelectionCollection       selections;
179     selections.setDebugLevel(impl_->debugLevel_);
180
181     TrajectoryAnalysisSettings      settings;
182     TrajectoryAnalysisRunnerCommon  common(&settings);
183
184     if (!impl_->parseOptions(&settings, &common, &selections, &argc, argv))
185     {
186         return 0;
187     }
188
189     common.initTopology(&selections);
190     selections.compile();
191
192     const TopologyInformation &topology = common.topologyInformation();
193     module->initAnalysis(settings, topology);
194
195     // Load first frame.
196     common.initFirstFrame();
197     module->initAfterFirstFrame(common.frame());
198
199     t_pbc  pbc;
200     t_pbc *ppbc = settings.hasPBC() ? &pbc : NULL;
201
202     int    nframes = 0;
203     AnalysisDataParallelOptions         dataOptions;
204     TrajectoryAnalysisModuleDataPointer pdata(
205             module->startFrames(dataOptions, selections));
206     do
207     {
208         common.initFrame();
209         t_trxframe &frame = common.frame();
210         if (ppbc != NULL)
211         {
212             set_pbc(ppbc, topology.ePBC(), frame.box);
213         }
214
215         selections.evaluate(&frame, ppbc);
216         module->analyzeFrame(nframes, frame, ppbc, pdata.get());
217
218         nframes++;
219     }
220     while (common.readNextFrame());
221     module->finishFrames(pdata.get());
222     if (pdata.get() != NULL)
223     {
224         pdata->finish();
225     }
226     pdata.reset();
227
228     if (common.hasTrajectory())
229     {
230         fprintf(stderr, "Analyzed %d frames, last time %.3f\n",
231                 nframes, common.frame().time);
232     }
233     else
234     {
235         fprintf(stderr, "Analyzed topology coordinates\n");
236     }
237
238     // Restore the maximal groups for dynamic selections.
239     selections.evaluateFinal(nframes);
240
241     module->finishAnalysis(nframes);
242     module->writeOutput();
243
244     return 0;
245 }
246
247
248 void
249 TrajectoryAnalysisCommandLineRunner::writeHelp(const CommandLineHelpContext &context)
250 {
251     // TODO: This method duplicates some code from run().
252     // See how to best refactor it to share the common code.
253     SelectionCollection             selections;
254     TrajectoryAnalysisSettings      settings;
255     TrajectoryAnalysisRunnerCommon  common(&settings);
256
257     Options options(NULL, NULL);
258     Options moduleOptions(impl_->module_->name(), impl_->module_->description());
259     Options commonOptions("common", "Common analysis control");
260     Options selectionOptions("selection", "Common selection control");
261
262     impl_->module_->initOptions(&moduleOptions, &settings);
263     common.initOptions(&commonOptions);
264     selections.initOptions(&selectionOptions);
265
266     options.addSubSection(&commonOptions);
267     options.addSubSection(&selectionOptions);
268     options.addSubSection(&moduleOptions);
269
270     SelectionOptionManager seloptManager(&selections);
271     setManagerForSelectionOptions(&options, &seloptManager);
272
273     CommandLineHelpWriter(options)
274         .setShowDescriptions(true)
275         .setTimeUnitString(settings.timeUnitManager().timeUnitAsString())
276         .writeHelp(context);
277 }
278
279
280 /*! \internal \brief
281  * Command line module for a trajectory analysis module.
282  *
283  * \ingroup module_trajectoryanalysis
284  */
285 class TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule
286     : public CommandLineModuleInterface
287 {
288     public:
289         /*! \brief
290          * Constructs a module.
291          *
292          * \param[in] name         Name for the module.
293          * \param[in] description  One-line description for the module.
294          * \param[in] factory      Factory method to create the analysis module.
295          *
296          * Does not throw.  This is important for correct implementation of
297          * runAsMain().
298          */
299         RunnerCommandLineModule(const char *name, const char *description,
300                                 ModuleFactoryMethod factory)
301             : name_(name), description_(description), factory_(factory)
302         {
303         }
304
305         virtual const char *name() const { return name_; }
306         virtual const char *shortDescription() const { return description_; };
307
308         virtual int run(int argc, char *argv[]);
309         virtual void writeHelp(const CommandLineHelpContext &context) const;
310
311     private:
312         const char             *name_;
313         const char             *description_;
314         ModuleFactoryMethod     factory_;
315
316         GMX_DISALLOW_COPY_AND_ASSIGN(RunnerCommandLineModule);
317 };
318
319 int TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::run(
320         int argc, char *argv[])
321 {
322     TrajectoryAnalysisModulePointer     module(factory_());
323     TrajectoryAnalysisCommandLineRunner runner(module.get());
324     return runner.run(argc, argv);
325 }
326
327 void TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::writeHelp(
328         const CommandLineHelpContext &context) const
329 {
330     // TODO: Implement #969.
331     if (context.writerContext().outputFormat() != eHelpOutputFormat_Console)
332     {
333         return;
334     }
335     TrajectoryAnalysisModulePointer     module(factory_());
336     TrajectoryAnalysisCommandLineRunner runner(module.get());
337     runner.writeHelp(context);
338 }
339
340 // static
341 int
342 TrajectoryAnalysisCommandLineRunner::runAsMain(
343         int argc, char *argv[], ModuleFactoryMethod factory)
344 {
345     Impl::RunnerCommandLineModule module(NULL, NULL, factory);
346     return CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
347 }
348
349 // static
350 void
351 TrajectoryAnalysisCommandLineRunner::registerModule(
352         CommandLineModuleManager *manager, const char *name,
353         const char *description, ModuleFactoryMethod factory)
354 {
355     CommandLineModulePointer module(
356             new Impl::RunnerCommandLineModule(name, description, factory));
357     manager->addModule(move(module));
358 }
359
360 } // namespace gmx