535797227b2a23974e6a13da5ed265b0a8c419b2
[pspp-builds.git] / src / language / stats / npar.q
1 /* PSPP - a program for statistical analysis. -*-c-*-
2    Copyright (C) 2006, 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 #include <config.h>
18
19
20 #include <language/stats/npar.h>
21
22 #include <math.h>
23
24 #include <data/case.h>
25 #include <data/casegrouper.h>
26 #include <data/casereader.h>
27 #include <data/dictionary.h>
28 #include <data/procedure.h>
29 #include <language/command.h>
30 #include <language/lexer/lexer.h>
31 #include <language/lexer/variable-parser.h>
32 #include <language/stats/binomial.h>
33 #include <language/stats/chisquare.h>
34 #include <language/stats/wilcoxon.h>
35 #include <language/stats/sign.h>
36 #include <libpspp/cast.h>
37 #include <libpspp/hash.h>
38 #include <libpspp/pool.h>
39 #include <libpspp/taint.h>
40 #include <math/moments.h>
41
42 #include "npar-summary.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 /* (headers) */
48
49 /* (specification)
50    "NPAR TESTS" (npar_):
51    +chisquare=custom;
52    +binomial=custom;
53    +wilcoxon=custom;
54    +mcnemar=custom;
55    +sign=custom;
56    +cochran=varlist;
57    +friedman=varlist;
58    +kendall=varlist;
59    missing=miss:!analysis/listwise,
60    incl:include/!exclude;
61    method=custom;
62    +statistics[st_]=descriptives,quartiles,all.
63 */
64 /* (declarations) */
65 /* (functions) */
66
67
68 static struct cmd_npar_tests cmd;
69
70
71 struct npar_specs
72 {
73   struct pool *pool;
74   struct npar_test **test;
75   size_t n_tests;
76
77   const struct variable ** vv; /* Compendium of all variables
78                                   (those mentioned on ANY subcommand */
79   int n_vars; /* Number of variables in vv */
80
81   enum mv_class filter;    /* Missing values to filter. */
82
83   bool descriptives;       /* Descriptive statistics should be calculated */
84   bool quartiles;          /* Quartiles should be calculated */
85
86   bool exact;  /* Whether exact calculations have been requested */
87   double timer;   /* Maximum time (in minutes) to wait for exact calculations */
88 };
89
90 static void one_sample_insert_variables (const struct npar_test *test,
91                                          struct const_hsh_table *variables);
92
93 static void two_sample_insert_variables (const struct npar_test *test,
94                                          struct const_hsh_table *variables);
95
96
97
98 static void
99 npar_execute(struct casereader *input,
100              const struct npar_specs *specs,
101              const struct dataset *ds)
102 {
103   int t;
104   struct descriptives *summary_descriptives = NULL;
105
106   for ( t = 0 ; t < specs->n_tests; ++t )
107     {
108       const struct npar_test *test = specs->test[t];
109       if ( NULL == test->execute )
110         {
111           msg (SW, _("NPAR subcommand not currently implemented."));
112           continue;
113         }
114       test->execute (ds, casereader_clone (input), specs->filter, test, specs->exact, specs->timer);
115     }
116
117   if ( specs->descriptives )
118     {
119       summary_descriptives = xnmalloc (sizeof (*summary_descriptives),
120                                        specs->n_vars);
121
122       npar_summary_calc_descriptives (summary_descriptives,
123                                       casereader_clone (input),
124                                       dataset_dict (ds),
125                                       specs->vv, specs->n_vars,
126                                       specs->filter);
127     }
128
129   if ( (specs->descriptives || specs->quartiles)
130        && !taint_has_tainted_successor (casereader_get_taint (input)) )
131     do_summary_box (summary_descriptives, specs->vv, specs->n_vars );
132
133   free (summary_descriptives);
134   casereader_destroy (input);
135 }
136
137
138 int
139 cmd_npar_tests (struct lexer *lexer, struct dataset *ds)
140 {
141   bool ok;
142   int i;
143   struct npar_specs npar_specs = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
144   struct const_hsh_table *var_hash;
145   struct casegrouper *grouper;
146   struct casereader *input, *group;
147
148   npar_specs.pool = pool_create ();
149
150   var_hash = const_hsh_create_pool (npar_specs.pool, 0,
151                                     compare_vars_by_name, hash_var_by_name,
152                                     NULL, NULL);
153
154   if ( ! parse_npar_tests (lexer, ds, &cmd, &npar_specs) )
155     {
156       pool_destroy (npar_specs.pool);
157       return CMD_FAILURE;
158     }
159
160   for (i = 0; i < npar_specs.n_tests; ++i )
161     {
162       const struct npar_test *test = npar_specs.test[i];
163       test->insert_variables (test, var_hash);
164     }
165
166   npar_specs.vv = (const struct variable **) const_hsh_sort (var_hash);
167   npar_specs.n_vars = const_hsh_count (var_hash);
168
169   if ( cmd.sbc_statistics )
170     {
171       int i;
172
173       for ( i = 0 ; i < NPAR_ST_count; ++i )
174         {
175           if ( cmd.a_statistics[i] )
176             {
177               switch ( i )
178                 {
179                 case NPAR_ST_DESCRIPTIVES:
180                   npar_specs.descriptives = true;
181                   break;
182                 case NPAR_ST_QUARTILES:
183                   npar_specs.quartiles = true;
184                   break;
185                 case NPAR_ST_ALL:
186                   npar_specs.quartiles = true;
187                   npar_specs.descriptives = true;
188                   break;
189                 default:
190                   NOT_REACHED();
191                 };
192             }
193         }
194     }
195
196   npar_specs.filter = cmd.incl == NPAR_EXCLUDE ? MV_ANY : MV_SYSTEM;
197
198   input = proc_open (ds);
199   if ( cmd.miss == NPAR_LISTWISE )
200     {
201       input = casereader_create_filter_missing (input,
202                                                 npar_specs.vv,
203                                                 npar_specs.n_vars,
204                                                 npar_specs.filter,
205                                                 NULL, NULL);
206     }
207
208
209   grouper = casegrouper_create_splits (input, dataset_dict (ds));
210   while (casegrouper_get_next_group (grouper, &group))
211     npar_execute (group, &npar_specs, ds);
212   ok = casegrouper_destroy (grouper);
213   ok = proc_commit (ds) && ok;
214
215   const_hsh_destroy (var_hash);
216
217   pool_destroy (npar_specs.pool);
218
219   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
220 }
221
222 int
223 npar_custom_chisquare (struct lexer *lexer, struct dataset *ds,
224                        struct cmd_npar_tests *cmd UNUSED, void *aux )
225 {
226   struct npar_specs *specs = aux;
227
228   struct chisquare_test *cstp = pool_alloc(specs->pool, sizeof(*cstp));
229   struct one_sample_test *tp = &cstp->parent;
230   struct npar_test *nt = &tp->parent;
231
232   nt->execute = chisquare_execute;
233   nt->insert_variables = one_sample_insert_variables;
234
235   if (!parse_variables_const_pool (lexer, specs->pool, dataset_dict (ds),
236                                    &tp->vars, &tp->n_vars,
237                                    PV_NO_SCRATCH | PV_NO_DUPLICATE))
238     {
239       return 2;
240     }
241
242   cstp->ranged = false;
243
244   if ( lex_match (lexer, '('))
245     {
246       cstp->ranged = true;
247       if ( ! lex_force_num (lexer)) return 0;
248       cstp->lo = lex_integer (lexer);
249       lex_get (lexer);
250       lex_force_match (lexer, ',');
251       if (! lex_force_num (lexer) ) return 0;
252       cstp->hi = lex_integer (lexer);
253       if ( cstp->lo >= cstp->hi )
254         {
255           msg(ME,
256               _("The specified value of HI (%d) is "
257                 "lower than the specified value of LO (%d)"),
258               cstp->hi, cstp->lo);
259           return 0;
260         }
261       lex_get (lexer);
262       if (! lex_force_match (lexer, ')')) return 0;
263     }
264
265   cstp->n_expected = 0;
266   cstp->expected = NULL;
267   if ( lex_match (lexer, '/') )
268     {
269       if ( lex_match_id (lexer, "EXPECTED") )
270         {
271           lex_force_match (lexer, '=');
272           if ( ! lex_match_id (lexer, "EQUAL") )
273             {
274               double f;
275               int n;
276               while ( lex_is_number(lexer) )
277                 {
278                   int i;
279                   n = 1;
280                   f = lex_number (lexer);
281                   lex_get (lexer);
282                   if ( lex_match (lexer, '*'))
283                     {
284                       n = f;
285                       f = lex_number (lexer);
286                       lex_get (lexer);
287                     }
288                   lex_match (lexer, ',');
289
290                   cstp->n_expected += n;
291                   cstp->expected = pool_realloc (specs->pool,
292                                                  cstp->expected,
293                                                  sizeof(double) *
294                                                  cstp->n_expected);
295                   for ( i = cstp->n_expected - n ;
296                         i < cstp->n_expected;
297                         ++i )
298                     cstp->expected[i] = f;
299
300                 }
301             }
302         }
303       else
304         lex_put_back (lexer, '/');
305     }
306
307   if ( cstp->ranged && cstp->n_expected > 0 &&
308        cstp->n_expected != cstp->hi - cstp->lo + 1 )
309     {
310       msg(ME,
311           _("%d expected values were given, but the specified "
312             "range (%d-%d) requires exactly %d values."),
313           cstp->n_expected, cstp->lo, cstp->hi,
314           cstp->hi - cstp->lo +1);
315       return 0;
316     }
317
318   specs->n_tests++;
319   specs->test = pool_realloc (specs->pool,
320                               specs->test,
321                               sizeof(*specs->test) * specs->n_tests);
322
323   specs->test[specs->n_tests - 1] = nt;
324
325   return 1;
326 }
327
328
329 int
330 npar_custom_binomial (struct lexer *lexer, struct dataset *ds,
331                       struct cmd_npar_tests *cmd UNUSED, void *aux)
332 {
333   struct npar_specs *specs = aux;
334   struct binomial_test *btp = pool_alloc(specs->pool, sizeof(*btp));
335   struct one_sample_test *tp = &btp->parent;
336   struct npar_test *nt = &tp->parent;
337
338   nt->execute = binomial_execute;
339   nt->insert_variables = one_sample_insert_variables;
340
341   btp->category1 = btp->category2 = btp->cutpoint = SYSMIS;
342
343   btp->p = 0.5;
344
345   if ( lex_match (lexer, '(') )
346     {
347       if ( lex_force_num (lexer) )
348         {
349           btp->p = lex_number (lexer);
350           lex_get (lexer);
351           lex_force_match (lexer, ')');
352         }
353       else
354         return 0;
355     }
356   else
357     /* Kludge: q2c swallows the '=' so put it back here  */
358      lex_put_back (lexer, '=');
359
360
361   if ( lex_match (lexer, '=') )
362     {
363       if (parse_variables_const_pool (lexer, specs->pool, dataset_dict (ds),
364                                       &tp->vars, &tp->n_vars,
365                                       PV_NUMERIC | PV_NO_SCRATCH | PV_NO_DUPLICATE) )
366         {
367           if ( lex_match (lexer, '('))
368             {
369               lex_force_num (lexer);
370               btp->category1 = lex_number (lexer);
371               lex_get (lexer);
372               if ( lex_match (lexer, ','))
373                 {
374                   if ( ! lex_force_num (lexer) ) return 2;
375                   btp->category2 = lex_number (lexer);
376                   lex_get (lexer);
377                 }
378               else
379                 {
380                   btp->cutpoint = btp->category1;
381                 }
382
383               lex_force_match (lexer, ')');
384             }
385         }
386       else
387         return 2;
388
389     }
390
391   specs->n_tests++;
392   specs->test = pool_realloc (specs->pool,
393                               specs->test,
394                               sizeof(*specs->test) * specs->n_tests);
395
396   specs->test[specs->n_tests - 1] = nt;
397
398   return 1;
399 }
400
401
402 bool parse_two_sample_related_test (struct lexer *lexer,
403                                     const struct dictionary *dict,
404                                     struct cmd_npar_tests *cmd,
405                                     struct two_sample_test *test_parameters,
406                                     struct pool *pool
407                                     );
408
409
410 bool
411 parse_two_sample_related_test (struct lexer *lexer,
412                                const struct dictionary *dict,
413                                struct cmd_npar_tests *cmd UNUSED,
414                                struct two_sample_test *test_parameters,
415                                struct pool *pool
416                                )
417 {
418   int n = 0;
419   bool paired = false;
420   bool with = false;
421   const struct variable **vlist1;
422   size_t n_vlist1;
423
424   const struct variable **vlist2;
425   size_t n_vlist2;
426
427   test_parameters->parent.insert_variables = two_sample_insert_variables;
428
429   if (!parse_variables_const_pool (lexer, pool,
430                                    dict,
431                                    &vlist1, &n_vlist1,
432                                    PV_NUMERIC | PV_NO_SCRATCH | PV_NO_DUPLICATE) )
433     return false;
434
435   if ( lex_match(lexer, T_WITH))
436     {
437       with = true;
438       if ( !parse_variables_const_pool (lexer, pool, dict,
439                                         &vlist2, &n_vlist2,
440                                         PV_NUMERIC | PV_NO_SCRATCH | PV_NO_DUPLICATE) )
441         return false;
442
443       paired = (lex_match (lexer, '(') &&
444                 lex_match_id (lexer, "PAIRED") && lex_match (lexer, ')'));
445     }
446
447
448   if ( with )
449     {
450       if (paired)
451         {
452           if ( n_vlist1 != n_vlist2)
453             msg (SE, _("PAIRED was specified but the number of variables "
454                        "preceding WITH (%zu) did not match the number "
455                        "following (%zu)."), n_vlist1, n_vlist2);
456
457           test_parameters->n_pairs = n_vlist1 ;
458         }
459       else
460         {
461           test_parameters->n_pairs = n_vlist1 * n_vlist2;
462         }
463     }
464   else
465     {
466       test_parameters->n_pairs = (n_vlist1 * (n_vlist1 - 1)) / 2 ;
467     }
468
469   test_parameters->pairs =
470     pool_alloc (pool, sizeof ( variable_pair) * test_parameters->n_pairs);
471
472   if ( with )
473     {
474       if (paired)
475         {
476           int i;
477           assert (n_vlist1 == n_vlist2);
478           for ( i = 0 ; i < n_vlist1; ++i )
479             {
480               test_parameters->pairs[n][1] = vlist1[i];
481               test_parameters->pairs[n][0] = vlist2[i];
482               n++;
483             }
484         }
485       else
486         {
487           int i,j;
488           for ( i = 0 ; i < n_vlist1; ++i )
489             {
490               for ( j = 0 ; j < n_vlist2; ++j )
491                 {
492                   test_parameters->pairs[n][1] = vlist1[i];
493                   test_parameters->pairs[n][0] = vlist2[j];
494                   n++;
495                 }
496             }
497         }
498     }
499   else
500     {
501       int i,j;
502       for ( i = 0 ; i < n_vlist1 - 1; ++i )
503         {
504           for ( j = i + 1 ; j < n_vlist1; ++j )
505             {
506               assert ( n < test_parameters->n_pairs);
507               test_parameters->pairs[n][1] = vlist1[i];
508               test_parameters->pairs[n][0] = vlist1[j];
509               n++;
510             }
511         }
512     }
513
514   assert ( n == test_parameters->n_pairs);
515
516   return true;
517 }
518
519 int
520 npar_custom_wilcoxon (struct lexer *lexer,
521                       struct dataset *ds,
522                       struct cmd_npar_tests *cmd, void *aux )
523 {
524   struct npar_specs *specs = aux;
525
526   struct two_sample_test *tp = pool_alloc (specs->pool, sizeof(*tp));
527   struct npar_test *nt = &tp->parent;
528   nt->execute = wilcoxon_execute;
529
530   if (!parse_two_sample_related_test (lexer, dataset_dict (ds), cmd,
531                                       tp, specs->pool) )
532     return 0;
533
534   specs->n_tests++;
535   specs->test = pool_realloc (specs->pool,
536                               specs->test,
537                               sizeof(*specs->test) * specs->n_tests);
538   specs->test[specs->n_tests - 1] = nt;
539
540   return 1;
541 }
542
543 int
544 npar_custom_mcnemar (struct lexer *lexer,
545                      struct dataset *ds,
546                      struct cmd_npar_tests *cmd, void *aux )
547 {
548   struct npar_specs *specs = aux;
549
550   struct two_sample_test *tp = pool_alloc(specs->pool, sizeof(*tp));
551   struct npar_test *nt = &tp->parent;
552   nt->execute = NULL;
553
554
555   if (!parse_two_sample_related_test (lexer, dataset_dict (ds),
556                                       cmd, tp, specs->pool) )
557     return 0;
558
559   specs->n_tests++;
560   specs->test = pool_realloc (specs->pool,
561                               specs->test,
562                               sizeof(*specs->test) * specs->n_tests);
563   specs->test[specs->n_tests - 1] = nt;
564
565   return 1;
566 }
567
568 int
569 npar_custom_sign (struct lexer *lexer, struct dataset *ds,
570                   struct cmd_npar_tests *cmd, void *aux )
571 {
572   struct npar_specs *specs = aux;
573
574   struct two_sample_test *tp = pool_alloc(specs->pool, sizeof(*tp));
575   struct npar_test *nt = &tp->parent;
576
577   nt->execute = sign_execute;
578
579   if (!parse_two_sample_related_test (lexer, dataset_dict (ds), cmd,
580                                       tp, specs->pool) )
581     return 0;
582
583   specs->n_tests++;
584   specs->test = pool_realloc (specs->pool,
585                               specs->test,
586                               sizeof(*specs->test) * specs->n_tests);
587   specs->test[specs->n_tests - 1] = nt;
588
589   return 1;
590 }
591
592 /* Insert the variables for TEST into VAR_HASH */
593 static void
594 one_sample_insert_variables (const struct npar_test *test,
595                              struct const_hsh_table *var_hash)
596 {
597   int i;
598   struct one_sample_test *ost = UP_CAST (test, struct one_sample_test, parent);
599
600   for ( i = 0 ; i < ost->n_vars ; ++i )
601     const_hsh_insert (var_hash, ost->vars[i]);
602 }
603
604 static void
605 two_sample_insert_variables (const struct npar_test *test,
606                              struct const_hsh_table *var_hash)
607 {
608   int i;
609
610   const struct two_sample_test *tst = (const struct two_sample_test *) test;
611
612   for ( i = 0 ; i < tst->n_pairs ; ++i )
613     {
614       variable_pair *pair = &tst->pairs[i];
615
616       const_hsh_insert (var_hash, (*pair)[0]);
617       const_hsh_insert (var_hash, (*pair)[1]);
618     }
619
620 }
621
622
623 static int
624 npar_custom_method (struct lexer *lexer, struct dataset *ds UNUSED,
625                     struct cmd_npar_tests *test UNUSED, void *aux)
626 {
627   struct npar_specs *specs = aux;
628
629   if ( lex_match_id (lexer, "EXACT") )
630     {
631       specs->exact = true;
632       specs->timer = 0.0;
633       if (lex_match_id (lexer, "TIMER"))
634         {
635           specs->timer = 5.0;
636
637           if ( lex_match (lexer, '('))
638             {
639               if ( lex_force_num (lexer) )
640                 {
641                   specs->timer = lex_number (lexer);
642                   lex_get (lexer);
643                 }
644               lex_force_match (lexer, ')');
645             }
646         }
647     }
648
649   return 1;
650 }