Uniform code path for writing out console help.
[alexxy/gromacs.git] / src / gromacs / trajectoryanalysis / runnercommon.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  * 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::TrajectoryAnalysisRunnerCommon.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_trajectoryanalysis
41  */
42 #include "runnercommon.h"
43
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif
47
48 #include <string.h>
49
50 #include "gromacs/legacyheaders/oenv.h"
51 #include "gromacs/legacyheaders/rmpbc.h"
52 #include "gromacs/legacyheaders/smalloc.h"
53 #include "gromacs/legacyheaders/statutil.h"
54 #include "gromacs/legacyheaders/tpxio.h"
55 #include "gromacs/legacyheaders/vec.h"
56
57 #include "gromacs/options/basicoptions.h"
58 #include "gromacs/options/filenameoption.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/selection/indexutil.h"
61 #include "gromacs/selection/selectioncollection.h"
62 #include "gromacs/selection/selectionfileoption.h"
63 #include "gromacs/trajectoryanalysis/analysissettings.h"
64 #include "gromacs/utility/exceptions.h"
65 #include "gromacs/utility/gmxassert.h"
66 #include "gromacs/utility/stringutil.h"
67
68 #include "analysissettings-impl.h"
69
70 namespace gmx
71 {
72
73 class TrajectoryAnalysisRunnerCommon::Impl
74 {
75     public:
76         Impl(TrajectoryAnalysisSettings *settings);
77         ~Impl();
78
79         void finishTrajectory();
80
81         TrajectoryAnalysisSettings &settings_;
82         TopologyInformation         topInfo_;
83
84         //! Name of the trajectory file (empty if not provided).
85         std::string                 trjfile_;
86         //! Name of the topology file (empty if no topology provided).
87         std::string                 topfile_;
88         //! Name of the index file (empty if no index file provided).
89         std::string                 ndxfile_;
90         double                      startTime_;
91         double                      endTime_;
92         double                      deltaTime_;
93
94         gmx_ana_indexgrps_t        *grps_;
95         bool                        bTrajOpen_;
96         //! The current frame, or \p NULL if no frame loaded yet.
97         t_trxframe                 *fr;
98         gmx_rmpbc_t                 gpbc_;
99         //! Used to store the status variable from read_first_frame().
100         t_trxstatus                *status_;
101         output_env_t                oenv_;
102 };
103
104
105 TrajectoryAnalysisRunnerCommon::Impl::Impl(TrajectoryAnalysisSettings *settings)
106     : settings_(*settings),
107       startTime_(0.0), endTime_(0.0), deltaTime_(0.0),
108       grps_(NULL),
109       bTrajOpen_(false), fr(NULL), gpbc_(NULL), status_(NULL), oenv_(NULL)
110 {
111 }
112
113
114 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
115 {
116     if (grps_ != NULL)
117     {
118         gmx_ana_indexgrps_free(grps_);
119     }
120     finishTrajectory();
121     if (fr)
122     {
123         // There doesn't seem to be a function for freeing frame data
124         sfree(fr->x);
125         sfree(fr->v);
126         sfree(fr->f);
127         sfree(fr);
128     }
129     if (oenv_ != NULL)
130     {
131         output_env_done(oenv_);
132     }
133 }
134
135
136 void
137 TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
138 {
139     if (bTrajOpen_)
140     {
141         close_trx(status_);
142         bTrajOpen_ = false;
143     }
144     if (gpbc_ != NULL)
145     {
146         gmx_rmpbc_done(gpbc_);
147         gpbc_ = NULL;
148     }
149 }
150
151 /*********************************************************************
152  * TrajectoryAnalysisRunnerCommon
153  */
154
155 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(
156         TrajectoryAnalysisSettings *settings)
157     : impl_(new Impl(settings))
158 {
159 }
160
161
162 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon()
163 {
164 }
165
166
167 void
168 TrajectoryAnalysisRunnerCommon::initOptions(Options *options)
169 {
170     TrajectoryAnalysisSettings &settings = impl_->settings_;
171
172     // Add common file name arguments.
173     options->addOption(FileNameOption("f")
174                            .filetype(eftTrajectory).inputFile()
175                            .store(&impl_->trjfile_)
176                            .defaultBasename("traj")
177                            .description("Input trajectory or single configuration"));
178     options->addOption(FileNameOption("s")
179                            .filetype(eftTopology).inputFile()
180                            .store(&impl_->topfile_)
181                            .defaultBasename("topol")
182                            .description("Input structure"));
183     options->addOption(FileNameOption("n")
184                            .filetype(eftIndex).inputFile()
185                            .store(&impl_->ndxfile_)
186                            .defaultBasename("index")
187                            .description("Extra index groups"));
188     options->addOption(SelectionFileOption("sf"));
189
190     // Add options for trajectory time control.
191     options->addOption(DoubleOption("b").store(&impl_->startTime_).timeValue()
192                            .description("First frame (%t) to read from trajectory"));
193     options->addOption(DoubleOption("e").store(&impl_->endTime_).timeValue()
194                            .description("Last frame (%t) to read from trajectory"));
195     options->addOption(DoubleOption("dt").store(&impl_->deltaTime_).timeValue()
196                            .description("Only use frame if t MOD dt == first time (%t)"));
197
198     // Add time unit option.
199     settings.impl_->timeUnitManager.addTimeUnitOption(options, "tu");
200
201     // Add plot options.
202     settings.impl_->plotSettings.addOptions(options);
203
204     // Add common options for trajectory processing.
205     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
206     {
207         options->addOption(BooleanOption("rmpbc").store(&settings.impl_->bRmPBC)
208                                .description("Make molecules whole for each frame"));
209     }
210     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
211     {
212         options->addOption(BooleanOption("pbc").store(&settings.impl_->bPBC)
213                                .description("Use periodic boundary conditions for distance calculation"));
214     }
215 }
216
217
218 void
219 TrajectoryAnalysisRunnerCommon::scaleTimeOptions(Options *options)
220 {
221     impl_->settings_.impl_->timeUnitManager.scaleTimeOptions(options);
222 }
223
224
225 void
226 TrajectoryAnalysisRunnerCommon::optionsFinished(Options *options)
227 {
228     impl_->settings_.impl_->plotSettings.setTimeUnit(
229             impl_->settings_.impl_->timeUnitManager.timeUnit());
230
231     if (impl_->trjfile_.empty() && impl_->topfile_.empty())
232     {
233         GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
234     }
235
236     if (options->isSet("b"))
237     {
238         setTimeValue(TBEGIN, impl_->startTime_);
239     }
240     if (options->isSet("e"))
241     {
242         setTimeValue(TEND, impl_->endTime_);
243     }
244     if (options->isSet("dt"))
245     {
246         setTimeValue(TDELTA, impl_->deltaTime_);
247     }
248 }
249
250
251 void
252 TrajectoryAnalysisRunnerCommon::initIndexGroups(SelectionCollection *selections)
253 {
254     if (impl_->ndxfile_.empty())
255     {
256         // TODO: Initialize default selections
257         selections->setIndexGroups(NULL);
258     }
259     else
260     {
261         gmx_ana_indexgrps_init(&impl_->grps_, NULL, impl_->ndxfile_.c_str());
262         selections->setIndexGroups(impl_->grps_);
263     }
264 }
265
266
267 void
268 TrajectoryAnalysisRunnerCommon::doneIndexGroups(SelectionCollection *selections)
269 {
270     if (impl_->grps_ != NULL)
271     {
272         selections->setIndexGroups(NULL);
273         gmx_ana_indexgrps_free(impl_->grps_);
274         impl_->grps_ = NULL;
275     }
276 }
277
278
279 void
280 TrajectoryAnalysisRunnerCommon::initTopology(SelectionCollection *selections)
281 {
282     const TrajectoryAnalysisSettings &settings = impl_->settings_;
283     bool bRequireTop
284         = settings.hasFlag(TrajectoryAnalysisSettings::efRequireTop)
285             || selections->requiresTopology();
286     if (bRequireTop && impl_->topfile_.empty())
287     {
288         GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
289     }
290
291     // Load the topology if requested.
292     if (!impl_->topfile_.empty())
293     {
294         char  title[STRLEN];
295
296         snew(impl_->topInfo_.top_, 1);
297         impl_->topInfo_.bTop_ = read_tps_conf(impl_->topfile_.c_str(), title,
298                                               impl_->topInfo_.top_, &impl_->topInfo_.ePBC_,
299                                               &impl_->topInfo_.xtop_, NULL, impl_->topInfo_.boxtop_, TRUE);
300         if (hasTrajectory()
301             && !settings.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
302         {
303             sfree(impl_->topInfo_.xtop_);
304             impl_->topInfo_.xtop_ = NULL;
305         }
306     }
307
308     // Read the first frame if we don't know the maximum number of atoms
309     // otherwise.
310     int  natoms = -1;
311     if (!impl_->topInfo_.hasTopology())
312     {
313         initFirstFrame();
314         natoms = impl_->fr->natoms;
315     }
316     selections->setTopology(impl_->topInfo_.topology(), natoms);
317
318     /*
319        if (impl_->bSelDump)
320        {
321         gmx_ana_poscalc_coll_print_tree(stderr, impl_->pcc);
322         fprintf(stderr, "\n");
323        }
324      */
325 }
326
327
328 void
329 TrajectoryAnalysisRunnerCommon::initFirstFrame()
330 {
331     // Return if we have already initialized the trajectory.
332     if (impl_->fr)
333     {
334         return;
335     }
336     time_unit_t time_unit
337         = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
338     output_env_init(&impl_->oenv_, 0, NULL, time_unit, FALSE, exvgNONE, 0, 0);
339
340     int frflags = impl_->settings_.frflags();
341     frflags |= TRX_NEED_X;
342
343     snew(impl_->fr, 1);
344
345     const TopologyInformation &top = impl_->topInfo_;
346     if (hasTrajectory())
347     {
348         if (!read_first_frame(impl_->oenv_, &impl_->status_,
349                               impl_->trjfile_.c_str(), impl_->fr, frflags))
350         {
351             GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
352         }
353         impl_->bTrajOpen_ = true;
354
355         if (top.hasTopology() && impl_->fr->natoms > top.topology()->atoms.nr)
356         {
357             GMX_THROW(InconsistentInputError(formatString(
358                                                      "Trajectory (%d atoms) does not match topology (%d atoms)",
359                                                      impl_->fr->natoms, top.topology()->atoms.nr)));
360         }
361         // TODO: Check index groups if they have been initialized based on the topology.
362         /*
363            if (top)
364            {
365             for (int i = 0; i < impl_->sel->nr(); ++i)
366             {
367                 gmx_ana_index_check(impl_->sel->sel(i)->indexGroup(),
368                                     impl_->fr->natoms);
369             }
370            }
371          */
372     }
373     else
374     {
375         // Prepare a frame from topology information.
376         // TODO: Initialize more of the fields.
377         if (frflags & (TRX_NEED_V))
378         {
379             GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
380         }
381         if (frflags & (TRX_NEED_F))
382         {
383             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
384         }
385         impl_->fr->flags  = frflags;
386         impl_->fr->natoms = top.topology()->atoms.nr;
387         impl_->fr->bX     = TRUE;
388         snew(impl_->fr->x, impl_->fr->natoms);
389         memcpy(impl_->fr->x, top.xtop_,
390                sizeof(*impl_->fr->x) * impl_->fr->natoms);
391         impl_->fr->bBox   = TRUE;
392         copy_mat(const_cast<rvec *>(top.boxtop_), impl_->fr->box);
393     }
394
395     set_trxframe_ePBC(impl_->fr, top.ePBC());
396     if (top.hasTopology() && impl_->settings_.hasRmPBC())
397     {
398         impl_->gpbc_ = gmx_rmpbc_init(&top.topology()->idef, top.ePBC(),
399                                       impl_->fr->natoms);
400     }
401 }
402
403
404 bool
405 TrajectoryAnalysisRunnerCommon::readNextFrame()
406 {
407     bool bContinue = false;
408     if (hasTrajectory())
409     {
410         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
411     }
412     if (!bContinue)
413     {
414         impl_->finishTrajectory();
415     }
416     return bContinue;
417 }
418
419
420 void
421 TrajectoryAnalysisRunnerCommon::initFrame()
422 {
423     if (impl_->gpbc_ != NULL)
424     {
425         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
426     }
427 }
428
429
430 bool
431 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
432 {
433     return !impl_->trjfile_.empty();
434 }
435
436
437 const TopologyInformation &
438 TrajectoryAnalysisRunnerCommon::topologyInformation() const
439 {
440     return impl_->topInfo_;
441 }
442
443
444 t_trxframe &
445 TrajectoryAnalysisRunnerCommon::frame() const
446 {
447     GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
448     return *impl_->fr;
449 }
450
451 } // namespace gmx