e9ab64c29ddd4879aebe06487834ed9399e14258
[pspp-builds.git] / src / language / stats / chisquare.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 2006, 2007 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    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, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19 #include <config.h>
20
21 #include <language/stats/chisquare.h>
22
23 #include <stdlib.h>
24 #include <math.h>
25
26 #include <data/case.h>
27 #include <data/casereader.h>
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/value-labels.h>
31 #include <data/variable.h>
32 #include <language/stats/freq.h>
33 #include <language/stats/npar.h>
34 #include <libpspp/alloc.h>
35 #include <libpspp/assertion.h>
36 #include <libpspp/compiler.h>
37 #include <libpspp/hash.h>
38 #include <libpspp/message.h>
39 #include <libpspp/taint.h>
40 #include <output/table.h>
41
42 #include <gsl/gsl_cdf.h>
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 /* Return a hash table containing the frequency counts of each
48    value of VAR in CF .
49    It is the caller's responsibility to free the hash table when
50    no longer required.
51 */
52 static struct hsh_table *
53 create_freq_hash_with_range (const struct dictionary *dict,
54                              struct casereader *input,
55                              const struct variable *var,
56                              double lo,
57                              double hi)
58 {
59   bool warn = true;
60   float i_d;
61   struct ccase c;
62
63   struct hsh_table *freq_hash =
64     hsh_create (4, compare_freq, hash_freq,
65                 free_freq_mutable_hash,
66                 (void *) var);
67
68   /* Populate the hash with zero entries */
69   for (i_d = trunc (lo); i_d <= trunc (hi); i_d += 1.0 )
70     {
71       union value the_value;
72       struct freq_mutable *fr = xmalloc (sizeof (*fr));
73
74       the_value.f = i_d;
75
76       fr->value = value_dup (&the_value, 0);
77       fr->count = 0;
78
79       hsh_insert (freq_hash, fr);
80     }
81
82   while (casereader_read (input, &c))
83     {
84       union value obs_value;
85       struct freq **existing_fr;
86       struct freq *fr = xmalloc(sizeof  (*fr));
87       fr->value = case_data (&c, var);
88
89       fr->count = dict_get_case_weight (dict, &c, &warn);
90
91       obs_value.f = trunc (fr->value->f);
92
93       if ( obs_value.f < lo || obs_value.f > hi)
94         {
95           free (fr);
96           case_destroy (&c);
97           continue;
98         }
99
100       fr->value = &obs_value;
101
102       existing_fr = (struct freq **) hsh_probe (freq_hash, fr);
103
104       /* This must exist in the hash, because we previously populated it
105          with zero counts */
106       assert (*existing_fr);
107
108       (*existing_fr)->count += fr->count;
109       free (fr);
110
111       case_destroy (&c);
112     }
113   if (casereader_destroy (input))
114     return freq_hash;
115   else
116     {
117       hsh_destroy (freq_hash);
118       return NULL;
119     }
120 }
121
122
123 /* Return a hash table containing the frequency counts of each
124    value of VAR in INPUT .
125    It is the caller's responsibility to free the hash table when
126    no longer required.
127 */
128 static struct hsh_table *
129 create_freq_hash (const struct dictionary *dict,
130                   struct casereader *input,
131                   const struct variable *var)
132 {
133   bool warn = true;
134   struct ccase c;
135
136   struct hsh_table *freq_hash =
137     hsh_create (4, compare_freq, hash_freq,
138                 free_freq_mutable_hash,
139                 (void *) var);
140
141   for (; casereader_read (input, &c); case_destroy (&c))
142     {
143       struct freq **existing_fr;
144       struct freq *fr = xmalloc(sizeof  (*fr));
145       fr->value = case_data (&c, var);
146
147       fr->count = dict_get_case_weight (dict, &c, &warn);
148
149       existing_fr = (struct freq **) hsh_probe (freq_hash, fr);
150       if ( *existing_fr)
151         {
152           (*existing_fr)->count += fr->count;
153           free (fr);
154         }
155       else
156         {
157           *existing_fr = fr;
158           fr->value = value_dup (fr->value, var_get_width (var));
159         }
160     }
161   if (casereader_destroy (input))
162     return freq_hash;
163   else
164     {
165       hsh_destroy (freq_hash);
166       return NULL;
167     }
168 }
169
170
171
172 static struct tab_table *
173 create_variable_frequency_table (const struct dictionary *dict,
174                                  struct casereader *input,
175                                  const struct chisquare_test *test,
176                                  int v,
177                                  struct hsh_table **freq_hash)
178
179 {
180   int i;
181   const struct one_sample_test *ost = (const struct one_sample_test*)test;
182   int n_cells;
183   struct tab_table *table ;
184   const struct variable *var =  ost->vars[v];
185
186   *freq_hash = create_freq_hash (dict, input, var);
187   if (*freq_hash == NULL)
188     return NULL;
189
190   n_cells = hsh_count (*freq_hash);
191
192   if ( test->n_expected > 0 && n_cells != test->n_expected )
193     {
194       msg(ME, _("CHISQUARE test specified %d expected values, but"
195                 " %d distinct values were encountered in variable %s."),
196           test->n_expected, n_cells,
197           var_get_name (var)
198           );
199       return NULL;
200     }
201
202   table = tab_create(4, n_cells + 2, 0);
203   tab_dim (table, tab_natural_dimensions);
204
205   tab_title (table, var_to_string(var));
206   tab_text (table, 1, 0, TAB_LEFT, _("Observed N"));
207   tab_text (table, 2, 0, TAB_LEFT, _("Expected N"));
208   tab_text (table, 3, 0, TAB_LEFT, _("Residual"));
209
210   tab_headers (table, 1, 0, 1, 0);
211
212   tab_box (table, TAL_1, TAL_1, -1, -1,
213            0, 0, table->nc - 1, tab_nr(table) - 1 );
214
215   tab_hline (table, TAL_1, 0, tab_nc(table) - 1, 1);
216
217   tab_vline (table, TAL_2, 1, 0, tab_nr(table) - 1);
218   for ( i = 2 ; i < 4 ; ++i )
219     tab_vline (table, TAL_1, i, 0, tab_nr(table) - 1);
220
221
222   tab_text (table, 0, table->nr - 1, TAB_LEFT, _("Total"));
223
224   return table;
225 }
226
227
228 static struct tab_table *
229 create_combo_frequency_table (const struct chisquare_test *test)
230 {
231   int i;
232   const struct one_sample_test *ost = (const struct one_sample_test*)test;
233
234   struct tab_table *table ;
235
236   int n_cells = test->hi - test->lo + 1;
237
238   table = tab_create(1 + ost->n_vars * 4, n_cells + 3, 0);
239   tab_dim (table, tab_natural_dimensions);
240
241   tab_title (table, _("Frequencies"));
242   for ( i = 0 ; i < ost->n_vars ; ++i )
243     {
244       const struct variable *var = ost->vars[i];
245       tab_text (table, i * 4 + 1, 1, TAB_LEFT, _("Category"));
246       tab_text (table, i * 4 + 2, 1, TAB_LEFT, _("Observed N"));
247       tab_text (table, i * 4 + 3, 1, TAB_LEFT, _("Expected N"));
248       tab_text (table, i * 4 + 4, 1, TAB_LEFT, _("Residual"));
249
250       tab_vline (table, TAL_2, i * 4 + 1,
251                  0, tab_nr (table) - 1);
252
253       tab_vline (table, TAL_1, i * 4 + 2,
254                  0, tab_nr (table) - 1);
255
256       tab_vline (table, TAL_1, i * 4 + 3,
257                  1, tab_nr (table) - 1);
258
259       tab_vline (table, TAL_1, i * 4 + 4,
260                  1, tab_nr (table) - 1);
261
262
263       tab_joint_text (table,
264                       i * 4 + 1, 0,
265                       i * 4 + 4, 0,
266                       TAB_CENTER,
267                       var_to_string (var));
268     }
269
270   for ( i = test->lo ; i <= test->hi ; ++i )
271     tab_float (table, 0, 2 + i - test->lo,
272                TAB_LEFT, 1 + i - test->lo, 8, 0);
273
274   tab_headers (table, 1, 0, 2, 0);
275
276   tab_box (table, TAL_1, TAL_1, -1, -1,
277            0, 0, table->nc - 1, tab_nr(table) - 1 );
278
279   tab_hline (table, TAL_1, 1, tab_nc(table) - 1, 1);
280   tab_hline (table, TAL_1, 0, tab_nc(table) - 1, 2);
281
282   tab_text (table, 0, table->nr - 1, TAB_LEFT, _("Total"));
283
284   return table;
285 }
286
287
288 static struct tab_table *
289 create_stats_table (const struct chisquare_test *test)
290 {
291   const struct one_sample_test *ost = (const struct one_sample_test*) test;
292
293   struct tab_table *table;
294   table = tab_create (1 + ost->n_vars, 4, 0);
295   tab_dim (table, tab_natural_dimensions);
296   tab_title (table, _("Test Statistics"));
297   tab_headers (table, 1, 0, 1, 0);
298
299   tab_box (table, TAL_1, TAL_1, -1, -1,
300            0, 0, tab_nc(table) - 1, tab_nr(table) - 1 );
301
302   tab_box (table, -1, -1, -1, TAL_1,
303            1, 0, tab_nc(table) - 1, tab_nr(table) - 1 );
304
305
306   tab_vline (table, TAL_2, 1, 0, tab_nr (table) - 1);
307   tab_hline (table, TAL_1, 0, tab_nc (table) - 1, 1);
308
309
310   tab_text (table, 0, 1, TAB_LEFT, _("Chi-Square"));
311   tab_text (table, 0, 2, TAB_LEFT, _("df"));
312   tab_text (table, 0, 3, TAB_LEFT, _("Asymp. Sig."));
313
314   return table;
315 }
316
317
318 void
319 chisquare_execute (const struct dataset *ds,
320                    struct casereader *input,
321                    enum mv_class exclude,
322                    const struct npar_test *test)
323 {
324   const struct dictionary *dict = dataset_dict (ds);
325   int v, i;
326   struct one_sample_test *ost = (struct one_sample_test *) test;
327   struct chisquare_test *cst = (struct chisquare_test *) test;
328   int n_cells = 0;
329   double total_expected = 0.0;
330
331   double *df = xzalloc (sizeof (*df) * ost->n_vars);
332   double *xsq = xzalloc (sizeof (*df) * ost->n_vars);
333   bool ok;
334
335   for ( i = 0 ; i < cst->n_expected ; ++i )
336     total_expected += cst->expected[i];
337
338   if ( cst->ranged == false )
339     {
340       for ( v = 0 ; v < ost->n_vars ; ++v )
341         {
342           double total_obs = 0.0;
343           struct hsh_table *freq_hash = NULL;
344           struct casereader *reader =
345             casereader_create_filter_missing (casereader_clone (input),
346                                               &ost->vars[v], 1, exclude, NULL);
347           struct tab_table *freq_table =
348             create_variable_frequency_table(dict, reader, cst, v, &freq_hash);
349
350           struct freq **ff;
351
352           if ( NULL == freq_table )
353             continue;
354           ff = (struct freq **) hsh_sort (freq_hash);
355
356           n_cells = hsh_count (freq_hash);
357
358           for ( i = 0 ; i < n_cells ; ++i )
359             total_obs += ff[i]->count;
360
361           xsq[v] = 0.0;
362           for ( i = 0 ; i < n_cells ; ++i )
363             {
364               double exp;
365               const union value *observed_value = ff[i]->value;
366
367               /* The key */
368               tab_text (freq_table, 0, i + 1, TAB_LEFT,
369                         var_get_value_name (ost->vars[v], observed_value));
370
371               /* The observed N */
372               tab_float (freq_table, 1, i + 1, TAB_NONE,
373                          ff[i]->count, 8, 0);
374
375               if ( cst->n_expected > 0 )
376                 exp = cst->expected[i] * total_obs / total_expected ;
377               else
378                 exp = total_obs / (double) n_cells;
379
380               tab_float (freq_table, 2, i + 1, TAB_NONE,
381                          exp, 8, 2);
382
383               /* The residual */
384               tab_float (freq_table, 3, i + 1, TAB_NONE,
385                          ff[i]->count - exp, 8, 2);
386
387               xsq[v] += (ff[i]->count - exp) * (ff[i]->count - exp) / exp;
388             }
389
390           df[v] = n_cells - 1.0;
391
392           tab_float (freq_table, 1, i + 1, TAB_NONE,
393                      total_obs, 8, 0);
394
395           tab_submit (freq_table);
396
397           hsh_destroy (freq_hash);
398         }
399     }
400   else  /* ranged == true */
401     {
402       struct tab_table *freq_table = create_combo_frequency_table (cst);
403
404       n_cells = cst->hi - cst->lo + 1;
405
406       for ( v = 0 ; v < ost->n_vars ; ++v )
407         {
408           double total_obs = 0.0;
409           struct casereader *reader =
410             casereader_create_filter_missing (casereader_clone (input),
411                                               &ost->vars[v], 1, exclude, NULL);
412           struct hsh_table *freq_hash =
413             create_freq_hash_with_range (dict, reader,
414                                          ost->vars[v], cst->lo, cst->hi);
415
416           struct freq **ff;
417
418           if (freq_hash == NULL)
419             continue;
420
421           ff = (struct freq **) hsh_sort (freq_hash);
422           assert ( n_cells == hsh_count (freq_hash));
423
424           for ( i = 0 ; i < hsh_count (freq_hash) ; ++i )
425             total_obs += ff[i]->count;
426
427           xsq[v] = 0.0;
428           for ( i = 0 ; i < hsh_count (freq_hash) ; ++i )
429             {
430               double exp;
431
432               const union value *observed_value = ff[i]->value;
433
434               /* The key */
435               tab_text  (freq_table, v * 4 + 1, i + 2 , TAB_LEFT,
436                          var_get_value_name (ost->vars[v], observed_value));
437
438               /* The observed N */
439               tab_float (freq_table, v * 4 + 2, i + 2 , TAB_NONE,
440                          ff[i]->count, 8, 0);
441
442               if ( cst->n_expected > 0 )
443                 exp = cst->expected[i] * total_obs / total_expected ;
444               else
445                 exp = total_obs / (double) hsh_count (freq_hash);
446
447               /* The expected N */
448               tab_float (freq_table, v * 4 + 3, i + 2 , TAB_NONE,
449                          exp, 8, 2);
450
451               /* The residual */
452               tab_float (freq_table, v * 4 + 4, i + 2 , TAB_NONE,
453                          ff[i]->count - exp, 8, 2);
454
455               xsq[v] += (ff[i]->count - exp) * (ff[i]->count - exp) / exp;
456             }
457
458
459           tab_float (freq_table, v * 4 + 2, tab_nr (freq_table) - 1, TAB_NONE,
460                      total_obs, 8, 0);
461
462           df[v] = n_cells - 1.0;
463
464           hsh_destroy (freq_hash);
465         }
466
467       tab_submit (freq_table);
468     }
469   ok = !taint_has_tainted_successor (casereader_get_taint (input));
470   casereader_destroy (input);
471
472   if (ok)
473     {
474       struct tab_table *stats_table = create_stats_table (cst);
475
476       /* Populate the summary statistics table */
477       for ( v = 0 ; v < ost->n_vars ; ++v )
478         {
479           const struct variable *var = ost->vars[v];
480
481           tab_text (stats_table, 1 + v, 0, TAB_CENTER, var_get_name (var));
482
483           tab_float (stats_table, 1 + v, 1, TAB_NONE, xsq[v], 8,3);
484           tab_float (stats_table, 1 + v, 2, TAB_NONE, df[v], 8,0);
485
486           tab_float (stats_table, 1 + v, 3, TAB_NONE,
487                      gsl_cdf_chisq_Q (xsq[v], df[v]), 8,3);
488         }
489       tab_submit (stats_table);
490     }
491
492   free (xsq);
493   free (df);
494 }
495