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