89619bcca54555bf2c7358bb677d7fdf30f9d179
[pspp] / src / math / histogram.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2004, 2008, 2009, 2011 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
19 #include "math/histogram.h"
20
21 #include <gsl/gsl_histogram.h>
22 #include <math.h>
23
24 #include "libpspp/assertion.h"
25 #include "libpspp/cast.h"
26 #include "math/chart-geometry.h"
27
28 #include "gl/xalloc.h"
29
30 void
31 histogram_add (struct histogram *h, double y, double c)
32 {
33   struct statistic *stat = &h->parent;
34   stat->accumulate (stat, NULL, c, 0, y);
35 }
36
37
38
39 static void
40 acc (struct statistic *s, const struct ccase *cx UNUSED, double c, double cc UNUSED, double y)
41 {
42   struct histogram *hist = UP_CAST (s, struct histogram, parent);
43
44   gsl_histogram_accumulate (hist->gsl_hist, y, c);
45 }
46
47
48 static void
49 destroy (struct statistic *s)
50 {
51   struct histogram *h = UP_CAST (s, struct histogram, parent);
52   gsl_histogram_free (h->gsl_hist);
53   free (s);
54 }
55
56
57 struct histogram *
58 histogram_create (double bin_width, double min, double max)
59 {
60   int bins;
61   struct histogram *h = xmalloc (sizeof *h);
62   struct statistic *stat = &h->parent;
63   const short max_sign = max >= 0;
64   const short min_sign = min >= 0;
65
66   double upper_limit, lower_limit;
67
68   assert (max >= min);
69
70   lower_limit = trunc (2 * abs (min) / bin_width) - 1;
71   lower_limit *= bin_width / 2;
72   lower_limit *= min_sign;
73
74   upper_limit = trunc (2 * abs(max) / bin_width) + 1;
75   upper_limit *= bin_width / 2;
76   upper_limit *= max_sign;
77   
78   bins = (upper_limit - lower_limit) / bin_width;
79
80   h->gsl_hist = gsl_histogram_alloc (bins);
81
82   gsl_histogram_set_ranges_uniform (h->gsl_hist, lower_limit, upper_limit);
83
84   stat->accumulate = acc;
85   stat->destroy = destroy;
86
87   return h;
88 }
89