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