Merge commit 'origin/stable'
[pspp-builds.git] / src / math / histogram.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2004, 2008 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
23 #include <gsl/gsl_histogram.h>
24 #include "chart-geometry.h"
25 #include <math.h>
26
27
28 void
29 histogram_add (struct histogram *h, double y, double c)
30 {
31   ((struct statistic *)h)->accumulate ((struct statistic *) h, NULL, c, 0, y);
32 }
33
34
35
36 static void
37 acc (struct statistic *s, const struct ccase *cx UNUSED, double c, double cc UNUSED, double y)
38 {
39   struct histogram *hist = (struct histogram *) s;
40
41   gsl_histogram_accumulate (hist->gsl_hist, y, c);
42 }
43
44
45 static void
46 destroy (struct statistic *s)
47 {
48   struct histogram *h = (struct histogram *) s;
49   gsl_histogram_free (h->gsl_hist);
50   free (s);
51 }
52
53
54 struct statistic *
55 histogram_create (int bins, double min, double max)
56 {
57   struct histogram *h = xmalloc (sizeof *h);
58   struct statistic *stat = (struct statistic *) h;
59   double upper_limit, lower_limit;
60
61   double bin_width = chart_rounded_tick ((max - min) / (double) bins);
62   double bin_width_2 = bin_width / 2.0;
63
64   int n =  ceil (max / (bin_width_2) ) ;
65
66   assert (max > min);
67
68   if ( ! (n % 2 ) ) n++;
69   upper_limit = n * bin_width_2;
70
71   n =  floor (min / (bin_width_2) ) ;
72   if ( ! (n % 2 ) ) n--;
73   lower_limit = n * bin_width_2;
74
75   h->gsl_hist = gsl_histogram_alloc (bins);
76   gsl_histogram_set_ranges_uniform (h->gsl_hist, lower_limit, upper_limit);
77
78   stat->accumulate = acc;
79   stat->destroy = destroy;
80
81   return stat;
82 }
83