Merge branch release-4-6
[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  * 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 /*! \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 AnalysisDataModuleParallel
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 frameCount() const;
383
384         virtual int flags() const;
385
386         virtual bool parallelDataStarted(
387             AbstractAnalysisData              *data,
388             const AnalysisDataParallelOptions &options);
389         virtual void frameStarted(const AnalysisDataFrameHeader &header);
390         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
391         virtual void frameFinished(const AnalysisDataFrameHeader &header);
392         virtual void dataFinished();
393
394     private:
395         virtual AnalysisDataFrameRef tryGetDataFrameInternal(int index) const;
396         virtual bool requestStorageInternal(int nframes);
397
398         PrivateImplPointer<internal::BasicHistogramImpl> impl_;
399
400         // Copy and assign disallowed by base.
401 };
402
403
404 /*! \brief
405  * Data module for per-frame weighted histograms.
406  *
407  * Output data contains the same number of frames and data sets as the input
408  * data.  Each frame contains the histogram(s) for the points in that frame,
409  * interpreted such that the first column passed to pointsAdded() determines
410  * the bin and the rest give weights to be added to that bin (input data should
411  * have at least two colums, and at least two columns should be added at the
412  * same time).
413  * Each input data set is processed independently into the corresponding output
414  * data set.
415  * All input columns for a data set are averaged into the same histogram.
416  * The number of columns for all data sets equals the number of bins in the
417  * histogram.
418  *
419  * \inpublicapi
420  * \ingroup module_analysisdata
421  */
422 class AnalysisDataWeightedHistogramModule : public AbstractAnalysisData,
423                                             public AnalysisDataModuleParallel
424 {
425     public:
426         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule()
427         AnalysisDataWeightedHistogramModule();
428         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &)
429         explicit AnalysisDataWeightedHistogramModule(const AnalysisHistogramSettings &settings);
430         virtual ~AnalysisDataWeightedHistogramModule();
431
432         //! \copydoc AnalysisDataSimpleHistogramModule::init()
433         void init(const AnalysisHistogramSettings &settings);
434
435         //! \copydoc AnalysisDataSimpleHistogramModule::averager()
436         AbstractAverageHistogram &averager();
437
438         //! \copydoc AnalysisDataSimpleHistogramModule::settings()
439         const AnalysisHistogramSettings &settings() const;
440
441         virtual int frameCount() const;
442
443         virtual int flags() const;
444
445         virtual bool parallelDataStarted(
446             AbstractAnalysisData              *data,
447             const AnalysisDataParallelOptions &options);
448         virtual void frameStarted(const AnalysisDataFrameHeader &header);
449         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
450         virtual void frameFinished(const AnalysisDataFrameHeader &header);
451         virtual void dataFinished();
452
453     private:
454         virtual AnalysisDataFrameRef tryGetDataFrameInternal(int index) const;
455         virtual bool requestStorageInternal(int nframes);
456
457         PrivateImplPointer<internal::BasicHistogramImpl> impl_;
458
459         // Copy and assign disallowed by base.
460 };
461
462
463 /*! \brief
464  * Data module for bin averages.
465  *
466  * Output data contains one row for each bin; see AbstractAverageHistogram.
467  * Output data contains one column for each input data set.
468  * The value in a column is the average over all frames of that data set for
469  * that bin.
470  * The input data is interpreted such that the first column passed to
471  * pointsAdded() determines the bin and the rest give values to be added to
472  * that bin (input data should have at least two colums, and at least two
473  * columns should be added at the same time).
474  * All input columns for a data set are averaged into the same histogram.
475  *
476  * \inpublicapi
477  * \ingroup module_analysisdata
478  */
479 class AnalysisDataBinAverageModule : public AbstractAnalysisArrayData,
480                                      public AnalysisDataModuleSerial
481 {
482     public:
483         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule()
484         AnalysisDataBinAverageModule();
485         //! \copydoc AnalysisDataSimpleHistogramModule::AnalysisDataSimpleHistogramModule(const AnalysisHistogramSettings &)
486         explicit AnalysisDataBinAverageModule(const AnalysisHistogramSettings &settings);
487         virtual ~AnalysisDataBinAverageModule();
488
489         //! \copydoc AnalysisDataSimpleHistogramModule::init()
490         void init(const AnalysisHistogramSettings &settings);
491
492         //! \copydoc AnalysisDataSimpleHistogramModule::settings()
493         const AnalysisHistogramSettings &settings() const;
494
495         virtual int flags() const;
496
497         virtual void dataStarted(AbstractAnalysisData *data);
498         virtual void frameStarted(const AnalysisDataFrameHeader &header);
499         virtual void pointsAdded(const AnalysisDataPointSetRef &points);
500         virtual void frameFinished(const AnalysisDataFrameHeader &header);
501         virtual void dataFinished();
502
503     private:
504         class Impl;
505
506         PrivateImplPointer<Impl>   impl_;
507
508         // Copy and assign disallowed by base.
509 };
510
511 //! Smart pointer to manage an AnalysisDataSimpleHistogramModule object.
512 typedef boost::shared_ptr<AnalysisDataSimpleHistogramModule>
513     AnalysisDataSimpleHistogramModulePointer;
514 //! Smart pointer to manage an AnalysisDataWeightedHistogramModule object.
515 typedef boost::shared_ptr<AnalysisDataWeightedHistogramModule>
516     AnalysisDataWeightedHistogramModulePointer;
517 //! Smart pointer to manage an AnalysisDataBinAverageModule object.
518 typedef boost::shared_ptr<AnalysisDataBinAverageModule>
519     AnalysisDataBinAverageModulePointer;
520
521 } // namespace gmx
522
523 #endif