Merge branch release-4-6 into master
[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, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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 #include "gromacs/legacyheaders/statutil.h"
51
52 #include "gromacs/analysisdata/paralleloptions.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/onlinehelp/helpwritercontext.h"
58 #include "gromacs/options/options.h"
59 #include "gromacs/selection/selectioncollection.h"
60 #include "gromacs/selection/selectionoptionmanager.h"
61 #include "gromacs/trajectoryanalysis/analysismodule.h"
62 #include "gromacs/trajectoryanalysis/analysissettings.h"
63 #include "gromacs/trajectoryanalysis/runnercommon.h"
64 #include "gromacs/utility/exceptions.h"
65 #include "gromacs/utility/file.h"
66 #include "gromacs/utility/gmxassert.h"
67 #include "gromacs/utility/programinfo.h"
68
69 namespace gmx
70 {
71
72 /********************************************************************
73  * TrajectoryAnalysisCommandLineRunner::Impl
74  */
75
76 class TrajectoryAnalysisCommandLineRunner::Impl
77 {
78     public:
79         class RunnerCommandLineModule;
80
81         Impl(TrajectoryAnalysisModule *module);
82         ~Impl();
83
84         void printHelp(const Options                        &options,
85                        const TrajectoryAnalysisSettings     &settings,
86                        const TrajectoryAnalysisRunnerCommon &common);
87         bool parseOptions(TrajectoryAnalysisSettings *settings,
88                           TrajectoryAnalysisRunnerCommon *common,
89                           SelectionCollection *selections,
90                           int *argc, char *argv[]);
91
92         TrajectoryAnalysisModule *module_;
93         int                       debugLevel_;
94 };
95
96
97 TrajectoryAnalysisCommandLineRunner::Impl::Impl(
98         TrajectoryAnalysisModule *module)
99     : module_(module), debugLevel_(0)
100 {
101 }
102
103
104 TrajectoryAnalysisCommandLineRunner::Impl::~Impl()
105 {
106 }
107
108
109 void
110 TrajectoryAnalysisCommandLineRunner::Impl::printHelp(
111         const Options                        &options,
112         const TrajectoryAnalysisSettings     &settings,
113         const TrajectoryAnalysisRunnerCommon &common)
114 {
115     TrajectoryAnalysisRunnerCommon::HelpFlags flags = common.helpFlags();
116     if (flags != 0)
117     {
118         HelpWriterContext context(&File::standardError(),
119                                   eHelpOutputFormat_Console);
120         CommandLineHelpWriter(options)
121             .setShowDescriptions(flags & TrajectoryAnalysisRunnerCommon::efHelpShowDescriptions)
122             .setShowHidden(flags & TrajectoryAnalysisRunnerCommon::efHelpShowHidden)
123             .setTimeUnitString(settings.timeUnitManager().timeUnitAsString())
124             .writeHelp(context);
125     }
126 }
127
128
129 bool
130 TrajectoryAnalysisCommandLineRunner::Impl::parseOptions(
131         TrajectoryAnalysisSettings *settings,
132         TrajectoryAnalysisRunnerCommon *common,
133         SelectionCollection *selections,
134         int *argc, char *argv[])
135 {
136     Options options(NULL, NULL);
137     Options moduleOptions(module_->name(), module_->description());
138     Options commonOptions("common", "Common analysis control");
139     Options selectionOptions("selection", "Common selection control");
140     module_->initOptions(&moduleOptions, settings);
141     common->initOptions(&commonOptions);
142     selections->initOptions(&selectionOptions);
143
144     options.addSubSection(&commonOptions);
145     options.addSubSection(&selectionOptions);
146     options.addSubSection(&moduleOptions);
147
148     SelectionOptionManager seloptManager(selections);
149     setManagerForSelectionOptions(&options, &seloptManager);
150
151     {
152         CommandLineParser  parser(&options);
153         try
154         {
155             parser.parse(argc, argv);
156         }
157         catch (const UserInputError &ex)
158         {
159             printHelp(options, *settings, *common);
160             throw;
161         }
162         printHelp(options, *settings, *common);
163         common->scaleTimeOptions(&options);
164         options.finish();
165     }
166
167     if (!common->optionsFinished(&commonOptions))
168     {
169         return false;
170     }
171     module_->optionsFinished(&moduleOptions, settings);
172
173     common->initIndexGroups(selections);
174
175     // TODO: Check whether the input is a pipe.
176     bool bInteractive = true;
177     seloptManager.parseRequestedFromStdin(bInteractive);
178     common->doneIndexGroups(selections);
179
180     return true;
181 }
182
183
184 /********************************************************************
185  * TrajectoryAnalysisCommandLineRunner
186  */
187
188 TrajectoryAnalysisCommandLineRunner::TrajectoryAnalysisCommandLineRunner(
189         TrajectoryAnalysisModule *module)
190     : impl_(new Impl(module))
191 {
192 }
193
194
195 TrajectoryAnalysisCommandLineRunner::~TrajectoryAnalysisCommandLineRunner()
196 {
197 }
198
199
200 void
201 TrajectoryAnalysisCommandLineRunner::setSelectionDebugLevel(int debuglevel)
202 {
203     impl_->debugLevel_ = 1;
204 }
205
206
207 int
208 TrajectoryAnalysisCommandLineRunner::run(int argc, char *argv[])
209 {
210     TrajectoryAnalysisModule *module = impl_->module_;
211
212     SelectionCollection  selections;
213     selections.setDebugLevel(impl_->debugLevel_);
214
215     TrajectoryAnalysisSettings      settings;
216     TrajectoryAnalysisRunnerCommon  common(&settings);
217
218     if (!impl_->parseOptions(&settings, &common, &selections, &argc, argv))
219     {
220         return 0;
221     }
222
223     common.initTopology(&selections);
224     selections.compile();
225
226     const TopologyInformation &topology = common.topologyInformation();
227     module->initAnalysis(settings, topology);
228
229     // Load first frame.
230     common.initFirstFrame();
231     module->initAfterFirstFrame(common.frame());
232
233     t_pbc  pbc;
234     t_pbc *ppbc = settings.hasPBC() ? &pbc : NULL;
235
236     int    nframes = 0;
237     AnalysisDataParallelOptions         dataOptions;
238     TrajectoryAnalysisModuleDataPointer pdata(
239             module->startFrames(dataOptions, selections));
240     do
241     {
242         common.initFrame();
243         t_trxframe &frame = common.frame();
244         if (ppbc != NULL)
245         {
246             set_pbc(ppbc, topology.ePBC(), frame.box);
247         }
248
249         selections.evaluate(&frame, ppbc);
250         module->analyzeFrame(nframes, frame, ppbc, pdata.get());
251
252         nframes++;
253     }
254     while (common.readNextFrame());
255     module->finishFrames(pdata.get());
256     if (pdata.get() != NULL)
257     {
258         pdata->finish();
259     }
260     pdata.reset();
261
262     if (common.hasTrajectory())
263     {
264         fprintf(stderr, "Analyzed %d frames, last time %.3f\n",
265                 nframes, common.frame().time);
266     }
267     else
268     {
269         fprintf(stderr, "Analyzed topology coordinates\n");
270     }
271
272     // Restore the maximal groups for dynamic selections.
273     selections.evaluateFinal(nframes);
274
275     module->finishAnalysis(nframes);
276     module->writeOutput();
277
278     return 0;
279 }
280
281
282 void
283 TrajectoryAnalysisCommandLineRunner::writeHelp(const HelpWriterContext &context)
284 {
285     // TODO: This method duplicates some code from run() and Impl::printHelp().
286     // See how to best refactor it to share the common code.
287     SelectionCollection             selections;
288     TrajectoryAnalysisSettings      settings;
289     TrajectoryAnalysisRunnerCommon  common(&settings);
290
291     Options options(NULL, NULL);
292     Options moduleOptions(impl_->module_->name(), impl_->module_->description());
293     Options commonOptions("common", "Common analysis control");
294     Options selectionOptions("selection", "Common selection control");
295
296     impl_->module_->initOptions(&moduleOptions, &settings);
297     common.initOptions(&commonOptions);
298     selections.initOptions(&selectionOptions);
299
300     options.addSubSection(&commonOptions);
301     options.addSubSection(&selectionOptions);
302     options.addSubSection(&moduleOptions);
303
304     SelectionOptionManager seloptManager(&selections);
305     setManagerForSelectionOptions(&options, &seloptManager);
306
307     CommandLineHelpWriter(options)
308         .setShowDescriptions(true)
309         .setTimeUnitString(settings.timeUnitManager().timeUnitAsString())
310         .writeHelp(context);
311 }
312
313
314 /*! \internal \brief
315  * Command line module for a trajectory analysis module.
316  *
317  * \ingroup module_trajectoryanalysis
318  */
319 class TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule
320     : public CommandLineModuleInterface
321 {
322     public:
323         /*! \brief
324          * Constructs a module.
325          *
326          * \param[in] name         Name for the module.
327          * \param[in] description  One-line description for the module.
328          * \param[in] factory      Factory method to create the analysis module.
329          *
330          * Does not throw.  This is important for correct implementation of
331          * runAsMain().
332          */
333         RunnerCommandLineModule(const char *name, const char *description,
334                                 ModuleFactoryMethod factory)
335             : name_(name), description_(description), factory_(factory)
336         {
337         }
338
339         virtual const char *name() const { return name_; }
340         virtual const char *shortDescription() const { return description_; };
341
342         virtual int run(int argc, char *argv[]);
343         virtual void writeHelp(const HelpWriterContext &context) const;
344
345     private:
346         const char             *name_;
347         const char             *description_;
348         ModuleFactoryMethod     factory_;
349
350         GMX_DISALLOW_COPY_AND_ASSIGN(RunnerCommandLineModule);
351 };
352
353 int TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::run(
354         int argc, char *argv[])
355 {
356     TrajectoryAnalysisModulePointer     module(factory_());
357     TrajectoryAnalysisCommandLineRunner runner(module.get());
358     return runner.run(argc, argv);
359 }
360
361 void TrajectoryAnalysisCommandLineRunner::Impl::RunnerCommandLineModule::writeHelp(
362         const HelpWriterContext &context) const
363 {
364     TrajectoryAnalysisModulePointer     module(factory_());
365     TrajectoryAnalysisCommandLineRunner runner(module.get());
366     runner.writeHelp(context);
367 }
368
369 // static
370 int
371 TrajectoryAnalysisCommandLineRunner::runAsMain(
372         int argc, char *argv[], ModuleFactoryMethod factory)
373 {
374     Impl::RunnerCommandLineModule module(NULL, NULL, factory);
375     return CommandLineModuleManager::runAsMainSingleModule(argc, argv, &module);
376 }
377
378 // static
379 void
380 TrajectoryAnalysisCommandLineRunner::registerModule(
381         CommandLineModuleManager *manager, const char *name,
382         const char *description, ModuleFactoryMethod factory)
383 {
384     CommandLineModulePointer module(
385             new Impl::RunnerCommandLineModule(name, description, factory));
386     manager->addModule(move(module));
387 }
388
389 } // namespace gmx