Make cases simpler, faster, and easier to understand.
[pspp-builds.git] / src / language / stats / wilcoxon.c
1 /* Pspp - a program for statistical analysis.
2    Copyright (C) 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
18
19 #include <config.h>
20 #include "wilcoxon.h"
21 #include <data/variable.h>
22 #include <data/casereader.h>
23 #include <data/casewriter.h>
24 #include <data/subcase.h>
25 #include <math/sort.h>
26 #include <libpspp/message.h>
27 #include <xalloc.h>
28 #include <output/table.h>
29 #include <data/procedure.h>
30 #include <data/dictionary.h>
31 #include <misc/wx-mp-sr.h>
32 #include <gsl/gsl_cdf.h>
33 #include <unistd.h>
34 #include <signal.h>
35 #include <libpspp/assertion.h>
36
37 static double timed_wilcoxon_significance (double w, long int n, double timer);
38
39
40 static double
41 append_difference (const struct ccase *c, casenumber n UNUSED, void *aux)
42 {
43   const variable_pair *vp = aux;
44
45   return case_data (c, (*vp)[0])->f - case_data (c, (*vp)[1])->f;
46 }
47
48 static void show_ranks_box (const struct wilcoxon_state *,
49                             const struct two_sample_test *);
50
51 static void show_tests_box (const struct wilcoxon_state *,
52                             const struct two_sample_test *,
53                             bool exact, double timer);
54
55
56
57 static void
58 distinct_callback (double v UNUSED, casenumber n, double w UNUSED, void *aux)
59 {
60   struct wilcoxon_state *ws = aux;
61
62   ws->tiebreaker += pow3 (n) - n;
63 }
64
65 #define WEIGHT_IDX 2
66
67 void
68 wilcoxon_execute (const struct dataset *ds,
69                   struct casereader *input,
70                   enum mv_class exclude,
71                   const struct npar_test *test,
72                   bool exact,
73                   double timer)
74 {
75   int i;
76   bool warn = true;
77   const struct dictionary *dict = dataset_dict (ds);
78   const struct two_sample_test *t2s = (struct two_sample_test *) test;
79
80   struct wilcoxon_state *ws = xcalloc (sizeof (*ws), t2s->n_pairs);
81   const struct variable *weight = dict_get_weight (dict);
82   struct variable *weightx = var_create_internal (WEIGHT_IDX);
83
84   input =
85     casereader_create_filter_weight (input, dict, &warn, NULL);
86
87   for (i = 0 ; i < t2s->n_pairs; ++i )
88     {
89       struct casereader *r = casereader_clone (input);
90       struct casewriter *writer;
91       struct ccase *c;
92       struct subcase ordering;
93       variable_pair *vp = &t2s->pairs[i];
94
95       const int reader_width = weight ? 3 : 2;
96
97       ws[i].sign = var_create_internal (0);
98       ws[i].absdiff = var_create_internal (1);
99
100       r = casereader_create_filter_missing (r, *vp, 2,
101                                             exclude,
102                                             NULL, NULL);
103
104       subcase_init_var (&ordering, ws[i].absdiff, SC_ASCEND);
105       writer = sort_create_writer (&ordering, reader_width);
106       subcase_destroy (&ordering);
107
108       for (; (c = casereader_read (r)) != NULL; case_unref (c))
109         {
110           struct ccase *output = case_create (reader_width);
111           double d = append_difference (c, 0, vp);
112
113           if (d > 0)
114             {
115               case_data_rw (output, ws[i].sign)->f = 1.0;
116
117             }
118           else if (d < 0)
119             {
120               case_data_rw (output, ws[i].sign)->f = -1.0;
121             }
122           else
123             {
124               double w = 1.0;
125               if (weight)
126                 w = case_data (c, weight)->f;
127
128               /* Central point values should be dropped */
129               ws[i].n_zeros += w;
130               continue;
131             }
132
133           case_data_rw (output, ws[i].absdiff)->f = fabs (d);
134
135           if (weight)
136            case_data_rw (output, weightx)->f = case_data (c, weight)->f;
137
138           casewriter_write (writer, output);
139         }
140       casereader_destroy (r);
141       ws[i].reader = casewriter_make_reader (writer);
142     }
143
144   for (i = 0 ; i < t2s->n_pairs; ++i )
145     {
146       struct casereader *rr ;
147       struct ccase *c;
148       enum rank_error err = 0;
149
150       rr = casereader_create_append_rank (ws[i].reader, ws[i].absdiff,
151                                           weight ? weightx : NULL, &err,
152                                           distinct_callback, &ws[i]
153                                           );
154
155       for (; (c = casereader_read (rr)) != NULL; case_unref (c))
156         {
157           double sign = case_data (c, ws[i].sign)->f;
158           double rank = case_data_idx (c, weight ? 3 : 2)->f;
159           double w = 1.0;
160           if (weight)
161             w = case_data (c, weightx)->f;
162
163           if ( sign > 0 )
164             {
165               ws[i].positives.sum += rank * w;
166               ws[i].positives.n += w;
167             }
168           else if (sign < 0)
169             {
170               ws[i].negatives.sum += rank * w;
171               ws[i].negatives.n += w;
172             }
173           else
174             NOT_REACHED ();
175         }
176
177       casereader_destroy (rr);
178     }
179
180   casereader_destroy (input);
181
182   var_destroy (weightx);
183
184   show_ranks_box (ws, t2s);
185   show_tests_box (ws, t2s, exact, timer);
186
187   for (i = 0 ; i < t2s->n_pairs; ++i )
188     {
189       var_destroy (ws[i].sign);
190       var_destroy (ws[i].absdiff);
191     }
192
193   free (ws);
194 }
195
196
197 \f
198
199 #include "gettext.h"
200 #define _(msgid) gettext (msgid)
201
202 static void
203 show_ranks_box (const struct wilcoxon_state *ws, const struct two_sample_test *t2s)
204 {
205   size_t i;
206   struct tab_table *table = tab_create (5, 1 + 4 * t2s->n_pairs, 0);
207
208   tab_dim (table, tab_natural_dimensions);
209
210   tab_title (table, _("Ranks"));
211
212   tab_headers (table, 2, 0, 1, 0);
213
214   /* Vertical lines inside the box */
215   tab_box (table, 0, 0, -1, TAL_1,
216            1, 0, table->nc - 1, tab_nr (table) - 1 );
217
218   /* Box around entire table */
219   tab_box (table, TAL_2, TAL_2, -1, -1,
220            0, 0, table->nc - 1, tab_nr (table) - 1 );
221
222
223   tab_text (table,  2, 0,  TAB_CENTER, _("N"));
224   tab_text (table,  3, 0,  TAB_CENTER, _("Mean Rank"));
225   tab_text (table,  4, 0,  TAB_CENTER, _("Sum of Ranks"));
226
227
228   for (i = 0 ; i < t2s->n_pairs; ++i)
229     {
230       variable_pair *vp = &t2s->pairs[i];
231
232       struct string pair_name;
233       ds_init_cstr (&pair_name, var_to_string ((*vp)[0]));
234       ds_put_cstr (&pair_name, " - ");
235       ds_put_cstr (&pair_name, var_to_string ((*vp)[1]));
236
237       tab_text (table, 1, 1 + i * 4, TAB_LEFT, _("Negative Ranks"));
238       tab_text (table, 1, 2 + i * 4, TAB_LEFT, _("Positive Ranks"));
239       tab_text (table, 1, 3 + i * 4, TAB_LEFT, _("Ties"));
240       tab_text (table, 1, 4 + i * 4, TAB_LEFT, _("Total"));
241
242       tab_hline (table, TAL_1, 0, table->nc - 1, 1 + i * 4);
243
244
245       tab_text (table, 0, 1 + i * 4, TAB_LEFT, ds_cstr (&pair_name));
246       ds_destroy (&pair_name);
247
248
249       /* N */
250       tab_float (table, 2, 1 + i * 4, TAB_RIGHT, ws[i].negatives.n, 8, 0);
251       tab_float (table, 2, 2 + i * 4, TAB_RIGHT, ws[i].positives.n, 8, 0);
252       tab_float (table, 2, 3 + i * 4, TAB_RIGHT, ws[i].n_zeros, 8, 0);
253
254       tab_float (table, 2, 4 + i * 4, TAB_RIGHT,
255                  ws[i].n_zeros + ws[i].positives.n + ws[i].negatives.n, 8, 0);
256
257       /* Sums */
258       tab_float (table, 4, 1 + i * 4, TAB_RIGHT, ws[i].negatives.sum, 8, 2);
259       tab_float (table, 4, 2 + i * 4, TAB_RIGHT, ws[i].positives.sum, 8, 2);
260
261
262       /* Means */
263       tab_float (table, 3, 1 + i * 4, TAB_RIGHT,
264                  ws[i].negatives.sum / (double) ws[i].negatives.n, 8, 2);
265
266       tab_float (table, 3, 2 + i * 4, TAB_RIGHT,
267                  ws[i].positives.sum / (double) ws[i].positives.n, 8, 2);
268
269     }
270
271   tab_hline (table, TAL_2, 0, table->nc - 1, 1);
272   tab_vline (table, TAL_2, 2, 0, table->nr - 1);
273
274
275   tab_submit (table);
276 }
277
278
279 static void
280 show_tests_box (const struct wilcoxon_state *ws,
281                 const struct two_sample_test *t2s,
282                 bool exact,
283                 double timer
284                 )
285 {
286   size_t i;
287   struct tab_table *table = tab_create (1 + t2s->n_pairs, exact ? 5 : 3, 0);
288
289   tab_dim (table, tab_natural_dimensions);
290
291   tab_title (table, _("Test Statistics"));
292
293   tab_headers (table, 1, 0, 1, 0);
294
295   /* Vertical lines inside the box */
296   tab_box (table, 0, 0, -1, TAL_1,
297            0, 0, table->nc - 1, tab_nr (table) - 1 );
298
299   /* Box around entire table */
300   tab_box (table, TAL_2, TAL_2, -1, -1,
301            0, 0, table->nc - 1, tab_nr (table) - 1 );
302
303
304   tab_text (table,  0, 1,  TAB_LEFT, _("Z"));
305   tab_text (table,  0, 2,  TAB_LEFT, _("Asymp. Sig (2-tailed)"));
306
307   if ( exact )
308     {
309       tab_text (table,  0, 3,  TAB_LEFT, _("Exact Sig (2-tailed)"));
310       tab_text (table,  0, 4,  TAB_LEFT, _("Exact Sig (1-tailed)"));
311
312 #if 0
313       tab_text (table,  0, 5,  TAB_LEFT, _("Point Probability"));
314 #endif
315     }
316
317   for (i = 0 ; i < t2s->n_pairs; ++i)
318     {
319       double z;
320       double n = ws[i].positives.n + ws[i].negatives.n;
321       variable_pair *vp = &t2s->pairs[i];
322
323       struct string pair_name;
324       ds_init_cstr (&pair_name, var_to_string ((*vp)[0]));
325       ds_put_cstr (&pair_name, " - ");
326       ds_put_cstr (&pair_name, var_to_string ((*vp)[1]));
327
328
329       tab_text (table, 1 + i, 0, TAB_CENTER, ds_cstr (&pair_name));
330       ds_destroy (&pair_name);
331
332       z = MIN (ws[i].positives.sum, ws[i].negatives.sum);
333       z -= n * (n + 1)/ 4.0;
334
335       z /= sqrt (n * (n + 1) * (2*n + 1)/24.0 - ws[i].tiebreaker / 48.0);
336
337       tab_float (table, 1 + i, 1, TAB_RIGHT, z, 8, 3);
338
339       tab_float (table, 1 + i, 2, TAB_RIGHT,
340                  2.0 * gsl_cdf_ugaussian_P (z),
341                  8, 3);
342
343       if (exact)
344         {
345           double p =
346             timed_wilcoxon_significance (ws[i].positives.sum,
347                                          n,
348                                          timer );
349
350           if ( p == SYSMIS)
351             {
352               msg (MW, _("Exact significance was not calculated after %.2f minutes. Skipping test."), timer);
353             }
354           else
355             {
356               tab_float (table, 1 + i, 3, TAB_RIGHT, p, 8, 3);
357               tab_float (table, 1 + i, 4, TAB_RIGHT, p / 2.0, 8, 3);
358             }
359         }
360     }
361
362   tab_hline (table, TAL_2, 0, table->nc - 1, 1);
363   tab_vline (table, TAL_2, 1, 0, table->nr - 1);
364
365
366   tab_submit (table);
367 }
368
369 \f
370
371 #include <setjmp.h>
372
373 static sigjmp_buf env;
374
375 static void
376 give_up_callback (int signal UNUSED)
377 {
378   siglongjmp (env, 1);
379 }
380
381 static double
382 timed_wilcoxon_significance (double w, long int n, double timer)
383 {
384   double p = SYSMIS;
385
386   sigset_t set;
387
388   struct sigaction timeout_action;
389   struct sigaction old_action;
390
391   if (timer <= 0 )
392     return LevelOfSignificanceWXMPSR (w, n);
393
394   sigemptyset (&set);
395
396   timeout_action.sa_mask = set;
397   timeout_action.sa_flags = 0;
398
399   timeout_action.sa_handler = give_up_callback;
400
401   if ( 0 == sigsetjmp (env, 1))
402     {
403       sigaction (SIGALRM, &timeout_action, &old_action);
404       alarm (timer * 60.0);
405
406       p = LevelOfSignificanceWXMPSR (w, n);
407     }
408
409   sigaction (SIGALRM, &old_action, NULL);
410
411   return p;
412 }