Rename all source files from - to _ for consistency.
[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,2016,2017,2018,2019, 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 <cstring>
47
48 #include <algorithm>
49 #include <string>
50
51 #include "gromacs/fileio/oenv.h"
52 #include "gromacs/fileio/timecontrol.h"
53 #include "gromacs/fileio/trxio.h"
54 #include "gromacs/math/vec.h"
55 #include "gromacs/options/basicoptions.h"
56 #include "gromacs/options/filenameoption.h"
57 #include "gromacs/options/ioptionscontainer.h"
58 #include "gromacs/pbcutil/rmpbc.h"
59 #include "gromacs/selection/selection.h"
60 #include "gromacs/selection/selectioncollection.h"
61 #include "gromacs/selection/selectionoption.h"
62 #include "gromacs/selection/selectionoptionbehavior.h"
63 #include "gromacs/topology/topology.h"
64 #include "gromacs/trajectory/trajectoryframe.h"
65 #include "gromacs/trajectoryanalysis/analysissettings.h"
66 #include "gromacs/trajectoryanalysis/topologyinformation.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"
73
74 #include "analysissettings_impl.h"
75
76 namespace gmx
77 {
78
79 class TrajectoryAnalysisRunnerCommon::Impl : public ITopologyProvider
80 {
81     public:
82         explicit Impl(TrajectoryAnalysisSettings *settings);
83         ~Impl() override;
84
85         bool hasTrajectory() const { return !trjfile_.empty(); }
86
87         void initTopology(bool required);
88         void initFirstFrame();
89         void initFrameIndexGroup();
90         void finishTrajectory();
91
92         // From ITopologyProvider
93         gmx_mtop_t *getTopology(bool required) override
94         {
95             initTopology(required);
96             return topInfo_.mtop_.get();
97         }
98         int getAtomCount() override
99         {
100             if (!topInfo_.hasTopology())
101             {
102                 if (trajectoryGroup_.isValid())
103                 {
104                     GMX_THROW(InconsistentInputError("-fgroup is only supported when -s is also specified"));
105                 }
106                 // Read the first frame if we don't know the maximum number of
107                 // atoms otherwise.
108                 initFirstFrame();
109                 return fr->natoms;
110             }
111             return -1;
112         }
113
114         TrajectoryAnalysisSettings &settings_;
115         TopologyInformation         topInfo_;
116
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_;
128
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_;
136 };
137
138
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(nullptr), gpbc_(nullptr), status_(nullptr), oenv_(nullptr)
144 {
145 }
146
147
148 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
149 {
150     finishTrajectory();
151     if (fr != nullptr)
152     {
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);
159     }
160     if (oenv_ != nullptr)
161     {
162         output_env_done(oenv_);
163     }
164 }
165
166 void
167 TrajectoryAnalysisRunnerCommon::Impl::initTopology(bool required)
168 {
169     // Return immediately if the topology has already been loaded.
170     if (topInfo_.hasTopology())
171     {
172         return;
173     }
174
175     if (required && topfile_.empty())
176     {
177         GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
178     }
179
180     // Load the topology if requested.
181     if (!topfile_.empty())
182     {
183         topInfo_.fillFromInputFile(topfile_);
184         if (hasTrajectory()
185             && !settings_.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
186         {
187             topInfo_.xtop_.clear();
188         }
189         if (hasTrajectory()
190             && !settings_.hasFlag(TrajectoryAnalysisSettings::efUseTopV))
191         {
192             topInfo_.vtop_.clear();
193         }
194     }
195 }
196
197 void
198 TrajectoryAnalysisRunnerCommon::Impl::initFirstFrame()
199 {
200     // Return if we have already initialized the trajectory.
201     if (fr != nullptr)
202     {
203         return;
204     }
205     time_unit_t time_unit
206         = static_cast<time_unit_t>(settings_.timeUnit() + 1); // NOLINT(bugprone-misplaced-widening-cast)
207     output_env_init(&oenv_, getProgramContext(), time_unit, FALSE, exvgNONE, 0);
208
209     int frflags = settings_.frflags();
210     frflags |= TRX_NEED_X;
211
212     snew(fr, 1);
213
214     if (hasTrajectory())
215     {
216         if (!read_first_frame(oenv_, &status_, trjfile_.c_str(), fr, frflags))
217         {
218             GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
219         }
220         bTrajOpen_ = true;
221
222         if (topInfo_.hasTopology())
223         {
224             const int topologyAtomCount = topInfo_.mtop()->natoms;
225             if (fr->natoms > topologyAtomCount)
226             {
227                 const std::string message
228                     = formatString("Trajectory (%d atoms) does not match topology (%d atoms)",
229                                    fr->natoms, topologyAtomCount);
230                 GMX_THROW(InconsistentInputError(message));
231             }
232         }
233     }
234     else
235     {
236         // Prepare a frame from topology information.
237         if (frflags & (TRX_NEED_F))
238         {
239             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
240         }
241         fr->natoms = topInfo_.mtop()->natoms;
242         fr->bX     = TRUE;
243         snew(fr->x, fr->natoms);
244         memcpy(fr->x, topInfo_.xtop_.data(),
245                sizeof(*fr->x) * fr->natoms);
246         if (frflags & (TRX_NEED_V))
247         {
248             if (topInfo_.vtop_.empty())
249             {
250                 GMX_THROW(InvalidInputError("Velocities were required, but could not be read from the topology file"));
251             }
252             fr->bV = TRUE;
253             snew(fr->v, fr->natoms);
254             memcpy(fr->v, topInfo_.vtop_.data(),
255                    sizeof(*fr->v) * fr->natoms);
256         }
257         fr->bBox   = TRUE;
258         copy_mat(topInfo_.boxtop_, fr->box);
259     }
260
261     set_trxframe_ePBC(fr, topInfo_.ePBC());
262     if (topInfo_.hasTopology() && settings_.hasRmPBC())
263     {
264         gpbc_             = gmx_rmpbc_init(topInfo_);
265     }
266 }
267
268 void
269 TrajectoryAnalysisRunnerCommon::Impl::initFrameIndexGroup()
270 {
271     if (!trajectoryGroup_.isValid())
272     {
273         return;
274     }
275     GMX_RELEASE_ASSERT(bTrajOpen_,
276                        "Trajectory index only makes sense with a real trajectory");
277     if (trajectoryGroup_.atomCount() != fr->natoms)
278     {
279         const std::string message = formatString(
280                     "Selection specified with -fgroup has %d atoms, but "
281                     "the trajectory (-f) has %d atoms.",
282                     trajectoryGroup_.atomCount(), fr->natoms);
283         GMX_THROW(InconsistentInputError(message));
284     }
285     fr->bIndex = TRUE;
286     snew(fr->index, trajectoryGroup_.atomCount());
287     std::copy(trajectoryGroup_.atomIndices().begin(),
288               trajectoryGroup_.atomIndices().end(),
289               fr->index);
290 }
291
292 void
293 TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
294 {
295     if (bTrajOpen_)
296     {
297         close_trx(status_);
298         bTrajOpen_ = false;
299     }
300     if (gpbc_ != nullptr)
301     {
302         gmx_rmpbc_done(gpbc_);
303         gpbc_ = nullptr;
304     }
305 }
306
307 /*********************************************************************
308  * TrajectoryAnalysisRunnerCommon
309  */
310
311 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(
312         TrajectoryAnalysisSettings *settings)
313     : impl_(new Impl(settings))
314 {
315 }
316
317
318 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon()
319 {
320 }
321
322
323 ITopologyProvider *
324 TrajectoryAnalysisRunnerCommon::topologyProvider()
325 {
326     return impl_.get();
327 }
328
329
330 void
331 TrajectoryAnalysisRunnerCommon::initOptions(IOptionsContainer *options,
332                                             TimeUnitBehavior  *timeUnitBehavior)
333 {
334     TrajectoryAnalysisSettings &settings = impl_->settings_;
335
336     // Add common file name arguments.
337     options->addOption(FileNameOption("f")
338                            .filetype(eftTrajectory).inputFile()
339                            .store(&impl_->trjfile_)
340                            .defaultBasename("traj")
341                            .description("Input trajectory or single configuration"));
342     options->addOption(FileNameOption("s")
343                            .filetype(eftTopology).inputFile()
344                            .store(&impl_->topfile_)
345                            .defaultBasename("topol")
346                            .description("Input structure"));
347
348     // Add options for trajectory time control.
349     options->addOption(DoubleOption("b")
350                            .store(&impl_->startTime_).storeIsSet(&impl_->bStartTimeSet_)
351                            .timeValue()
352                            .description("First frame (%t) to read from trajectory"));
353     options->addOption(DoubleOption("e")
354                            .store(&impl_->endTime_).storeIsSet(&impl_->bEndTimeSet_)
355                            .timeValue()
356                            .description("Last frame (%t) to read from trajectory"));
357     options->addOption(DoubleOption("dt")
358                            .store(&impl_->deltaTime_).storeIsSet(&impl_->bDeltaTimeSet_)
359                            .timeValue()
360                            .description("Only use frame if t MOD dt == first time (%t)"));
361
362     // Add time unit option.
363     timeUnitBehavior->setTimeUnitFromEnvironment();
364     timeUnitBehavior->addTimeUnitOption(options, "tu");
365     timeUnitBehavior->setTimeUnitStore(&impl_->settings_.impl_->timeUnit);
366
367     options->addOption(SelectionOption("fgroup")
368                            .store(&impl_->trajectoryGroup_)
369                            .onlySortedAtoms().onlyStatic()
370                            .description("Atoms stored in the trajectory file "
371                                         "(if not set, assume first N atoms)"));
372
373     // Add plot options.
374     settings.impl_->plotSettings.initOptions(options);
375
376     // Add common options for trajectory processing.
377     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
378     {
379         options->addOption(BooleanOption("rmpbc").store(&settings.impl_->bRmPBC)
380                                .description("Make molecules whole for each frame"));
381     }
382     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
383     {
384         options->addOption(BooleanOption("pbc").store(&settings.impl_->bPBC)
385                                .description("Use periodic boundary conditions for distance calculation"));
386     }
387 }
388
389
390 void
391 TrajectoryAnalysisRunnerCommon::optionsFinished()
392 {
393     if (impl_->trjfile_.empty() && impl_->topfile_.empty())
394     {
395         GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
396     }
397
398     if (impl_->trajectoryGroup_.isValid() && impl_->trjfile_.empty())
399     {
400         GMX_THROW(InconsistentInputError("-fgroup only makes sense together with a trajectory (-f)"));
401     }
402
403     impl_->settings_.impl_->plotSettings.setTimeUnit(impl_->settings_.timeUnit());
404
405     if (impl_->bStartTimeSet_)
406     {
407         setTimeValue(TBEGIN, impl_->startTime_);
408     }
409     if (impl_->bEndTimeSet_)
410     {
411         setTimeValue(TEND, impl_->endTime_);
412     }
413     if (impl_->bDeltaTimeSet_)
414     {
415         setTimeValue(TDELTA, impl_->deltaTime_);
416     }
417 }
418
419
420 void
421 TrajectoryAnalysisRunnerCommon::initTopology()
422 {
423     const bool topologyRequired =
424         impl_->settings_.hasFlag(TrajectoryAnalysisSettings::efRequireTop);
425     impl_->initTopology(topologyRequired);
426 }
427
428
429 void
430 TrajectoryAnalysisRunnerCommon::initFirstFrame()
431 {
432     impl_->initFirstFrame();
433 }
434
435
436 void
437 TrajectoryAnalysisRunnerCommon::initFrameIndexGroup()
438 {
439     impl_->initFrameIndexGroup();
440 }
441
442
443 bool
444 TrajectoryAnalysisRunnerCommon::readNextFrame()
445 {
446     bool bContinue = false;
447     if (hasTrajectory())
448     {
449         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
450     }
451     if (!bContinue)
452     {
453         impl_->finishTrajectory();
454     }
455     return bContinue;
456 }
457
458
459 void
460 TrajectoryAnalysisRunnerCommon::initFrame()
461 {
462     if (impl_->gpbc_ != nullptr)
463     {
464         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
465     }
466 }
467
468
469 bool
470 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
471 {
472     return impl_->hasTrajectory();
473 }
474
475
476 const TopologyInformation &
477 TrajectoryAnalysisRunnerCommon::topologyInformation() const
478 {
479     return impl_->topInfo_;
480 }
481
482
483 t_trxframe &
484 TrajectoryAnalysisRunnerCommon::frame() const
485 {
486     GMX_RELEASE_ASSERT(impl_->fr != nullptr, "Frame not available when accessed");
487     return *impl_->fr;
488 }
489
490 } // namespace gmx