2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010-2018, The GROMACS development team.
5 * Copyright (c) 2019,2020, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
38 * Implements gmx::TrajectoryAnalysisRunnerCommon.
40 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_trajectoryanalysis
45 #include "runnercommon.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/trajectoryanalysis/topologyinformation.h"
68 #include "gromacs/utility/cstringutil.h"
69 #include "gromacs/utility/exceptions.h"
70 #include "gromacs/utility/gmxassert.h"
71 #include "gromacs/utility/programcontext.h"
72 #include "gromacs/utility/smalloc.h"
73 #include "gromacs/utility/stringutil.h"
75 #include "analysissettings_impl.h"
80 class TrajectoryAnalysisRunnerCommon::Impl : public ITopologyProvider
83 explicit Impl(TrajectoryAnalysisSettings* settings);
86 bool hasTrajectory() const { return !trjfile_.empty(); }
88 void initTopology(bool required);
89 void initFirstFrame();
90 void initFrameIndexGroup();
91 void finishTrajectory();
93 // From ITopologyProvider
94 gmx_mtop_t* getTopology(bool required) override
96 initTopology(required);
97 return topInfo_.mtop_.get();
99 int getAtomCount() override
101 if (!topInfo_.hasTopology())
103 if (trajectoryGroup_.isValid())
105 GMX_THROW(InconsistentInputError(
106 "-fgroup is only supported when -s is also specified"));
108 // Read the first frame if we don't know the maximum number of
116 TrajectoryAnalysisSettings& settings_;
117 TopologyInformation topInfo_;
119 //! Name of the trajectory file (empty if not provided).
120 std::string trjfile_;
121 //! Name of the topology file (empty if no topology provided).
122 std::string topfile_;
123 Selection trajectoryGroup_;
132 //! The current frame, or \p NULL if no frame loaded yet.
135 //! Used to store the status variable from read_first_frame().
136 t_trxstatus* status_;
137 gmx_output_env_t* oenv_;
141 TrajectoryAnalysisRunnerCommon::Impl::Impl(TrajectoryAnalysisSettings* settings) :
142 settings_(*settings),
146 bStartTimeSet_(false),
148 bDeltaTimeSet_(false),
158 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
163 // There doesn't seem to be a function for freeing frame data
170 if (oenv_ != nullptr)
172 output_env_done(oenv_);
176 void TrajectoryAnalysisRunnerCommon::Impl::initTopology(bool required)
178 // Return immediately if the topology has already been loaded.
179 if (topInfo_.hasTopology())
184 if (required && topfile_.empty())
186 GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
189 // Load the topology if requested.
190 if (!topfile_.empty())
192 topInfo_.fillFromInputFile(topfile_);
193 if (hasTrajectory() && !settings_.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
195 topInfo_.xtop_.clear();
197 if (hasTrajectory() && !settings_.hasFlag(TrajectoryAnalysisSettings::efUseTopV))
199 topInfo_.vtop_.clear();
204 void TrajectoryAnalysisRunnerCommon::Impl::initFirstFrame()
206 // Return if we have already initialized the trajectory.
211 output_env_init(&oenv_, getProgramContext(), settings_.timeUnit(), FALSE, XvgFormat::None, 0);
213 int frflags = settings_.frflags();
214 frflags |= TRX_NEED_X;
220 if (!read_first_frame(oenv_, &status_, trjfile_.c_str(), fr, frflags))
222 GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
226 if (topInfo_.hasTopology())
228 const int topologyAtomCount = topInfo_.mtop()->natoms;
229 if (fr->natoms > topologyAtomCount)
231 const std::string message =
232 formatString("Trajectory (%d atoms) does not match topology (%d atoms)",
235 GMX_THROW(InconsistentInputError(message));
241 // Prepare a frame from topology information.
242 if (frflags & (TRX_NEED_F))
244 GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
246 fr->natoms = topInfo_.mtop()->natoms;
248 snew(fr->x, fr->natoms);
249 memcpy(fr->x, topInfo_.xtop_.data(), sizeof(*fr->x) * fr->natoms);
250 if (frflags & (TRX_NEED_V))
252 if (topInfo_.vtop_.empty())
254 GMX_THROW(InvalidInputError(
255 "Velocities were required, but could not be read from the topology file"));
258 snew(fr->v, fr->natoms);
259 memcpy(fr->v, topInfo_.vtop_.data(), sizeof(*fr->v) * fr->natoms);
262 copy_mat(topInfo_.boxtop_, fr->box);
265 setTrxFramePbcType(fr, topInfo_.pbcType());
266 if (topInfo_.hasTopology() && settings_.hasRmPBC())
268 gpbc_ = gmx_rmpbc_init(topInfo_);
272 void TrajectoryAnalysisRunnerCommon::Impl::initFrameIndexGroup()
274 if (!trajectoryGroup_.isValid())
278 GMX_RELEASE_ASSERT(bTrajOpen_, "Trajectory index only makes sense with a real trajectory");
279 if (trajectoryGroup_.atomCount() != fr->natoms)
281 const std::string message = formatString(
282 "Selection specified with -fgroup has %d atoms, but "
283 "the trajectory (-f) has %d atoms.",
284 trajectoryGroup_.atomCount(),
286 GMX_THROW(InconsistentInputError(message));
289 snew(fr->index, trajectoryGroup_.atomCount());
290 std::copy(trajectoryGroup_.atomIndices().begin(), trajectoryGroup_.atomIndices().end(), fr->index);
293 void TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
300 if (gpbc_ != nullptr)
302 gmx_rmpbc_done(gpbc_);
307 /*********************************************************************
308 * TrajectoryAnalysisRunnerCommon
311 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(TrajectoryAnalysisSettings* settings) :
312 impl_(new Impl(settings))
317 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon() {}
320 ITopologyProvider* TrajectoryAnalysisRunnerCommon::topologyProvider()
326 void TrajectoryAnalysisRunnerCommon::initOptions(IOptionsContainer* options, TimeUnitBehavior* timeUnitBehavior)
328 TrajectoryAnalysisSettings& settings = impl_->settings_;
330 // Add common file name arguments.
331 options->addOption(FileNameOption("f")
332 .filetype(eftTrajectory)
334 .store(&impl_->trjfile_)
335 .defaultBasename("traj")
336 .description("Input trajectory or single configuration"));
337 options->addOption(FileNameOption("s")
338 .filetype(eftTopology)
340 .store(&impl_->topfile_)
341 .defaultBasename("topol")
342 .description("Input structure"));
344 // Add options for trajectory time control.
345 options->addOption(DoubleOption("b")
346 .store(&impl_->startTime_)
347 .storeIsSet(&impl_->bStartTimeSet_)
349 .description("First frame (%t) to read from trajectory"));
350 options->addOption(DoubleOption("e")
351 .store(&impl_->endTime_)
352 .storeIsSet(&impl_->bEndTimeSet_)
354 .description("Last frame (%t) to read from trajectory"));
355 options->addOption(DoubleOption("dt")
356 .store(&impl_->deltaTime_)
357 .storeIsSet(&impl_->bDeltaTimeSet_)
359 .description("Only use frame if t MOD dt == first time (%t)"));
361 // Add time unit option.
362 timeUnitBehavior->setTimeUnitFromEnvironment();
363 timeUnitBehavior->addTimeUnitOption(options, "tu");
364 timeUnitBehavior->setTimeUnitStore(&impl_->settings_.impl_->timeUnit);
366 options->addOption(SelectionOption("fgroup")
367 .store(&impl_->trajectoryGroup_)
370 .description("Atoms stored in the trajectory file "
371 "(if not set, assume first N atoms)"));
374 settings.impl_->plotSettings.initOptions(options);
376 // Add common options for trajectory processing.
377 if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
380 BooleanOption("rmpbc").store(&settings.impl_->bRmPBC).description("Make molecules whole for each frame"));
382 if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
386 .store(&settings.impl_->bPBC)
387 .description("Use periodic boundary conditions for distance calculation"));
392 void TrajectoryAnalysisRunnerCommon::optionsFinished()
394 if (impl_->trjfile_.empty() && impl_->topfile_.empty())
396 GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
399 if (impl_->trajectoryGroup_.isValid() && impl_->trjfile_.empty())
402 InconsistentInputError("-fgroup only makes sense together with a trajectory (-f)"));
405 impl_->settings_.impl_->plotSettings.setTimeUnit(impl_->settings_.timeUnit());
407 if (impl_->bStartTimeSet_)
409 setTimeValue(TBEGIN, impl_->startTime_);
411 if (impl_->bEndTimeSet_)
413 setTimeValue(TEND, impl_->endTime_);
415 if (impl_->bDeltaTimeSet_)
417 setTimeValue(TDELTA, impl_->deltaTime_);
422 void TrajectoryAnalysisRunnerCommon::initTopology()
424 const bool topologyRequired = impl_->settings_.hasFlag(TrajectoryAnalysisSettings::efRequireTop);
425 impl_->initTopology(topologyRequired);
429 void TrajectoryAnalysisRunnerCommon::initFirstFrame()
431 impl_->initFirstFrame();
435 void TrajectoryAnalysisRunnerCommon::initFrameIndexGroup()
437 impl_->initFrameIndexGroup();
441 bool TrajectoryAnalysisRunnerCommon::readNextFrame()
443 bool bContinue = false;
446 bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
450 impl_->finishTrajectory();
456 void TrajectoryAnalysisRunnerCommon::initFrame()
458 if (impl_->gpbc_ != nullptr)
460 gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
465 bool TrajectoryAnalysisRunnerCommon::hasTrajectory() const
467 return impl_->hasTrajectory();
471 const TopologyInformation& TrajectoryAnalysisRunnerCommon::topologyInformation() const
473 return impl_->topInfo_;
477 t_trxframe& TrajectoryAnalysisRunnerCommon::frame() const
479 GMX_RELEASE_ASSERT(impl_->fr != nullptr, "Frame not available when accessed");