Update my e-mail address on author lines.
[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@gmail.com>
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     {
253         setTimeValue(TBEGIN, impl_->startTime_);
254     }
255     if (options->isSet("e"))
256     {
257         setTimeValue(TEND, impl_->endTime_);
258     }
259     if (options->isSet("dt"))
260     {
261         setTimeValue(TDELTA, impl_->deltaTime_);
262     }
263
264     return true;
265 }
266
267
268 void
269 TrajectoryAnalysisRunnerCommon::initIndexGroups(SelectionCollection *selections)
270 {
271     if (impl_->ndxfile_.empty())
272     {
273         // TODO: Initialize default selections
274         selections->setIndexGroups(NULL);
275     }
276     else
277     {
278         gmx_ana_indexgrps_init(&impl_->grps_, NULL, impl_->ndxfile_.c_str());
279         selections->setIndexGroups(impl_->grps_);
280     }
281 }
282
283
284 void
285 TrajectoryAnalysisRunnerCommon::doneIndexGroups(SelectionCollection *selections)
286 {
287     if (impl_->grps_ != NULL)
288     {
289         selections->setIndexGroups(NULL);
290         gmx_ana_indexgrps_free(impl_->grps_);
291         impl_->grps_ = NULL;
292     }
293 }
294
295
296 void
297 TrajectoryAnalysisRunnerCommon::initTopology(SelectionCollection *selections)
298 {
299     const TrajectoryAnalysisSettings &settings = impl_->settings_;
300     bool bRequireTop
301         = settings.hasFlag(TrajectoryAnalysisSettings::efRequireTop)
302             || selections->requiresTopology();
303     if (bRequireTop && impl_->topfile_.empty())
304     {
305         GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
306     }
307
308     // Load the topology if requested.
309     if (!impl_->topfile_.empty())
310     {
311         char  title[STRLEN];
312
313         snew(impl_->topInfo_.top_, 1);
314         impl_->topInfo_.bTop_ = read_tps_conf(impl_->topfile_.c_str(), title,
315                                               impl_->topInfo_.top_, &impl_->topInfo_.ePBC_,
316                                               &impl_->topInfo_.xtop_, NULL, impl_->topInfo_.boxtop_, TRUE);
317         if (hasTrajectory()
318             && !settings.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
319         {
320             sfree(impl_->topInfo_.xtop_);
321             impl_->topInfo_.xtop_ = NULL;
322         }
323     }
324
325     // Read the first frame if we don't know the maximum number of atoms
326     // otherwise.
327     int  natoms = -1;
328     if (!impl_->topInfo_.hasTopology())
329     {
330         initFirstFrame();
331         natoms = impl_->fr->natoms;
332     }
333     selections->setTopology(impl_->topInfo_.topology(), natoms);
334
335     /*
336        if (impl_->bSelDump)
337        {
338         gmx_ana_poscalc_coll_print_tree(stderr, impl_->pcc);
339         fprintf(stderr, "\n");
340        }
341      */
342 }
343
344
345 void
346 TrajectoryAnalysisRunnerCommon::initFirstFrame()
347 {
348     // Return if we have already initialized the trajectory.
349     if (impl_->fr)
350     {
351         return;
352     }
353     time_unit_t time_unit
354         = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
355     output_env_init(&impl_->oenv_, 0, NULL, time_unit, FALSE, exvgNONE, 0, 0);
356
357     int frflags = impl_->settings_.frflags();
358     frflags |= TRX_NEED_X;
359
360     snew(impl_->fr, 1);
361
362     const TopologyInformation &top = impl_->topInfo_;
363     if (hasTrajectory())
364     {
365         if (!read_first_frame(impl_->oenv_, &impl_->status_,
366                               impl_->trjfile_.c_str(), impl_->fr, frflags))
367         {
368             GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
369         }
370         impl_->bTrajOpen_ = true;
371
372         if (top.hasTopology() && impl_->fr->natoms > top.topology()->atoms.nr)
373         {
374             GMX_THROW(InconsistentInputError(formatString(
375                                                      "Trajectory (%d atoms) does not match topology (%d atoms)",
376                                                      impl_->fr->natoms, top.topology()->atoms.nr)));
377         }
378         // Check index groups if they have been initialized based on the topology.
379         /*
380            if (top)
381            {
382             for (int i = 0; i < impl_->sel->nr(); ++i)
383             {
384                 gmx_ana_index_check(impl_->sel->sel(i)->indexGroup(),
385                                     impl_->fr->natoms);
386             }
387            }
388          */
389     }
390     else
391     {
392         // Prepare a frame from topology information.
393         // TODO: Initialize more of the fields.
394         if (frflags & (TRX_NEED_V))
395         {
396             GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
397         }
398         if (frflags & (TRX_NEED_F))
399         {
400             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
401         }
402         impl_->fr->flags  = frflags;
403         impl_->fr->natoms = top.topology()->atoms.nr;
404         impl_->fr->bX     = TRUE;
405         snew(impl_->fr->x, impl_->fr->natoms);
406         memcpy(impl_->fr->x, top.xtop_,
407                sizeof(*impl_->fr->x) * impl_->fr->natoms);
408         impl_->fr->bBox   = TRUE;
409         copy_mat(const_cast<rvec *>(top.boxtop_), impl_->fr->box);
410     }
411
412     set_trxframe_ePBC(impl_->fr, top.ePBC());
413     if (top.hasTopology() && impl_->settings_.hasRmPBC())
414     {
415         impl_->gpbc_ = gmx_rmpbc_init(&top.topology()->idef, top.ePBC(),
416                                       impl_->fr->natoms, impl_->fr->box);
417     }
418 }
419
420
421 bool
422 TrajectoryAnalysisRunnerCommon::readNextFrame()
423 {
424     bool bContinue = false;
425     if (hasTrajectory())
426     {
427         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
428     }
429     if (!bContinue)
430     {
431         impl_->finishTrajectory();
432     }
433     return bContinue;
434 }
435
436
437 void
438 TrajectoryAnalysisRunnerCommon::initFrame()
439 {
440     if (impl_->gpbc_ != NULL)
441     {
442         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
443     }
444 }
445
446
447 TrajectoryAnalysisRunnerCommon::HelpFlags
448 TrajectoryAnalysisRunnerCommon::helpFlags() const
449 {
450     HelpFlags flags = 0;
451
452     if (!impl_->bQuiet_)
453     {
454         flags |= efHelpShowOptions;
455         if (impl_->bHelp_)
456         {
457             flags |= efHelpShowDescriptions;
458         }
459         if (impl_->bShowHidden_)
460         {
461             flags |= efHelpShowHidden;
462         }
463     }
464     return flags;
465 }
466
467 bool
468 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
469 {
470     return !impl_->trjfile_.empty();
471 }
472
473
474 const TopologyInformation &
475 TrajectoryAnalysisRunnerCommon::topologyInformation() const
476 {
477     return impl_->topInfo_;
478 }
479
480
481 t_trxframe &
482 TrajectoryAnalysisRunnerCommon::frame() const
483 {
484     GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
485     return *impl_->fr;
486 }
487
488 } // namespace gmx