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  * \inpublicapi
263  * \ingroup module_analysisdata
264  */
265 class AbstractAverageHistogram : public AbstractAnalysisArrayData
266 {
267     public:
268         virtual ~AbstractAverageHistogram();
269
270         //! Returns bin properties for the histogram.
271         const AnalysisHistogramSettings &settings() const { return settings_; }
272
273         /*! \brief
274          * Creates a copy of the histogram with double the bin width.
275          *
276          * \throws std::bad_alloc if out of memory.
277          *
278          * The caller is responsible of deleting the returned object.
279          */
280         AverageHistogramPointer resampleDoubleBinWidth(bool bIntegerBins) const;
281         /*! \brief
282          * Creates a deep copy of the histogram.
283          *
284          * \throws std::bad_alloc if out of memory.
285          *
286          * The returned histogram is not necessarily of the same dynamic type
287          * as the original object, but contains the same data from the point of
288          * view of the AbstractAverageHistogram interface.
289          *
290          * The caller is responsible of deleting the returned object.
291          */
292         AverageHistogramPointer clone() const;
293         //! Normalizes the histogram such that the integral over it is one.
294         void normalizeProbability();
295         //! Scales the value of each bin by an uniform scaling factor.
296         void scale(real norm);
297         //! Scales the value of each bin by a different scaling factor.
298         void scaleVector(real norm[]);
299         /*! \brief
300          * Notifies attached modules of the histogram data.
301          *
302          * After this function has been called, it is no longer possible to
303          * alter the histogram.
304          */
305         void done() { AbstractAnalysisArrayData::valuesReady(); }
306
307     protected:
308         /*! \brief
309          * Creates a histogram module with undefined bins.
310          *
311          * Bin parameters must be defined with init() before data input is
312          * started.
313          */
314         AbstractAverageHistogram();
315         //! Creates a histogram module with defined bin parameters.
316         explicit AbstractAverageHistogram(const AnalysisHistogramSettings &settings);
317
318         /*! \brief
319          * (Re)initializes the histogram from settings.
320          */
321         void init(const AnalysisHistogramSettings &settings);
322
323     private:
324         AnalysisHistogramSettings  settings_;
325
326         // Copy and assign disallowed by base.
327 };
328
329
330 /*! \brief
331  * Data module for per-frame histograms.
332  *
333  * Output data contains the same number of frames as the input data.
334  * Each frame contains the histogram for the points in that frame.
335  * All input columns are averaged into the same histogram.
336  * The number of columns equals the number of bins in the histogram.
337  *
338  * \inpublicapi
339  * \ingroup module_analysisdata
340  */
341 class AnalysisDataSimpleHistogramModule : public AbstractAnalysisData,
342                                           public AnalysisDataModuleInterface
343 {
344     public:
345         /*! \brief
346          * Creates a histogram module with undefined bins.
347          *
348          * Bin parameters must be defined with init() before data input is
349          * started.
350          */
351         AnalysisDataSimpleHistogramModule();
352         //! Creates a histogram module with defined bin parameters.
353         explicit AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &settings);
354         virtual ~AnalysisDataSimpleHistogramModule();
355
356         /*! \brief
357          * (Re)initializes the histogram from settings.
358          */
359         void init(const AnalysisHistogramSettings &settings);
360
361         /*! \brief
362          * Returns the average histogram over all frames.
363          *
364          * Can be called already before the histogram is calculated to
365          * customize the way the average histogram is calculated.
366          *
367          * \see AbstractAverageHistogram
368          */
369         AbstractAverageHistogram &averager();
370
371         //! Returns bin properties for the histogram.
372         const AnalysisHistogramSettings &settings() const;
373
374         virtual int flags() const;
375
376         virtual void dataStarted(AbstractAnalysisData *data);
377         virtual void frameStarted(const AnalysisDataFrameHeader &header);
378         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
379         virtual void frameFinished(const AnalysisDataFrameHeader &header);
380         virtual void dataFinished();
381
382     private:
383         virtual AnalysisDataFrameRef tryGetDataFrameInternal(int index) const;
384         virtual bool requestStorageInternal(int nframes);
385
386         PrivateImplPointer<internal::BasicHistogramImpl> impl_;
387
388         // Copy and assign disallowed by base.
389 };
390
391
392 /*! \brief
393  * Data module for per-frame weighted histograms.
394  *
395  * Output data contains the same number of frames as the input data.
396  * Each frame contains the histogram for the points in that frame, interpreted
397  * such that the first column passed to pointsAdded() determines the bin and
398  * the rest give weights to be added to that bin (input data should have at
399  * least two colums, and at least two columns should be added at the same time).
400  * All input columns are averaged into the same histogram.
401  * The number of columns equals the number of bins in the histogram.
402  *
403  * \inpublicapi
404  * \ingroup module_analysisdata
405  */
406 class AnalysisDataWeightedHistogramModule : public AbstractAnalysisData,
407                                             public AnalysisDataModuleInterface
408 {
409     public:
410         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule()
411         AnalysisDataWeightedHistogramModule();
412         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &)
413         explicit AnalysisDataWeightedHistogramModule(const AnalysisHistogramSettings &settings);
414         virtual ~AnalysisDataWeightedHistogramModule();
415
416         //! \copydoc AnalysisDataSimpleHistogramModule::init()
417         void init(const AnalysisHistogramSettings &settings);
418
419         //! \copydoc AnalysisDataSimpleHistogramModule::averager()
420         AbstractAverageHistogram &averager();
421
422         //! \copydoc AnalysisDataSimpleHistogramModule::settings()
423         const AnalysisHistogramSettings &settings() const;
424
425         virtual int flags() const;
426
427         virtual void dataStarted(AbstractAnalysisData *data);
428         virtual void frameStarted(const AnalysisDataFrameHeader &header);
429         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
430         virtual void frameFinished(const AnalysisDataFrameHeader &header);
431         virtual void dataFinished();
432
433     private:
434         virtual AnalysisDataFrameRef tryGetDataFrameInternal(int index) const;
435         virtual bool requestStorageInternal(int nframes);
436
437         PrivateImplPointer<internal::BasicHistogramImpl> impl_;
438
439         // Copy and assign disallowed by base.
440 };
441
442
443 /*! \brief
444  * Data module for bin averages.
445  *
446  * Output data contains one row for each bin; see AbstractAverageHistogram.
447  * Output data contains three columns: the first is the average over all frames
448  * for that bin, the second is the standard deviation of the values, and the
449  * third is the number of samples in that bin.
450  * The input data is interpreted such that the first column passed to
451  * pointsAdded() determines the bin and the rest give values to be added to
452  * that bin (input data should have at least two colums, and at least two
453  * columns should be added at the same time).
454  * All input columns are averaged into the same histogram.
455  *
456  * \inpublicapi
457  * \ingroup module_analysisdata
458  */
459 class AnalysisDataBinAverageModule : public AbstractAnalysisArrayData,
460                                      public AnalysisDataModuleInterface
461 {
462     public:
463         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule()
464         AnalysisDataBinAverageModule();
465         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &)
466         explicit AnalysisDataBinAverageModule(const AnalysisHistogramSettings &settings);
467         virtual ~AnalysisDataBinAverageModule();
468
469         //! \copydoc AnalysisDataSimpleHistogramModule::init()
470         void init(const AnalysisHistogramSettings &settings);
471
472         //! \copydoc AnalysisDataSimpleHistogramModule::settings()
473         const AnalysisHistogramSettings &settings() const;
474
475         virtual int flags() const;
476
477         virtual void dataStarted(AbstractAnalysisData *data);
478         virtual void frameStarted(const AnalysisDataFrameHeader &header);
479         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
480         virtual void frameFinished(const AnalysisDataFrameHeader &header);
481         virtual void dataFinished();
482
483     private:
484         class Impl;
485
486         PrivateImplPointer<Impl>   impl_;
487
488         // Copy and assign disallowed by base.
489 };
490
491 //! Smart pointer to manage an AnalysisDataSimpleHistogramModule object.
492 typedef boost::shared_ptr<AnalysisDataSimpleHistogramModule>
493     AnalysisDataSimpleHistogramModulePointer;
494 //! Smart pointer to manage an AnalysisDataWeightedHistogramModule object.
495 typedef boost::shared_ptr<AnalysisDataWeightedHistogramModule>
496     AnalysisDataWeightedHistogramModulePointer;
497 //! Smart pointer to manage an AnalysisDataBinAverageModule object.
498 typedef boost::shared_ptr<AnalysisDataBinAverageModule>
499     AnalysisDataBinAverageModulePointer;
500
501 } // namespace gmx
502
503 #endif