Merge release-5-0 into master
[alexxy/gromacs.git] / src / gromacs / trajectoryanalysis / modules / distance.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::analysismodules::Distance.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_trajectoryanalysis
41  */
42 #include "gmxpre.h"
43
44 #include "distance.h"
45
46 #include <string>
47
48 #include "gromacs/analysisdata/analysisdata.h"
49 #include "gromacs/analysisdata/modules/average.h"
50 #include "gromacs/analysisdata/modules/histogram.h"
51 #include "gromacs/analysisdata/modules/plot.h"
52 #include "gromacs/fileio/trx.h"
53 #include "gromacs/math/vec.h"
54 #include "gromacs/options/basicoptions.h"
55 #include "gromacs/options/filenameoption.h"
56 #include "gromacs/options/options.h"
57 #include "gromacs/pbcutil/pbc.h"
58 #include "gromacs/selection/selection.h"
59 #include "gromacs/selection/selectionoption.h"
60 #include "gromacs/trajectoryanalysis/analysissettings.h"
61 #include "gromacs/utility/arrayref.h"
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/stringutil.h"
64
65 namespace gmx
66 {
67
68 namespace analysismodules
69 {
70
71 namespace
72 {
73
74 class Distance : public TrajectoryAnalysisModule
75 {
76     public:
77         Distance();
78
79         virtual void initOptions(Options                    *options,
80                                  TrajectoryAnalysisSettings *settings);
81         virtual void initAnalysis(const TrajectoryAnalysisSettings &settings,
82                                   const TopologyInformation        &top);
83
84         virtual void analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc,
85                                   TrajectoryAnalysisModuleData *pdata);
86
87         virtual void finishAnalysis(int nframes);
88         virtual void writeOutput();
89
90     private:
91         SelectionList                            sel_;
92         std::string                              fnAverage_;
93         std::string                              fnAll_;
94         std::string                              fnXYZ_;
95         std::string                              fnHistogram_;
96         std::string                              fnAllStats_;
97         double                                   meanLength_;
98         double                                   lengthDev_;
99         double                                   binWidth_;
100
101         AnalysisData                             distances_;
102         AnalysisData                             xyz_;
103         AnalysisDataAverageModulePointer         summaryStatsModule_;
104         AnalysisDataAverageModulePointer         allStatsModule_;
105         AnalysisDataFrameAverageModulePointer    averageModule_;
106         AnalysisDataSimpleHistogramModulePointer histogramModule_;
107
108         // Copy and assign disallowed by base.
109 };
110
111 Distance::Distance()
112     : TrajectoryAnalysisModule(DistanceInfo::name, DistanceInfo::shortDescription),
113       meanLength_(0.1), lengthDev_(1.0), binWidth_(0.001)
114 {
115     summaryStatsModule_.reset(new AnalysisDataAverageModule());
116     summaryStatsModule_->setAverageDataSets(true);
117     distances_.addModule(summaryStatsModule_);
118     allStatsModule_.reset(new AnalysisDataAverageModule());
119     distances_.addModule(allStatsModule_);
120     averageModule_.reset(new AnalysisDataFrameAverageModule());
121     distances_.addModule(averageModule_);
122     histogramModule_.reset(new AnalysisDataSimpleHistogramModule());
123     distances_.addModule(histogramModule_);
124
125     registerAnalysisDataset(&distances_, "dist");
126     registerAnalysisDataset(&xyz_, "xyz");
127     registerBasicDataset(summaryStatsModule_.get(), "stats");
128     registerBasicDataset(allStatsModule_.get(), "allstats");
129     registerBasicDataset(averageModule_.get(), "average");
130     registerBasicDataset(&histogramModule_->averager(), "histogram");
131 }
132
133
134 void
135 Distance::initOptions(Options *options, TrajectoryAnalysisSettings * /*settings*/)
136 {
137     static const char *const desc[] = {
138         "[THISMODULE] calculates distances between pairs of positions",
139         "as a function of time. Each selection specifies an independent set",
140         "of distances to calculate. Each selection should consist of pairs",
141         "of positions, and the distances are computed between positions 1-2,",
142         "3-4, etc.[PAR]",
143         "[TT]-oav[tt] writes the average distance as a function of time for",
144         "each selection.",
145         "[TT]-oall[tt] writes all the individual distances.",
146         "[TT]-oxyz[tt] does the same, but the x, y, and z components of the",
147         "distance are written instead of the norm.",
148         "[TT]-oh[tt] writes a histogram of the distances for each selection.",
149         "The location of the histogram is set with [TT]-len[tt] and",
150         "[TT]-tol[tt]. Bin width is set with [TT]-binw[tt].",
151         "[TT]-oallstat[tt] writes out the average and standard deviation for",
152         "each individual distance, calculated over the frames."
153     };
154
155     options->setDescription(desc);
156
157     options->addOption(FileNameOption("oav").filetype(eftPlot).outputFile()
158                            .store(&fnAverage_).defaultBasename("distave")
159                            .description("Average distances as function of time"));
160     options->addOption(FileNameOption("oall").filetype(eftPlot).outputFile()
161                            .store(&fnAll_).defaultBasename("dist")
162                            .description("All distances as function of time"));
163     options->addOption(FileNameOption("oxyz").filetype(eftPlot).outputFile()
164                            .store(&fnXYZ_).defaultBasename("distxyz")
165                            .description("Distance components as function of time"));
166     options->addOption(FileNameOption("oh").filetype(eftPlot).outputFile()
167                            .store(&fnHistogram_).defaultBasename("disthist")
168                            .description("Histogram of the distances"));
169     options->addOption(FileNameOption("oallstat").filetype(eftPlot).outputFile()
170                            .store(&fnAllStats_).defaultBasename("diststat")
171                            .description("Statistics for individual distances"));
172     options->addOption(SelectionOption("select").storeVector(&sel_)
173                            .required().dynamicMask().multiValue()
174                            .description("Position pairs to calculate distances for"));
175     // TODO: Extend the histogramming implementation to allow automatic
176     // extension of the histograms to cover the data, removing the need for
177     // the first two options.
178     options->addOption(DoubleOption("len").store(&meanLength_)
179                            .description("Mean distance for histogramming"));
180     options->addOption(DoubleOption("tol").store(&lengthDev_)
181                            .description("Width of full distribution as fraction of [TT]-len[tt]"));
182     options->addOption(DoubleOption("binw").store(&binWidth_)
183                            .description("Bin width for histogramming"));
184 }
185
186
187 /*! \brief
188  * Checks that selections conform to the expectations of the tool.
189  */
190 void checkSelections(const SelectionList &sel)
191 {
192     for (size_t g = 0; g < sel.size(); ++g)
193     {
194         if (sel[g].posCount() % 2 != 0)
195         {
196             std::string message = formatString(
197                         "Selection '%s' does not evaluate into an even number of positions "
198                         "(there are %d positions)",
199                         sel[g].name(), sel[g].posCount());
200             GMX_THROW(InconsistentInputError(message));
201         }
202         if (sel[g].isDynamic())
203         {
204             for (int i = 0; i < sel[g].posCount(); i += 2)
205             {
206                 if (sel[g].position(i).selected() != sel[g].position(i+1).selected())
207                 {
208                     std::string message =
209                         formatString("Dynamic selection %d does not select "
210                                      "a consistent set of pairs over the frames",
211                                      static_cast<int>(g + 1));
212                     GMX_THROW(InconsistentInputError(message));
213                 }
214             }
215         }
216     }
217 }
218
219
220 void
221 Distance::initAnalysis(const TrajectoryAnalysisSettings &settings,
222                        const TopologyInformation         & /*top*/)
223 {
224     checkSelections(sel_);
225
226     distances_.setDataSetCount(sel_.size());
227     xyz_.setDataSetCount(sel_.size());
228     for (size_t i = 0; i < sel_.size(); ++i)
229     {
230         const int distCount = sel_[i].posCount() / 2;
231         distances_.setColumnCount(i, distCount);
232         xyz_.setColumnCount(i, distCount * 3);
233     }
234     const double histogramMin = (1.0 - lengthDev_) * meanLength_;
235     const double histogramMax = (1.0 + lengthDev_) * meanLength_;
236     histogramModule_->init(histogramFromRange(histogramMin, histogramMax)
237                                .binWidth(binWidth_).includeAll());
238
239     if (!fnAverage_.empty())
240     {
241         AnalysisDataPlotModulePointer plotm(
242                 new AnalysisDataPlotModule(settings.plotSettings()));
243         plotm->setFileName(fnAverage_);
244         plotm->setTitle("Average distance");
245         plotm->setXAxisIsTime();
246         plotm->setYLabel("Distance (nm)");
247         for (size_t g = 0; g < sel_.size(); ++g)
248         {
249             plotm->appendLegend(sel_[g].name());
250         }
251         averageModule_->addModule(plotm);
252     }
253
254     if (!fnAll_.empty())
255     {
256         AnalysisDataPlotModulePointer plotm(
257                 new AnalysisDataPlotModule(settings.plotSettings()));
258         plotm->setFileName(fnAll_);
259         plotm->setTitle("Distance");
260         plotm->setXAxisIsTime();
261         plotm->setYLabel("Distance (nm)");
262         // TODO: Add legends? (there can be a massive amount of columns)
263         distances_.addModule(plotm);
264     }
265
266     if (!fnXYZ_.empty())
267     {
268         AnalysisDataPlotModulePointer plotm(
269                 new AnalysisDataPlotModule(settings.plotSettings()));
270         plotm->setFileName(fnAll_);
271         plotm->setTitle("Distance");
272         plotm->setXAxisIsTime();
273         plotm->setYLabel("Distance (nm)");
274         // TODO: Add legends? (there can be a massive amount of columns)
275         xyz_.addModule(plotm);
276     }
277
278     if (!fnHistogram_.empty())
279     {
280         AnalysisDataPlotModulePointer plotm(
281                 new AnalysisDataPlotModule(settings.plotSettings()));
282         plotm->setFileName(fnHistogram_);
283         plotm->setTitle("Distance histogram");
284         plotm->setXLabel("Distance (nm)");
285         plotm->setYLabel("Probability");
286         for (size_t g = 0; g < sel_.size(); ++g)
287         {
288             plotm->appendLegend(sel_[g].name());
289         }
290         histogramModule_->averager().addModule(plotm);
291     }
292
293     if (!fnAllStats_.empty())
294     {
295         AnalysisDataPlotModulePointer plotm(
296                 new AnalysisDataPlotModule(settings.plotSettings()));
297         plotm->setFileName(fnAllStats_);
298         plotm->setErrorsAsSeparateColumn(true);
299         plotm->setTitle("Statistics for individual distances");
300         plotm->setXLabel("Distance index");
301         plotm->setYLabel("Average/standard deviation (nm)");
302         for (size_t g = 0; g < sel_.size(); ++g)
303         {
304             plotm->appendLegend(std::string(sel_[g].name()) + " avg");
305             plotm->appendLegend(std::string(sel_[g].name()) + " std.dev.");
306         }
307         // TODO: Consider whether this output format is the best possible.
308         allStatsModule_->addModule(plotm);
309     }
310 }
311
312
313 void
314 Distance::analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc,
315                        TrajectoryAnalysisModuleData *pdata)
316 {
317     AnalysisDataHandle   distHandle = pdata->dataHandle(distances_);
318     AnalysisDataHandle   xyzHandle  = pdata->dataHandle(xyz_);
319     const SelectionList &sel        = pdata->parallelSelections(sel_);
320
321     checkSelections(sel);
322
323     distHandle.startFrame(frnr, fr.time);
324     xyzHandle.startFrame(frnr, fr.time);
325     for (size_t g = 0; g < sel.size(); ++g)
326     {
327         distHandle.selectDataSet(g);
328         xyzHandle.selectDataSet(g);
329         for (int i = 0, n = 0; i < sel[g].posCount(); i += 2, ++n)
330         {
331             const SelectionPosition &p1 = sel[g].position(i);
332             const SelectionPosition &p2 = sel[g].position(i+1);
333             rvec                     dx;
334             if (pbc != NULL)
335             {
336                 pbc_dx(pbc, p2.x(), p1.x(), dx);
337             }
338             else
339             {
340                 rvec_sub(p2.x(), p1.x(), dx);
341             }
342             real dist     = norm(dx);
343             bool bPresent = p1.selected() && p2.selected();
344             distHandle.setPoint(n, dist, bPresent);
345             xyzHandle.setPoints(n*3, 3, dx);
346         }
347     }
348     distHandle.finishFrame();
349     xyzHandle.finishFrame();
350 }
351
352
353 void
354 Distance::finishAnalysis(int /*nframes*/)
355 {
356     AbstractAverageHistogram &averageHistogram = histogramModule_->averager();
357     averageHistogram.normalizeProbability();
358     averageHistogram.done();
359 }
360
361
362 void
363 Distance::writeOutput()
364 {
365     SelectionList::const_iterator sel;
366     int                           index;
367     for (sel = sel_.begin(), index = 0; sel != sel_.end(); ++sel, ++index)
368     {
369         printf("%s:\n", sel->name());
370         printf("  Number of samples:  %d\n",
371                summaryStatsModule_->sampleCount(index, 0));
372         printf("  Average distance:   %-8.5f nm\n",
373                summaryStatsModule_->average(index, 0));
374         printf("  Standard deviation: %-8.5f nm\n",
375                summaryStatsModule_->standardDeviation(index, 0));
376     }
377 }
378
379 }       // namespace
380
381 const char DistanceInfo::name[]             = "distance";
382 const char DistanceInfo::shortDescription[] =
383     "Calculate distances between pairs of positions";
384
385 TrajectoryAnalysisModulePointer DistanceInfo::create()
386 {
387     return TrajectoryAnalysisModulePointer(new Distance);
388 }
389
390 } // namespace analysismodules
391
392 } // namespace gmx