Merge "Merge branch release-4-6 into master"
[alexxy/gromacs.git] / src / gromacs / analysisdata / modules / histogram.h
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 /*! \file
36  * \brief
37  * Declares analysis data modules for calculating histograms.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \inpublicapi
41  * \ingroup module_analysisdata
42  */
43 #ifndef GMX_ANALYSISDATA_MODULES_HISTOGRAM_H
44 #define GMX_ANALYSISDATA_MODULES_HISTOGRAM_H
45
46 #include "../abstractdata.h"
47 #include "../arraydata.h"
48 #include "../datamodule.h"
49 #include "../../utility/uniqueptr.h"
50
51 namespace gmx
52 {
53
54 class AnalysisHistogramSettings;
55
56 /*! \brief
57  * Provides "named parameter" idiom for constructing histograms.
58  *
59  * \see histogramFromBins()
60  * \see histogramFromRange()
61  *
62  * Methods in this class do not throw.
63  *
64  * \inpublicapi
65  * \ingroup module_analysisdata
66  */
67 class AnalysisHistogramSettingsInitializer
68 {
69     public:
70         /*! \brief
71          * Creates an empty initializer.
72          *
73          * Should not be called directly, but histogramFromRange() or
74          * histogramFromBins() should be used instead.
75          */
76         AnalysisHistogramSettingsInitializer();
77
78         /*! \brief
79          * Sets the first bin location.
80          *
81          * Typically should not be called directly, but through
82          * histogramFromBins().
83          */
84         AnalysisHistogramSettingsInitializer &start(real min)
85         { min_ = min; return *this; }
86         /*! \brief
87          * Sets the number of bins in the histogram.
88          *
89          * If only the first bin location is specified, this value is required
90          * (and automatically provided if histogramFromBins() is used).
91          * If both the first and last bins are specified, either this value or
92          * binWidth() is required.
93          */
94         AnalysisHistogramSettingsInitializer &binCount(int binCount)
95         { binCount_ = binCount; return *this; }
96         /*! \brief
97          * Sets the first and last bin locations.
98          *
99          * Typically should not be called directly, but through
100          * histogramFromRange().
101          */
102         AnalysisHistogramSettingsInitializer &range(real min, real max)
103         { min_ = min; max_ = max; return *this; }
104         /*! \brief
105          * Sets the bin width of the histogram.
106          *
107          * If only the first bin location is specified, this value is required
108          * (and automatically provided if histogramFromBins() is used).
109          * If both the first and last bins are specified, either this value or
110          * binCount() is required.
111          * If a bin width is provided with both first and last bin locations,
112          * and the given bin width does not divide the range exactly, the last
113          * bin location is adjusted to match.
114          */
115         AnalysisHistogramSettingsInitializer &binWidth(real binWidth)
116         { binWidth_ = binWidth; return *this; }
117         /*! \brief
118          * Indicate that first and last bin locations to specify bin centers.
119          *
120          * If set, the first and last bin locations are interpreted as bin
121          * centers.
122          * If not set (the default), the first and last bin locations are
123          * interpreted as the edges of the whole histogram.
124          *
125          * Cannot be specified together with roundRange().
126          */
127         AnalysisHistogramSettingsInitializer &integerBins(bool enabled = true)
128         { bIntegerBins_ = enabled; return *this; }
129         /*! \brief
130          * Round first and last bin locations.
131          *
132          * If set, the resulting histogram will cover the range specified, but
133          * the actual bin locations will be rounded such that the edges fall
134          * on multiples of the bin width.
135          * Only implemented when both first and last bin location and bin width
136          * are defined.
137          * Cannot be specified together with integerBins() or with binCount().
138          */
139         AnalysisHistogramSettingsInitializer &roundRange(bool enabled = true)
140         { bRoundRange_ = enabled; return *this; }
141         /*! \brief
142          * Sets the histogram to match all values.
143          *
144          * If set, the histogram behaves as if the bins at the ends extended to
145          * +-infinity.
146          */
147         AnalysisHistogramSettingsInitializer &includeAll(bool enabled = true)
148         { bIncludeAll_ = enabled; return *this; }
149
150     private:
151         real                    min_;
152         real                    max_;
153         real                    binWidth_;
154         int                     binCount_;
155         bool                    bIntegerBins_;
156         bool                    bRoundRange_;
157         bool                    bIncludeAll_;
158
159         friend class AnalysisHistogramSettings;
160 };
161
162 /*! \brief
163  * Initializes a histogram using a range and a bin width.
164  *
165  * Does not throw.
166  *
167  * \inpublicapi
168  */
169 inline AnalysisHistogramSettingsInitializer
170 histogramFromRange(real min, real max)
171 {
172     return AnalysisHistogramSettingsInitializer().range(min, max);
173 }
174
175 /*! \brief
176  * Initializes a histogram using bin width and the number of bins.
177  *
178  * Does not throw.
179  *
180  * \inpublicapi
181  */
182 inline AnalysisHistogramSettingsInitializer
183 histogramFromBins(real start, int nbins, real binwidth)
184 {
185     return AnalysisHistogramSettingsInitializer()
186                .start(start).binCount(nbins).binWidth(binwidth);
187 }
188
189
190 /*! \brief
191  * Contains parameters that specify histogram bin locations.
192  *
193  * Methods in this class do not throw.
194  *
195  * \inpublicapi
196  * \ingroup module_analysisdata
197  */
198 class AnalysisHistogramSettings
199 {
200     public:
201         //! Initializes undefined parameters.
202         AnalysisHistogramSettings();
203         /*! \brief
204          * Initializes parameters based on a named parameter object.
205          *
206          * This constructor is not explicit to allow initialization of
207          * histograms directly from AnalysisHistogramSettingsInitializer:
208          * \code
209            gmx::AnalysisDataSimpleHistogramModule *hist =
210                    new gmx::AnalysisDataSimpleHistogramModule(
211                            histogramFromRange(0.0, 5.0).binWidth(0.5));
212          * \endcode
213          */
214         AnalysisHistogramSettings(const AnalysisHistogramSettingsInitializer &settings);
215
216         //! Returns the left edge of the first bin.
217         real firstEdge() const { return firstEdge_; }
218         //! Returns the right edge of the first bin.
219         real lastEdge() const { return lastEdge_; }
220         //! Returns the number of bins in the histogram.
221         int binCount() const { return binCount_; }
222         //! Returns the width of a bin in the histogram.
223         real binWidth() const { return binWidth_; }
224         //! Whether values beyond the edges are mapped to the edge bins.
225         bool includeAll() const { return bAll_; }
226         //! Returns a zero-based bin index for a value, or -1 if not in range.
227         int findBin(real y) const;
228
229     private:
230         real                    firstEdge_;
231         real                    lastEdge_;
232         real                    binWidth_;
233         real                    inverseBinWidth_;
234         int                     binCount_;
235         bool                    bAll_;
236 };
237
238
239 namespace internal
240 {
241
242 class BasicHistogramImpl;
243
244 }   // namespace internal
245
246 class AbstractAverageHistogram;
247
248 //! Smart pointer to manage an AbstractAverageHistogram object.
249 typedef gmx_unique_ptr<AbstractAverageHistogram>::type
250     AverageHistogramPointer;
251
252 /*! \brief
253  * Base class for representing histograms averaged over frames.
254  *
255  * The averaging module for a per-frame histogram is always created by the
256  * histogram module class (e.g., AnalysisDataSimpleHistogramModule), and can be
257  * accessed using, e.g., AnalysisDataSimpleHistogramModule::averager().
258  * The user can alter some properties of the average histogram directly, but
259  * the main use of the object is to postprocess the histogram once the
260  * calculation is finished.
261  *
262  * This class can represent multiple histograms in one object: each column in
263  * the data is an independent histogram.
264  *
265  * \inpublicapi
266  * \ingroup module_analysisdata
267  */
268 class AbstractAverageHistogram : public AbstractAnalysisArrayData
269 {
270     public:
271         virtual ~AbstractAverageHistogram();
272
273         //! Returns bin properties for the histogram.
274         const AnalysisHistogramSettings &settings() const { return settings_; }
275
276         /*! \brief
277          * Creates a copy of the histogram with double the bin width.
278          *
279          * \throws std::bad_alloc if out of memory.
280          *
281          * The caller is responsible of deleting the returned object.
282          */
283         AverageHistogramPointer resampleDoubleBinWidth(bool bIntegerBins) const;
284         /*! \brief
285          * Creates a deep copy of the histogram.
286          *
287          * \throws std::bad_alloc if out of memory.
288          *
289          * The returned histogram is not necessarily of the same dynamic type
290          * as the original object, but contains the same data from the point of
291          * view of the AbstractAverageHistogram interface.
292          *
293          * The caller is responsible of deleting the returned object.
294          */
295         AverageHistogramPointer clone() const;
296         //! Normalizes the histogram such that the integral over it is one.
297         void normalizeProbability();
298         //! Scales a single histogram by a uniform scaling factor.
299         void scaleSingle(int index, real factor);
300         //! Scales all histograms by a uniform scaling factor.
301         void scaleAll(real factor);
302         //! Scales the value of each bin by a different scaling factor.
303         void scaleAllByVector(real factor[]);
304         /*! \brief
305          * Notifies attached modules of the histogram data.
306          *
307          * After this function has been called, it is no longer possible to
308          * alter the histogram.
309          */
310         void done() { AbstractAnalysisArrayData::valuesReady(); }
311
312     protected:
313         /*! \brief
314          * Creates a histogram module with undefined bins.
315          *
316          * Bin parameters must be defined with init() before data input is
317          * started.
318          */
319         AbstractAverageHistogram();
320         //! Creates a histogram module with defined bin parameters.
321         explicit AbstractAverageHistogram(const AnalysisHistogramSettings &settings);
322
323         /*! \brief
324          * (Re)initializes the histogram from settings.
325          */
326         void init(const AnalysisHistogramSettings &settings);
327
328     private:
329         AnalysisHistogramSettings  settings_;
330
331         // Copy and assign disallowed by base.
332 };
333
334
335 /*! \brief
336  * Data module for per-frame histograms.
337  *
338  * Output data contains the same number of frames and data sets as the input
339  * data.  Each frame contains the histogram(s) for the points in that frame.
340  * Each input data set is processed independently into the corresponding output
341  * data set.  Missing values are ignored.
342  * All input columns for a data set are averaged into the same histogram.
343  * The number of columns for all data sets equals the number of bins in the
344  * histogram.
345  *
346  * \inpublicapi
347  * \ingroup module_analysisdata
348  */
349 class AnalysisDataSimpleHistogramModule : public AbstractAnalysisData,
350                                           public AnalysisDataModuleInterface
351 {
352     public:
353         /*! \brief
354          * Creates a histogram module with undefined bins.
355          *
356          * Bin parameters must be defined with init() before data input is
357          * started.
358          */
359         AnalysisDataSimpleHistogramModule();
360         //! Creates a histogram module with defined bin parameters.
361         explicit AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &settings);
362         virtual ~AnalysisDataSimpleHistogramModule();
363
364         /*! \brief
365          * (Re)initializes the histogram from settings.
366          */
367         void init(const AnalysisHistogramSettings &settings);
368
369         /*! \brief
370          * Returns the average histogram over all frames.
371          *
372          * Can be called already before the histogram is calculated to
373          * customize the way the average histogram is calculated.
374          *
375          * \see AbstractAverageHistogram
376          */
377         AbstractAverageHistogram &averager();
378
379         //! Returns bin properties for the histogram.
380         const AnalysisHistogramSettings &settings() const;
381
382         virtual int flags() const;
383
384         virtual void dataStarted(AbstractAnalysisData *data);
385         virtual void frameStarted(const AnalysisDataFrameHeader &header);
386         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
387         virtual void frameFinished(const AnalysisDataFrameHeader &header);
388         virtual void dataFinished();
389
390     private:
391         virtual AnalysisDataFrameRef tryGetDataFrameInternal(int index) const;
392         virtual bool requestStorageInternal(int nframes);
393
394         PrivateImplPointer<internal::BasicHistogramImpl> impl_;
395
396         // Copy and assign disallowed by base.
397 };
398
399
400 /*! \brief
401  * Data module for per-frame weighted histograms.
402  *
403  * Output data contains the same number of frames and data sets as the input
404  * data.  Each frame contains the histogram(s) for the points in that frame,
405  * interpreted such that the first column passed to pointsAdded() determines
406  * the bin and the rest give weights to be added to that bin (input data should
407  * have at least two colums, and at least two columns should be added at the
408  * same time).
409  * Each input data set is processed independently into the corresponding output
410  * data set.
411  * All input columns for a data set are averaged into the same histogram.
412  * The number of columns for all data sets equals the number of bins in the
413  * histogram.
414  *
415  * \inpublicapi
416  * \ingroup module_analysisdata
417  */
418 class AnalysisDataWeightedHistogramModule : public AbstractAnalysisData,
419                                             public AnalysisDataModuleInterface
420 {
421     public:
422         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule()
423         AnalysisDataWeightedHistogramModule();
424         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &)
425         explicit AnalysisDataWeightedHistogramModule(const AnalysisHistogramSettings &settings);
426         virtual ~AnalysisDataWeightedHistogramModule();
427
428         //! \copydoc AnalysisDataSimpleHistogramModule::init()
429         void init(const AnalysisHistogramSettings &settings);
430
431         //! \copydoc AnalysisDataSimpleHistogramModule::averager()
432         AbstractAverageHistogram &averager();
433
434         //! \copydoc AnalysisDataSimpleHistogramModule::settings()
435         const AnalysisHistogramSettings &settings() const;
436
437         virtual int flags() const;
438
439         virtual void dataStarted(AbstractAnalysisData *data);
440         virtual void frameStarted(const AnalysisDataFrameHeader &header);
441         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
442         virtual void frameFinished(const AnalysisDataFrameHeader &header);
443         virtual void dataFinished();
444
445     private:
446         virtual AnalysisDataFrameRef tryGetDataFrameInternal(int index) const;
447         virtual bool requestStorageInternal(int nframes);
448
449         PrivateImplPointer<internal::BasicHistogramImpl> impl_;
450
451         // Copy and assign disallowed by base.
452 };
453
454
455 /*! \brief
456  * Data module for bin averages.
457  *
458  * Output data contains one row for each bin; see AbstractAverageHistogram.
459  * Output data contains one column for each input data set.
460  * The value in a column is the average over all frames of that data set for
461  * that bin.
462  * The input data is interpreted such that the first column passed to
463  * pointsAdded() determines the bin and the rest give values to be added to
464  * that bin (input data should have at least two colums, and at least two
465  * columns should be added at the same time).
466  * All input columns for a data set are averaged into the same histogram.
467  *
468  * \inpublicapi
469  * \ingroup module_analysisdata
470  */
471 class AnalysisDataBinAverageModule : public AbstractAnalysisArrayData,
472                                      public AnalysisDataModuleInterface
473 {
474     public:
475         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule()
476         AnalysisDataBinAverageModule();
477         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &)
478         explicit AnalysisDataBinAverageModule(const AnalysisHistogramSettings &settings);
479         virtual ~AnalysisDataBinAverageModule();
480
481         //! \copydoc AnalysisDataSimpleHistogramModule::init()
482         void init(const AnalysisHistogramSettings &settings);
483
484         //! \copydoc AnalysisDataSimpleHistogramModule::settings()
485         const AnalysisHistogramSettings &settings() const;
486
487         virtual int flags() const;
488
489         virtual void dataStarted(AbstractAnalysisData *data);
490         virtual void frameStarted(const AnalysisDataFrameHeader &header);
491         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
492         virtual void frameFinished(const AnalysisDataFrameHeader &header);
493         virtual void dataFinished();
494
495     private:
496         class Impl;
497
498         PrivateImplPointer<Impl>   impl_;
499
500         // Copy and assign disallowed by base.
501 };
502
503 //! Smart pointer to manage an AnalysisDataSimpleHistogramModule object.
504 typedef boost::shared_ptr<AnalysisDataSimpleHistogramModule>
505     AnalysisDataSimpleHistogramModulePointer;
506 //! Smart pointer to manage an AnalysisDataWeightedHistogramModule object.
507 typedef boost::shared_ptr<AnalysisDataWeightedHistogramModule>
508     AnalysisDataWeightedHistogramModulePointer;
509 //! Smart pointer to manage an AnalysisDataBinAverageModule object.
510 typedef boost::shared_ptr<AnalysisDataBinAverageModule>
511     AnalysisDataBinAverageModulePointer;
512
513 } // namespace gmx
514
515 #endif