d3c298f0c8ba6f10a0c6a665e24036612818f1a0
[alexxy/gromacs.git] / src / gromacs / gmxlib / statistics / histogram.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009,2010, 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 /*! \page histograms Histogram calculation
36  *
37  * Functions to calculate histograms are defined in histogram.h.
38  * The principle is simple: histogram calculation is set up with
39  * gmx_histogram_create() and gmx_histogram_set_*(), the histogram is sampled
40  * using the provided functions, and gmx_histogram_finish() is called to
41  * finish the sampling.
42  * Various post-processing functions can then be used to normalize the
43  * histogram in various ways and to write it into a file.
44  * gmx_histogram_get_*() can be used to access data from the histogram.
45  * gmx_histogram_free() can be used to free the memory allocated for a
46  * histogram.
47  *
48  *
49  * \section histogram_sampling Initialization and sampling
50  *
51  * A histogram calculation is initialized by calling gmx_histogram_create()
52  * or gmx_histogram_create_range().
53  * The first function takes the type of the histogram (see \ref e_histogram_t)
54  * and the number of bins, and allocates the necessary memory.
55  * The bin locations can be initialized with gmx_histogram_set_integerbins()
56  * and one of gmx_histogram_set_binwidth() and gmx_histogram_set_range().
57  * Only uniformly spaced bins are currently supported.
58  * The second initialization function takes the beginning and end of the range
59  * and the bin width.
60  * The treatment of values that fall outside the histogram range can be
61  * set with gmx_histogram_set_all().
62  * gmx_histogram_set_blocksize() can be used to specify a block size for error
63  * estimates. If not called, no error estimates are calculated.
64  * Otherwise, a histogram is calculated for each block of given number of
65  * frames, and the error estimated as the error of the mean of these block
66  * histograms.
67  * If the number of frames is not divisible by the block size,
68  * the last block is discarded.
69  * gmx_histogram_set_block_output() can be used to write the individual
70  * block histograms to a file (it is currently not very flexible).
71  *
72  * After initialization, three sets of sampling functions are provided
73  * to sample the differen types of histograms:
74  *  - Use gmx_histogram_increment() or gmx_histogram_increment_bin() to
75  *    calculate simple histograms (\ref HIST_SIMPLE histograms).
76  *  - Use gmx_histogram_add() or gmx_histogram_add_to_bin() to calculate
77  *    histograms where different points can have different weight
78  *    (\ref HIST_WEIGHT histograms).
79  *  - Use gmx_histogram_add_item() or gmx_histogram_add_item_to_bin() to
80  *    calculate averages within each bin
81  *    (\ref HIST_BINAVER histograms).
82  *
83  * The functions aboge that take bin indices directly do no range checking,
84  * i.e., one must ensure that the bin number is between 0 and the number of
85  * bins in the histogram. In contrast, the functions that use real values to
86  * locate the correct bin use range checking, and silently discard values
87  * outside the histogram (unless gmx_histogram_set_all() has been called).
88  * gmx_histogram_find_bin() can be used to find the bin number corresponding
89  * to a value, adhering to the gmx_histogram_set_all() setting.
90  *
91  * After a frame is sampled, gmx_histogram_finish_frame() needs to be
92  * called.
93  * After all data is sampled, gmx_histogram_finish() should be called.
94  * After these calls, the histogram will be normalized such that the
95  * sum over all bins equals the average number of samples per frame, and
96  * the error field contains the error of the mean at each bin.
97  *
98  *
99  * \section histogram_processing Post-processing
100  *
101  * The following functions can be used to process the histograms:
102  *  - gmx_histogram_clone() makes a deep copy.
103  *  - gmx_histogram_resample_dblbw() also makes a deep copy,
104  *    but uses a binwidth that is double of the input one
105  *    (see below for usage).
106  *  - gmx_histogram_normalize_prob() normalizes a histogram such that its
107  *    integral becomes one.
108  *  - gmx_histogram_scale() and gmx_histogram_scale_vec() can be used
109  *    to scale a histogram uniformly or non-uniformly, respectively.
110  *
111  * There are also functions to write histograms to a file:
112  *  - gmx_histogram_write() writes a single histogram, optionally with
113  *    errors.
114  *  - gmx_histogram_write_array() writes multiple histograms with identical
115  *    bins. Values and/or errors can be written.
116  *  - gmx_histogram_write_cum_array() writes cumulative histograms for
117  *    multiple histograms with identical bins.
118  *
119  * gmx_histogram_resample_dblbw() is useful if a histogram and its
120  * cumulative sum are required at same points.
121  * One can then sample the histogram with half the desired binwidth, and
122  * then use gmx_histogram_resample_dblbw() to construct two different
123  * versions of the histogram (by changing \p bIntegerBins), one suitable for
124  * writing out the histogram and the other for writing the cumulative
125  * distribution.
126  *
127  * Access to the histogram data is also provided through the following
128  * functions:
129  *  - gmx_histogram_get_nbins()
130  *  - gmx_histogram_get_binwidth()
131  *  - gmx_histogram_get_value()
132  *  - gmx_histogram_get_bin_value()
133  *  - gmx_histogram_get_values()
134  *  - gmx_histogram_get_errors()
135  *
136  * gmx_histogram_free() can be used to free memory associated with a
137  * histogram when it is no longer needed.
138  */
139 /*! \internal \file
140  * \brief Implementation of functions in histogram.h.
141  */
142 #ifdef HAVE_CONFIG_H
143 #include <config.h>
144 #endif
145
146 #include <math.h>
147 #include <string.h>
148
149 #include <smalloc.h>
150 #include <vec.h>
151
152 #include <histogram.h>
153
154 /*! \internal \brief
155  * Stores data for a histogram.
156  */
157 struct gmx_histogram_t
158 {
159     /** The left edge of the first bin. */
160     real                 start;
161     /** The right edge of the last bin. */
162     real                 end;
163     /** Bin width. */
164     real                 binwidth;
165     /** Number of bins. */
166     int                  nbins;
167     /** The final histogram. */
168     double              *hist;
169     /** Standard deviation of each bin (calculated from block histograms). */
170     double              *histerr;
171
172     /** Histogram type. */
173     e_histogram_t        type;
174     /** Histogram flags; */
175     int                  flags;
176     /** Block size for averaging. */
177     int                  bsize;
178     /** Output file for block histograms (can be NULL). */
179     FILE                *blockfp;
180
181     /** Inverse bin width. */
182     real                 invbw;
183     /** Current histogram value. */
184     double              *chist;
185     /** Current histogram count. */
186     int                 *cn;
187     /** Number of frames read for the current block so far. */
188     int                  nframes;
189     /** Number of blocks averaged so far. */
190     int                  nblocks;
191 };
192
193 /*!
194  * \param[out] hp      Histogram to create.
195  * \param[in]  type    Histogram type to create;
196  * \param[in]  nbins   Number of bins.
197  * \returns    0 on success, a non-zero error code on error.
198  *
199  * Initialized the histogram structure \p h with the provided values,
200  * allocating the necessary memory.
201  */
202 int
203 gmx_histogram_create(gmx_histogram_t **hp, e_histogram_t type, int nbins)
204 {
205     gmx_histogram_t *h;
206
207     if (nbins <= 0)
208     {
209         *hp = NULL;
210         gmx_incons("number of histogram bins <= 0");
211         return EINVAL;
212     }
213
214     snew(h, 1);
215     h->start    = 0;
216     h->end      = 0;
217     h->binwidth = 0;
218     h->nbins    = nbins;
219     h->hist     = NULL;
220     h->histerr  = NULL;
221
222     h->type     = type;
223     h->flags    = 0;
224
225     h->bsize    = 0;
226     h->blockfp  = NULL;
227     h->invbw    = 0;
228     h->chist    = NULL;
229     h->cn       = NULL;
230     h->nframes  = 0;
231     h->nblocks  = 0;
232
233     snew(h->hist,    nbins + 1);
234     snew(h->histerr, nbins + 1);
235     snew(h->cn,      nbins + 1);
236     if (type != HIST_SIMPLE)
237     {
238         snew(h->chist, nbins + 1);
239     }
240     gmx_histogram_clear(h);
241
242     *hp = h;
243     return 0;
244 }
245
246 /*!
247  * \param[out] hp      Histogram to create.
248  * \param[in]  type    Histogram type to create;
249  * \param[in]  start   Left edge/center of the first bin
250  *   (depending on \p bIntegerBins).
251  * \param[in]  end     Right edge/center of the last bin
252  *   (depending on \p bIntegerBins).
253  * \param[in]  binw    Bin width.
254  * \param[in]  bIntegerBins If true, histogram bins are centered at
255  *   \c start+n*binwidth, otherwise the centers are at
256  *   \c start+(n+0.5)*binwidth.
257  * \returns    0 on success, a non-zero error code on error.
258  *
259  * Initialized the histogram structure \p h with the provided values,
260  * allocating the necessary memory.
261  */
262 int
263 gmx_histogram_create_range(gmx_histogram_t **hp, e_histogram_t type,
264                            real start, real end, real binw, gmx_bool bIntegerBins)
265 {
266     gmx_histogram_t *h;
267     int              nbins;
268     int              rc;
269
270     *hp = NULL;
271     if (start >= end || binw <= 0)
272     {
273         gmx_incons("histogram left edge larger than right edge or bin width <= 0");
274         return EINVAL;
275     }
276
277     /* Adjust the end points and calculate the number of bins */
278     if (bIntegerBins)
279     {
280         nbins = ceil((end - start) / binw) + 1;
281         end   = start + (nbins - 1) * binw;
282     }
283     else
284     {
285         start = binw * floor(start / binw);
286         end   = binw * ceil(end / binw);
287         if (start != 0)
288         {
289             start -= binw;
290         }
291         end  += binw;
292         nbins = (int)((end - start) / binw + 0.5);
293     }
294     /* Create the histogram */
295     rc = gmx_histogram_create(&h, type, nbins);
296     if (rc != 0)
297     {
298         return rc;
299     }
300     /* Set it up */
301     gmx_histogram_set_integerbins(h, bIntegerBins);
302     gmx_histogram_set_binwidth(h, start, binw);
303
304     *hp = h;
305     return 0;
306 }
307
308 /*!
309  * \param[in,out] h       Histogram to clear.
310  *
311  * Histograms are automatically cleared when initialized; you only need to
312  * call this function if you want to reuse a histogram structure that has
313  * already been used for sampling.
314  */
315 void
316 gmx_histogram_clear(gmx_histogram_t *h)
317 {
318     int              i;
319
320     if (h->nbins <= 0)
321     {
322         return;
323     }
324     for (i = 0; i <= h->nbins; ++i)
325     {
326         h->hist[i]    = 0;
327         h->histerr[i] = 0;
328         if (h->chist)
329         {
330             h->chist[i] = 0;
331         }
332         h->cn[i]      = 0;
333     }
334     h->nframes      = 0;
335     h->nblocks      = 0;
336 }
337
338 /*!
339  * \param[in] h  Histogram to free.
340  *
341  * The pointer \p h is invalid after the call.
342  */
343 void
344 gmx_histogram_free(gmx_histogram_t *h)
345 {
346     sfree(h->chist);
347     sfree(h->cn);
348     sfree(h->hist);
349     sfree(h->histerr);
350     sfree(h);
351 }
352
353 /*!
354  * \param[in,out] h      Histogram data structure.
355  * \param[in]     start  Left edge/center of the first bin
356  *   (depending on gmx_histogram_set_integerbins()).
357  * \param[in]     binw   Bin width.
358  * \returns       0 on success, a non-zero error code on error.
359  */
360 int
361 gmx_histogram_set_binwidth(gmx_histogram_t *h, real start, real binw)
362 {
363     if (binw <= 0)
364     {
365         gmx_incons("histogram binwidth <= 0");
366         return EINVAL;
367     }
368     if (h->flags & HIST_INTEGERBINS)
369     {
370         start   -= 0.5*binw;
371     }
372     h->start     = start;
373     h->binwidth  = binw;
374     h->end       = start + h->nbins * binw;
375     h->invbw     = 1.0/binw;
376     h->flags    |= HIST_INITBW;
377     return 0;
378 }
379
380 /*!
381  * \param[in,out] h      Histogram data structure.
382  * \param[in]     start  Left edge/center of the first bin
383  *   (depending on gmx_histogram_set_integerbins()).
384  * \param[in]     end    Right edge/center of the last bin
385  *   (depending on gmx_histogram_set_integerbins()).
386  * \returns       0 on success, a non-zero error code on error.
387  */
388 int
389 gmx_histogram_set_range(gmx_histogram_t *h, real start, real end)
390 {
391     if (start >= end)
392     {
393         gmx_incons("histogram left edge larger than right edge");
394         return EINVAL;
395     }
396     h->start         = start;
397     h->end           = end;
398     if (h->flags & HIST_INTEGERBINS)
399     {
400         h->binwidth  = (end - start) / (h->nbins - 1);
401         start       -= 0.5*h->binwidth;
402         end         += 0.5*h->binwidth;
403     }
404     else
405     {
406         h->binwidth  = (end - start) / h->nbins;
407     }
408     h->invbw         = 1.0/h->binwidth;
409     h->flags        &= ~HIST_INITBW;
410     return 0;
411 }
412
413 /*!
414  * \param[in,out] h      Histogram data structure.
415  * \param[in]     bIntegerBins If true, histogram bins are centered at
416  *   \c start+n*binwidth, otherwise the centers are at
417  *   \c start+(n+0.5)*binwidth.
418  */
419 void
420 gmx_histogram_set_integerbins(gmx_histogram_t *h, gmx_bool bIntegerBins)
421 {
422     /* Adjust the ranges if they have been initialized */
423     if (h->start < h->end)
424     {
425         if (h->flags & HIST_INTEGERBINS)
426         {
427             h->start   += 0.5*h->binwidth;
428             if (h->flags & HIST_INITBW)
429             {
430                 h->end += 0.5*h->binwidth;
431             }
432             else
433             {
434                 h->end -= 0.5*h->binwidth;
435             }
436         }
437         if (bIntegerBins)
438         {
439             h->start   -= 0.5*h->binwidth;
440             if (h->flags & HIST_INITBW)
441             {
442                 h->end -= 0.5*h->binwidth;
443             }
444             else
445             {
446                 h->end += 0.5*h->binwidth;
447             }
448         }
449     }
450     if (bIntegerBins)
451     {
452         h->flags |= HIST_INTEGERBINS;
453     }
454     else
455     {
456         h->flags &= ~HIST_INTEGERBINS;
457     }
458 }
459
460 /*!
461  * \param[in,out] h     Histogram data structure.
462  * \param[in]     bAll  If true, values outside the histogram edges are added
463  *   to the bins at the edges.
464  *
465  * \p bAll can be used to avoid rounding errors in cases where the histogram
466  * spans the full range of possible values. If set, the values that are at
467  * the exact maximum are still correctly included.
468  */
469 void
470 gmx_histogram_set_all(gmx_histogram_t *h, gmx_bool bAll)
471 {
472     if (bAll)
473     {
474         h->flags |= HIST_ALL;
475     }
476     else
477     {
478         h->flags &= ~HIST_ALL;
479     }
480 }
481
482 /*!
483  * \param[in,out] h      Histogram data structure.
484  * \param[in]     bsize  Block size for error estimates.
485  * \returns       0 on success, a non-zero error code on error.
486  *
487  * If \p bsize is zero, no block averaging or error estimates are done.
488  * This is also the case if this function is not called.
489  */
490 int
491 gmx_histogram_set_blocksize(gmx_histogram_t *h, int bsize)
492 {
493     if (bsize < 0)
494     {
495         gmx_incons("histogram block size < 0");
496         return EINVAL;
497     }
498     h->bsize = bsize;
499     return 0;
500 }
501
502 /*!
503  * \param[in,out] h  Histogram data structure.
504  * \param[in]     fp File for block output.
505  * \returns       0 on success, a non-zero error code on error.
506  *
507  * Sets a file into which each block histogram (the histogram after each
508  * \c gmx_histogram_t::bsize frames) is written.
509  * All histograms are written to the same file, separated by empty lines.
510  * If this function is not called, the block histograms are only used for
511  * error estimation, not written to a file.
512  */
513 int
514 gmx_histogram_set_block_output(gmx_histogram_t *h, FILE *fp)
515 {
516     if (h->bsize <= 0)
517     {
518         gmx_incons("histogram block size not set but output initialized");
519         return EINVAL;
520     }
521     h->blockfp = fp;
522     return 0;
523 }
524
525 /*!
526  * \param[in] h     Histogram data.
527  * \param[in] pos   Position.
528  * \returns   Bin index in \p h corresponding to \p pos, or -1 if there is no
529  *    such bin.
530  *
531  * If gmx_histogram_set_all() has been called with TRUE, values outside the
532  * histogram are mapped to the bins at the edges.
533  */
534 int
535 gmx_histogram_find_bin(gmx_histogram_t *h, real pos)
536 {
537     if (pos < h->start)
538     {
539         if (h->flags & HIST_ALL)
540         {
541             return 0;
542         }
543         else
544         {
545             return -1;
546         }
547     }
548     else if (pos >= h->end)
549     {
550         if (h->flags & HIST_ALL)
551         {
552             return h->nbins - 1;
553         }
554         else
555         {
556             return -1;
557         }
558     }
559     /* Calculate the bin index if we are inside the box */
560     return (int)((pos - h->start)*h->invbw);
561 }
562
563 /*!
564  * \param[in] h     Histogram data.
565  * \returns   Number of bins in \p h.
566  */
567 int
568 gmx_histogram_get_nbins(gmx_histogram_t *h)
569 {
570     return h->nbins;
571 }
572
573 /*!
574  * \param[in] h     Histogram data.
575  * \returns   Bin width of \p h, 0 if no binwidth has been set.
576  */
577 real
578 gmx_histogram_get_binwidth(gmx_histogram_t *h)
579 {
580     return h->binwidth;
581 }
582
583 /*!
584  * \param[in]  h     Histogram data.
585  * \param[in]  pos   Position.
586  * \param[out] value Pointer to receive the value (can be NULL).
587  * \param[out] err   Pointer to receive the value (can be NULL).
588  *
589  * If \p pos is outside the range of the histogram, zeros are returned.
590  */
591 void
592 gmx_histogram_get_value(gmx_histogram_t *h, real pos, double *value, double *err)
593 {
594     int     bin;
595     double  v, e;
596
597     if (pos < h->start || pos > h->end)
598     {
599         v = e = 0;
600     }
601     else
602     {
603         bin = gmx_histogram_find_bin(h, pos);
604         if (bin < 0)
605         {
606             v = e = 0;
607         }
608         else
609         {
610             v = h->hist[bin];
611             e = h->histerr[bin];
612         }
613     }
614     if (value)
615     {
616         *value = v;
617     }
618     if (err)
619     {
620         *err = e;
621     }
622 }
623
624 /*!
625  * \param[in]  h     Histogram data.
626  * \param[in]  bin   Bin number.
627  * \param[out] value Pointer to receive the value (can be NULL).
628  * \param[out] err   Pointer to receive the value (can be NULL).
629  *
630  * If \p bin is outside the valid range, zeros are returned.
631  */
632 void
633 gmx_histogram_get_bin_value(gmx_histogram_t *h, int bin, double *value, double *err)
634 {
635     double  v, e;
636
637     if (bin < 0 || bin >= h->nbins)
638     {
639         v = e = 0;
640     }
641     else
642     {
643         v = h->hist[bin];
644         e = h->histerr[bin];
645     }
646     if (value)
647     {
648         *value = v;
649     }
650     if (err)
651     {
652         *err = e;
653     }
654 }
655
656 /*!
657  * \param[in]  h     Histogram data.
658  * \returns    Pointer to an array of values for \p h.
659  *
660  * The returned array has one element for each bin of \p h.
661  * The returned pointer should not be freed.
662  */
663 double *
664 gmx_histogram_get_values(gmx_histogram_t *h)
665 {
666     return h->hist;
667 }
668
669 /*!
670  * \param[in]  h     Histogram data.
671  * \returns    Pointer to an array of errors for \p h.
672  *
673  * The returned array has one element for each bin of \p h.
674  * The returned pointer should not be freed.
675  */
676 double *
677 gmx_histogram_get_errors(gmx_histogram_t *h)
678 {
679     return h->histerr;
680 }
681
682 /*!
683  * \param[in,out] h     Histogram data.
684  * \param[in]     pos   Position.
685  */
686 void
687 gmx_histogram_increment(gmx_histogram_t *h, real pos)
688 {
689     int bin = gmx_histogram_find_bin(h, pos);
690     if (bin < 0)
691     {
692         return;
693     }
694     h->cn[bin]++;
695 }
696
697 /*!
698  * \param[in,out] h     Histogram data.
699  * \param[in]     pos   Position.
700  * \param[in]     value Value to add.
701  */
702 void
703 gmx_histogram_add(gmx_histogram_t *h, real pos, double value)
704 {
705     int bin = gmx_histogram_find_bin(h, pos);
706     if (bin < 0)
707     {
708         return;
709     }
710     h->chist[bin] += value;
711 }
712
713 /*!
714  * \param[in,out] h     Histogram data.
715  * \param[in]     pos   Position.
716  * \param[in]     value Value to add.
717  */
718 void
719 gmx_histogram_add_item(gmx_histogram_t *h, real pos, double value)
720 {
721     int bin = gmx_histogram_find_bin(h, pos);
722     if (bin < 0)
723     {
724         return;
725     }
726     h->chist[bin] += value;
727     h->cn[bin]++;
728 }
729
730 /*!
731  * \param[in,out] h     Histogram data.
732  * \param[in]     bin   Bin number.
733  *
734  * No checks for out-of-bound errors are done: \p bin should be >=0 and
735  * < \p h->nbins.
736  */
737 void
738 gmx_histogram_increment_bin(gmx_histogram_t *h, int bin)
739 {
740     h->cn[bin]++;
741 }
742
743 /*!
744  * \param[in,out] h     Histogram data.
745  * \param[in]     bin   Bin number.
746  * \param[in]     value Value to add.
747  *
748  * No checks for out-of-bound errors are done: \p bin should be >=0 and
749  * < \p h->nbins.
750  */
751 void
752 gmx_histogram_add_to_bin(gmx_histogram_t *h, int bin, double value)
753 {
754     h->chist[bin] += value;
755 }
756
757 /*!
758  * \param[in,out] h     Histogram data.
759  * \param[in]     bin   Bin number.
760  * \param[in]     value Value to add.
761  *
762  * No checks for out-of-bound errors are done: \p bin should be >=0 and
763  * < \p h->nbins.
764  */
765 void
766 gmx_histogram_add_item_to_bin(gmx_histogram_t *h, int bin, double value)
767 {
768     h->chist[bin] += value;
769     h->cn[bin]++;
770 }
771
772 /*! \brief
773  * Processes a sampled block histogram.
774  *
775  * \param[in,out] h    Histogram data structure.
776  */
777 static void
778 finish_histogram_block(gmx_histogram_t *h)
779 {
780     int   i;
781     real  v;
782
783     if (h->nframes == 0)
784     {
785         return;
786     }
787
788     if (h->flags & HIST_ALL)
789     {
790         if (h->chist)
791         {
792             h->chist[h->nbins-1] += h->chist[h->nbins];
793         }
794         h->cn[h->nbins-1] += h->cn[h->nbins];
795     }
796
797     for (i = 0; i <= h->nbins; ++i)
798     {
799         if (h->chist)
800         {
801             v = h->chist[i] / (h->cn[i] > 0 ? h->cn[i] : h->nframes);
802         }
803         else
804         {
805             v = ((real)h->cn[i]) / h->nframes;
806         }
807         if (h->blockfp)
808         {
809             fprintf(h->blockfp, "%10g %10g\n", h->start + (i+0.5)*h->binwidth, v);
810         }
811         h->hist[i]    += v;
812         h->histerr[i] += sqr(v);
813         if (h->chist)
814         {
815             h->chist[i] = 0;
816         }
817         h->cn[i] = 0;
818     }
819     if (h->blockfp)
820     {
821         fprintf(h->blockfp, "\n");
822     }
823     h->nblocks++;
824     h->nframes = 0;
825 }
826
827 /*!
828  * \param[in,out] h    Histogram data structure.
829  *
830  * Should be called after each frame of data.
831  *
832  * \see gmx_histogram_finish()
833  */
834 void
835 gmx_histogram_finish_frame(gmx_histogram_t *h)
836 {
837     h->nframes++;
838     if (h->nframes == h->bsize)
839     {
840         finish_histogram_block(h);
841     }
842 }
843
844 /*!
845  * \param[in,out] h    Histogram data structure.
846  *
847  * Normalizes the histogram.
848  * Should be called after all frames have been sampled and before any
849  * post-processing of the histogram.
850  * If block size has not been set with gmx_histogram_set_blocksize(),
851  * this function does no normalization, but it should still be called,
852  * otherwise the \c gmx_histogram_t::hist array will contain only zeros.
853  *
854  * \see gmx_histogram_finish_frame()
855  */
856 void
857 gmx_histogram_finish(gmx_histogram_t *h)
858 {
859     int  i;
860
861     if (h->nframes > 0 || h->bsize == 0)
862     {
863         if (h->nframes < h->bsize)
864         {
865             fprintf(stderr, "Last block smaller (%d frames) than the target size (%d frames) skipped \n",
866                     h->nframes, h->bsize);
867         }
868         else
869         {
870             finish_histogram_block(h);
871         }
872     }
873     if (h->nblocks == 0)
874     {
875         return;
876     }
877
878     for (i = 0; i <= h->nbins; ++i)
879     {
880         h->hist[i]    /= h->nblocks;
881         h->histerr[i] /= h->nblocks;
882         h->histerr[i]  = sqrt((h->histerr[i] - sqr(h->hist[i])) / h->nblocks);
883     }
884 }
885
886 /*!
887  * \param[out] destp        Destination histogram.
888  * \param[in]  src          Source histogram.
889  * \param[in]  bIntegerBins Control bin center position.
890  *
891  * Uses \p src to create a new histogram that has double the binwidth.
892  * If \p bIntegerBins is TRUE, the first new bin will be centered at
893  * \c src->start, otherwise the left edge will be at \c src->start.
894  *
895  * This function is mostly useful if one needs to sample both the
896  * histogram and the cumulative histogram at same points.
897  * To achieve this, first sample a histogram with half the desired
898  * binwidth, and then use this function to create two different verions
899  * of it with different values of \p bIntegerBins.
900  * gmx_histogram_write_array() and gmx_histogram_write_cum_array() can
901  * now used to write out the values correctly at identical values.
902  *
903  * Should be called only after gmx_histogram_finish() has been called.
904  * \p src should have been sampled without gmx_histogram_set_integerbins().
905  */
906 void
907 gmx_histogram_resample_dblbw(gmx_histogram_t **destp, gmx_histogram_t *src,
908                              gmx_bool bIntegerBins)
909 {
910     gmx_histogram_t *dest;
911     int              i, j;
912     real             v, ve;
913
914     gmx_histogram_create(destp, src->type, src->nbins / 2);
915     dest = *destp;
916     sfree(dest->chist); dest->chist = NULL;
917     sfree(dest->cn);    dest->cn    = NULL;
918     gmx_histogram_set_binwidth(dest, src->start, src->binwidth * 2);
919     gmx_histogram_set_integerbins(dest, bIntegerBins);
920
921     for (i = j = 0; i < dest->nbins; ++i)
922     {
923         if (bIntegerBins && i == 0)
924         {
925             v  = src->hist[0];
926             ve = sqr(src->histerr[0]);
927             ++j;
928         }
929         else
930         {
931             v  = src->hist[j]         + src->hist[j+1];
932             ve = sqr(src->histerr[j]) + sqr(src->histerr[j+1]);
933             j += 2;
934         }
935         ve               = sqrt(ve);
936         dest->hist[i]    = v;
937         dest->histerr[i] = ve;
938     }
939     dest->hist[dest->nbins]    = 0;
940     dest->histerr[dest->nbins] = 0;
941 }
942
943 /*!
944  * \param[out] destp Destination histogram.
945  * \param[in]  src   Source histogram.
946  *
947  * Makes a clone of \p src for post-processing.
948  */
949 void
950 gmx_histogram_clone(gmx_histogram_t **destp, gmx_histogram_t *src)
951 {
952     gmx_histogram_t *dest;
953
954     snew(dest, 1);
955     memcpy(dest, src, sizeof(*dest));
956
957     /* These are not needed in post-processing */
958     dest->blockfp = NULL;
959     dest->chist   = NULL;
960     dest->cn      = NULL;
961
962     /* Make a deep copy of the actual histograms */
963     snew(dest->hist,    src->nbins+1);
964     snew(dest->histerr, src->nbins+1);
965     memcpy(dest->hist,    src->hist,    (src->nbins+1)*sizeof(real));
966     memcpy(dest->histerr, src->histerr, (src->nbins+1)*sizeof(real));
967
968     *destp = dest;
969 }
970
971 /*!
972  * \param[in,out] h  Histogram to normalize.
973  *
974  * Normalizes the histogram such that its integral equals one.
975  */
976 void
977 gmx_histogram_normalize_prob(gmx_histogram_t *h)
978 {
979     int  i;
980     real sum;
981     real normfac;
982
983     sum = 0;
984     for (i = 0; i <= h->nbins; ++i)
985     {
986         sum += h->hist[i];
987     }
988
989     normfac = h->invbw / sum;
990     gmx_histogram_scale(h, normfac);
991 }
992
993 /*!
994  * \param[in,out] h    Histogram to normalize.
995  * \param[in]     norm Scaling factor.
996  *
997  * All bin values are multiplied by \p norm.
998  */
999 void
1000 gmx_histogram_scale(gmx_histogram_t *h, real norm)
1001 {
1002     int  i;
1003
1004     for (i = 0; i <= h->nbins; ++i)
1005     {
1006         h->hist[i]    *= norm;
1007         h->histerr[i] *= norm;
1008     }
1009 }
1010
1011 /*!
1012  * \param[in,out] h    Histogram to normalize.
1013  * \param[in]     norm Scaling vector.
1014  *
1015  * The i'th bin is multiplied by \p norm[i].
1016  */
1017 void
1018 gmx_histogram_scale_vec(gmx_histogram_t *h, real norm[])
1019 {
1020     int  i;
1021
1022     for (i = 0; i < h->nbins; ++i)
1023     {
1024         h->hist[i]    *= norm[i];
1025         h->histerr[i] *= norm[i];
1026     }
1027     h->hist[h->nbins]    *= norm[h->nbins-1];
1028     h->histerr[h->nbins] *= norm[h->nbins-1];
1029 }
1030
1031 /*! \brief
1032  * Makes some checks on output histograms and finds the maximum number of bins.
1033  *
1034  * \param[in]  n     Number of histograms in \p h.
1035  * \param[in]  h     Array of histograms.
1036  * \param[out] nbins Pointer to a value that will receive the maximum number
1037  *   of bins in \p h.
1038  */
1039 static void
1040 prepare_output(int n, gmx_histogram_t *h[], int *nbins)
1041 {
1042     int  j;
1043
1044     *nbins = 0;
1045     for (j = 0; j < n; ++j)
1046     {
1047         if (!gmx_within_tol(h[j]->start, h[0]->start, GMX_REAL_EPS))
1048         {
1049             fprintf(stderr, "gmx_ana_histogram_write: histogram start values not identical\n");
1050         }
1051         if (!gmx_within_tol(h[j]->binwidth, h[0]->binwidth, GMX_REAL_EPS))
1052         {
1053             fprintf(stderr, "gmx_ana_histogram_write: bin widths not identical\n");
1054         }
1055         if (*nbins < h[j]->nbins)
1056         {
1057             *nbins = h[j]->nbins;
1058         }
1059     }
1060 }
1061
1062 /*!
1063  * \param[in] fp           Output file.
1064  * \param[in] h            Array of histograms to write.
1065  * \param[in] bErrors      If TRUE, histogram errors are written.
1066  *
1067  * Convenience wrapper for gmx_histogram_write_array() for writing a single
1068  * histogram.
1069  *
1070  * \see gmx_histogram_write_array()
1071  */
1072 void
1073 gmx_histogram_write(FILE *fp, gmx_histogram_t *h, gmx_bool bErrors)
1074 {
1075     gmx_histogram_write_array(fp, 1, &h, TRUE, bErrors);
1076 }
1077
1078 /*!
1079  * \param[in] fp           Output file.
1080  * \param[in] n            Number of histograms in \p h.
1081  * \param[in] h            Array of histograms to write.
1082  * \param[in] bValue       If TRUE, histogram values are written.
1083  * \param[in] bErrors      If TRUE, histogram errors are written.
1084  *
1085  * All the histograms in the array \p h should have the same bin widths and
1086  * left edges, otherwise the behavior is undefined.
1087  * The output format is one bin per line. The first number on the line is the
1088  * center of the bin, followed by one or two numbers for each histogram
1089  * (depending on \p bValue and \p bErrors).
1090  * If both \p bValue and \p bErrors are both TRUE, the values are written
1091  * before the errors.
1092  */
1093 void
1094 gmx_histogram_write_array(FILE *fp, int n, gmx_histogram_t *h[],
1095                           gmx_bool bValue, gmx_bool bErrors)
1096 {
1097     int           i, j, nbins;
1098
1099     prepare_output(n, h, &nbins);
1100     for (i = 0; i < nbins; ++i)
1101     {
1102         fprintf(fp, "%10g", h[0]->start + (i+0.5)*h[0]->binwidth);
1103         for (j = 0; j < n; ++j)
1104         {
1105             if (bValue)
1106             {
1107                 fprintf(fp, " %10g", i < h[j]->nbins ? h[j]->hist[i] : 0.0);
1108             }
1109             if (bErrors)
1110             {
1111                 fprintf(fp, " %10g", i < h[j]->nbins ? h[j]->histerr[i] : 0.0);
1112             }
1113         }
1114         fprintf(fp, "\n");
1115     }
1116     fprintf(fp, "\n");
1117 }
1118
1119 /*!
1120  * \param[in] fp           Output file.
1121  * \param[in] n            Number of histograms in \p h.
1122  * \param[in] h            Array of histograms to write.
1123  * \param[in] bValue       If TRUE, histogram values are written.
1124  * \param[in] bErrors      If TRUE, histogram errors are written.
1125  *
1126  * Works as gmx_histogram_write_array(), but writes the cumulative
1127  * histograms.
1128  * The first column in output will be the right edges of the bins.
1129  *
1130  * \note
1131  * Error output is not currently supported (zeros will be written if asked).
1132  *
1133  * \see gmx_histogram_write_array()
1134  */
1135 void
1136 gmx_histogram_write_cum_array(FILE *fp, int n, gmx_histogram_t *h[],
1137                               gmx_bool bValue, gmx_bool bErrors)
1138 {
1139     int           i, j, nbins;
1140     double       *sum;
1141
1142     prepare_output(n, h, &nbins);
1143     snew(sum, n);
1144
1145     fprintf(fp, "%10g", h[0]->start);
1146     for (j = 0; j < n; ++j)
1147     {
1148         if (bValue)
1149         {
1150             fprintf(fp, " %10g", 0.0);
1151         }
1152         if (bErrors)
1153         {
1154             fprintf(fp, " %10g", 0.0);
1155         }
1156     }
1157     fprintf(fp, "\n");
1158     for (i = 0; i < nbins; ++i)
1159     {
1160         fprintf(fp, "%10g", h[0]->start + (i+1)*h[0]->binwidth);
1161         for (j = 0; j < n; ++j)
1162         {
1163             sum[j] += i < h[j]->nbins ? h[j]->hist[i] : 0.0;
1164             if (bValue)
1165             {
1166                 fprintf(fp, " %10g", sum[j]);
1167             }
1168             /* TODO: Error output not implemented */
1169             if (bErrors)
1170             {
1171                 fprintf(fp, " %10g", 0.0);
1172             }
1173         }
1174         fprintf(fp, "\n");
1175     }
1176     fprintf(fp, "\n");
1177
1178     sfree(sum);
1179 }