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