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