befa025b175b9cf1d3bd5a93fe4413d7634a4723
[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
97         gmx_ana_indexgrps_t        *grps_;
98         bool                        bTrajOpen_;
99         //! The current frame, or \p NULL if no frame loaded yet.
100         t_trxframe                 *fr;
101         gmx_rmpbc_t                 gpbc_;
102         //! Used to store the status variable from read_first_frame().
103         t_trxstatus                *status_;
104         output_env_t                oenv_;
105 };
106
107
108 TrajectoryAnalysisRunnerCommon::Impl::Impl(TrajectoryAnalysisSettings *settings)
109     : settings_(*settings),
110       startTime_(0.0), endTime_(0.0), deltaTime_(0.0),
111       grps_(NULL),
112       bTrajOpen_(false), fr(NULL), gpbc_(NULL), status_(NULL), oenv_(NULL)
113 {
114 }
115
116
117 TrajectoryAnalysisRunnerCommon::Impl::~Impl()
118 {
119     if (grps_ != NULL)
120     {
121         gmx_ana_indexgrps_free(grps_);
122     }
123     finishTrajectory();
124     if (fr)
125     {
126         // There doesn't seem to be a function for freeing frame data
127         sfree(fr->x);
128         sfree(fr->v);
129         sfree(fr->f);
130         sfree(fr);
131     }
132     if (oenv_ != NULL)
133     {
134         output_env_done(oenv_);
135     }
136 }
137
138
139 void
140 TrajectoryAnalysisRunnerCommon::Impl::finishTrajectory()
141 {
142     if (bTrajOpen_)
143     {
144         close_trx(status_);
145         bTrajOpen_ = false;
146     }
147     if (gpbc_ != NULL)
148     {
149         gmx_rmpbc_done(gpbc_);
150         gpbc_ = NULL;
151     }
152 }
153
154 /*********************************************************************
155  * TrajectoryAnalysisRunnerCommon
156  */
157
158 TrajectoryAnalysisRunnerCommon::TrajectoryAnalysisRunnerCommon(
159         TrajectoryAnalysisSettings *settings)
160     : impl_(new Impl(settings))
161 {
162 }
163
164
165 TrajectoryAnalysisRunnerCommon::~TrajectoryAnalysisRunnerCommon()
166 {
167 }
168
169
170 void
171 TrajectoryAnalysisRunnerCommon::initOptions(IOptionsContainer *options)
172 {
173     TrajectoryAnalysisSettings &settings = impl_->settings_;
174
175     // Add common file name arguments.
176     options->addOption(FileNameOption("f")
177                            .filetype(eftTrajectory).inputFile()
178                            .store(&impl_->trjfile_)
179                            .defaultBasename("traj")
180                            .description("Input trajectory or single configuration"));
181     options->addOption(FileNameOption("s")
182                            .filetype(eftTopology).inputFile()
183                            .store(&impl_->topfile_)
184                            .defaultBasename("topol")
185                            .description("Input structure"));
186     options->addOption(FileNameOption("n")
187                            .filetype(eftIndex).inputFile()
188                            .store(&impl_->ndxfile_)
189                            .defaultBasename("index")
190                            .description("Extra index groups"));
191
192     // Add options for trajectory time control.
193     options->addOption(DoubleOption("b").store(&impl_->startTime_).timeValue()
194                            .description("First frame (%t) to read from trajectory"));
195     options->addOption(DoubleOption("e").store(&impl_->endTime_).timeValue()
196                            .description("Last frame (%t) to read from trajectory"));
197     options->addOption(DoubleOption("dt").store(&impl_->deltaTime_).timeValue()
198                            .description("Only use frame if t MOD dt == first time (%t)"));
199
200     // Add time unit option.
201     settings.impl_->timeUnitManager.addTimeUnitOption(options, "tu");
202
203     // Add plot options.
204     settings.impl_->plotSettings.initOptions(options);
205
206     // Add common options for trajectory processing.
207     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserRmPBC))
208     {
209         options->addOption(BooleanOption("rmpbc").store(&settings.impl_->bRmPBC)
210                                .description("Make molecules whole for each frame"));
211     }
212     if (!settings.hasFlag(TrajectoryAnalysisSettings::efNoUserPBC))
213     {
214         options->addOption(BooleanOption("pbc").store(&settings.impl_->bPBC)
215                                .description("Use periodic boundary conditions for distance calculation"));
216     }
217
218     options->addOption(SelectionFileOption("sf"));
219 }
220
221
222 void
223 TrajectoryAnalysisRunnerCommon::scaleTimeOptions(Options *options)
224 {
225     impl_->settings_.impl_->timeUnitManager.scaleTimeOptions(options);
226 }
227
228
229 void
230 TrajectoryAnalysisRunnerCommon::optionsFinished(Options *options)
231 {
232     impl_->settings_.impl_->plotSettings.setTimeUnit(
233             impl_->settings_.impl_->timeUnitManager.timeUnit());
234
235     if (impl_->trjfile_.empty() && impl_->topfile_.empty())
236     {
237         GMX_THROW(InconsistentInputError("No trajectory or topology provided, nothing to do!"));
238     }
239
240     if (options->isSet("b"))
241     {
242         setTimeValue(TBEGIN, impl_->startTime_);
243     }
244     if (options->isSet("e"))
245     {
246         setTimeValue(TEND, impl_->endTime_);
247     }
248     if (options->isSet("dt"))
249     {
250         setTimeValue(TDELTA, impl_->deltaTime_);
251     }
252 }
253
254
255 void
256 TrajectoryAnalysisRunnerCommon::initIndexGroups(SelectionCollection *selections,
257                                                 bool                 bUseDefaults)
258 {
259     if (impl_->ndxfile_.empty())
260     {
261         if (!bUseDefaults)
262         {
263             selections->setIndexGroups(NULL);
264             return;
265         }
266         initTopology(selections);
267     }
268     const char *const ndxfile
269         = (!impl_->ndxfile_.empty() ? impl_->ndxfile_.c_str() : NULL);
270     gmx_ana_indexgrps_init(&impl_->grps_, impl_->topInfo_.topology(), ndxfile);
271     selections->setIndexGroups(impl_->grps_);
272 }
273
274
275 void
276 TrajectoryAnalysisRunnerCommon::doneIndexGroups(SelectionCollection *selections)
277 {
278     if (impl_->grps_ != NULL)
279     {
280         selections->setIndexGroups(NULL);
281         gmx_ana_indexgrps_free(impl_->grps_);
282         impl_->grps_ = NULL;
283     }
284 }
285
286
287 void
288 TrajectoryAnalysisRunnerCommon::initTopology(SelectionCollection *selections)
289 {
290     // Return immediately if the topology has already been loaded.
291     if (impl_->topInfo_.hasTopology())
292     {
293         return;
294     }
295
296     const TrajectoryAnalysisSettings &settings = impl_->settings_;
297     const bool bRequireTop
298         = settings.hasFlag(TrajectoryAnalysisSettings::efRequireTop)
299             || selections->requiresTopology();
300     if (bRequireTop && impl_->topfile_.empty())
301     {
302         GMX_THROW(InconsistentInputError("No topology provided, but one is required for analysis"));
303     }
304
305     // Load the topology if requested.
306     if (!impl_->topfile_.empty())
307     {
308         char  title[STRLEN];
309
310         snew(impl_->topInfo_.top_, 1);
311         impl_->topInfo_.bTop_ = read_tps_conf(impl_->topfile_.c_str(), title,
312                                               impl_->topInfo_.top_, &impl_->topInfo_.ePBC_,
313                                               &impl_->topInfo_.xtop_, NULL, impl_->topInfo_.boxtop_, TRUE);
314         if (hasTrajectory()
315             && !settings.hasFlag(TrajectoryAnalysisSettings::efUseTopX))
316         {
317             sfree(impl_->topInfo_.xtop_);
318             impl_->topInfo_.xtop_ = NULL;
319         }
320     }
321
322     // Read the first frame if we don't know the maximum number of atoms
323     // otherwise.
324     int  natoms = -1;
325     if (!impl_->topInfo_.hasTopology())
326     {
327         initFirstFrame();
328         natoms = impl_->fr->natoms;
329     }
330     selections->setTopology(impl_->topInfo_.topology(), natoms);
331
332     /*
333        if (impl_->bSelDump)
334        {
335         gmx_ana_poscalc_coll_print_tree(stderr, impl_->pcc);
336         fprintf(stderr, "\n");
337        }
338      */
339 }
340
341
342 void
343 TrajectoryAnalysisRunnerCommon::initFirstFrame()
344 {
345     // Return if we have already initialized the trajectory.
346     if (impl_->fr)
347     {
348         return;
349     }
350     time_unit_t time_unit
351         = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
352     output_env_init(&impl_->oenv_, getProgramContext(), time_unit, FALSE, exvgNONE, 0);
353
354     int frflags = impl_->settings_.frflags();
355     frflags |= TRX_NEED_X;
356
357     snew(impl_->fr, 1);
358
359     const TopologyInformation &top = impl_->topInfo_;
360     if (hasTrajectory())
361     {
362         if (!read_first_frame(impl_->oenv_, &impl_->status_,
363                               impl_->trjfile_.c_str(), impl_->fr, frflags))
364         {
365             GMX_THROW(FileIOError("Could not read coordinates from trajectory"));
366         }
367         impl_->bTrajOpen_ = true;
368
369         if (top.hasTopology() && impl_->fr->natoms > top.topology()->atoms.nr)
370         {
371             GMX_THROW(InconsistentInputError(formatString(
372                                                      "Trajectory (%d atoms) does not match topology (%d atoms)",
373                                                      impl_->fr->natoms, top.topology()->atoms.nr)));
374         }
375     }
376     else
377     {
378         // Prepare a frame from topology information.
379         // TODO: Initialize more of the fields.
380         if (frflags & (TRX_NEED_V))
381         {
382             GMX_THROW(NotImplementedError("Velocity reading from a topology not implemented"));
383         }
384         if (frflags & (TRX_NEED_F))
385         {
386             GMX_THROW(InvalidInputError("Forces cannot be read from a topology"));
387         }
388         impl_->fr->flags  = frflags;
389         impl_->fr->natoms = top.topology()->atoms.nr;
390         impl_->fr->bX     = TRUE;
391         snew(impl_->fr->x, impl_->fr->natoms);
392         memcpy(impl_->fr->x, top.xtop_,
393                sizeof(*impl_->fr->x) * impl_->fr->natoms);
394         impl_->fr->bBox   = TRUE;
395         copy_mat(const_cast<rvec *>(top.boxtop_), impl_->fr->box);
396     }
397
398     set_trxframe_ePBC(impl_->fr, top.ePBC());
399     if (top.hasTopology() && impl_->settings_.hasRmPBC())
400     {
401         impl_->gpbc_ = gmx_rmpbc_init(&top.topology()->idef, top.ePBC(),
402                                       impl_->fr->natoms);
403     }
404 }
405
406
407 bool
408 TrajectoryAnalysisRunnerCommon::readNextFrame()
409 {
410     bool bContinue = false;
411     if (hasTrajectory())
412     {
413         bContinue = read_next_frame(impl_->oenv_, impl_->status_, impl_->fr);
414     }
415     if (!bContinue)
416     {
417         impl_->finishTrajectory();
418     }
419     return bContinue;
420 }
421
422
423 void
424 TrajectoryAnalysisRunnerCommon::initFrame()
425 {
426     if (impl_->gpbc_ != NULL)
427     {
428         gmx_rmpbc_trxfr(impl_->gpbc_, impl_->fr);
429     }
430 }
431
432
433 bool
434 TrajectoryAnalysisRunnerCommon::hasTrajectory() const
435 {
436     return !impl_->trjfile_.empty();
437 }
438
439
440 const TopologyInformation &
441 TrajectoryAnalysisRunnerCommon::topologyInformation() const
442 {
443     return impl_->topInfo_;
444 }
445
446
447 t_trxframe &
448 TrajectoryAnalysisRunnerCommon::frame() const
449 {
450     GMX_RELEASE_ASSERT(impl_->fr != NULL, "Frame not available when accessed");
451     return *impl_->fr;
452 }
453
454 } // namespace gmx