51ee291f95651be59c024cf4c57c49c8528e3769
[pspp-builds.git] / src / language / stats / kruskal-wallis.c
1 /* Pspp - a program for statistical analysis.
2    Copyright (C) 2010 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
18 #include <config.h>
19
20 #include "kruskal-wallis.h"
21
22 #include <gsl/gsl_cdf.h>
23 #include <math.h>
24
25 #include <data/casereader.h>
26 #include <data/casewriter.h>
27 #include <data/dictionary.h>
28 #include <data/format.h>
29 #include <data/procedure.h>
30 #include <data/subcase.h>
31 #include <data/variable.h>
32
33 #include <libpspp/assertion.h>
34 #include <libpspp/message.h>
35 #include <libpspp/misc.h>
36 #include <libpspp/hmap.h>
37 #include <math/sort.h>
38
39
40 #include "minmax.h"
41 #include "xalloc.h"
42
43
44 static bool
45 include_func (const struct ccase *c, void *aux)
46 {
47   const struct n_sample_test *nst = aux;
48
49   if (0 < value_compare_3way (&nst->val1, case_data (c, nst->indep_var), var_get_width (nst->indep_var)))
50     return false;
51
52   if (0 > value_compare_3way (&nst->val2, case_data (c, nst->indep_var), var_get_width (nst->indep_var)))
53     return false;
54
55   return true;
56 }
57
58
59 struct rank_entry
60 {
61   struct hmap_node node;
62   union value group;
63
64   double sum_of_ranks;
65   double n;
66 };
67
68 static struct rank_entry *
69 find_rank_entry (const struct hmap *map, const union value *group, size_t width)
70 {
71   struct rank_entry *re = NULL;
72   size_t hash  = value_hash (group, width, 0);
73
74   HMAP_FOR_EACH_WITH_HASH (re, struct rank_entry, node, hash, map)
75     {
76       if (0 == value_compare_3way (group, &re->group, width))
77         return re;
78     }
79   
80   return re;
81 }
82
83 static void
84 distinct_callback (double v UNUSED, casenumber t, double w UNUSED, void *aux)
85 {
86   double *tiebreaker = aux;
87
88   *tiebreaker += pow3 (t) - t;
89 }
90
91
92 struct kw
93 {
94   struct hmap map;
95   double h;
96 };
97
98 static void show_ranks_box (const struct n_sample_test *nst, const struct kw *kw, int n_groups);
99 static void show_sig_box (const struct n_sample_test *nst, const struct kw *kw);
100
101 void
102 kruskal_wallis_execute (const struct dataset *ds,
103                         struct casereader *input,
104                         enum mv_class exclude,
105                         const struct npar_test *test,
106                         bool exact UNUSED,
107                         double timer UNUSED)
108 {
109   int i;
110   struct ccase *c;
111   bool warn = true;
112   const struct dictionary *dict = dataset_dict (ds);
113   const struct n_sample_test *nst = UP_CAST (test, const struct n_sample_test, parent);
114   const struct caseproto *proto ;
115   size_t rank_idx ;
116
117   int total_n_groups = 0.0;
118
119   struct kw *kw = xcalloc (nst->n_vars, sizeof *kw);
120
121   /* If the independent variable is missing, then we ignore the case */
122   input = casereader_create_filter_missing (input, 
123                                             &nst->indep_var, 1,
124                                             exclude,
125                                             NULL, NULL);
126
127   input = casereader_create_filter_weight (input, dict, &warn, NULL);
128
129   /* Remove all those cases which are outside the range (val1, val2) */
130   input = casereader_create_filter_func (input, include_func, NULL, 
131         CONST_CAST (struct n_sample_test *, nst), NULL);
132
133   proto = casereader_get_proto (input);
134   rank_idx = caseproto_get_n_widths (proto);
135
136   /* Rank cases by the v value */
137   for (i = 0; i < nst->n_vars; ++i)
138     {
139       double tiebreaker = 0.0;
140       bool warn = true;
141       enum rank_error rerr = 0;
142       struct casereader *rr;
143       struct casereader *r = casereader_clone (input);
144
145       r = sort_execute_1var (r, nst->vars[i]);
146
147       /* Ignore missings in the test variable */
148       r = casereader_create_filter_missing (r, &nst->vars[i], 1,
149                                             exclude,
150                                             NULL, NULL);
151
152       rr = casereader_create_append_rank (r, 
153                                           nst->vars[i],
154                                           dict_get_weight (dict),
155                                           &rerr,
156                                           distinct_callback, &tiebreaker);
157
158       hmap_init (&kw[i].map);
159       for (; (c = casereader_read (rr)); case_unref (c))
160         {
161           const union value *group = case_data (c, nst->indep_var);
162           const size_t group_var_width = var_get_width (nst->indep_var);
163           struct rank_entry *rank = find_rank_entry (&kw[i].map, group, group_var_width); 
164
165           if ( NULL == rank)
166             {
167               rank = xzalloc (sizeof *rank);
168               value_clone (&rank->group, group, group_var_width);
169
170               hmap_insert (&kw[i].map, &rank->node,
171                            value_hash (&rank->group, group_var_width, 0));
172             }
173
174           rank->sum_of_ranks += case_data_idx (c, rank_idx)->f;
175           rank->n += dict_get_case_weight (dict, c, &warn);
176
177           /* If this assertion fires, then either the data wasn't sorted or some other
178              problem occured */
179           assert (rerr == 0);
180         }
181
182       casereader_destroy (rr);
183
184       {
185         struct rank_entry *mre;
186         double n = 0.0;
187
188         HMAP_FOR_EACH (mre, struct rank_entry, node, &kw[i].map)
189           {
190             kw[i].h += pow2 (mre->sum_of_ranks) / mre->n;
191             n += mre->n;
192
193             total_n_groups ++;
194           }
195         kw[i].h *= 12 / (n * ( n + 1));
196         kw[i].h -= 3 * (n + 1) ; 
197
198         kw[i].h /= 1 - tiebreaker/ (pow3 (n) - n);
199       }
200     }
201
202   casereader_destroy (input);
203   
204   show_ranks_box (nst, kw, total_n_groups);
205   show_sig_box (nst, kw);
206
207   for (i = 0 ; i < nst->n_vars; ++i)
208     {
209       struct rank_entry *mre, *next;
210       HMAP_FOR_EACH_SAFE (mre, next, struct rank_entry, node, &kw[i].map)
211         {
212           hmap_delete (&kw[i].map, &mre->node);
213           free (mre);
214         }
215       hmap_destroy (&kw[i].map);
216     }
217
218   free (kw);
219 }
220
221 \f
222 #include <output/tab.h>
223 #include "gettext.h"
224 #define _(msgid) gettext (msgid)
225
226
227 static void
228 show_ranks_box (const struct n_sample_test *nst, const struct kw *kw, int n_groups)
229 {
230   int row;
231   int i;
232   const int row_headers = 2;
233   const int column_headers = 1;
234   struct tab_table *table =
235     tab_create (row_headers + 2, column_headers + n_groups + nst->n_vars);
236
237   tab_headers (table, row_headers, 0, column_headers, 0);
238
239   tab_title (table, _("Ranks"));
240
241   /* Vertical lines inside the box */
242   tab_box (table, 1, 0, -1, TAL_1,
243            row_headers, 0, tab_nc (table) - 1, tab_nr (table) - 1 );
244
245   /* Box around the table */
246   tab_box (table, TAL_2, TAL_2, -1, -1,
247            0,  0, tab_nc (table) - 1, tab_nr (table) - 1 );
248
249   tab_text (table, 1, 0, TAT_TITLE, 
250             var_to_string (nst->indep_var)
251             );
252
253   tab_text (table, 3, 0, 0, _("Mean Rank"));
254   tab_text (table, 2, 0, 0, _("N"));
255
256   tab_hline (table, TAL_2, 0, tab_nc (table) -1, column_headers);
257   tab_vline (table, TAL_2, row_headers, 0, tab_nr (table) - 1);
258
259
260   row = column_headers;
261   for (i = 0 ; i < nst->n_vars ; ++i)
262     {
263       int tot = 0;
264       const struct rank_entry *re;
265
266       if (i > 0)
267         tab_hline (table, TAL_1, 0, tab_nc (table) -1, row);
268       
269       tab_text (table,  0, row,
270                 TAT_TITLE, var_to_string (nst->vars[i]));
271
272       HMAP_FOR_EACH (re, const struct rank_entry, node, &kw[i].map)
273         {
274           struct string str;
275           ds_init_empty (&str);
276
277           var_append_value_name (nst->indep_var, &re->group, &str);
278
279           tab_text   (table, 1, row, TAB_LEFT, ds_cstr (&str));
280           tab_double (table, 2, row, TAB_LEFT, re->n, &F_8_0);
281           tab_double (table, 3, row, TAB_LEFT, re->sum_of_ranks / re->n, 0);
282
283           tot += re->n;
284           row++;
285           ds_destroy (&str);
286         }
287       tab_double (table, 2, row, TAB_LEFT,
288                   tot, &F_8_0);
289       tab_text (table, 1, row++, TAB_LEFT, _("Total"));
290     }
291
292   tab_submit (table);
293 }
294
295
296 static void
297 show_sig_box (const struct n_sample_test *nst, const struct kw *kw)
298 {
299   int i;
300   const int row_headers = 1;
301   const int column_headers = 1;
302   struct tab_table *table =
303     tab_create (row_headers + nst->n_vars * 2, column_headers + 3);
304
305   tab_headers (table, row_headers, 0, column_headers, 0);
306
307   tab_title (table, _("Test Statistics"));
308
309   tab_text (table,  0, column_headers,
310             TAT_TITLE | TAB_LEFT , _("Chi-Square"));
311
312   tab_text (table,  0, 1 + column_headers,
313             TAT_TITLE | TAB_LEFT, _("df"));
314
315   tab_text (table,  0, 2 + column_headers,
316             TAT_TITLE | TAB_LEFT, _("Asymp. Sig."));
317
318   /* Box around the table */
319   tab_box (table, TAL_2, TAL_2, -1, -1,
320            0,  0, tab_nc (table) - 1, tab_nr (table) - 1 );
321
322
323   tab_hline (table, TAL_2, 0, tab_nc (table) -1, column_headers);
324   tab_vline (table, TAL_2, row_headers, 0, tab_nr (table) - 1);
325
326   for (i = 0 ; i < nst->n_vars; ++i)
327     {
328       const double df = hmap_count (&kw[i].map) - 1;
329       tab_text (table, column_headers + 1 + i, 0, TAT_TITLE, 
330                 var_to_string (nst->vars[i])
331                 );
332
333       tab_double (table, column_headers + 1 + i, 1, 0,
334                   kw[i].h, 0);
335
336       tab_double (table, column_headers + 1 + i, 2, 0,
337                   df, &F_8_0);
338
339       tab_double (table, column_headers + 1 + i, 3, 0,
340                   gsl_cdf_chisq_Q (kw[i].h, df),
341                   0);
342     }
343
344   tab_submit (table);
345 }