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