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