Merge branch 'master' into pygromacs
[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,2014,2015, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source 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 "gmxpre.h"
43
44 #include "runnercommon.h"
45
46 #include <string.h>
47
48 #include "gromacs/fileio/confio.h"
49 #include "gromacs/fileio/timecontrol.h"
50 #include "gromacs/fileio/trx.h"
51 #include "gromacs/fileio/trxio.h"
52 #include "gromacs/legacyheaders/oenv.h"
53 #include "gromacs/math/vec.h"
54 #include "gromacs/options/basicoptions.h"
55 #include "gromacs/options/filenameoption.h"
56 #include "gromacs/options/ioptionscontainer.h"
57 #include "gromacs/options/options.h"
58 #include "gromacs/pbcutil/rmpbc.h"
59 #include "gromacs/selection/indexutil.h"
60 #include "gromacs/selection/selectioncollection.h"
61 #include "gromacs/selection/selectionfileoption.h"
62 #include "gromacs/topology/topology.h"
63 #include "gromacs/trajectoryanalysis/analysissettings.h"
64 #include "gromacs/utility/cstringutil.h"
65 #include "gromacs/utility/exceptions.h"
66 #include "gromacs/utility/gmxassert.h"
67 #include "gromacs/utility/programcontext.h"
68 #include "gromacs/utility/smalloc.h"
69 #include "gromacs/utility/stringutil.h"
70
71 #include "analysissettings-impl.h"
72
73 namespace gmx
74 {
75
76 class TrajectoryAnalysisRunnerCommon::Impl
77 {
78     public:
79         Impl(TrajectoryAnalysisSettings *settings);
80         ~Impl();
81
82         void finishTrajectory();
83
84         TrajectoryAnalysisSettings &settings_;
85         TopologyInformation         topInfo_;
86
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         bool                        bStartTimeSet_;
97         bool                        bEndTimeSet_;
98         bool                        bDeltaTimeSet_;
99
100         gmx_ana_indexgrps_t        *grps_;
101         bool                        bTrajOpen_;
102         //! The current frame, or \p NULL if no frame loaded yet.
103         t_trxframe                 *fr;
104         gmx_rmpbc_t                 gpbc_;
105         //! Used to store the status variable from read_first_frame().
106         t_trxstatus                *status_;
107         output_env_t                oenv_;
108 };
109
110
111 TrajectoryAnalysisRunnerCommon::Impl::Impl(TrajectoryAnalysisSettings *settings)
112     : settings_(*settings),
113       startTime_(0.0), endTime_(0.0), deltaTime_(0.0),
114       bStartTimeSet_(false), bEndTimeSet_(false), bDeltaTimeSet_(false),
115       grps_(NULL),
116       bTrajOpen_(false), fr(NULL), gpbc_(NULL), status_(NULL), oenv_(NULL)
117 {
118 }
119
120
121 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
122 {
123     if (grps_ != NULL)
124     {
125         gmx_ana_indexgrps_free(grps_);
126     }
127     finishTrajectory();
128     if (fr)
129     {
130         // There doesn't seem to be a function for freeing frame data
131         sfree(fr->x);
132         sfree(fr->v);
133         sfree(fr->f);
134         sfree(fr);
135     }
136     if (oenv_ != NULL)
137     {
138         output_env_done(oenv_);
139     }
140 }
141
142
143 void
144 TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
145 {
146     if (bTrajOpen_)
147     {
148         close_trx(status_);
149         bTrajOpen_ = false;
150     }
151     if (gpbc_ != NULL)
152     {
153         gmx_rmpbc_done(gpbc_);
154         gpbc_ = NULL;
155     }
156 }
157
158 /*********************************************************************
159  * TrajectoryAnalysisRunnerCommon
160  */
161
162 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(
163         TrajectoryAnalysisSettings *settings)
164     : impl_(new Impl(settings))
165 {
166 }
167
168
169 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon()
170 {
171 }
172
173
174 void
175 TrajectoryAnalysisRunnerCommon::initOptions(IOptionsContainer *options)
176 {
177     TrajectoryAnalysisSettings &settings = impl_->settings_;
178
179     // Add common file name arguments.
180     options->addOption(FileNameOption("f")
181                            .filetype(eftTrajectory).inputFile()
182                            .store(&impl_->trjfile_)
183                            .defaultBasename("traj")
184                            .description("Input trajectory or single configuration"));
185     options->addOption(FileNameOption("s")
186                            .filetype(eftTopology).inputFile()
187                            .store(&impl_->topfile_)
188                            .defaultBasename("topol")
189                            .description("Input structure"));
190     options->addOption(FileNameOption("n")
191                            .filetype(eftIndex).inputFile()
192                            .store(&impl_->ndxfile_)
193                            .defaultBasename("index")
194                            .description("Extra index groups"));
195
196     // Add options for trajectory time control.
197     options->addOption(DoubleOption("b")
198                            .store(&impl_->startTime_).storeIsSet(&impl_->bStartTimeSet_)
199                            .timeValue()
200                            .description("First frame (%t) to read from trajectory"));
201     options->addOption(DoubleOption("e")
202                            .store(&impl_->endTime_).storeIsSet(&impl_->bEndTimeSet_)
203                            .timeValue()
204                            .description("Last frame (%t) to read from trajectory"));
205     options->addOption(DoubleOption("dt")
206                            .store(&impl_->deltaTime_).storeIsSet(&impl_->bDeltaTimeSet_)
207                            .timeValue()
208                            .description("Only use frame if t MOD dt == first time (%t)"));
209
210     // Add time unit option.
211     settings.impl_->timeUnitManager.addTimeUnitOption(options, "tu");
212
213     // Add plot options.
214     settings.impl_->plotSettings.initOptions(options);
215
216     // Add common options for trajectory processing.
217     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
218     {
219         options->addOption(BooleanOption("rmpbc").store(&settings.impl_->bRmPBC)
220                                .description("Make molecules whole for each frame"));
221     }
222     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
223     {
224         options->addOption(BooleanOption("pbc").store(&settings.impl_->bPBC)
225                                .description("Use periodic boundary conditions for distance calculation"));
226     }
227
228     options->addOption(SelectionFileOption("sf"));
229 }
230
231
232 void
233 TrajectoryAnalysisRunnerCommon::scaleTimeOptions(Options *options)
234 {
235     impl_->settings_.impl_->timeUnitManager.scaleTimeOptions(options);
236 }
237
238
239 void
240 TrajectoryAnalysisRunnerCommon::optionsFinished()
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 (impl_->bStartTimeSet_)
251     {
252         setTimeValue(TBEGIN, impl_->startTime_);
253     }
254     if (impl_->bEndTimeSet_)
255     {
256         setTimeValue(TEND, impl_->endTime_);
257     }
258     if (impl_->bDeltaTimeSet_)
259     {
260         setTimeValue(TDELTA, impl_->deltaTime_);
261     }
262 }
263
264
265 void
266 TrajectoryAnalysisRunnerCommon::initIndexGroups(SelectionCollection *selections,
267                                                 bool                 bUseDefaults)
268 {
269     if (impl_->ndxfile_.empty())
270     {
271         if (!bUseDefaults)
272         {
273             selections->setIndexGroups(NULL);
274             return;
275         }
276         initTopology(selections);
277     }
278     const char *const ndxfile
279         = (!impl_->ndxfile_.empty() ? impl_->ndxfile_.c_str() : NULL);
280     gmx_ana_indexgrps_init(&impl_->grps_, impl_->topInfo_.topology(), ndxfile);
281     selections->setIndexGroups(impl_->grps_);
282 }
283
284
285 void
286 TrajectoryAnalysisRunnerCommon::doneIndexGroups(SelectionCollection *selections)
287 {
288     if (impl_->grps_ != NULL)
289     {
290         selections->setIndexGroups(NULL);
291         gmx_ana_indexgrps_free(impl_->grps_);
292         impl_->grps_ = NULL;
293     }
294 }
295
296 void
297 TrajectoryAnalysisRunnerCommon::initTopology(SelectionCollection *selections)
298 {
299     const TrajectoryAnalysisSettings &settings = impl_->settings_;
300     const 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() && !impl_->topInfo_.hasTopology())
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_, getProgramContext(), time_unit, FALSE, exvgNONE, 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     }
379     else
380     {
381         // Prepare a frame from topology information.
382         // TODO: Initialize more of the fields.
383         if (frflags & (TRX_NEED_V))
384         {
385             GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
386         }
387         if (frflags & (TRX_NEED_F))
388         {
389             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
390         }
391         impl_->fr->flags  = frflags;
392         impl_->fr->natoms = top.topology()->atoms.nr;
393         impl_->fr->bX     = TRUE;
394         snew(impl_->fr->x, impl_->fr->natoms);
395         memcpy(impl_->fr->x, top.xtop_,
396                sizeof(*impl_->fr->x) * impl_->fr->natoms);
397         impl_->fr->bBox   = TRUE;
398         copy_mat(const_cast<rvec *>(top.boxtop_), impl_->fr->box);
399     }
400
401     set_trxframe_ePBC(impl_->fr, top.ePBC());
402     if (top.hasTopology() && impl_->settings_.hasRmPBC())
403     {
404         impl_->gpbc_ = gmx_rmpbc_init(&top.topology()->idef, top.ePBC(),
405                                       impl_->fr->natoms);
406     }
407 }
408
409
410 bool
411 TrajectoryAnalysisRunnerCommon::readNextFrame()
412 {
413     bool bContinue = false;
414     if (hasTrajectory())
415     {
416         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
417     }
418     if (!bContinue)
419     {
420         impl_->finishTrajectory();
421     }
422     return bContinue;
423 }
424
425
426 void
427 TrajectoryAnalysisRunnerCommon::initFrame()
428 {
429     if (impl_->gpbc_ != NULL)
430     {
431         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
432     }
433 }
434
435
436 bool
437 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
438 {
439     return !impl_->trjfile_.empty();
440 }
441
442
443 const TopologyInformation &
444 TrajectoryAnalysisRunnerCommon::topologyInformation() const
445 {
446     return impl_->topInfo_;
447 }
448
449
450 t_trxframe &
451 TrajectoryAnalysisRunnerCommon::frame() const
452 {
453     GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
454     return *impl_->fr;
455 }
456
457 } // namespace gmx