Oneway: Fix problems with MISSING=ANALYSIS
[pspp] / src / language / stats / oneway.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 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 #include <config.h>
18
19 #include <data/case.h>
20 #include <data/casegrouper.h>
21 #include <data/casereader.h>
22
23 #include <math/covariance.h>
24 #include <math/categoricals.h>
25 #include <math/moments.h>
26 #include <gsl/gsl_matrix.h>
27 #include <linreg/sweep.h>
28
29 #include <libpspp/ll.h>
30
31 #include <language/lexer/lexer.h>
32 #include <language/lexer/variable-parser.h>
33 #include <language/lexer/value-parser.h>
34 #include <language/command.h>
35
36 #include <data/procedure.h>
37 #include <data/value.h>
38 #include <data/dictionary.h>
39
40 #include <language/dictionary/split-file.h>
41 #include <libpspp/hash.h>
42 #include <libpspp/taint.h>
43 #include <math/group-proc.h>
44 #include <math/levene.h>
45 #include <libpspp/misc.h>
46
47 #include <output/tab.h>
48
49 #include <gsl/gsl_cdf.h>
50 #include <math.h>
51 #include <data/format.h>
52
53 #include <libpspp/message.h>
54
55 #include "gettext.h"
56 #define _(msgid) gettext (msgid)
57
58 enum missing_type
59   {
60     MISS_LISTWISE,
61     MISS_ANALYSIS,
62   };
63
64 enum statistics
65   {
66     STATS_DESCRIPTIVES = 0x0001,
67     STATS_HOMOGENEITY = 0x0002
68   };
69
70 struct coeff_node
71 {
72   struct ll ll; 
73   double coeff; 
74 };
75
76
77 struct contrasts_node
78 {
79   struct ll ll; 
80   struct ll_list coefficient_list;
81
82   bool bad_count; /* True if the number of coefficients does not equal the number of groups */
83 };
84
85 struct oneway_spec
86 {
87   size_t n_vars;
88   const struct variable **vars;
89
90   const struct variable *indep_var;
91
92   enum statistics stats;
93
94   enum missing_type missing_type;
95   enum mv_class exclude;
96
97   /* List of contrasts */
98   struct ll_list contrast_list;
99
100   /* The weight variable */
101   const struct variable *wv;
102
103 };
104
105 /* Per category data */
106 struct descriptive_data
107 {
108   const struct variable *var;
109   struct moments1 *mom;
110
111   double minimum;
112   double maximum;
113 };
114
115 /* Workspace variable for each dependent variable */
116 struct per_var_ws
117 {
118   struct covariance *cov;
119
120   double sst;
121   double sse;
122   double ssa;
123
124   int n_groups;
125
126   double mse;
127 };
128
129 struct oneway_workspace
130 {
131   /* The number of distinct values of the independent variable, when all
132      missing values are disregarded */
133   int actual_number_of_groups;
134
135   /* A  hash table containing all the distinct values of the independent
136      variable */
137   struct hsh_table *group_hash;
138
139   struct per_var_ws *vws;
140
141   /* An array of descriptive data.  One for each dependent variable */
142   struct descriptive_data **dd_total;
143 };
144
145 /* Routines to show the output tables */
146 static void show_anova_table (const struct oneway_spec *, const struct oneway_workspace *);
147 static void show_descriptives (const struct oneway_spec *, const struct oneway_workspace *);
148 static void show_homogeneity (const struct oneway_spec *, const struct oneway_workspace *);
149
150 static void output_oneway (const struct oneway_spec *, struct oneway_workspace *ws);
151 static void run_oneway (const struct oneway_spec *cmd, struct casereader *input, const struct dataset *ds);
152
153 int
154 cmd_oneway (struct lexer *lexer, struct dataset *ds)
155 {
156   const struct dictionary *dict = dataset_dict (ds);  
157   struct oneway_spec oneway ;
158   oneway.n_vars = 0;
159   oneway.vars = NULL;
160   oneway.indep_var = NULL;
161   oneway.stats = 0;
162   oneway.missing_type = MISS_ANALYSIS;
163   oneway.exclude = MV_ANY;
164   oneway.wv = dict_get_weight (dict);
165
166   ll_init (&oneway.contrast_list);
167
168   
169   if ( lex_match (lexer, '/'))
170     {
171       if (!lex_force_match_id (lexer, "VARIABLES"))
172         {
173           goto error;
174         }
175       lex_match (lexer, '=');
176     }
177
178   if (!parse_variables_const (lexer, dict,
179                               &oneway.vars, &oneway.n_vars,
180                               PV_NO_DUPLICATE | PV_NUMERIC))
181     goto error;
182
183   lex_force_match (lexer, T_BY);
184
185   oneway.indep_var = parse_variable_const (lexer, dict);
186
187   while (lex_token (lexer) != '.')
188     {
189       lex_match (lexer, '/');
190
191       if (lex_match_id (lexer, "STATISTICS"))
192         {
193           lex_match (lexer, '=');
194           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
195             {
196               if (lex_match_id (lexer, "DESCRIPTIVES"))
197                 {
198                   oneway.stats |= STATS_DESCRIPTIVES;
199                 }
200               else if (lex_match_id (lexer, "HOMOGENEITY"))
201                 {
202                   oneway.stats |= STATS_HOMOGENEITY;
203                 }
204               else
205                 {
206                   lex_error (lexer, NULL);
207                   goto error;
208                 }
209             }
210         }
211       else if (lex_match_id (lexer, "CONTRAST"))
212         {
213           struct contrasts_node *cl = xzalloc (sizeof *cl);
214
215           struct ll_list *coefficient_list = &cl->coefficient_list;
216           lex_match (lexer, '=');
217
218           ll_init (coefficient_list);
219
220           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
221             {
222               if ( lex_is_number (lexer))
223                 {
224                   struct coeff_node *cc = xmalloc (sizeof *cc);
225                   cc->coeff = lex_number (lexer);
226
227                   ll_push_tail (coefficient_list, &cc->ll);
228                   lex_get (lexer);
229                 }
230               else
231                 {
232                   lex_error (lexer, NULL);
233                   goto error;
234                 }
235             }
236
237           ll_push_tail (&oneway.contrast_list, &cl->ll);
238         }
239       else if (lex_match_id (lexer, "MISSING"))
240         {
241           lex_match (lexer, '=');
242           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
243             {
244               if (lex_match_id (lexer, "INCLUDE"))
245                 {
246                   oneway.exclude = MV_SYSTEM;
247                 }
248               else if (lex_match_id (lexer, "EXCLUDE"))
249                 {
250                   oneway.exclude = MV_ANY;
251                 }
252               else if (lex_match_id (lexer, "LISTWISE"))
253                 {
254                   oneway.missing_type = MISS_LISTWISE;
255                 }
256               else if (lex_match_id (lexer, "ANALYSIS"))
257                 {
258                   oneway.missing_type = MISS_ANALYSIS;
259                 }
260               else
261                 {
262                   lex_error (lexer, NULL);
263                   goto error;
264                 }
265             }
266         }
267       else
268         {
269           lex_error (lexer, NULL);
270           goto error;
271         }
272     }
273
274
275   {
276     struct casegrouper *grouper;
277     struct casereader *group;
278     bool ok;
279
280     grouper = casegrouper_create_splits (proc_open (ds), dict);
281     while (casegrouper_get_next_group (grouper, &group))
282       run_oneway (&oneway, group, ds);
283     ok = casegrouper_destroy (grouper);
284     ok = proc_commit (ds) && ok;
285   }
286
287   free (oneway.vars);
288   return CMD_SUCCESS;
289
290  error:
291   free (oneway.vars);
292   return CMD_FAILURE;
293 }
294
295
296 \f
297
298 static int
299 compare_double_3way (const void *a_, const void *b_, const void *aux UNUSED)
300 {
301   const double *a = a_;
302   const double *b = b_;
303   return *a < *b ? -1 : *a > *b;
304 }
305
306 static unsigned
307 do_hash_double (const void *value_, const void *aux UNUSED)
308 {
309   const double *value = value_;
310   return hash_double (*value, 0);
311 }
312
313 static void
314 free_double (void *value_, const void *aux UNUSED)
315 {
316   double *value = value_;
317   free (value);
318 }
319
320
321
322 static void postcalc (const struct oneway_spec *cmd);
323 static void  precalc (const struct oneway_spec *cmd);
324
325 static struct descriptive_data *
326 dd_create (const struct variable *var)
327 {
328   struct descriptive_data *dd = xmalloc (sizeof *dd);
329
330   dd->mom = moments1_create (MOMENT_VARIANCE);
331   dd->minimum = DBL_MAX;
332   dd->maximum = -DBL_MAX;
333   dd->var = var;
334
335   return dd;
336 }
337
338
339 static void *
340 makeit (void *aux1, void *aux2 UNUSED)
341 {
342   const struct variable *var = aux1;
343
344   struct descriptive_data *dd = dd_create (var);
345
346   return dd;
347 }
348
349 static void 
350 updateit (void *user_data, 
351           enum mv_class exclude,
352           const struct variable *wv, 
353           const struct variable *catvar UNUSED,
354           const struct ccase *c,
355           void *aux1, void *aux2)
356 {
357   struct descriptive_data *dd = user_data;
358
359   const struct variable *varp = aux1;
360
361   const union value *valx = case_data (c, varp);
362
363   if ( var_is_value_missing (varp, valx, exclude))
364     return;
365
366   struct descriptive_data *dd_total = aux2;
367
368   double weight = 1.0;
369   if (wv)
370     weight = case_data (c, wv)->f;
371
372   moments1_add (dd->mom, valx->f, weight);
373   if (valx->f * weight < dd->minimum)
374     dd->minimum = valx->f * weight;
375
376   if (valx->f * weight > dd->maximum)
377     dd->maximum = valx->f * weight;
378
379   {
380     const struct variable *var = dd_total->var;
381     const union value *val = case_data (c, var);
382
383     moments1_add (dd_total->mom,
384                   val->f,
385                   weight);
386
387     if (val->f * weight < dd_total->minimum)
388       dd_total->minimum = val->f * weight;
389
390     if (val->f * weight > dd_total->maximum)
391       dd_total->maximum = val->f * weight;
392   }
393 }
394
395 static void
396 run_oneway (const struct oneway_spec *cmd,
397             struct casereader *input,
398             const struct dataset *ds)
399 {
400   int v;
401   struct taint *taint;
402   struct dictionary *dict = dataset_dict (ds);
403   struct casereader *reader;
404   struct ccase *c;
405
406   struct oneway_workspace ws;
407
408   ws.actual_number_of_groups = 0;
409   ws.vws = xmalloc (cmd->n_vars * sizeof (*ws.vws));
410   ws.dd_total = xmalloc (sizeof (struct descriptive_data) * cmd->n_vars);
411
412   for (v = 0 ; v < cmd->n_vars; ++v)
413     ws.dd_total[v] = dd_create (cmd->vars[v]);
414
415   for (v = 0; v < cmd->n_vars; ++v)
416     {
417       struct categoricals *cats = categoricals_create (&cmd->indep_var, 1,
418                                                        cmd->wv, cmd->exclude, 
419                                                        makeit,
420                                                        updateit,
421                                                        cmd->vars[v], ws.dd_total[v]);
422
423       ws.vws[v].cov = covariance_2pass_create (1, &cmd->vars[v],
424                                                cats, 
425                                                cmd->wv, cmd->exclude);
426     }
427
428   c = casereader_peek (input, 0);
429   if (c == NULL)
430     {
431       casereader_destroy (input);
432       return;
433     }
434   output_split_file_values (ds, c);
435   case_unref (c);
436
437   taint = taint_clone (casereader_get_taint (input));
438
439   ws.group_hash = hsh_create (4,
440                                   compare_double_3way,
441                                   do_hash_double,
442                                   free_double,
443                                   cmd->indep_var);
444
445   precalc (cmd);
446
447   input = casereader_create_filter_missing (input, &cmd->indep_var, 1,
448                                             cmd->exclude, NULL, NULL);
449   if (cmd->missing_type == MISS_LISTWISE)
450     input = casereader_create_filter_missing (input, cmd->vars, cmd->n_vars,
451                                               cmd->exclude, NULL, NULL);
452   input = casereader_create_filter_weight (input, dict, NULL, NULL);
453
454   reader = casereader_clone (input);
455
456   for (; (c = casereader_read (reader)) != NULL; case_unref (c))
457     {
458       size_t i;
459
460       const double weight = dict_get_case_weight (dict, c, NULL);
461
462       const union value *indep_val = case_data (c, cmd->indep_var);
463       void **p = hsh_probe (ws.group_hash, &indep_val->f);
464       if (*p == NULL)
465         {
466           double *value = *p = xmalloc (sizeof *value);
467           *value = indep_val->f;
468         }
469
470       for (i = 0; i < cmd->n_vars; ++i)
471         {
472           const struct variable *v = cmd->vars[i];
473           const union value *val = case_data (c, v);
474
475           if ( MISS_ANALYSIS == cmd->missing_type)
476             {
477               if ( var_is_value_missing (v, val, cmd->exclude))
478                 continue;
479             }
480
481           {
482             struct per_var_ws *pvw = &ws.vws[i];
483
484             covariance_accumulate_pass1 (pvw->cov, c);
485           }
486
487           struct group_proc *gp = group_proc_get (cmd->vars[i]);
488           struct hsh_table *group_hash = gp->group_hash;
489
490           struct group_statistics *gs;
491
492           gs = hsh_find (group_hash, indep_val );
493
494           if ( ! gs )
495             {
496               gs = xmalloc (sizeof *gs);
497               gs->id = *indep_val;
498               gs->sum = 0;
499               gs->n = 0;
500               gs->ssq = 0;
501               gs->sum_diff = 0;
502               gs->minimum = DBL_MAX;
503               gs->maximum = -DBL_MAX;
504
505               hsh_insert ( group_hash, gs );
506             }
507
508           if (!var_is_value_missing (v, val, cmd->exclude))
509             {
510               struct group_statistics *totals = &gp->ugs;
511
512               totals->n += weight;
513               totals->sum += weight * val->f;
514               totals->ssq += weight * pow2 (val->f);
515
516               if ( val->f * weight  < totals->minimum )
517                 totals->minimum = val->f * weight;
518
519               if ( val->f * weight  > totals->maximum )
520                 totals->maximum = val->f * weight;
521
522               gs->n += weight;
523               gs->sum += weight * val->f;
524               gs->ssq += weight * pow2 (val->f);
525
526               if ( val->f * weight  < gs->minimum )
527                 gs->minimum = val->f * weight;
528
529               if ( val->f * weight  > gs->maximum )
530                 gs->maximum = val->f * weight;
531             }
532
533           gp->n_groups = hsh_count (group_hash );
534         }
535
536     }
537   casereader_destroy (reader);
538   reader = casereader_clone (input);
539   for ( ; (c = casereader_read (reader) ); case_unref (c))
540     {
541       int i;
542       for (i = 0; i < cmd->n_vars; ++i)
543         {
544           struct per_var_ws *pvw = &ws.vws[i];
545           const struct variable *v = cmd->vars[i];
546           const union value *val = case_data (c, v);
547
548           if ( MISS_ANALYSIS == cmd->missing_type)
549             {
550               if ( var_is_value_missing (v, val, cmd->exclude))
551                 continue;
552             }
553
554           covariance_accumulate_pass2 (pvw->cov, c);
555         }
556     }
557   casereader_destroy (reader);
558
559   for (v = 0; v < cmd->n_vars; ++v)
560     {
561       struct per_var_ws *pvw = &ws.vws[v];
562       gsl_matrix *cm = covariance_calculate_unnormalized (pvw->cov);
563       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
564
565       double n;
566       moments1_calculate (ws.dd_total[v]->mom, &n, NULL, NULL, NULL, NULL);
567
568       pvw->sst = gsl_matrix_get (cm, 0, 0);
569
570       //      gsl_matrix_fprintf (stdout, cm, "%g ");
571
572       reg_sweep (cm, 0);
573
574       pvw->sse = gsl_matrix_get (cm, 0, 0);
575
576       pvw->ssa = pvw->sst - pvw->sse;
577
578       pvw->n_groups = categoricals_total (cats);
579
580       pvw->mse = (pvw->sst - pvw->ssa) / (n - pvw->n_groups);
581     }
582
583   postcalc (cmd);
584
585   
586   for (v = 0; v < cmd->n_vars; ++v)
587     {
588       struct categoricals *cats = covariance_get_categoricals (ws.vws[v].cov);
589
590       categoricals_done (cats);
591       
592       if (categoricals_total (cats) > ws.actual_number_of_groups)
593         ws.actual_number_of_groups = categoricals_total (cats);
594     }
595
596   if ( cmd->stats & STATS_HOMOGENEITY )
597     levene (dict, casereader_clone (input), cmd->indep_var,
598             cmd->n_vars, cmd->vars, cmd->exclude);
599
600   casereader_destroy (input);
601
602   if (!taint_has_tainted_successor (taint))
603     output_oneway (cmd, &ws);
604
605   taint_destroy (taint);
606 }
607
608 /* Pre calculations */
609 static void
610 precalc (const struct oneway_spec *cmd)
611 {
612   size_t i = 0;
613
614   for (i = 0; i < cmd->n_vars; ++i)
615     {
616       struct group_proc *gp = group_proc_get (cmd->vars[i]);
617       struct group_statistics *totals = &gp->ugs;
618
619       /* Create a hash for each of the dependent variables.
620          The hash contains a group_statistics structure,
621          and is keyed by value of the independent variable */
622
623       gp->group_hash = hsh_create (4, compare_group, hash_group,
624                                    (hsh_free_func *) free_group,
625                                    cmd->indep_var);
626
627       totals->sum = 0;
628       totals->n = 0;
629       totals->ssq = 0;
630       totals->sum_diff = 0;
631       totals->maximum = -DBL_MAX;
632       totals->minimum = DBL_MAX;
633     }
634 }
635
636 /* Post calculations for the ONEWAY command */
637 static void
638 postcalc (const struct oneway_spec *cmd)
639 {
640   size_t i = 0;
641
642   for (i = 0; i < cmd->n_vars; ++i)
643     {
644       struct group_proc *gp = group_proc_get (cmd->vars[i]);
645       struct hsh_table *group_hash = gp->group_hash;
646       struct group_statistics *totals = &gp->ugs;
647
648       struct hsh_iterator g;
649       struct group_statistics *gs;
650
651       for (gs =  hsh_first (group_hash, &g);
652            gs != 0;
653            gs = hsh_next (group_hash, &g))
654         {
655           gs->mean = gs->sum / gs->n;
656           gs->s_std_dev = sqrt (gs->ssq / gs->n - pow2 (gs->mean));
657
658           gs->std_dev = sqrt (
659                               gs->n / (gs->n - 1) *
660                               ( gs->ssq / gs->n - pow2 (gs->mean))
661                               );
662
663           gs->se_mean = gs->std_dev / sqrt (gs->n);
664           gs->mean_diff = gs->sum_diff / gs->n;
665         }
666
667       totals->mean = totals->sum / totals->n;
668       totals->std_dev = sqrt (
669                               totals->n / (totals->n - 1) *
670                               (totals->ssq / totals->n - pow2 (totals->mean))
671                               );
672
673       totals->se_mean = totals->std_dev / sqrt (totals->n);
674     }
675 }
676
677 static void show_contrast_coeffs (const struct oneway_spec *cmd, const struct oneway_workspace *ws);
678 static void show_contrast_tests (const struct oneway_spec *cmd, const struct oneway_workspace *ws);
679
680 static void
681 output_oneway (const struct oneway_spec *cmd, struct oneway_workspace *ws)
682 {
683   size_t i = 0;
684
685   /* Check the sanity of the given contrast values */
686   struct contrasts_node *coeff_list  = NULL;
687   ll_for_each (coeff_list, struct contrasts_node, ll, &cmd->contrast_list)
688     {
689       struct coeff_node *cn = NULL;
690       double sum = 0;
691       struct ll_list *cl = &coeff_list->coefficient_list;
692       ++i;
693
694       if (ll_count (cl) != ws->actual_number_of_groups)
695         {
696           msg (SW,
697                _("Number of contrast coefficients must equal the number of groups"));
698           coeff_list->bad_count = true;
699           continue;
700         }
701
702       ll_for_each (cn, struct coeff_node, ll, cl)
703         sum += cn->coeff;
704
705       if ( sum != 0.0 )
706         msg (SW, _("Coefficients for contrast %zu do not total zero"), i);
707     }
708
709   if (cmd->stats & STATS_DESCRIPTIVES)
710     show_descriptives (cmd, ws);
711
712   if (cmd->stats & STATS_HOMOGENEITY)
713     show_homogeneity (cmd, ws);
714
715   show_anova_table (cmd, ws);
716
717   if (ll_count (&cmd->contrast_list) > 0)
718     {
719       show_contrast_coeffs (cmd, ws);
720       show_contrast_tests (cmd, ws);
721     }
722
723   /* Clean up */
724   for (i = 0; i < cmd->n_vars; ++i )
725     {
726       struct hsh_table *group_hash = group_proc_get (cmd->vars[i])->group_hash;
727
728       hsh_destroy (group_hash);
729     }
730
731   hsh_destroy (ws->group_hash);
732 }
733
734
735 /* Show the ANOVA table */
736 static void
737 show_anova_table (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
738 {
739   size_t i;
740   int n_cols =7;
741   size_t n_rows = cmd->n_vars * 3 + 1;
742
743   struct tab_table *t = tab_create (n_cols, n_rows);
744
745   tab_headers (t, 2, 0, 1, 0);
746
747   tab_box (t,
748            TAL_2, TAL_2,
749            -1, TAL_1,
750            0, 0,
751            n_cols - 1, n_rows - 1);
752
753   tab_hline (t, TAL_2, 0, n_cols - 1, 1 );
754   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
755   tab_vline (t, TAL_0, 1, 0, 0);
756
757   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Sum of Squares"));
758   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df"));
759   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
760   tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("F"));
761   tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
762
763
764   for (i = 0; i < cmd->n_vars; ++i)
765     {
766       double n;
767       moments1_calculate (ws->dd_total[i]->mom, &n, NULL, NULL, NULL, NULL);
768
769       const struct per_var_ws *pvw = &ws->vws[i];
770       const double df1 = pvw->n_groups - 1;
771       const double df2 = n - pvw->n_groups;
772       const double msa = pvw->ssa / df1;
773
774       const char *s = var_to_string (cmd->vars[i]);
775
776       tab_text (t, 0, i * 3 + 1, TAB_LEFT | TAT_TITLE, s);
777       tab_text (t, 1, i * 3 + 1, TAB_LEFT | TAT_TITLE, _("Between Groups"));
778       tab_text (t, 1, i * 3 + 2, TAB_LEFT | TAT_TITLE, _("Within Groups"));
779       tab_text (t, 1, i * 3 + 3, TAB_LEFT | TAT_TITLE, _("Total"));
780
781       if (i > 0)
782         tab_hline (t, TAL_1, 0, n_cols - 1, i * 3 + 1);
783
784
785       /* Sums of Squares */
786       tab_double (t, 2, i * 3 + 1, 0, pvw->ssa, NULL);
787       tab_double (t, 2, i * 3 + 3, 0, pvw->sst, NULL);
788       tab_double (t, 2, i * 3 + 2, 0, pvw->sse, NULL);
789
790
791       /* Degrees of freedom */
792       tab_fixed (t, 3, i * 3 + 1, 0, df1, 4, 0);
793       tab_fixed (t, 3, i * 3 + 2, 0, df2, 4, 0);
794       tab_fixed (t, 3, i * 3 + 3, 0, n - 1, 4, 0);
795
796       /* Mean Squares */
797       tab_double (t, 4, i * 3 + 1, TAB_RIGHT, msa, NULL);
798       tab_double (t, 4, i * 3 + 2, TAB_RIGHT, pvw->mse, NULL);
799
800       {
801         const double F = msa / pvw->mse ;
802
803         /* The F value */
804         tab_double (t, 5, i * 3 + 1, 0,  F, NULL);
805
806         /* The significance */
807         tab_double (t, 6, i * 3 + 1, 0, gsl_cdf_fdist_Q (F, df1, df2), NULL);
808       }
809     }
810
811   tab_title (t, _("ANOVA"));
812   tab_submit (t);
813 }
814
815
816 /* Show the descriptives table */
817 static void
818 show_descriptives (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
819 {
820   size_t v;
821   int n_cols = 10;
822   struct tab_table *t;
823   int row;
824
825   const double confidence = 0.95;
826   const double q = (1.0 - confidence) / 2.0;
827
828   const struct fmt_spec *wfmt = cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
829
830   int n_rows = 2;
831
832   for (v = 0; v < cmd->n_vars; ++v)
833     n_rows += ws->actual_number_of_groups + 1;
834
835   t = tab_create (n_cols, n_rows);
836   tab_headers (t, 2, 0, 2, 0);
837
838   /* Put a frame around the entire box, and vertical lines inside */
839   tab_box (t,
840            TAL_2, TAL_2,
841            -1, TAL_1,
842            0, 0,
843            n_cols - 1, n_rows - 1);
844
845   /* Underline headers */
846   tab_hline (t, TAL_2, 0, n_cols - 1, 2);
847   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
848
849   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("N"));
850   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Mean"));
851   tab_text (t, 4, 1, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
852   tab_text (t, 5, 1, TAB_CENTER | TAT_TITLE, _("Std. Error"));
853
854
855   tab_vline (t, TAL_0, 7, 0, 0);
856   tab_hline (t, TAL_1, 6, 7, 1);
857   tab_joint_text_format (t, 6, 0, 7, 0, TAB_CENTER | TAT_TITLE,
858                          _("%g%% Confidence Interval for Mean"),
859                          confidence*100.0);
860
861   tab_text (t, 6, 1, TAB_CENTER | TAT_TITLE, _("Lower Bound"));
862   tab_text (t, 7, 1, TAB_CENTER | TAT_TITLE, _("Upper Bound"));
863
864   tab_text (t, 8, 1, TAB_CENTER | TAT_TITLE, _("Minimum"));
865   tab_text (t, 9, 1, TAB_CENTER | TAT_TITLE, _("Maximum"));
866
867   tab_title (t, _("Descriptives"));
868
869   row = 2;
870   for (v = 0; v < cmd->n_vars; ++v)
871     {
872       const char *s = var_to_string (cmd->vars[v]);
873       const struct fmt_spec *fmt = var_get_print_format (cmd->vars[v]);
874
875       int count = 0;
876
877       struct per_var_ws *pvw = &ws->vws[v];
878       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
879
880       tab_text (t, 0, row, TAB_LEFT | TAT_TITLE, s);
881       if ( v > 0)
882         tab_hline (t, TAL_1, 0, n_cols - 1, row);
883
884       for (count = 0; count < categoricals_total (cats); ++count)
885         {
886           double T;
887           double n, mean, variance;
888           double std_dev, std_error ;
889
890           struct string vstr;
891
892           const union value *gval = categoricals_get_value_by_subscript (cats, count);
893           const struct descriptive_data *dd = categoricals_get_user_data_by_subscript (cats, count);
894
895           moments1_calculate (dd->mom, &n, &mean, &variance, NULL, NULL);
896
897           std_dev = sqrt (variance);
898           std_error = std_dev / sqrt (n) ;
899
900           ds_init_empty (&vstr);
901
902           var_append_value_name (cmd->indep_var, gval, &vstr);
903
904           tab_text (t, 1, row + count,
905                     TAB_LEFT | TAT_TITLE,
906                     ds_cstr (&vstr));
907
908           ds_destroy (&vstr);
909
910           /* Now fill in the numbers ... */
911
912           tab_fixed (t, 2, row + count, 0, n, 8, 0);
913
914           tab_double (t, 3, row + count, 0, mean, NULL);
915
916           tab_double (t, 4, row + count, 0, std_dev, NULL);
917
918
919           tab_double (t, 5, row + count, 0, std_error, NULL);
920
921           /* Now the confidence interval */
922
923           T = gsl_cdf_tdist_Qinv (q, n - 1);
924
925           tab_double (t, 6, row + count, 0,
926                       mean - T * std_error, NULL);
927
928           tab_double (t, 7, row + count, 0,
929                       mean + T * std_error, NULL);
930
931           /* Min and Max */
932
933           tab_double (t, 8, row + count, 0,  dd->minimum, fmt);
934           tab_double (t, 9, row + count, 0,  dd->maximum, fmt);
935         }
936
937       {
938         double T;
939         double n, mean, variance;
940         double std_dev;
941         double std_error;
942
943         moments1_calculate (ws->dd_total[v]->mom, &n, &mean, &variance, NULL, NULL);
944
945         std_dev = sqrt (variance);
946         std_error = std_dev / sqrt (n) ;
947
948         tab_text (t, 1, row + count,
949                   TAB_LEFT | TAT_TITLE, _("Total"));
950
951         tab_double (t, 2, row + count, 0, n, wfmt);
952
953         tab_double (t, 3, row + count, 0, mean, NULL);
954
955         tab_double (t, 4, row + count, 0, std_dev, NULL);
956
957         tab_double (t, 5, row + count, 0, std_error, NULL);
958
959         /* Now the confidence interval */
960         T = gsl_cdf_tdist_Qinv (q, n - 1);
961
962         tab_double (t, 6, row + count, 0,
963                     mean - T * std_error, NULL);
964
965         tab_double (t, 7, row + count, 0,
966                     mean + T * std_error, NULL);
967
968         /* Min and Max */
969         tab_double (t, 8, row + count, 0,  ws->dd_total[v]->minimum, fmt);
970         tab_double (t, 9, row + count, 0,  ws->dd_total[v]->maximum, fmt);
971       }
972
973       row += categoricals_total (cats) + 1;
974     }
975
976   tab_submit (t);
977 }
978
979 /* Show the homogeneity table */
980 static void
981 show_homogeneity (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
982 {
983   size_t v;
984   int n_cols = 5;
985   size_t n_rows = cmd->n_vars + 1;
986
987   struct tab_table *t = tab_create (n_cols, n_rows);
988   tab_headers (t, 1, 0, 1, 0);
989
990   /* Put a frame around the entire box, and vertical lines inside */
991   tab_box (t,
992            TAL_2, TAL_2,
993            -1, TAL_1,
994            0, 0,
995            n_cols - 1, n_rows - 1);
996
997
998   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
999   tab_vline (t, TAL_2, 1, 0, n_rows - 1);
1000
1001   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Levene Statistic"));
1002   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("df1"));
1003   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df2"));
1004   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
1005
1006   tab_title (t, _("Test of Homogeneity of Variances"));
1007
1008   for (v = 0; v < cmd->n_vars; ++v)
1009     {
1010       double n;
1011       moments1_calculate (ws->dd_total[v]->mom, &n, NULL, NULL, NULL, NULL);
1012
1013       const struct per_var_ws *pvw = &ws->vws[v];
1014       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
1015
1016       const struct variable *var = cmd->vars[v];
1017       const struct group_proc *gp = group_proc_get (cmd->vars[v]);
1018       const char *s = var_to_string (var);
1019
1020       const double df1 = pvw->n_groups - 1;
1021       const double df2 = n - pvw->n_groups;
1022       double F = gp->levene;
1023
1024       tab_text (t, 0, v + 1, TAB_LEFT | TAT_TITLE, s);
1025
1026
1027       tab_double (t, 1, v + 1, TAB_RIGHT, F, NULL);
1028       tab_fixed (t, 2, v + 1, TAB_RIGHT, df1, 8, 0);
1029       tab_fixed (t, 3, v + 1, TAB_RIGHT, df2, 8, 0);
1030
1031       /* Now the significance */
1032       tab_double (t, 4, v + 1, TAB_RIGHT, gsl_cdf_fdist_Q (F, df1, df2), NULL);
1033     }
1034
1035   tab_submit (t);
1036 }
1037
1038
1039 /* Show the contrast coefficients table */
1040 static void
1041 show_contrast_coeffs (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
1042 {
1043   int c_num = 0;
1044   struct ll *cli;
1045
1046   int n_contrasts = ll_count (&cmd->contrast_list);
1047   int n_cols = 2 + ws->actual_number_of_groups;
1048   int n_rows = 2 + n_contrasts;
1049
1050   struct tab_table *t;
1051
1052   const struct covariance *cov = ws->vws[0].cov ;
1053
1054   t = tab_create (n_cols, n_rows);
1055   tab_headers (t, 2, 0, 2, 0);
1056
1057   /* Put a frame around the entire box, and vertical lines inside */
1058   tab_box (t,
1059            TAL_2, TAL_2,
1060            -1, TAL_1,
1061            0, 0,
1062            n_cols - 1, n_rows - 1);
1063
1064   tab_box (t,
1065            -1, -1,
1066            TAL_0, TAL_0,
1067            2, 0,
1068            n_cols - 1, 0);
1069
1070   tab_box (t,
1071            -1, -1,
1072            TAL_0, TAL_0,
1073            0, 0,
1074            1, 1);
1075
1076   tab_hline (t, TAL_1, 2, n_cols - 1, 1);
1077   tab_hline (t, TAL_2, 0, n_cols - 1, 2);
1078
1079   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
1080
1081   tab_title (t, _("Contrast Coefficients"));
1082
1083   tab_text (t,  0, 2, TAB_LEFT | TAT_TITLE, _("Contrast"));
1084
1085
1086   tab_joint_text (t, 2, 0, n_cols - 1, 0, TAB_CENTER | TAT_TITLE,
1087                   var_to_string (cmd->indep_var));
1088
1089   for ( cli = ll_head (&cmd->contrast_list);
1090         cli != ll_null (&cmd->contrast_list);
1091         cli = ll_next (cli))
1092     {
1093       int count = 0;
1094       struct contrasts_node *cn = ll_data (cli, struct contrasts_node, ll);
1095       struct ll *coeffi ;
1096
1097       tab_text_format (t, 1, c_num + 2, TAB_CENTER, "%d", c_num + 1);
1098
1099       for (coeffi = ll_head (&cn->coefficient_list);
1100            coeffi != ll_null (&cn->coefficient_list);
1101            ++count, coeffi = ll_next (coeffi))
1102         {
1103           const struct categoricals *cats = covariance_get_categoricals (cov);
1104           const union value *val = categoricals_get_value_by_subscript (cats, count);
1105           struct string vstr;
1106
1107           ds_init_empty (&vstr);
1108
1109           var_append_value_name (cmd->indep_var, val, &vstr);
1110
1111           tab_text (t, count + 2, 1, TAB_CENTER | TAT_TITLE, ds_cstr (&vstr));
1112
1113           ds_destroy (&vstr);
1114
1115           if (cn->bad_count)
1116             tab_text (t, count + 2, c_num + 2, TAB_RIGHT, "?" );
1117           else
1118             {
1119               struct coeff_node *coeffn = ll_data (coeffi, struct coeff_node, ll);
1120
1121               tab_text_format (t, count + 2, c_num + 2, TAB_RIGHT, "%g", coeffn->coeff);
1122             }
1123         }
1124       ++c_num;
1125     }
1126
1127   tab_submit (t);
1128 }
1129
1130
1131 /* Show the results of the contrast tests */
1132 static void
1133 show_contrast_tests (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
1134 {
1135   int n_contrasts = ll_count (&cmd->contrast_list);
1136   size_t v;
1137   int n_cols = 8;
1138   size_t n_rows = 1 + cmd->n_vars * 2 * n_contrasts;
1139
1140   struct tab_table *t;
1141
1142   t = tab_create (n_cols, n_rows);
1143   tab_headers (t, 3, 0, 1, 0);
1144
1145   /* Put a frame around the entire box, and vertical lines inside */
1146   tab_box (t,
1147            TAL_2, TAL_2,
1148            -1, TAL_1,
1149            0, 0,
1150            n_cols - 1, n_rows - 1);
1151
1152   tab_box (t,
1153            -1, -1,
1154            TAL_0, TAL_0,
1155            0, 0,
1156            2, 0);
1157
1158   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
1159   tab_vline (t, TAL_2, 3, 0, n_rows - 1);
1160
1161   tab_title (t, _("Contrast Tests"));
1162
1163   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Contrast"));
1164   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Value of Contrast"));
1165   tab_text (t,  4, 0, TAB_CENTER | TAT_TITLE, _("Std. Error"));
1166   tab_text (t,  5, 0, TAB_CENTER | TAT_TITLE, _("t"));
1167   tab_text (t,  6, 0, TAB_CENTER | TAT_TITLE, _("df"));
1168   tab_text (t,  7, 0, TAB_CENTER | TAT_TITLE, _("Sig. (2-tailed)"));
1169
1170   for (v = 0; v < cmd->n_vars; ++v)
1171     {
1172       const struct per_var_ws *pvw = &ws->vws[v];
1173       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
1174       struct ll *cli;
1175       int i = 0;
1176       int lines_per_variable = 2 * n_contrasts;
1177
1178       tab_text (t,  0, (v * lines_per_variable) + 1, TAB_LEFT | TAT_TITLE,
1179                 var_to_string (cmd->vars[v]));
1180
1181       for ( cli = ll_head (&cmd->contrast_list);
1182             cli != ll_null (&cmd->contrast_list);
1183             ++i, cli = ll_next (cli))
1184         {
1185           struct contrasts_node *cn = ll_data (cli, struct contrasts_node, ll);
1186           struct ll *coeffi ;
1187           int ci = 0;
1188           double contrast_value = 0.0;
1189           double coef_msq = 0.0;
1190
1191           double T;
1192           double std_error_contrast;
1193           double df;
1194           double sec_vneq = 0.0;
1195
1196           /* Note: The calculation of the degrees of freedom in the
1197              "variances not equal" case is painfull!!
1198              The following formula may help to understand it:
1199              \frac{\left (\sum_{i=1}^k{c_i^2\frac{s_i^2}{n_i}}\right)^2}
1200              {
1201              \sum_{i=1}^k\left (
1202              \frac{\left (c_i^2\frac{s_i^2}{n_i}\right)^2}  {n_i-1}
1203              \right)
1204              }
1205           */
1206
1207           double df_denominator = 0.0;
1208           double df_numerator = 0.0;
1209
1210           double grand_n;
1211           moments1_calculate (ws->dd_total[v]->mom, &grand_n, NULL, NULL, NULL, NULL);
1212           df = grand_n - pvw->n_groups;
1213
1214           if ( i == 0 )
1215             {
1216               tab_text (t,  1, (v * lines_per_variable) + i + 1,
1217                         TAB_LEFT | TAT_TITLE,
1218                         _("Assume equal variances"));
1219
1220               tab_text (t,  1, (v * lines_per_variable) + i + 1 + n_contrasts,
1221                         TAB_LEFT | TAT_TITLE,
1222                         _("Does not assume equal"));
1223             }
1224
1225           tab_text_format (t,  2, (v * lines_per_variable) + i + 1,
1226                            TAB_CENTER | TAT_TITLE, "%d", i + 1);
1227
1228
1229           tab_text_format (t,  2,
1230                            (v * lines_per_variable) + i + 1 + n_contrasts,
1231                            TAB_CENTER | TAT_TITLE, "%d", i + 1);
1232
1233           if (cn->bad_count)
1234             continue;
1235
1236           for (coeffi = ll_head (&cn->coefficient_list);
1237                coeffi != ll_null (&cn->coefficient_list);
1238                ++ci, coeffi = ll_next (coeffi))
1239             {
1240               double n, mean, variance;
1241               const struct descriptive_data *dd = categoricals_get_user_data_by_subscript (cats, ci);
1242
1243               moments1_calculate (dd->mom, &n, &mean, &variance, NULL, NULL);
1244
1245               struct coeff_node *cn = ll_data (coeffi, struct coeff_node, ll);
1246               const double coef = cn->coeff; 
1247
1248               const double winv = variance / n;
1249
1250               contrast_value += coef * mean;
1251
1252               coef_msq += (pow2 (coef)) / n;
1253
1254               sec_vneq += (pow2 (coef)) * variance / n;
1255
1256               df_numerator += (pow2 (coef)) * winv;
1257               df_denominator += pow2((pow2 (coef)) * winv) / (n - 1);
1258             }
1259
1260           sec_vneq = sqrt (sec_vneq);
1261
1262           df_numerator = pow2 (df_numerator);
1263
1264           tab_double (t,  3, (v * lines_per_variable) + i + 1,
1265                       TAB_RIGHT, contrast_value, NULL);
1266
1267           tab_double (t,  3, (v * lines_per_variable) + i + 1 +
1268                       n_contrasts,
1269                       TAB_RIGHT, contrast_value, NULL);
1270
1271           std_error_contrast = sqrt (pvw->mse * coef_msq);
1272
1273           /* Std. Error */
1274           tab_double (t,  4, (v * lines_per_variable) + i + 1,
1275                       TAB_RIGHT, std_error_contrast,
1276                       NULL);
1277
1278           T = fabs (contrast_value / std_error_contrast);
1279
1280           /* T Statistic */
1281
1282           tab_double (t,  5, (v * lines_per_variable) + i + 1,
1283                       TAB_RIGHT, T,
1284                       NULL);
1285
1286
1287           /* Degrees of Freedom */
1288           tab_fixed (t,  6, (v * lines_per_variable) + i + 1,
1289                      TAB_RIGHT,  df,
1290                      8, 0);
1291
1292
1293           /* Significance TWO TAILED !!*/
1294           tab_double (t,  7, (v * lines_per_variable) + i + 1,
1295                       TAB_RIGHT,  2 * gsl_cdf_tdist_Q (T, df),
1296                       NULL);
1297
1298           /* Now for the Variances NOT Equal case */
1299
1300           /* Std. Error */
1301           tab_double (t,  4,
1302                       (v * lines_per_variable) + i + 1 + n_contrasts,
1303                       TAB_RIGHT, sec_vneq,
1304                       NULL);
1305
1306           T = contrast_value / sec_vneq;
1307           tab_double (t,  5,
1308                       (v * lines_per_variable) + i + 1 + n_contrasts,
1309                       TAB_RIGHT, T,
1310                       NULL);
1311
1312           df = df_numerator / df_denominator;
1313
1314           tab_double (t,  6,
1315                       (v * lines_per_variable) + i + 1 + n_contrasts,
1316                       TAB_RIGHT, df,
1317                       NULL);
1318
1319           /* The Significance */
1320           tab_double (t, 7, (v * lines_per_variable) + i + 1 + n_contrasts,
1321                       TAB_RIGHT,  2 * gsl_cdf_tdist_Q (T,df),
1322                       NULL);
1323         }
1324
1325       if ( v > 0 )
1326         tab_hline (t, TAL_1, 0, n_cols - 1, (v * lines_per_variable) + 1);
1327     }
1328
1329   tab_submit (t);
1330 }
1331
1332