Remove Options::isSet()
[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
297 void
298 TrajectoryAnalysisRunnerCommon::initTopology(SelectionCollection *selections)
299 {
300     // Return immediately if the topology has already been loaded.
301     if (impl_->topInfo_.hasTopology())
302     {
303         return;
304     }
305
306     const TrajectoryAnalysisSettings &settings = impl_->settings_;
307     const bool bRequireTop
308         = settings.hasFlag(TrajectoryAnalysisSettings::efRequireTop)
309             || selections->requiresTopology();
310     if (bRequireTop && impl_->topfile_.empty())
311     {
312         GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
313     }
314
315     // Load the topology if requested.
316     if (!impl_->topfile_.empty())
317     {
318         char  title[STRLEN];
319
320         snew(impl_->topInfo_.top_, 1);
321         impl_->topInfo_.bTop_ = read_tps_conf(impl_->topfile_.c_str(), title,
322                                               impl_->topInfo_.top_, &impl_->topInfo_.ePBC_,
323                                               &impl_->topInfo_.xtop_, NULL, impl_->topInfo_.boxtop_, TRUE);
324         if (hasTrajectory()
325             && !settings.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
326         {
327             sfree(impl_->topInfo_.xtop_);
328             impl_->topInfo_.xtop_ = NULL;
329         }
330     }
331
332     // Read the first frame if we don't know the maximum number of atoms
333     // otherwise.
334     int  natoms = -1;
335     if (!impl_->topInfo_.hasTopology())
336     {
337         initFirstFrame();
338         natoms = impl_->fr->natoms;
339     }
340     selections->setTopology(impl_->topInfo_.topology(), natoms);
341
342     /*
343        if (impl_->bSelDump)
344        {
345         gmx_ana_poscalc_coll_print_tree(stderr, impl_->pcc);
346         fprintf(stderr, "\n");
347        }
348      */
349 }
350
351
352 void
353 TrajectoryAnalysisRunnerCommon::initFirstFrame()
354 {
355     // Return if we have already initialized the trajectory.
356     if (impl_->fr)
357     {
358         return;
359     }
360     time_unit_t time_unit
361         = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
362     output_env_init(&impl_->oenv_, getProgramContext(), time_unit, FALSE, exvgNONE, 0);
363
364     int frflags = impl_->settings_.frflags();
365     frflags |= TRX_NEED_X;
366
367     snew(impl_->fr, 1);
368
369     const TopologyInformation &top = impl_->topInfo_;
370     if (hasTrajectory())
371     {
372         if (!read_first_frame(impl_->oenv_, &impl_->status_,
373                               impl_->trjfile_.c_str(), impl_->fr, frflags))
374         {
375             GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
376         }
377         impl_->bTrajOpen_ = true;
378
379         if (top.hasTopology() && impl_->fr->natoms > top.topology()->atoms.nr)
380         {
381             GMX_THROW(InconsistentInputError(formatString(
382                                                      "Trajectory (%d atoms) does not match topology (%d atoms)",
383                                                      impl_->fr->natoms, top.topology()->atoms.nr)));
384         }
385     }
386     else
387     {
388         // Prepare a frame from topology information.
389         // TODO: Initialize more of the fields.
390         if (frflags & (TRX_NEED_V))
391         {
392             GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
393         }
394         if (frflags & (TRX_NEED_F))
395         {
396             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
397         }
398         impl_->fr->flags  = frflags;
399         impl_->fr->natoms = top.topology()->atoms.nr;
400         impl_->fr->bX     = TRUE;
401         snew(impl_->fr->x, impl_->fr->natoms);
402         memcpy(impl_->fr->x, top.xtop_,
403                sizeof(*impl_->fr->x) * impl_->fr->natoms);
404         impl_->fr->bBox   = TRUE;
405         copy_mat(const_cast<rvec *>(top.boxtop_), impl_->fr->box);
406     }
407
408     set_trxframe_ePBC(impl_->fr, top.ePBC());
409     if (top.hasTopology() && impl_->settings_.hasRmPBC())
410     {
411         impl_->gpbc_ = gmx_rmpbc_init(&top.topology()->idef, top.ePBC(),
412                                       impl_->fr->natoms);
413     }
414 }
415
416
417 bool
418 TrajectoryAnalysisRunnerCommon::readNextFrame()
419 {
420     bool bContinue = false;
421     if (hasTrajectory())
422     {
423         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
424     }
425     if (!bContinue)
426     {
427         impl_->finishTrajectory();
428     }
429     return bContinue;
430 }
431
432
433 void
434 TrajectoryAnalysisRunnerCommon::initFrame()
435 {
436     if (impl_->gpbc_ != NULL)
437     {
438         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
439     }
440 }
441
442
443 bool
444 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
445 {
446     return !impl_->trjfile_.empty();
447 }
448
449
450 const TopologyInformation &
451 TrajectoryAnalysisRunnerCommon::topologyInformation() const
452 {
453     return impl_->topInfo_;
454 }
455
456
457 t_trxframe &
458 TrajectoryAnalysisRunnerCommon::frame() const
459 {
460     GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
461     return *impl_->fr;
462 }
463
464 } // namespace gmx