6a8ebfef9d4aab29d649babe48e225f999a72290
[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[], bool full=true);
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[], bool full)
110 {
111     FileNameOptionManager  fileoptManager;
112     SelectionOptionManager seloptManager(selections);
113     Options                options(NULL, NULL);
114
115     options.addManager(&fileoptManager);
116     options.addManager(&seloptManager);
117     if (full) {
118             IOptionsContainer &commonOptions = options.addGroup();
119     }
120     IOptionsContainer &moduleOptions = options.addGroup();
121
122     module_->initOptions(&moduleOptions, settings);
123     if (full) {
124             common->initOptions(&commonOptions);
125     }
126     selections->initOptions(&commonOptions);
127
128     {
129         CommandLineParser  parser(&options);
130         // TODO: Print the help if user provides an invalid option?
131         // Or just add a message advising the user to invoke the help?
132         parser.parse(argc, argv);
133         common->scaleTimeOptions(&options);
134         options.finish();
135     }
136
137     if (full) {
138             common->optionsFinished();
139     }
140     module_->optionsFinished(settings);
141
142     common->initIndexGroups(selections, bUseDefaultGroups_);
143
144     const bool bInteractive = StandardInputStream::instance().isInteractive();
145     seloptManager.parseRequestedFromStdin(bInteractive);
146
147     common->doneIndexGroups(selections);
148     common->initTopology(selections);
149
150     selections->compile();
151 }
152
153
154 /********************************************************************
155  * TrajectoryAnalysisCommandLineRunner
156  */
157
158 TrajectoryAnalysisCommandLineRunner::TrajectoryAnalysisCommandLineRunner(
159         TrajectoryAnalysisModule *module)
160     : impl_(new Impl(module))
161 {
162 }
163
164
165 TrajectoryAnalysisCommandLineRunner::~TrajectoryAnalysisCommandLineRunner()
166 {
167 }
168
169
170 void
171 TrajectoryAnalysisCommandLineRunner::setUseDefaultGroups(bool bUseDefaults)
172 {
173     impl_->bUseDefaultGroups_ = bUseDefaults;
174 }
175
176
177 void
178 TrajectoryAnalysisCommandLineRunner::setSelectionDebugLevel(int debuglevel)
179 {
180     impl_->debugLevel_ = debuglevel;
181 }
182
183
184 int
185 TrajectoryAnalysisCommandLineRunner::run(int argc, char *argv[])
186 {
187     TrajectoryAnalysisModule *module = impl_->module_;
188
189     SelectionCollection       selections;
190     selections.setDebugLevel(impl_->debugLevel_);
191
192     TrajectoryAnalysisSettings      settings;
193     TrajectoryAnalysisRunnerCommon  common(&settings);
194
195     impl_->parseOptions(&settings, &common, &selections, &argc, argv);
196
197     const TopologyInformation &topology = common.topologyInformation();
198     module->initAnalysis(settings, topology);
199
200     TrajectoryAnalysisModule::Batch batch = module->getBatch();
201     std::vector<SelectionCollection*> batchSelections;
202     std::vector<Impl*> impls;
203     for (size_t i = 0; i < batch.size(); i++) {
204         TrajectoryAnalysisModule *bmodule = batch[i];
205         batchSelections.push_back(new SelectionCollection());
206         impls.push_back(new Impl(bmodule));
207         std::vector<char*> modArgv = module->getArgv(i);
208         int modArgc = modArgv.size();
209         impls.back()->parseOptions(&settings, &common, batchSelections.back(), &modArgc, modArgv.data(), false);
210
211         batch[i]->initAnalysis(settings, topology);
212     }
213
214     // Load first frame.
215     common.initFirstFrame();
216     module->initAfterFirstFrame(settings, common.frame());
217
218     t_pbc  pbc;
219     t_pbc *ppbc = settings.hasPBC() ? &pbc : NULL;
220
221     int    nframes = 0;
222     AnalysisDataParallelOptions         dataOptions;
223     TrajectoryAnalysisModuleDataPointer pdata(
224             module->startFrames(dataOptions, selections));
225
226     std::vector<AnalysisDataParallelOptions> batchOptions;
227     std::vector<TrajectoryAnalysisModuleDataPointer> batchDataPointers;
228     for (size_t i = 0; i < batch.size(); i++) {
229         batch[i]->initAfterFirstFrame(settings, common.frame());
230
231         batchOptions.push_back(AnalysisDataParallelOptions());
232         batchDataPointers.push_back(batch[i]->startFrames(
233             batchOptions.back(), *batchSelections[i]));
234     }
235
236     do
237     {
238         common.initFrame();
239         t_trxframe &frame = common.frame();
240         if (ppbc != NULL)
241         {
242             set_pbc(ppbc, topology.ePBC(), frame.box);
243         }
244
245         for (size_t i = 0; i < batch.size(); i++) {
246             batchSelections[i]->evaluate(&frame, ppbc);
247             batch[i]->analyzeFrame(nframes, frame, ppbc, batchDataPointers[i].get());
248             batch[i]->finishFrameSerial(nframes);
249         }
250         selections.evaluate(&frame, ppbc);
251         module->analyzeFrame(nframes, frame, ppbc, pdata.get());
252         module->finishFrameSerial(nframes);
253
254         ++nframes;
255     }
256     while (common.readNextFrame());
257     for (size_t i = 0; i < batch.size(); i++) {
258         batch[i]->finishFrames(batchDataPointers[i].get());
259         if (batchDataPointers[i].get() != NULL) {
260             batchDataPointers[i]->finish();
261         }
262         batchDataPointers[i].reset();
263     }
264
265     module->finishFrames(pdata.get());
266     if (pdata.get() != NULL)
267     {
268         pdata->finish();
269     }
270     pdata.reset();
271
272     if (common.hasTrajectory())
273     {
274         fprintf(stderr, "Analyzed %d frames, last time %.3f\n",
275                 nframes, common.frame().time);
276     }
277     else
278     {
279         fprintf(stderr, "Analyzed topology coordinates\n");
280     }
281
282     // Restore the maximal groups for dynamic selections.
283     for (size_t i = 0; i < batch.size(); i++) {
284         batchSelections[i]->evaluateFinal(nframes);
285         batch[i]->finishAnalysis(nframes);
286         batch[i]->writeOutput();
287
288         delete batchSelections[i];
289         delete impls[i];
290     }
291
292     selections.evaluateFinal(nframes);
293
294     module->finishAnalysis(nframes);
295     module->writeOutput();
296
297     return 0;
298 }
299
300
301 void
302 TrajectoryAnalysisCommandLineRunner::writeHelp(const CommandLineHelpContext &context)
303 {
304     // TODO: This method duplicates some code from run().
305     // See how to best refactor it to share the common code.
306     SelectionCollection             selections;
307     TrajectoryAnalysisSettings      settings;
308     TrajectoryAnalysisRunnerCommon  common(&settings);
309
310     SelectionOptionManager          seloptManager(&selections);
311     Options                         options(NULL, NULL);
312
313     options.addManager(&seloptManager);
314     IOptionsContainer &commonOptions = options.addGroup();
315     IOptionsContainer &moduleOptions = options.addGroup();
316
317     impl_->module_->initOptions(&moduleOptions, &settings);
318     common.initOptions(&commonOptions);
319     selections.initOptions(&commonOptions);
320
321     CommandLineHelpWriter(options)
322         .setHelpText(settings.helpText())
323         .setTimeUnitString(settings.timeUnitManager().timeUnitAsString())
324         .writeHelp(context);
325 }
326
327
328 /*! \internal \brief
329  * Command line module for a trajectory analysis module.
330  *
331  * \ingroup module_trajectoryanalysis
332  */
333 class TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule
334     : public ICommandLineModule
335 {
336     public:
337         /*! \brief
338          * Constructs a module.
339          *
340          * \param[in] name         Name for the module.
341          * \param[in] description  One-line description for the module.
342          * \param[in] factory      Factory method to create the analysis module.
343          *
344          * Does not throw.  This is important for correct implementation of
345          * runAsMain().
346          */
347         RunnerCommandLineModule(const char *name, const char *description,
348                                 ModuleFactoryMethod factory)
349             : name_(name), description_(description), hasFunction_(true), factory_(factory), functor_(NULL)
350         {
351         }
352
353         /*! \brief
354          * Overloaded constructor accepting a functor instead of function pointer.
355          */
356         RunnerCommandLineModule(const char *name, const char *description,
357                                 ModuleFactoryFunctor *factory)
358             : name_(name), description_(description), hasFunction_(false), factory_(NULL), functor_(factory)
359         {
360         }
361
362         virtual const char *name() const { return name_; }
363         virtual const char *shortDescription() const { return description_; };
364
365         virtual void init(CommandLineModuleSettings *settings);
366         virtual int run(int argc, char *argv[]);
367         virtual void writeHelp(const CommandLineHelpContext &context) const;
368
369     private:
370         const char            *name_;
371         const char            *description_;
372         bool                   hasFunction_;
373         ModuleFactoryMethod    factory_;
374         ModuleFactoryFunctor   *functor_;
375
376         GMX_DISALLOW_COPY_AND_ASSIGN(RunnerCommandLineModule);
377 };
378
379 void TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::init(
380         CommandLineModuleSettings * /*settings*/)
381 {
382 }
383
384 int TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::run(
385         int argc, char *argv[])
386 {
387     TrajectoryAnalysisModulePointer     module(hasFunction_? factory_() : (*functor_)());
388     TrajectoryAnalysisCommandLineRunner runner(module.get());
389     return runner.run(argc, argv);
390 }
391
392 void TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::writeHelp(
393         const CommandLineHelpContext &context) const
394 {
395     TrajectoryAnalysisModulePointer     module(hasFunction_? factory_() : (*functor_)());
396     TrajectoryAnalysisCommandLineRunner runner(module.get());
397     runner.writeHelp(context);
398 }
399
400 // static
401 int
402 TrajectoryAnalysisCommandLineRunner::runAsMain(
403         int argc, char *argv[], ModuleFactoryMethod factory)
404 {
405     Impl::RunnerCommandLineModule module(NULL, NULL, factory);
406     return CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
407 }
408
409 // static
410 int
411 TrajectoryAnalysisCommandLineRunner::runAsMain(
412         int argc, char *argv[], ModuleFactoryFunctor *factory)
413 {
414     Impl::RunnerCommandLineModule module(NULL, NULL, factory);
415     return CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
416 }
417
418 // static
419 void
420 TrajectoryAnalysisCommandLineRunner::registerModule(
421         CommandLineModuleManager *manager, const char *name,
422         const char *description, ModuleFactoryMethod factory)
423 {
424     CommandLineModulePointer module(
425             new Impl::RunnerCommandLineModule(name, description, factory));
426     manager->addModule(move(module));
427 }
428
429 } // namespace gmx