Convert some mdrun utility code to C++
[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,2014,2015, 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 "gmxpre.h"
43
44 #include "cmdlinerunner.h"
45
46 #include "gromacs/analysisdata/paralleloptions.h"
47 #include "gromacs/commandline/cmdlinehelpcontext.h"
48 #include "gromacs/commandline/cmdlinehelpwriter.h"
49 #include "gromacs/commandline/cmdlinemodule.h"
50 #include "gromacs/commandline/cmdlinemodulemanager.h"
51 #include "gromacs/commandline/cmdlineparser.h"
52 #include "gromacs/fileio/trx.h"
53 #include "gromacs/options/filenameoptionmanager.h"
54 #include "gromacs/options/options.h"
55 #include "gromacs/pbcutil/pbc.h"
56 #include "gromacs/selection/selectioncollection.h"
57 #include "gromacs/selection/selectionoptionmanager.h"
58 #include "gromacs/trajectoryanalysis/analysismodule.h"
59 #include "gromacs/trajectoryanalysis/analysissettings.h"
60 #include "gromacs/utility/exceptions.h"
61 #include "gromacs/utility/filestream.h"
62 #include "gromacs/utility/gmxassert.h"
63
64 #include "runnercommon.h"
65
66 namespace gmx
67 {
68
69 /********************************************************************
70  * TrajectoryAnalysisCommandLineRunner::Impl
71  */
72
73 class TrajectoryAnalysisCommandLineRunner::Impl
74 {
75     public:
76         class RunnerCommandLineModule;
77
78         Impl(TrajectoryAnalysisModule *module);
79         ~Impl();
80
81         void parseOptions(TrajectoryAnalysisSettings *settings,
82                           TrajectoryAnalysisRunnerCommon *common,
83                           SelectionCollection *selections,
84                           int *argc, char *argv[]);
85
86         TrajectoryAnalysisModule *module_;
87         bool                      bUseDefaultGroups_;
88         int                       debugLevel_;
89 };
90
91
92 TrajectoryAnalysisCommandLineRunner::Impl::Impl(
93         TrajectoryAnalysisModule *module)
94     : module_(module), bUseDefaultGroups_(true), debugLevel_(0)
95 {
96 }
97
98
99 TrajectoryAnalysisCommandLineRunner::Impl::~Impl()
100 {
101 }
102
103
104 void
105 TrajectoryAnalysisCommandLineRunner::Impl::parseOptions(
106         TrajectoryAnalysisSettings *settings,
107         TrajectoryAnalysisRunnerCommon *common,
108         SelectionCollection *selections,
109         int *argc, char *argv[])
110 {
111     FileNameOptionManager  fileoptManager;
112     SelectionOptionManager seloptManager(selections);
113     Options                options(NULL, NULL);
114
115     options.addManager(&fileoptManager);
116     options.addManager(&seloptManager);
117     IOptionsContainer &commonOptions = options.addGroup();
118     IOptionsContainer &moduleOptions = options.addGroup();
119
120     module_->initOptions(&moduleOptions, settings);
121     common->initOptions(&commonOptions);
122     selections->initOptions(&commonOptions);
123
124     {
125         CommandLineParser  parser(&options);
126         // TODO: Print the help if user provides an invalid option?
127         // Or just add a message advising the user to invoke the help?
128         parser.parse(argc, argv);
129         common->scaleTimeOptions(&options);
130         options.finish();
131     }
132
133     common->optionsFinished();
134     module_->optionsFinished(settings);
135
136     common->initIndexGroups(selections, bUseDefaultGroups_);
137
138     const bool bInteractive = StandardInputStream::instance().isInteractive();
139     seloptManager.parseRequestedFromStdin(bInteractive);
140     common->doneIndexGroups(selections);
141
142     common->initTopology(selections);
143     selections->compile();
144 }
145
146
147 /********************************************************************
148  * TrajectoryAnalysisCommandLineRunner
149  */
150
151 TrajectoryAnalysisCommandLineRunner::TrajectoryAnalysisCommandLineRunner(
152         TrajectoryAnalysisModule *module)
153     : impl_(new Impl(module))
154 {
155 }
156
157
158 TrajectoryAnalysisCommandLineRunner::~TrajectoryAnalysisCommandLineRunner()
159 {
160 }
161
162
163 void
164 TrajectoryAnalysisCommandLineRunner::setUseDefaultGroups(bool bUseDefaults)
165 {
166     impl_->bUseDefaultGroups_ = bUseDefaults;
167 }
168
169
170 void
171 TrajectoryAnalysisCommandLineRunner::setSelectionDebugLevel(int debuglevel)
172 {
173     impl_->debugLevel_ = debuglevel;
174 }
175
176
177 int
178 TrajectoryAnalysisCommandLineRunner::run(int argc, char *argv[])
179 {
180     TrajectoryAnalysisModule *module = impl_->module_;
181
182     SelectionCollection       selections;
183     selections.setDebugLevel(impl_->debugLevel_);
184
185     TrajectoryAnalysisSettings      settings;
186     TrajectoryAnalysisRunnerCommon  common(&settings);
187
188     impl_->parseOptions(&settings, &common, &selections, &argc, argv);
189
190     const TopologyInformation &topology = common.topologyInformation();
191     module->initAnalysis(settings, topology);
192
193     // Load first frame.
194     common.initFirstFrame();
195     module->initAfterFirstFrame(settings, common.frame());
196
197     t_pbc  pbc;
198     t_pbc *ppbc = settings.hasPBC() ? &pbc : NULL;
199
200     int    nframes = 0;
201     AnalysisDataParallelOptions         dataOptions;
202     TrajectoryAnalysisModuleDataPointer pdata(
203             module->startFrames(dataOptions, selections));
204     do
205     {
206         common.initFrame();
207         t_trxframe &frame = common.frame();
208         if (ppbc != NULL)
209         {
210             set_pbc(ppbc, topology.ePBC(), frame.box);
211         }
212
213         selections.evaluate(&frame, ppbc);
214         module->analyzeFrame(nframes, frame, ppbc, pdata.get());
215         module->finishFrameSerial(nframes);
216
217         ++nframes;
218     }
219     while (common.readNextFrame());
220     module->finishFrames(pdata.get());
221     if (pdata.get() != NULL)
222     {
223         pdata->finish();
224     }
225     pdata.reset();
226
227     if (common.hasTrajectory())
228     {
229         fprintf(stderr, "Analyzed %d frames, last time %.3f\n",
230                 nframes, common.frame().time);
231     }
232     else
233     {
234         fprintf(stderr, "Analyzed topology coordinates\n");
235     }
236
237     // Restore the maximal groups for dynamic selections.
238     selections.evaluateFinal(nframes);
239
240     module->finishAnalysis(nframes);
241     module->writeOutput();
242
243     return 0;
244 }
245
246
247 void
248 TrajectoryAnalysisCommandLineRunner::writeHelp(const CommandLineHelpContext &context)
249 {
250     // TODO: This method duplicates some code from run().
251     // See how to best refactor it to share the common code.
252     SelectionCollection             selections;
253     TrajectoryAnalysisSettings      settings;
254     TrajectoryAnalysisRunnerCommon  common(&settings);
255
256     SelectionOptionManager          seloptManager(&selections);
257     Options                         options(NULL, NULL);
258
259     options.addManager(&seloptManager);
260     IOptionsContainer &commonOptions = options.addGroup();
261     IOptionsContainer &moduleOptions = options.addGroup();
262
263     impl_->module_->initOptions(&moduleOptions, &settings);
264     common.initOptions(&commonOptions);
265     selections.initOptions(&commonOptions);
266
267     CommandLineHelpWriter(options)
268         .setHelpText(settings.helpText())
269         .setTimeUnitString(settings.timeUnitManager().timeUnitAsString())
270         .writeHelp(context);
271 }
272
273
274 /*! \internal \brief
275  * Command line module for a trajectory analysis module.
276  *
277  * \ingroup module_trajectoryanalysis
278  */
279 class TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule
280     : public ICommandLineModule
281 {
282     public:
283         /*! \brief
284          * Constructs a module.
285          *
286          * \param[in] name         Name for the module.
287          * \param[in] description  One-line description for the module.
288          * \param[in] factory      Factory method to create the analysis module.
289          *
290          * Does not throw.  This is important for correct implementation of
291          * runAsMain().
292          */
293         RunnerCommandLineModule(const char *name, const char *description,
294                                 ModuleFactoryMethod factory)
295             : name_(name), description_(description), factory_(factory)
296         {
297         }
298
299         virtual const char *name() const { return name_; }
300         virtual const char *shortDescription() const { return description_; };
301
302         virtual void init(CommandLineModuleSettings *settings);
303         virtual int run(int argc, char *argv[]);
304         virtual void writeHelp(const CommandLineHelpContext &context) const;
305
306     private:
307         const char             *name_;
308         const char             *description_;
309         ModuleFactoryMethod     factory_;
310
311         GMX_DISALLOW_COPY_AND_ASSIGN(RunnerCommandLineModule);
312 };
313
314 void TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::init(
315         CommandLineModuleSettings * /*settings*/)
316 {
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     TrajectoryAnalysisModulePointer     module(factory_());
331     TrajectoryAnalysisCommandLineRunner runner(module.get());
332     runner.writeHelp(context);
333 }
334
335 // static
336 int
337 TrajectoryAnalysisCommandLineRunner::runAsMain(
338         int argc, char *argv[], ModuleFactoryMethod factory)
339 {
340     Impl::RunnerCommandLineModule module(NULL, NULL, factory);
341     return CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
342 }
343
344 // static
345 void
346 TrajectoryAnalysisCommandLineRunner::registerModule(
347         CommandLineModuleManager *manager, const char *name,
348         const char *description, ModuleFactoryMethod factory)
349 {
350     CommandLineModulePointer module(
351             new Impl::RunnerCommandLineModule(name, description, factory));
352     manager->addModule(move(module));
353 }
354
355 } // namespace gmx