e189b47091faee8304ee1a557042cd0f2cff873c
[pspp-builds.git] / src / math / np.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 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 "np.h"
19 #include <math/moments.h>
20 #include <gl/xalloc.h>
21 #include <stdlib.h>
22 #include <math.h>
23 #include <gsl/gsl_cdf.h>
24 #include <libpspp/compiler.h>
25 #include <data/case.h>
26 #include <data/casewriter.h>
27
28 static void
29 destroy (struct statistic *stat)
30 {
31   struct order_stats *os = (struct order_stats *) stat;
32   free (os);
33 }
34
35
36 static void
37 acc (struct statistic *s, const struct ccase *cx UNUSED,
38      double c, double cc, double y)
39 {
40   struct ccase cp;
41   struct np *np = (struct np *) s;
42   double rank = np->prev_cc + (c + 1) / 2.0;
43
44   double ns = gsl_cdf_ugaussian_Pinv (rank / ( np->n + 1 ));
45
46   double z = (y - np->mean) / np->stddev;
47
48   double dns = z - ns;
49
50   maximize (&np->ns_max, ns);
51   minimize (&np->ns_min, ns);
52
53   maximize (&np->dns_max, dns);
54   minimize (&np->dns_min, dns);
55
56   maximize (&np->y_max, y);
57   minimize (&np->y_min, y);
58
59   case_create (&cp, n_NP_IDX);
60
61   case_data_rw_idx (&cp, NP_IDX_Y)->f = y;
62   case_data_rw_idx (&cp, NP_IDX_NS)->f = ns;
63   case_data_rw_idx (&cp, NP_IDX_DNS)->f = dns;
64
65   casewriter_write (np->writer, &cp);
66
67   np->prev_cc = cc;
68 }
69
70 struct order_stats *
71 np_create (const struct moments1 *m)
72 {
73   double variance;
74   struct np *np = xzalloc (sizeof (*np));
75   struct statistic *stat = (struct statistic *) np;
76   struct order_stats *os = (struct order_stats *) np;
77
78   np->prev_cc = 0;
79
80   moments1_calculate (m, &np->n, &np->mean, &variance, NULL, NULL);
81
82   np->stddev = sqrt (variance);
83
84   np->y_min = np->ns_min = np->dns_min = DBL_MAX;
85   np->y_max = np->ns_max = np->dns_max = -DBL_MAX;
86
87   np->writer = autopaging_writer_create (n_NP_IDX);
88
89   os->k = 0;
90   stat->destroy = destroy;
91   stat->accumulate = acc;
92
93   return os;
94 }