Add readConfAndTopology
[gromacs.git] / src / gromacs / trajectoryanalysis / runnercommon.cpp
blobccb119fe808c244ee955cc72d53ea61852123aef
1 /*
2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010,2011,2012,2013,2014,2015,2016, 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.
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.
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.
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.
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.
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.
35 /*! \internal \file
36 * \brief
37 * Implements gmx::TrajectoryAnalysisRunnerCommon.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_trajectoryanalysis
42 #include "gmxpre.h"
44 #include "runnercommon.h"
46 #include <string.h>
48 #include <algorithm>
49 #include <string>
51 #include "gromacs/fileio/confio.h"
52 #include "gromacs/fileio/oenv.h"
53 #include "gromacs/fileio/timecontrol.h"
54 #include "gromacs/fileio/trxio.h"
55 #include "gromacs/math/vec.h"
56 #include "gromacs/options/basicoptions.h"
57 #include "gromacs/options/filenameoption.h"
58 #include "gromacs/options/ioptionscontainer.h"
59 #include "gromacs/pbcutil/rmpbc.h"
60 #include "gromacs/selection/selection.h"
61 #include "gromacs/selection/selectioncollection.h"
62 #include "gromacs/selection/selectionoption.h"
63 #include "gromacs/selection/selectionoptionbehavior.h"
64 #include "gromacs/topology/topology.h"
65 #include "gromacs/trajectory/trajectoryframe.h"
66 #include "gromacs/trajectoryanalysis/analysissettings.h"
67 #include "gromacs/utility/cstringutil.h"
68 #include "gromacs/utility/exceptions.h"
69 #include "gromacs/utility/gmxassert.h"
70 #include "gromacs/utility/programcontext.h"
71 #include "gromacs/utility/smalloc.h"
72 #include "gromacs/utility/stringutil.h"
74 #include "analysissettings-impl.h"
76 namespace gmx
79 class TrajectoryAnalysisRunnerCommon::Impl : public ITopologyProvider
81 public:
82 explicit Impl(TrajectoryAnalysisSettings *settings);
83 ~Impl();
85 bool hasTrajectory() const { return !trjfile_.empty(); }
87 void initTopology(bool required);
88 void initFirstFrame();
89 void initFrameIndexGroup();
90 void finishTrajectory();
92 // From ITopologyProvider
93 virtual t_topology *getTopology(bool required)
95 initTopology(required);
96 return topInfo_.topology();
98 virtual int getAtomCount()
100 if (!topInfo_.hasTopology())
102 if (trajectoryGroup_.isValid())
104 GMX_THROW(InconsistentInputError("-fgroup is only supported when -s is also specified"));
106 // Read the first frame if we don't know the maximum number of
107 // atoms otherwise.
108 initFirstFrame();
109 return fr->natoms;
111 return -1;
114 TrajectoryAnalysisSettings &settings_;
115 TopologyInformation topInfo_;
117 //! Name of the trajectory file (empty if not provided).
118 std::string trjfile_;
119 //! Name of the topology file (empty if no topology provided).
120 std::string topfile_;
121 Selection trajectoryGroup_;
122 double startTime_;
123 double endTime_;
124 double deltaTime_;
125 bool bStartTimeSet_;
126 bool bEndTimeSet_;
127 bool bDeltaTimeSet_;
129 bool bTrajOpen_;
130 //! The current frame, or \p NULL if no frame loaded yet.
131 t_trxframe *fr;
132 gmx_rmpbc_t gpbc_;
133 //! Used to store the status variable from read_first_frame().
134 t_trxstatus *status_;
135 gmx_output_env_t *oenv_;
139 TrajectoryAnalysisRunnerCommon::Impl::Impl(TrajectoryAnalysisSettings *settings)
140 : settings_(*settings),
141 startTime_(0.0), endTime_(0.0), deltaTime_(0.0),
142 bStartTimeSet_(false), bEndTimeSet_(false), bDeltaTimeSet_(false),
143 bTrajOpen_(false), fr(NULL), gpbc_(NULL), status_(NULL), oenv_(NULL)
148 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
150 finishTrajectory();
151 if (fr != nullptr)
153 // There doesn't seem to be a function for freeing frame data
154 sfree(fr->x);
155 sfree(fr->v);
156 sfree(fr->f);
157 sfree(fr->index);
158 sfree(fr);
160 if (oenv_ != nullptr)
162 output_env_done(oenv_);
166 void
167 TrajectoryAnalysisRunnerCommon::Impl::initTopology(bool required)
169 // Return immediately if the topology has already been loaded.
170 if (topInfo_.hasTopology())
172 return;
175 if (required && topfile_.empty())
177 GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
180 // Load the topology if requested.
181 if (!topfile_.empty())
183 snew(topInfo_.top_, 1);
184 topInfo_.bTop_ = read_tps_conf(topfile_.c_str(), topInfo_.top_, &topInfo_.ePBC_,
185 &topInfo_.xtop_, NULL, topInfo_.boxtop_, FALSE);
186 if (!topInfo_.top_->atoms.haveMass)
188 // Try to read masses from database, be silent about missing masses
189 atomsSetMassesBasedOnNames(&topInfo_.top_->atoms, FALSE);
191 if (hasTrajectory()
192 && !settings_.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
194 sfree(topInfo_.xtop_);
195 topInfo_.xtop_ = NULL;
200 void
201 TrajectoryAnalysisRunnerCommon::Impl::initFirstFrame()
203 // Return if we have already initialized the trajectory.
204 if (fr != NULL)
206 return;
208 time_unit_t time_unit
209 = static_cast<time_unit_t>(settings_.timeUnit() + 1);
210 output_env_init(&oenv_, getProgramContext(), time_unit, FALSE, exvgNONE, 0);
212 int frflags = settings_.frflags();
213 frflags |= TRX_NEED_X;
215 snew(fr, 1);
217 if (hasTrajectory())
219 if (!read_first_frame(oenv_, &status_, trjfile_.c_str(), fr, frflags))
221 GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
223 bTrajOpen_ = true;
225 if (topInfo_.hasTopology())
227 const int topologyAtomCount = topInfo_.topology()->atoms.nr;
228 if (fr->natoms > topologyAtomCount)
230 const std::string message
231 = formatString("Trajectory (%d atoms) does not match topology (%d atoms)",
232 fr->natoms, topologyAtomCount);
233 GMX_THROW(InconsistentInputError(message));
237 else
239 // Prepare a frame from topology information.
240 // TODO: Initialize more of the fields.
241 if (frflags & (TRX_NEED_V))
243 GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
245 if (frflags & (TRX_NEED_F))
247 GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
249 fr->natoms = topInfo_.topology()->atoms.nr;
250 fr->bX = TRUE;
251 snew(fr->x, fr->natoms);
252 memcpy(fr->x, topInfo_.xtop_,
253 sizeof(*fr->x) * fr->natoms);
254 fr->bBox = TRUE;
255 copy_mat(topInfo_.boxtop_, fr->box);
258 set_trxframe_ePBC(fr, topInfo_.ePBC());
259 if (topInfo_.hasTopology() && settings_.hasRmPBC())
261 gpbc_ = gmx_rmpbc_init(&topInfo_.topology()->idef, topInfo_.ePBC(),
262 fr->natoms);
266 void
267 TrajectoryAnalysisRunnerCommon::Impl::initFrameIndexGroup()
269 if (!trajectoryGroup_.isValid())
271 return;
273 GMX_RELEASE_ASSERT(bTrajOpen_,
274 "Trajectory index only makes sense with a real trajectory");
275 if (trajectoryGroup_.atomCount() != fr->natoms)
277 const std::string message = formatString(
278 "Selection specified with -fgroup has %d atoms, but "
279 "the trajectory (-f) has %d atoms.",
280 trajectoryGroup_.atomCount(), fr->natoms);
281 GMX_THROW(InconsistentInputError(message));
283 fr->bIndex = TRUE;
284 snew(fr->index, trajectoryGroup_.atomCount());
285 std::copy(trajectoryGroup_.atomIndices().begin(),
286 trajectoryGroup_.atomIndices().end(),
287 fr->index);
290 void
291 TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
293 if (bTrajOpen_)
295 close_trx(status_);
296 bTrajOpen_ = false;
298 if (gpbc_ != NULL)
300 gmx_rmpbc_done(gpbc_);
301 gpbc_ = NULL;
305 /*********************************************************************
306 * TrajectoryAnalysisRunnerCommon
309 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(
310 TrajectoryAnalysisSettings *settings)
311 : impl_(new Impl(settings))
316 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon()
321 ITopologyProvider *
322 TrajectoryAnalysisRunnerCommon::topologyProvider()
324 return impl_.get();
328 void
329 TrajectoryAnalysisRunnerCommon::initOptions(IOptionsContainer *options,
330 TimeUnitBehavior *timeUnitBehavior)
332 TrajectoryAnalysisSettings &settings = impl_->settings_;
334 // Add common file name arguments.
335 options->addOption(FileNameOption("f")
336 .filetype(eftTrajectory).inputFile()
337 .store(&impl_->trjfile_)
338 .defaultBasename("traj")
339 .description("Input trajectory or single configuration"));
340 options->addOption(FileNameOption("s")
341 .filetype(eftTopology).inputFile()
342 .store(&impl_->topfile_)
343 .defaultBasename("topol")
344 .description("Input structure"));
346 // Add options for trajectory time control.
347 options->addOption(DoubleOption("b")
348 .store(&impl_->startTime_).storeIsSet(&impl_->bStartTimeSet_)
349 .timeValue()
350 .description("First frame (%t) to read from trajectory"));
351 options->addOption(DoubleOption("e")
352 .store(&impl_->endTime_).storeIsSet(&impl_->bEndTimeSet_)
353 .timeValue()
354 .description("Last frame (%t) to read from trajectory"));
355 options->addOption(DoubleOption("dt")
356 .store(&impl_->deltaTime_).storeIsSet(&impl_->bDeltaTimeSet_)
357 .timeValue()
358 .description("Only use frame if t MOD dt == first time (%t)"));
360 // Add time unit option.
361 timeUnitBehavior->setTimeUnitFromEnvironment();
362 timeUnitBehavior->addTimeUnitOption(options, "tu");
363 timeUnitBehavior->setTimeUnitStore(&impl_->settings_.impl_->timeUnit);
365 options->addOption(SelectionOption("fgroup")
366 .store(&impl_->trajectoryGroup_)
367 .onlySortedAtoms().onlyStatic()
368 .description("Atoms stored in the trajectory file "
369 "(if not set, assume first N atoms)"));
371 // Add plot options.
372 settings.impl_->plotSettings.initOptions(options);
374 // Add common options for trajectory processing.
375 if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
377 options->addOption(BooleanOption("rmpbc").store(&settings.impl_->bRmPBC)
378 .description("Make molecules whole for each frame"));
380 if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
382 options->addOption(BooleanOption("pbc").store(&settings.impl_->bPBC)
383 .description("Use periodic boundary conditions for distance calculation"));
388 void
389 TrajectoryAnalysisRunnerCommon::optionsFinished()
391 if (impl_->trjfile_.empty() && impl_->topfile_.empty())
393 GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
396 if (impl_->trajectoryGroup_.isValid() && impl_->trjfile_.empty())
398 GMX_THROW(InconsistentInputError("-fgroup only makes sense together with a trajectory (-f)"));
401 impl_->settings_.impl_->plotSettings.setTimeUnit(impl_->settings_.timeUnit());
403 if (impl_->bStartTimeSet_)
405 setTimeValue(TBEGIN, impl_->startTime_);
407 if (impl_->bEndTimeSet_)
409 setTimeValue(TEND, impl_->endTime_);
411 if (impl_->bDeltaTimeSet_)
413 setTimeValue(TDELTA, impl_->deltaTime_);
418 void
419 TrajectoryAnalysisRunnerCommon::initTopology()
421 const bool topologyRequired =
422 impl_->settings_.hasFlag(TrajectoryAnalysisSettings::efRequireTop);
423 impl_->initTopology(topologyRequired);
427 void
428 TrajectoryAnalysisRunnerCommon::initFirstFrame()
430 impl_->initFirstFrame();
434 void
435 TrajectoryAnalysisRunnerCommon::initFrameIndexGroup()
437 impl_->initFrameIndexGroup();
441 bool
442 TrajectoryAnalysisRunnerCommon::readNextFrame()
444 bool bContinue = false;
445 if (hasTrajectory())
447 bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
449 if (!bContinue)
451 impl_->finishTrajectory();
453 return bContinue;
457 void
458 TrajectoryAnalysisRunnerCommon::initFrame()
460 if (impl_->gpbc_ != NULL)
462 gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
467 bool
468 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
470 return impl_->hasTrajectory();
474 const TopologyInformation &
475 TrajectoryAnalysisRunnerCommon::topologyInformation() const
477 return impl_->topInfo_;
481 t_trxframe &
482 TrajectoryAnalysisRunnerCommon::frame() const
484 GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
485 return *impl_->fr;
488 } // namespace gmx