Merge remote-tracking branch 'origin/release-4-6' into HEAD
[alexxy/gromacs.git] / src / gromacs / trajectoryanalysis / runnercommon.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements gmx::TrajectoryAnalysisRunnerCommon.
34  *
35  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36  * \ingroup module_trajectoryanalysis
37  */
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #include <string.h>
43
44 #include "oenv.h"
45 #include "rmpbc.h"
46 #include "smalloc.h"
47 #include "statutil.h"
48 #include "tpxio.h"
49 #include "vec.h"
50
51 #include "gromacs/options/basicoptions.h"
52 #include "gromacs/options/filenameoption.h"
53 #include "gromacs/options/options.h"
54 #include "gromacs/selection/indexutil.h"
55 #include "gromacs/selection/selectioncollection.h"
56 #include "gromacs/selection/selectionfileoption.h"
57 #include "gromacs/trajectoryanalysis/analysissettings.h"
58 #include "gromacs/trajectoryanalysis/runnercommon.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/gmxassert.h"
61 #include "gromacs/utility/stringutil.h"
62
63 #include "analysissettings-impl.h"
64
65 namespace gmx
66 {
67
68 class TrajectoryAnalysisRunnerCommon::Impl
69 {
70     public:
71         Impl(TrajectoryAnalysisSettings *settings);
72         ~Impl();
73
74         void finishTrajectory();
75
76         TrajectoryAnalysisSettings &settings_;
77         TopologyInformation     topInfo_;
78
79         bool                    bHelp_;
80         bool                    bShowHidden_;
81         bool                    bQuiet_;
82         //! Name of the trajectory file (empty if not provided).
83         std::string             trjfile_;
84         //! Name of the topology file (empty if no topology provided).
85         std::string             topfile_;
86         //! Name of the index file (empty if no index file provided).
87         std::string             ndxfile_;
88         double                  startTime_;
89         double                  endTime_;
90         double                  deltaTime_;
91
92         gmx_ana_indexgrps_t    *grps_;
93         bool                    bTrajOpen_;
94         //! The current frame, or \p NULL if no frame loaded yet.
95         t_trxframe          *fr;
96         gmx_rmpbc_t             gpbc_;
97         //! Used to store the status variable from read_first_frame().
98         t_trxstatus            *status_;
99         output_env_t            oenv_;
100 };
101
102
103 TrajectoryAnalysisRunnerCommon::Impl::Impl(TrajectoryAnalysisSettings *settings)
104     : settings_(*settings),
105       bHelp_(false), bShowHidden_(false), bQuiet_(false),
106       startTime_(0.0), endTime_(0.0), deltaTime_(0.0),
107       grps_(NULL),
108       bTrajOpen_(false), fr(NULL), gpbc_(NULL), status_(NULL), oenv_(NULL)
109 {
110 }
111
112
113 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
114 {
115     if (grps_ != NULL)
116     {
117         gmx_ana_indexgrps_free(grps_);
118     }
119     finishTrajectory();
120     if (fr)
121     {
122         // There doesn't seem to be a function for freeing frame data
123         sfree(fr->x);
124         sfree(fr->v);
125         sfree(fr->f);
126         sfree(fr);
127     }
128     if (oenv_ != NULL)
129     {
130         output_env_done(oenv_);
131     }
132 }
133
134
135 void
136 TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
137 {
138     if (bTrajOpen_)
139     {
140         close_trx(status_);
141         bTrajOpen_ = false;
142     }
143     if (gpbc_ != NULL)
144     {
145         gmx_rmpbc_done(gpbc_);
146         gpbc_ = NULL;
147     }
148 }
149
150 /*********************************************************************
151  * TrajectoryAnalysisRunnerCommon
152  */
153
154 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(
155         TrajectoryAnalysisSettings *settings)
156     : impl_(new Impl(settings))
157 {
158 }
159
160
161 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon()
162 {
163 }
164
165
166 void
167 TrajectoryAnalysisRunnerCommon::initOptions(Options *options)
168 {
169     TrajectoryAnalysisSettings &settings = impl_->settings_;
170
171     // Add options for help.
172     options->addOption(BooleanOption("h").store(&impl_->bHelp_)
173                            .description("Print help and quit"));
174     options->addOption(BooleanOption("hidden").store(&impl_->bShowHidden_)
175                            .hidden()
176                            .description("Show hidden options"));
177     options->addOption(BooleanOption("quiet").store(&impl_->bQuiet_)
178                            .hidden()
179                            .description("Hide options in normal run"));
180
181     // Add common file name arguments.
182     options->addOption(FileNameOption("f")
183                            .filetype(eftTrajectory).inputFile()
184                            .store(&impl_->trjfile_)
185                            .defaultBasename("traj")
186                            .description("Input trajectory or single configuration"));
187     options->addOption(FileNameOption("s")
188                            .filetype(eftTopology).inputFile()
189                            .store(&impl_->topfile_)
190                            .defaultBasename("topol")
191                            .description("Input structure"));
192     options->addOption(FileNameOption("n")
193                            .filetype(eftIndex).inputFile()
194                            .store(&impl_->ndxfile_)
195                            .defaultBasename("index")
196                            .description("Extra index groups"));
197     options->addOption(SelectionFileOption("sf"));
198
199     // Add options for trajectory time control.
200     options->addOption(DoubleOption("b").store(&impl_->startTime_).timeValue()
201                            .description("First frame (%t) to read from trajectory"));
202     options->addOption(DoubleOption("e").store(&impl_->endTime_).timeValue()
203                            .description("Last frame (%t) to read from trajectory"));
204     options->addOption(DoubleOption("dt").store(&impl_->deltaTime_).timeValue()
205                            .description("Only use frame if t MOD dt == first time (%t)"));
206
207     // Add time unit option.
208     settings.impl_->timeUnitManager.addTimeUnitOption(options, "tu");
209
210     // Add plot options.
211     settings.impl_->plotSettings.addOptions(options);
212
213     // Add common options for trajectory processing.
214     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
215     {
216         options->addOption(BooleanOption("rmpbc").store(&settings.impl_->bRmPBC)
217                                .description("Make molecules whole for each frame"));
218     }
219     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
220     {
221         options->addOption(BooleanOption("pbc").store(&settings.impl_->bPBC)
222                                .description("Use periodic boundary conditions for distance calculation"));
223     }
224 }
225
226
227 void
228 TrajectoryAnalysisRunnerCommon::scaleTimeOptions(Options *options)
229 {
230     impl_->settings_.impl_->timeUnitManager.scaleTimeOptions(options);
231 }
232
233
234 bool
235 TrajectoryAnalysisRunnerCommon::optionsFinished(Options *options)
236 {
237     if (impl_->bHelp_)
238     {
239         return false;
240     }
241
242     impl_->settings_.impl_->plotSettings.setTimeUnit(
243             impl_->settings_.impl_->timeUnitManager.timeUnit());
244
245     if (impl_->trjfile_.empty() && impl_->topfile_.empty())
246     {
247         GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
248     }
249
250     if (options->isSet("b"))
251         setTimeValue(TBEGIN, impl_->startTime_);
252     if (options->isSet("e"))
253         setTimeValue(TEND, impl_->endTime_);
254     if (options->isSet("dt"))
255         setTimeValue(TDELTA, impl_->deltaTime_);
256
257     return true;
258 }
259
260
261 void
262 TrajectoryAnalysisRunnerCommon::initIndexGroups(SelectionCollection *selections)
263 {
264     if (impl_->ndxfile_.empty())
265     {
266         // TODO: Initialize default selections
267         selections->setIndexGroups(NULL);
268     }
269     else
270     {
271         gmx_ana_indexgrps_init(&impl_->grps_, NULL, impl_->ndxfile_.c_str());
272         selections->setIndexGroups(impl_->grps_);
273     }
274 }
275
276
277 void
278 TrajectoryAnalysisRunnerCommon::doneIndexGroups(SelectionCollection *selections)
279 {
280     if (impl_->grps_ != NULL)
281     {
282         selections->setIndexGroups(NULL);
283         gmx_ana_indexgrps_free(impl_->grps_);
284         impl_->grps_ = NULL;
285     }
286 }
287
288
289 void
290 TrajectoryAnalysisRunnerCommon::initTopology(SelectionCollection *selections)
291 {
292     const TrajectoryAnalysisSettings &settings = impl_->settings_;
293     bool bRequireTop
294         = settings.hasFlag(TrajectoryAnalysisSettings::efRequireTop)
295           || selections->requiresTopology();
296     if (bRequireTop && impl_->topfile_.empty())
297     {
298         GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
299     }
300
301     // Load the topology if requested.
302     if (!impl_->topfile_.empty())
303     {
304         char  title[STRLEN];
305
306         snew(impl_->topInfo_.top_, 1);
307         impl_->topInfo_.bTop_ = read_tps_conf(impl_->topfile_.c_str(), title,
308                 impl_->topInfo_.top_, &impl_->topInfo_.ePBC_,
309                 &impl_->topInfo_.xtop_, NULL, impl_->topInfo_.boxtop_, TRUE);
310         if (hasTrajectory()
311             && !settings.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
312         {
313             sfree(impl_->topInfo_.xtop_);
314             impl_->topInfo_.xtop_ = NULL;
315         }
316     }
317
318     // Read the first frame if we don't know the maximum number of atoms
319     // otherwise.
320     int  natoms = -1;
321     if (!impl_->topInfo_.hasTopology())
322     {
323         initFirstFrame();
324         natoms = impl_->fr->natoms;
325     }
326     selections->setTopology(impl_->topInfo_.topology(), natoms);
327
328     /*
329     if (impl_->bSelDump)
330     {
331         gmx_ana_poscalc_coll_print_tree(stderr, impl_->pcc);
332         fprintf(stderr, "\n");
333     }
334     */
335 }
336
337
338 void
339 TrajectoryAnalysisRunnerCommon::initFirstFrame()
340 {
341     // Return if we have already initialized the trajectory.
342     if (impl_->fr)
343     {
344         return;
345     }
346     time_unit_t time_unit
347         = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
348     output_env_init(&impl_->oenv_, 0, NULL, time_unit, FALSE, exvgNONE, 0, 0);
349
350     int frflags = impl_->settings_.frflags();
351     frflags |= TRX_NEED_X;
352
353     snew(impl_->fr, 1);
354
355     const TopologyInformation &top = impl_->topInfo_;
356     if (hasTrajectory())
357     {
358         if (!read_first_frame(impl_->oenv_, &impl_->status_,
359                               impl_->trjfile_.c_str(), impl_->fr, frflags))
360         {
361             GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
362         }
363         impl_->bTrajOpen_ = true;
364
365         if (top.hasTopology() && impl_->fr->natoms > top.topology()->atoms.nr)
366         {
367             GMX_THROW(InconsistentInputError(formatString(
368                       "Trajectory (%d atoms) does not match topology (%d atoms)",
369                       impl_->fr->natoms, top.topology()->atoms.nr)));
370         }
371         // Check index groups if they have been initialized based on the topology.
372         /*
373         if (top)
374         {
375             for (int i = 0; i < impl_->sel->nr(); ++i)
376             {
377                 gmx_ana_index_check(impl_->sel->sel(i)->indexGroup(),
378                                     impl_->fr->natoms);
379             }
380         }
381         */
382     }
383     else
384     {
385         // Prepare a frame from topology information.
386         // TODO: Initialize more of the fields.
387         if (frflags & (TRX_NEED_V))
388         {
389             GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
390         }
391         if (frflags & (TRX_NEED_F))
392         {
393             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
394         }
395         impl_->fr->flags  = frflags;
396         impl_->fr->natoms = top.topology()->atoms.nr;
397         impl_->fr->bX     = TRUE;
398         snew(impl_->fr->x, impl_->fr->natoms);
399         memcpy(impl_->fr->x, top.xtop_,
400                sizeof(*impl_->fr->x) * impl_->fr->natoms);
401         impl_->fr->bBox   = TRUE;
402         copy_mat(const_cast<rvec *>(top.boxtop_), impl_->fr->box);
403     }
404
405     set_trxframe_ePBC(impl_->fr, top.ePBC());
406     if (top.hasTopology() && impl_->settings_.hasRmPBC())
407     {
408         impl_->gpbc_ = gmx_rmpbc_init(&top.topology()->idef, top.ePBC(),
409                                       impl_->fr->natoms, impl_->fr->box);
410     }
411 }
412
413
414 bool
415 TrajectoryAnalysisRunnerCommon::readNextFrame()
416 {
417     bool bContinue = false;
418     if (hasTrajectory())
419     {
420         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
421     }
422     if (!bContinue)
423     {
424         impl_->finishTrajectory();
425     }
426     return bContinue;
427 }
428
429
430 void
431 TrajectoryAnalysisRunnerCommon::initFrame()
432 {
433     if (impl_->gpbc_ != NULL)
434     {
435         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
436     }
437 }
438
439
440 TrajectoryAnalysisRunnerCommon::HelpFlags
441 TrajectoryAnalysisRunnerCommon::helpFlags() const
442 {
443     HelpFlags flags = 0;
444
445     if (!impl_->bQuiet_)
446     {
447         flags |= efHelpShowOptions;
448         if (impl_->bHelp_)
449         {
450             flags |= efHelpShowDescriptions;
451         }
452         if (impl_->bShowHidden_)
453         {
454             flags |= efHelpShowHidden;
455         }
456     }
457     return flags;
458 }
459
460 bool
461 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
462 {
463     return !impl_->trjfile_.empty();
464 }
465
466
467 const TopologyInformation &
468 TrajectoryAnalysisRunnerCommon::topologyInformation() const
469 {
470     return impl_->topInfo_;
471 }
472
473
474 t_trxframe &
475 TrajectoryAnalysisRunnerCommon::frame() const
476 {
477     GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
478     return *impl_->fr;
479 }
480
481 } // namespace gmx