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