3c88c3858f61c6b1c2230843a7b9151a47902956
[pspp] / src / math / histogram.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2004, 2008, 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18 #include "histogram.h"
19
20 #include <gl/xalloc.h>
21 #include <libpspp/assertion.h>
22 #include <libpspp/cast.h>
23
24 #include <gsl/gsl_histogram.h>
25 #include "chart-geometry.h"
26 #include <math.h>
27
28
29 void
30 histogram_add (struct histogram *h, double y, double c)
31 {
32   struct statistic *stat = &h->parent;
33   stat->accumulate (stat, NULL, c, 0, y);
34 }
35
36
37
38 static void
39 acc (struct statistic *s, const struct ccase *cx UNUSED, double c, double cc UNUSED, double y)
40 {
41   struct histogram *hist = UP_CAST (s, struct histogram, parent);
42
43   gsl_histogram_accumulate (hist->gsl_hist, y, c);
44 }
45
46
47 static void
48 destroy (struct statistic *s)
49 {
50   struct histogram *h = UP_CAST (s, struct histogram, parent);
51   gsl_histogram_free (h->gsl_hist);
52   free (s);
53 }
54
55
56 struct histogram *
57 histogram_create (int bins, double min, double max)
58 {
59   struct histogram *h = xmalloc (sizeof *h);
60   struct statistic *stat = &h->parent;
61   double upper_limit, lower_limit;
62
63   double bin_width = chart_rounded_tick ((max - min) / (double) bins);
64   double bin_width_2 = bin_width / 2.0;
65
66   int n =  ceil (max / (bin_width_2) ) ;
67
68   assert (max > min);
69
70   if ( ! (n % 2 ) ) n++;
71   upper_limit = n * bin_width_2;
72
73   n =  floor (min / (bin_width_2) ) ;
74   if ( ! (n % 2 ) ) n--;
75   lower_limit = n * bin_width_2;
76
77   h->gsl_hist = gsl_histogram_alloc (bins);
78   gsl_histogram_set_ranges_uniform (h->gsl_hist, lower_limit, upper_limit);
79
80   stat->accumulate = acc;
81   stat->destroy = destroy;
82
83   return h;
84 }
85