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