f2214e49e2bd273b2ca1c4fee673f58229071d65
[pspp] / src / language / stats / oneway.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2012, 2013, 2014 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 <float.h>
20 #include <gsl/gsl_cdf.h>
21 #include <gsl/gsl_matrix.h>
22 #include <math.h>
23
24 #include "data/case.h"
25 #include "data/casegrouper.h"
26 #include "data/casereader.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/value.h"
31 #include "language/command.h"
32 #include "language/dictionary/split-file.h"
33 #include "language/lexer/lexer.h"
34 #include "language/lexer/value-parser.h"
35 #include "language/lexer/variable-parser.h"
36 #include "libpspp/ll.h"
37 #include "libpspp/message.h"
38 #include "libpspp/misc.h"
39 #include "libpspp/taint.h"
40 #include "linreg/sweep.h"
41 #include "tukey/tukey.h"
42 #include "math/categoricals.h"
43 #include "math/interaction.h"
44 #include "math/covariance.h"
45 #include "math/levene.h"
46 #include "math/moments.h"
47 #include "output/tab.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51 #define N_(msgid) msgid
52
53 /* Workspace variable for each dependent variable */
54 struct per_var_ws
55 {
56   struct interaction *iact;
57   struct categoricals *cat;
58   struct covariance *cov;
59   struct levene *nl;
60
61   double n;
62
63   double sst;
64   double sse;
65   double ssa;
66
67   int n_groups;
68
69   double mse;
70 };
71
72 /* Per category data */
73 struct descriptive_data
74 {
75   const struct variable *var;
76   struct moments1 *mom;
77
78   double minimum;
79   double maximum;
80 };
81
82 enum missing_type
83   {
84     MISS_LISTWISE,
85     MISS_ANALYSIS,
86   };
87
88 enum statistics
89   {
90     STATS_DESCRIPTIVES = 0x0001,
91     STATS_HOMOGENEITY = 0x0002
92   };
93
94 struct coeff_node
95 {
96   struct ll ll; 
97   double coeff; 
98 };
99
100
101 struct contrasts_node
102 {
103   struct ll ll; 
104   struct ll_list coefficient_list;
105 };
106
107
108 struct oneway_spec;
109
110 typedef double df_func (const struct per_var_ws *pvw, const struct moments1 *mom_i, const struct moments1 *mom_j);
111 typedef double ts_func (int k, const struct moments1 *mom_i, const struct moments1 *mom_j, double std_err);
112 typedef double p1tail_func (double ts, double df1, double df2);
113
114 typedef double pinv_func (double std_err, double alpha, double df, int k, const struct moments1 *mom_i, const struct moments1 *mom_j);
115
116
117 struct posthoc
118 {
119   const char *syntax;
120   const char *label;
121
122   df_func *dff;
123   ts_func *tsf;
124   p1tail_func *p1f;
125
126   pinv_func *pinv;
127 };
128
129 struct oneway_spec
130 {
131   size_t n_vars;
132   const struct variable **vars;
133
134   const struct variable *indep_var;
135
136   enum statistics stats;
137
138   enum missing_type missing_type;
139   enum mv_class exclude;
140
141   /* List of contrasts */
142   struct ll_list contrast_list;
143
144   /* The weight variable */
145   const struct variable *wv;
146
147   /* The confidence level for multiple comparisons */
148   double alpha;
149
150   int *posthoc;
151   int n_posthoc;
152 };
153
154 static double
155 df_common (const struct per_var_ws *pvw, const struct moments1 *mom_i UNUSED, const struct moments1 *mom_j UNUSED)
156 {
157   return  pvw->n - pvw->n_groups;
158 }
159
160 static double
161 df_individual (const struct per_var_ws *pvw UNUSED, const struct moments1 *mom_i, const struct moments1 *mom_j)
162 {
163   double n_i, var_i;
164   double n_j, var_j;
165   double nom,denom;
166
167   moments1_calculate (mom_i, &n_i, NULL, &var_i, 0, 0);  
168   moments1_calculate (mom_j, &n_j, NULL, &var_j, 0, 0);
169   
170   if ( n_i <= 1.0 || n_j <= 1.0)
171     return SYSMIS;
172
173   nom = pow2 (var_i/n_i + var_j/n_j);
174   denom = pow2 (var_i/n_i) / (n_i - 1) + pow2 (var_j/n_j) / (n_j - 1);
175
176   return nom / denom;
177 }
178
179 static double lsd_pinv (double std_err, double alpha, double df, int k UNUSED, const struct moments1 *mom_i UNUSED, const struct moments1 *mom_j UNUSED)
180 {
181   return std_err * gsl_cdf_tdist_Pinv (1.0 - alpha / 2.0, df);
182 }
183
184 static double bonferroni_pinv (double std_err, double alpha, double df, int k, const struct moments1 *mom_i UNUSED, const struct moments1 *mom_j UNUSED)
185 {
186   const int m = k * (k - 1) / 2;
187   return std_err * gsl_cdf_tdist_Pinv (1.0 - alpha / (2.0 * m), df);
188 }
189
190 static double sidak_pinv (double std_err, double alpha, double df, int k, const struct moments1 *mom_i UNUSED, const struct moments1 *mom_j UNUSED)
191 {
192   const double m = k * (k - 1) / 2;
193   double lp = 1.0 - exp (log (1.0 - alpha) / m ) ;
194   return std_err * gsl_cdf_tdist_Pinv (1.0 - lp / 2.0, df);
195 }
196
197 static double tukey_pinv (double std_err, double alpha, double df, int k, const struct moments1 *mom_i UNUSED, const struct moments1 *mom_j UNUSED)
198 {
199   if ( k < 2 || df < 2)
200     return SYSMIS;
201
202   return std_err / sqrt (2.0)  * qtukey (1 - alpha, 1.0, k, df, 1, 0);
203 }
204
205 static double scheffe_pinv (double std_err, double alpha, double df, int k, const struct moments1 *mom_i UNUSED, const struct moments1 *mom_j UNUSED)
206 {
207   double x = (k - 1) * gsl_cdf_fdist_Pinv (1.0 - alpha, k - 1, df);
208   return std_err * sqrt (x);
209 }
210
211 static double gh_pinv (double std_err UNUSED, double alpha, double df, int k, const struct moments1 *mom_i, const struct moments1 *mom_j)
212 {
213   double n_i, mean_i, var_i;
214   double n_j, mean_j, var_j;
215   double m;
216
217   moments1_calculate (mom_i, &n_i, &mean_i, &var_i, 0, 0);  
218   moments1_calculate (mom_j, &n_j, &mean_j, &var_j, 0, 0);
219
220   m = sqrt ((var_i/n_i + var_j/n_j) / 2.0);
221
222   if ( k < 2 || df < 2)
223     return SYSMIS;
224
225   return m * qtukey (1 - alpha, 1.0, k, df, 1, 0);
226 }
227
228
229 static double 
230 multiple_comparison_sig (double std_err,
231                                        const struct per_var_ws *pvw,
232                                        const struct descriptive_data *dd_i, const struct descriptive_data *dd_j,
233                                        const struct posthoc *ph)
234 {
235   int k = pvw->n_groups;
236   double df = ph->dff (pvw, dd_i->mom, dd_j->mom);
237   double ts = ph->tsf (k, dd_i->mom, dd_j->mom, std_err);
238   if ( df == SYSMIS)
239     return SYSMIS;
240   return  ph->p1f (ts, k - 1, df);
241 }
242
243 static double 
244 mc_half_range (const struct oneway_spec *cmd, const struct per_var_ws *pvw, double std_err, const struct descriptive_data *dd_i, const struct descriptive_data *dd_j, const struct posthoc *ph)
245 {
246   int k = pvw->n_groups;
247   double df = ph->dff (pvw, dd_i->mom, dd_j->mom);
248   if ( df == SYSMIS)
249     return SYSMIS;
250
251   return ph->pinv (std_err, cmd->alpha, df, k, dd_i->mom, dd_j->mom);
252 }
253
254 static double tukey_1tailsig (double ts, double df1, double df2)
255 {
256   double twotailedsig;
257
258   if (df2 < 2 || df1 < 1)
259     return SYSMIS;
260
261   twotailedsig = 1.0 - ptukey (ts, 1.0, df1 + 1, df2, 1, 0);
262
263   return twotailedsig / 2.0;
264 }
265
266 static double lsd_1tailsig (double ts, double df1 UNUSED, double df2)
267 {
268   return ts < 0 ? gsl_cdf_tdist_P (ts, df2) : gsl_cdf_tdist_Q (ts, df2);
269 }
270
271 static double sidak_1tailsig (double ts, double df1, double df2)
272 {
273   double ex = (df1 + 1.0) * df1 / 2.0;
274   double lsd_sig = 2 * lsd_1tailsig (ts, df1, df2);
275
276   return 0.5 * (1.0 - pow (1.0 - lsd_sig, ex));
277 }
278
279 static double bonferroni_1tailsig (double ts, double df1, double df2)
280 {
281   const int m = (df1 + 1) * df1 / 2;
282
283   double p = ts < 0 ? gsl_cdf_tdist_P (ts, df2) : gsl_cdf_tdist_Q (ts, df2);
284   p *= m;
285
286   return p > 0.5 ? 0.5 : p;
287 }
288
289 static double scheffe_1tailsig (double ts, double df1, double df2)
290 {
291   return 0.5 * gsl_cdf_fdist_Q (ts, df1, df2);
292 }
293
294
295 static double tukey_test_stat (int k UNUSED, const struct moments1 *mom_i, const struct moments1 *mom_j, double std_err)
296 {
297   double ts;
298   double n_i, mean_i, var_i;
299   double n_j, mean_j, var_j;
300
301   moments1_calculate (mom_i, &n_i, &mean_i, &var_i, 0, 0);  
302   moments1_calculate (mom_j, &n_j, &mean_j, &var_j, 0, 0);
303
304   ts =  (mean_i - mean_j) / std_err;
305   ts = fabs (ts) * sqrt (2.0);
306
307   return ts;
308 }
309
310 static double lsd_test_stat (int k UNUSED, const struct moments1 *mom_i, const struct moments1 *mom_j, double std_err)
311 {
312   double n_i, mean_i, var_i;
313   double n_j, mean_j, var_j;
314
315   moments1_calculate (mom_i, &n_i, &mean_i, &var_i, 0, 0);  
316   moments1_calculate (mom_j, &n_j, &mean_j, &var_j, 0, 0);
317
318   return (mean_i - mean_j) / std_err;
319 }
320
321 static double scheffe_test_stat (int k, const struct moments1 *mom_i, const struct moments1 *mom_j, double std_err)
322 {
323   double t;
324   double n_i, mean_i, var_i;
325   double n_j, mean_j, var_j;
326
327   moments1_calculate (mom_i, &n_i, &mean_i, &var_i, 0, 0);  
328   moments1_calculate (mom_j, &n_j, &mean_j, &var_j, 0, 0);
329
330   t = (mean_i - mean_j) / std_err;
331   t = pow2 (t);
332   t /= k - 1;
333
334   return t;
335 }
336
337 static double gh_test_stat (int k UNUSED, const struct moments1 *mom_i, const struct moments1 *mom_j, double std_err UNUSED)
338 {
339   double ts;
340   double thing;
341   double n_i, mean_i, var_i;
342   double n_j, mean_j, var_j;
343
344   moments1_calculate (mom_i, &n_i, &mean_i, &var_i, 0, 0);  
345   moments1_calculate (mom_j, &n_j, &mean_j, &var_j, 0, 0);
346
347   thing = var_i / n_i + var_j / n_j;
348   thing /= 2.0;
349   thing = sqrt (thing);
350
351   ts = (mean_i - mean_j) / thing;
352
353   return fabs (ts);
354 }
355
356
357
358 static const struct posthoc ph_tests [] = 
359   {
360     { "LSD",        N_("LSD"),          df_common, lsd_test_stat,     lsd_1tailsig,          lsd_pinv},
361     { "TUKEY",      N_("Tukey HSD"),    df_common, tukey_test_stat,   tukey_1tailsig,        tukey_pinv},
362     { "BONFERRONI", N_("Bonferroni"),   df_common, lsd_test_stat,     bonferroni_1tailsig,   bonferroni_pinv},
363     { "SCHEFFE",    N_("Scheffé"),      df_common, scheffe_test_stat, scheffe_1tailsig,      scheffe_pinv},
364     { "GH",         N_("Games-Howell"), df_individual, gh_test_stat,  tukey_1tailsig,        gh_pinv},
365     { "SIDAK",      N_("Å idák"),        df_common, lsd_test_stat,     sidak_1tailsig,        sidak_pinv}
366   };
367
368
369 struct oneway_workspace
370 {
371   /* The number of distinct values of the independent variable, when all
372      missing values are disregarded */
373   int actual_number_of_groups;
374
375   struct per_var_ws *vws;
376
377   /* An array of descriptive data.  One for each dependent variable */
378   struct descriptive_data **dd_total;
379 };
380
381 /* Routines to show the output tables */
382 static void show_anova_table (const struct oneway_spec *, const struct oneway_workspace *);
383 static void show_descriptives (const struct oneway_spec *, const struct oneway_workspace *);
384 static void show_homogeneity (const struct oneway_spec *, const struct oneway_workspace *);
385
386 static void output_oneway (const struct oneway_spec *, struct oneway_workspace *ws);
387 static void run_oneway (const struct oneway_spec *cmd, struct casereader *input, const struct dataset *ds);
388
389
390 static void
391 destroy_coeff_list (struct contrasts_node *coeff_list)
392 {
393   struct coeff_node *cn = NULL;
394   struct coeff_node *cnx = NULL;
395   struct ll_list *cl = &coeff_list->coefficient_list;
396   
397   ll_for_each_safe (cn, cnx, struct coeff_node, ll, cl)
398     {
399       free (cn);
400     }
401   
402   free (coeff_list);
403 }
404
405 static void
406 oneway_cleanup (struct oneway_spec *cmd)
407 {
408   struct contrasts_node *coeff_list  = NULL;
409   struct contrasts_node *coeff_next  = NULL;
410   ll_for_each_safe (coeff_list, coeff_next, struct contrasts_node, ll, &cmd->contrast_list)
411     {
412       destroy_coeff_list (coeff_list);
413     }
414
415   free (cmd->posthoc);
416 }
417
418
419
420 int
421 cmd_oneway (struct lexer *lexer, struct dataset *ds)
422 {
423   const struct dictionary *dict = dataset_dict (ds);  
424   struct oneway_spec oneway ;
425   oneway.n_vars = 0;
426   oneway.vars = NULL;
427   oneway.indep_var = NULL;
428   oneway.stats = 0;
429   oneway.missing_type = MISS_ANALYSIS;
430   oneway.exclude = MV_ANY;
431   oneway.wv = dict_get_weight (dict);
432   oneway.alpha = 0.05;
433   oneway.posthoc = NULL;
434   oneway.n_posthoc = 0;
435
436   ll_init (&oneway.contrast_list);
437
438   
439   if ( lex_match (lexer, T_SLASH))
440     {
441       if (!lex_force_match_id (lexer, "VARIABLES"))
442         {
443           goto error;
444         }
445       lex_match (lexer, T_EQUALS);
446     }
447
448   if (!parse_variables_const (lexer, dict,
449                               &oneway.vars, &oneway.n_vars,
450                               PV_NO_DUPLICATE | PV_NUMERIC))
451     goto error;
452
453   lex_force_match (lexer, T_BY);
454
455   oneway.indep_var = parse_variable_const (lexer, dict);
456
457   while (lex_token (lexer) != T_ENDCMD)
458     {
459       lex_match (lexer, T_SLASH);
460
461       if (lex_match_id (lexer, "STATISTICS"))
462         {
463           lex_match (lexer, T_EQUALS);
464           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
465             {
466               if (lex_match_id (lexer, "DESCRIPTIVES"))
467                 {
468                   oneway.stats |= STATS_DESCRIPTIVES;
469                 }
470               else if (lex_match_id (lexer, "HOMOGENEITY"))
471                 {
472                   oneway.stats |= STATS_HOMOGENEITY;
473                 }
474               else
475                 {
476                   lex_error (lexer, NULL);
477                   goto error;
478                 }
479             }
480         }
481       else if (lex_match_id (lexer, "POSTHOC"))
482         {
483           lex_match (lexer, T_EQUALS);
484           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
485             {
486               int p;
487               bool method = false;
488               for (p = 0 ; p < sizeof (ph_tests) / sizeof (struct posthoc); ++p)
489                 {
490                   if (lex_match_id (lexer, ph_tests[p].syntax))
491                     {
492                       oneway.n_posthoc++;
493                       oneway.posthoc = xrealloc (oneway.posthoc, sizeof (*oneway.posthoc) * oneway.n_posthoc);
494                       oneway.posthoc[oneway.n_posthoc - 1] = p;
495                       method = true;
496                       break;
497                     }
498                 }
499               if ( method == false)
500                 {
501                   if (lex_match_id (lexer, "ALPHA"))
502                     {
503                       if ( !lex_force_match (lexer, T_LPAREN))
504                         goto error;
505                       lex_force_num (lexer);
506                       oneway.alpha = lex_number (lexer);
507                       lex_get (lexer);
508                       if ( !lex_force_match (lexer, T_RPAREN))
509                         goto error;
510                     }
511                   else
512                     {
513                       msg (SE, _("The post hoc analysis method %s is not supported."), lex_tokcstr (lexer));
514                       lex_error (lexer, NULL);
515                       goto error;
516                     }
517                 }
518             }
519         }
520       else if (lex_match_id (lexer, "CONTRAST"))
521         {
522           struct contrasts_node *cl = xzalloc (sizeof *cl);
523
524           struct ll_list *coefficient_list = &cl->coefficient_list;
525           lex_match (lexer, T_EQUALS);
526
527           ll_init (coefficient_list);
528
529           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
530             {
531               if ( lex_is_number (lexer))
532                 {
533                   struct coeff_node *cc = xmalloc (sizeof *cc);
534                   cc->coeff = lex_number (lexer);
535
536                   ll_push_tail (coefficient_list, &cc->ll);
537                   lex_get (lexer);
538                 }
539               else
540                 {
541                   destroy_coeff_list (cl);
542                   lex_error (lexer, NULL);
543                   goto error;
544                 }
545             }
546
547           ll_push_tail (&oneway.contrast_list, &cl->ll);
548         }
549       else if (lex_match_id (lexer, "MISSING"))
550         {
551           lex_match (lexer, T_EQUALS);
552           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
553             {
554               if (lex_match_id (lexer, "INCLUDE"))
555                 {
556                   oneway.exclude = MV_SYSTEM;
557                 }
558               else if (lex_match_id (lexer, "EXCLUDE"))
559                 {
560                   oneway.exclude = MV_ANY;
561                 }
562               else if (lex_match_id (lexer, "LISTWISE"))
563                 {
564                   oneway.missing_type = MISS_LISTWISE;
565                 }
566               else if (lex_match_id (lexer, "ANALYSIS"))
567                 {
568                   oneway.missing_type = MISS_ANALYSIS;
569                 }
570               else
571                 {
572                   lex_error (lexer, NULL);
573                   goto error;
574                 }
575             }
576         }
577       else
578         {
579           lex_error (lexer, NULL);
580           goto error;
581         }
582     }
583
584
585   {
586     struct casegrouper *grouper;
587     struct casereader *group;
588     bool ok;
589
590     grouper = casegrouper_create_splits (proc_open (ds), dict);
591     while (casegrouper_get_next_group (grouper, &group))
592       run_oneway (&oneway, group, ds);
593     ok = casegrouper_destroy (grouper);
594     ok = proc_commit (ds) && ok;
595   }
596
597   oneway_cleanup (&oneway);
598   free (oneway.vars);
599   return CMD_SUCCESS;
600
601  error:
602   oneway_cleanup (&oneway);
603   free (oneway.vars);
604   return CMD_FAILURE;
605 }
606
607
608 \f
609
610
611 static struct descriptive_data *
612 dd_create (const struct variable *var)
613 {
614   struct descriptive_data *dd = xmalloc (sizeof *dd);
615
616   dd->mom = moments1_create (MOMENT_VARIANCE);
617   dd->minimum = DBL_MAX;
618   dd->maximum = -DBL_MAX;
619   dd->var = var;
620
621   return dd;
622 }
623
624 static void
625 dd_destroy (struct descriptive_data *dd)
626 {
627   moments1_destroy (dd->mom);
628   free (dd);
629 }
630
631 static void *
632 makeit (const void *aux1, void *aux2 UNUSED)
633 {
634   const struct variable *var = aux1;
635
636   struct descriptive_data *dd = dd_create (var);
637
638   return dd;
639 }
640
641 static void 
642 killit (const void *aux1 UNUSED, void *aux2 UNUSED, void *user_data)
643 {
644   struct descriptive_data *dd = user_data;
645
646   dd_destroy (dd);
647 }
648
649
650 static void 
651 updateit (const void *aux1, void *aux2, void *user_data,
652           const struct ccase *c, double weight)
653 {
654   struct descriptive_data *dd = user_data;
655
656   const struct variable *varp = aux1;
657
658   const union value *valx = case_data (c, varp);
659
660   struct descriptive_data *dd_total = aux2;
661
662   moments1_add (dd->mom, valx->f, weight);
663   if (valx->f < dd->minimum)
664     dd->minimum = valx->f;
665
666   if (valx->f > dd->maximum)
667     dd->maximum = valx->f;
668
669   {
670     const struct variable *var = dd_total->var;
671     const union value *val = case_data (c, var);
672
673     moments1_add (dd_total->mom,
674                   val->f,
675                   weight);
676
677     if (val->f < dd_total->minimum)
678       dd_total->minimum = val->f;
679
680     if (val->f > dd_total->maximum)
681       dd_total->maximum = val->f;
682   }
683 }
684
685 static void
686 run_oneway (const struct oneway_spec *cmd,
687             struct casereader *input,
688             const struct dataset *ds)
689 {
690   int v;
691   struct taint *taint;
692   struct dictionary *dict = dataset_dict (ds);
693   struct casereader *reader;
694   struct ccase *c;
695
696   struct oneway_workspace ws;
697
698   ws.actual_number_of_groups = 0;
699   ws.vws = xzalloc (cmd->n_vars * sizeof (*ws.vws));
700   ws.dd_total = xmalloc (sizeof (struct descriptive_data) * cmd->n_vars);
701
702   for (v = 0 ; v < cmd->n_vars; ++v)
703     ws.dd_total[v] = dd_create (cmd->vars[v]);
704
705   for (v = 0; v < cmd->n_vars; ++v)
706     {
707       struct payload payload;
708       payload.create = makeit;
709       payload.update = updateit;
710       payload.calculate = NULL;
711       payload.destroy = killit;
712
713       ws.vws[v].iact = interaction_create (cmd->indep_var);
714       ws.vws[v].cat = categoricals_create (&ws.vws[v].iact, 1, cmd->wv,
715                                            cmd->exclude, cmd->exclude);
716
717       categoricals_set_payload (ws.vws[v].cat, &payload, 
718                                 CONST_CAST (struct variable *, cmd->vars[v]),
719                                 ws.dd_total[v]);
720
721
722       ws.vws[v].cov = covariance_2pass_create (1, &cmd->vars[v],
723                                                ws.vws[v].cat, 
724                                                cmd->wv, cmd->exclude);
725       ws.vws[v].nl = levene_create (var_get_width (cmd->indep_var), NULL);
726     }
727
728   c = casereader_peek (input, 0);
729   if (c == NULL)
730     {
731       casereader_destroy (input);
732       goto finish;
733     }
734   output_split_file_values (ds, c);
735   case_unref (c);
736
737   taint = taint_clone (casereader_get_taint (input));
738
739   input = casereader_create_filter_missing (input, &cmd->indep_var, 1,
740                                             cmd->exclude, NULL, NULL);
741   if (cmd->missing_type == MISS_LISTWISE)
742     input = casereader_create_filter_missing (input, cmd->vars, cmd->n_vars,
743                                               cmd->exclude, NULL, NULL);
744   input = casereader_create_filter_weight (input, dict, NULL, NULL);
745
746   reader = casereader_clone (input);
747   for (; (c = casereader_read (reader)) != NULL; case_unref (c))
748     {
749       int i;
750       double w = dict_get_case_weight (dict, c, NULL);
751
752       for (i = 0; i < cmd->n_vars; ++i)
753         {
754           struct per_var_ws *pvw = &ws.vws[i];
755           const struct variable *v = cmd->vars[i];
756           const union value *val = case_data (c, v);
757
758           if ( MISS_ANALYSIS == cmd->missing_type)
759             {
760               if ( var_is_value_missing (v, val, cmd->exclude))
761                 continue;
762             }
763
764           covariance_accumulate_pass1 (pvw->cov, c);
765           levene_pass_one (pvw->nl, val->f, w, case_data (c, cmd->indep_var));
766         }
767     }
768   casereader_destroy (reader);
769
770   reader = casereader_clone (input);
771   for ( ; (c = casereader_read (reader) ); case_unref (c))
772     {
773       int i;
774       double w = dict_get_case_weight (dict, c, NULL);
775       for (i = 0; i < cmd->n_vars; ++i)
776         {
777           struct per_var_ws *pvw = &ws.vws[i];
778           const struct variable *v = cmd->vars[i];
779           const union value *val = case_data (c, v);
780
781           if ( MISS_ANALYSIS == cmd->missing_type)
782             {
783               if ( var_is_value_missing (v, val, cmd->exclude))
784                 continue;
785             }
786
787           covariance_accumulate_pass2 (pvw->cov, c);
788           levene_pass_two (pvw->nl, val->f, w, case_data (c, cmd->indep_var));
789         }
790     }
791   casereader_destroy (reader);
792
793   reader = casereader_clone (input);
794   for ( ; (c = casereader_read (reader) ); case_unref (c))
795     {
796       int i;
797       double w = dict_get_case_weight (dict, c, NULL);
798
799       for (i = 0; i < cmd->n_vars; ++i)
800         {
801           struct per_var_ws *pvw = &ws.vws[i];
802           const struct variable *v = cmd->vars[i];
803           const union value *val = case_data (c, v);
804
805           if ( MISS_ANALYSIS == cmd->missing_type)
806             {
807               if ( var_is_value_missing (v, val, cmd->exclude))
808                 continue;
809             }
810
811           levene_pass_three (pvw->nl, val->f, w, case_data (c, cmd->indep_var));
812         }
813     }
814   casereader_destroy (reader);
815
816
817   for (v = 0; v < cmd->n_vars; ++v)
818     {
819       const gsl_matrix *ucm;
820       gsl_matrix *cm;
821       struct per_var_ws *pvw = &ws.vws[v];
822       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
823       const bool ok = categoricals_sane (cats);
824
825       if ( ! ok)
826         {
827           msg (MW, 
828                _("Dependent variable %s has no non-missing values.  No analysis for this variable will be done."),
829                var_get_name (cmd->vars[v]));
830           continue;
831         }
832
833       ucm = covariance_calculate_unnormalized (pvw->cov);
834
835       cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
836       gsl_matrix_memcpy (cm, ucm);
837
838       moments1_calculate (ws.dd_total[v]->mom, &pvw->n, NULL, NULL, NULL, NULL);
839
840       pvw->sst = gsl_matrix_get (cm, 0, 0);
841
842       reg_sweep (cm, 0);
843
844       pvw->sse = gsl_matrix_get (cm, 0, 0);
845       gsl_matrix_free (cm);
846
847       pvw->ssa = pvw->sst - pvw->sse;
848
849       pvw->n_groups = categoricals_n_total (cats);
850
851       pvw->mse = (pvw->sst - pvw->ssa) / (pvw->n - pvw->n_groups);
852     }
853
854   for (v = 0; v < cmd->n_vars; ++v)
855     {
856       const struct categoricals *cats = covariance_get_categoricals (ws.vws[v].cov);
857
858       if ( ! categoricals_is_complete (cats))
859         {
860           continue;
861         }
862
863       if (categoricals_n_total (cats) > ws.actual_number_of_groups)
864         ws.actual_number_of_groups = categoricals_n_total (cats);
865     }
866
867   casereader_destroy (input);
868
869   if (!taint_has_tainted_successor (taint))
870     output_oneway (cmd, &ws);
871
872   taint_destroy (taint);
873
874  finish:
875
876   for (v = 0; v < cmd->n_vars; ++v)
877     {
878       covariance_destroy (ws.vws[v].cov);
879       levene_destroy (ws.vws[v].nl);
880       dd_destroy (ws.dd_total[v]);
881       interaction_destroy (ws.vws[v].iact);
882     }
883
884   free (ws.vws);
885   free (ws.dd_total);
886 }
887
888 static void show_contrast_coeffs (const struct oneway_spec *cmd, const struct oneway_workspace *ws);
889 static void show_contrast_tests (const struct oneway_spec *cmd, const struct oneway_workspace *ws);
890 static void show_comparisons (const struct oneway_spec *cmd, const struct oneway_workspace *ws, int depvar);
891
892 static void
893 output_oneway (const struct oneway_spec *cmd, struct oneway_workspace *ws)
894 {
895   size_t i = 0;
896
897   /* Check the sanity of the given contrast values */
898   struct contrasts_node *coeff_list  = NULL;
899   struct contrasts_node *coeff_next  = NULL;
900   ll_for_each_safe (coeff_list, coeff_next, struct contrasts_node, ll, &cmd->contrast_list)
901     {
902       struct coeff_node *cn = NULL;
903       double sum = 0;
904       struct ll_list *cl = &coeff_list->coefficient_list;
905       ++i;
906
907       if (ll_count (cl) != ws->actual_number_of_groups)
908         {
909           msg (SW,
910                _("In contrast list %zu, the number of coefficients (%zu) does not equal the number of groups (%d). This contrast list will be ignored."),
911                i, ll_count (cl), ws->actual_number_of_groups);
912
913           ll_remove (&coeff_list->ll);
914           destroy_coeff_list (coeff_list);
915           continue;
916         }
917
918       ll_for_each (cn, struct coeff_node, ll, cl)
919         sum += cn->coeff;
920
921       if ( sum != 0.0 )
922         msg (SW, _("Coefficients for contrast %zu do not total zero"), i);
923     }
924
925   if (cmd->stats & STATS_DESCRIPTIVES)
926     show_descriptives (cmd, ws);
927
928   if (cmd->stats & STATS_HOMOGENEITY)
929     show_homogeneity (cmd, ws);
930
931   show_anova_table (cmd, ws);
932
933   if (ll_count (&cmd->contrast_list) > 0)
934     {
935       show_contrast_coeffs (cmd, ws);
936       show_contrast_tests (cmd, ws);
937     }
938
939   if ( cmd->posthoc )
940     {
941       int v;
942       for (v = 0 ; v < cmd->n_vars; ++v)
943         {
944           const struct categoricals *cats = covariance_get_categoricals (ws->vws[v].cov);
945
946           if ( categoricals_is_complete (cats))
947             show_comparisons (cmd, ws, v);
948         }
949     }
950 }
951
952
953 /* Show the ANOVA table */
954 static void
955 show_anova_table (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
956 {
957   size_t i;
958   int n_cols =7;
959   size_t n_rows = cmd->n_vars * 3 + 1;
960
961   struct tab_table *t = tab_create (n_cols, n_rows);
962
963   tab_headers (t, 2, 0, 1, 0);
964
965   tab_box (t,
966            TAL_2, TAL_2,
967            -1, TAL_1,
968            0, 0,
969            n_cols - 1, n_rows - 1);
970
971   tab_hline (t, TAL_2, 0, n_cols - 1, 1 );
972   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
973   tab_vline (t, TAL_0, 1, 0, 0);
974
975   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Sum of Squares"));
976   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df"));
977   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
978   tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("F"));
979   tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Sig."));
980
981
982   for (i = 0; i < cmd->n_vars; ++i)
983     {
984       double n;
985       double df1, df2;
986       double msa;
987       const char *s = var_to_string (cmd->vars[i]);
988       const struct per_var_ws *pvw = &ws->vws[i];
989
990       moments1_calculate (ws->dd_total[i]->mom, &n, NULL, NULL, NULL, NULL);
991
992       df1 = pvw->n_groups - 1;
993       df2 = n - pvw->n_groups;
994       msa = pvw->ssa / df1;
995
996       tab_text (t, 0, i * 3 + 1, TAB_LEFT | TAT_TITLE, s);
997       tab_text (t, 1, i * 3 + 1, TAB_LEFT | TAT_TITLE, _("Between Groups"));
998       tab_text (t, 1, i * 3 + 2, TAB_LEFT | TAT_TITLE, _("Within Groups"));
999       tab_text (t, 1, i * 3 + 3, TAB_LEFT | TAT_TITLE, _("Total"));
1000
1001       if (i > 0)
1002         tab_hline (t, TAL_1, 0, n_cols - 1, i * 3 + 1);
1003
1004
1005       /* Sums of Squares */
1006       tab_double (t, 2, i * 3 + 1, 0, pvw->ssa, NULL, RC_OTHER);
1007       tab_double (t, 2, i * 3 + 3, 0, pvw->sst, NULL, RC_OTHER);
1008       tab_double (t, 2, i * 3 + 2, 0, pvw->sse, NULL, RC_OTHER);
1009
1010
1011       /* Degrees of freedom */
1012       tab_double (t, 3, i * 3 + 1, 0, df1, NULL, RC_INTEGER);
1013       tab_double (t, 3, i * 3 + 2, 0, df2,  NULL, RC_INTEGER); 
1014       tab_double (t, 3, i * 3 + 3, 0, n - 1, NULL, RC_INTEGER); 
1015
1016       /* Mean Squares */
1017       tab_double (t, 4, i * 3 + 1, TAB_RIGHT, msa, NULL, RC_OTHER);
1018       tab_double (t, 4, i * 3 + 2, TAB_RIGHT, pvw->mse, NULL, RC_OTHER);
1019
1020       {
1021         const double F = msa / pvw->mse ;
1022
1023         /* The F value */
1024         tab_double (t, 5, i * 3 + 1, 0,  F, NULL, RC_OTHER);
1025
1026         /* The significance */
1027         tab_double (t, 6, i * 3 + 1, 0, gsl_cdf_fdist_Q (F, df1, df2), NULL, RC_PVALUE);
1028       }
1029     }
1030
1031   tab_title (t, _("ANOVA"));
1032   tab_submit (t);
1033 }
1034
1035
1036 /* Show the descriptives table */
1037 static void
1038 show_descriptives (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
1039 {
1040   size_t v;
1041   int n_cols = 10;
1042   struct tab_table *t;
1043   int row;
1044
1045   const double confidence = 0.95;
1046   const double q = (1.0 - confidence) / 2.0;
1047
1048   const struct fmt_spec *wfmt = cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
1049
1050   int n_rows = 2;
1051
1052   for (v = 0; v < cmd->n_vars; ++v)
1053     n_rows += ws->actual_number_of_groups + 1;
1054
1055   t = tab_create (n_cols, n_rows);
1056   tab_set_format (t, RC_WEIGHT, wfmt);
1057   tab_headers (t, 2, 0, 2, 0);
1058
1059   /* Put a frame around the entire box, and vertical lines inside */
1060   tab_box (t,
1061            TAL_2, TAL_2,
1062            -1, TAL_1,
1063            0, 0,
1064            n_cols - 1, n_rows - 1);
1065
1066   /* Underline headers */
1067   tab_hline (t, TAL_2, 0, n_cols - 1, 2);
1068   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
1069
1070   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("N"));
1071   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Mean"));
1072   tab_text (t, 4, 1, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1073   tab_text (t, 5, 1, TAB_CENTER | TAT_TITLE, _("Std. Error"));
1074
1075
1076   tab_vline (t, TAL_0, 7, 0, 0);
1077   tab_hline (t, TAL_1, 6, 7, 1);
1078   tab_joint_text_format (t, 6, 0, 7, 0, TAB_CENTER | TAT_TITLE,
1079                          _("%g%% Confidence Interval for Mean"),
1080                          confidence*100.0);
1081
1082   tab_text (t, 6, 1, TAB_CENTER | TAT_TITLE, _("Lower Bound"));
1083   tab_text (t, 7, 1, TAB_CENTER | TAT_TITLE, _("Upper Bound"));
1084
1085   tab_text (t, 8, 1, TAB_CENTER | TAT_TITLE, _("Minimum"));
1086   tab_text (t, 9, 1, TAB_CENTER | TAT_TITLE, _("Maximum"));
1087
1088   tab_title (t, _("Descriptives"));
1089
1090   row = 2;
1091   for (v = 0; v < cmd->n_vars; ++v)
1092     {
1093       const char *s = var_to_string (cmd->vars[v]);
1094       const struct fmt_spec *fmt = var_get_print_format (cmd->vars[v]);
1095
1096       int count = 0;
1097
1098       struct per_var_ws *pvw = &ws->vws[v];
1099       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
1100
1101       tab_text (t, 0, row, TAB_LEFT | TAT_TITLE, s);
1102       if ( v > 0)
1103         tab_hline (t, TAL_1, 0, n_cols - 1, row);
1104
1105       for (count = 0; count < categoricals_n_total (cats); ++count)
1106         {
1107           double T;
1108           double n, mean, variance;
1109           double std_dev, std_error ;
1110
1111           struct string vstr;
1112
1113           const struct ccase *gcc = categoricals_get_case_by_category (cats, count);
1114           const struct descriptive_data *dd = categoricals_get_user_data_by_category (cats, count);
1115
1116           moments1_calculate (dd->mom, &n, &mean, &variance, NULL, NULL);
1117
1118           std_dev = sqrt (variance);
1119           std_error = std_dev / sqrt (n) ;
1120
1121           ds_init_empty (&vstr);
1122
1123           var_append_value_name (cmd->indep_var, case_data (gcc, cmd->indep_var), &vstr);
1124
1125           tab_text (t, 1, row + count,
1126                     TAB_LEFT | TAT_TITLE,
1127                     ds_cstr (&vstr));
1128
1129           ds_destroy (&vstr);
1130
1131           /* Now fill in the numbers ... */
1132
1133           tab_double (t, 2, row + count, 0, n, NULL, RC_WEIGHT);
1134
1135           tab_double (t, 3, row + count, 0, mean, NULL, RC_OTHER);
1136
1137           tab_double (t, 4, row + count, 0, std_dev, NULL, RC_OTHER);
1138
1139
1140           tab_double (t, 5, row + count, 0, std_error, NULL, RC_OTHER);
1141
1142           /* Now the confidence interval */
1143
1144           T = gsl_cdf_tdist_Qinv (q, n - 1);
1145
1146           tab_double (t, 6, row + count, 0,
1147                       mean - T * std_error, NULL, RC_OTHER);
1148
1149           tab_double (t, 7, row + count, 0,
1150                       mean + T * std_error, NULL, RC_OTHER);
1151
1152           /* Min and Max */
1153
1154           tab_double (t, 8, row + count, 0,  dd->minimum, fmt, RC_OTHER);
1155           tab_double (t, 9, row + count, 0,  dd->maximum, fmt, RC_OTHER);
1156         }
1157
1158       if (categoricals_is_complete (cats))
1159       {
1160         double T;
1161         double n, mean, variance;
1162         double std_dev;
1163         double std_error;
1164
1165         moments1_calculate (ws->dd_total[v]->mom, &n, &mean, &variance, NULL, NULL);
1166
1167         std_dev = sqrt (variance);
1168         std_error = std_dev / sqrt (n) ;
1169
1170         tab_text (t, 1, row + count,
1171                   TAB_LEFT | TAT_TITLE, _("Total"));
1172
1173         tab_double (t, 2, row + count, 0, n, NULL, RC_WEIGHT);
1174
1175         tab_double (t, 3, row + count, 0, mean, NULL, RC_OTHER);
1176
1177         tab_double (t, 4, row + count, 0, std_dev, NULL, RC_OTHER);
1178
1179         tab_double (t, 5, row + count, 0, std_error, NULL, RC_OTHER);
1180
1181         /* Now the confidence interval */
1182         T = gsl_cdf_tdist_Qinv (q, n - 1);
1183
1184         tab_double (t, 6, row + count, 0,
1185                     mean - T * std_error, NULL, RC_OTHER);
1186
1187         tab_double (t, 7, row + count, 0,
1188                     mean + T * std_error, NULL, RC_OTHER);
1189
1190
1191         /* Min and Max */
1192         tab_double (t, 8, row + count, 0,  ws->dd_total[v]->minimum, fmt, RC_OTHER);
1193         tab_double (t, 9, row + count, 0,  ws->dd_total[v]->maximum, fmt, RC_OTHER);
1194       }
1195
1196       row += categoricals_n_total (cats) + 1;
1197     }
1198
1199   tab_submit (t);
1200 }
1201
1202 /* Show the homogeneity table */
1203 static void
1204 show_homogeneity (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
1205 {
1206   size_t v;
1207   int n_cols = 5;
1208   size_t n_rows = cmd->n_vars + 1;
1209
1210   struct tab_table *t = tab_create (n_cols, n_rows);
1211   tab_headers (t, 1, 0, 1, 0);
1212
1213   /* Put a frame around the entire box, and vertical lines inside */
1214   tab_box (t,
1215            TAL_2, TAL_2,
1216            -1, TAL_1,
1217            0, 0,
1218            n_cols - 1, n_rows - 1);
1219
1220
1221   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
1222   tab_vline (t, TAL_2, 1, 0, n_rows - 1);
1223
1224   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Levene Statistic"));
1225   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("df1"));
1226   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df2"));
1227   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Sig."));
1228
1229   tab_title (t, _("Test of Homogeneity of Variances"));
1230
1231   for (v = 0; v < cmd->n_vars; ++v)
1232     {
1233       double n;
1234       const struct per_var_ws *pvw = &ws->vws[v];
1235       double F = levene_calculate (pvw->nl);
1236
1237       const struct variable *var = cmd->vars[v];
1238       const char *s = var_to_string (var);
1239       double df1, df2;
1240
1241       moments1_calculate (ws->dd_total[v]->mom, &n, NULL, NULL, NULL, NULL);
1242
1243       df1 = pvw->n_groups - 1;
1244       df2 = n - pvw->n_groups;
1245
1246       tab_text (t, 0, v + 1, TAB_LEFT | TAT_TITLE, s);
1247
1248       tab_double (t, 1, v + 1, TAB_RIGHT, F, NULL, RC_OTHER);
1249       tab_double (t, 2, v + 1, TAB_RIGHT, df1, NULL, RC_INTEGER);
1250       tab_double (t, 3, v + 1, TAB_RIGHT, df2, NULL, RC_INTEGER);
1251
1252       /* Now the significance */
1253       tab_double (t, 4, v + 1, TAB_RIGHT, gsl_cdf_fdist_Q (F, df1, df2), NULL, RC_PVALUE);
1254     }
1255
1256   tab_submit (t);
1257 }
1258
1259
1260 /* Show the contrast coefficients table */
1261 static void
1262 show_contrast_coeffs (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
1263 {
1264   int c_num = 0;
1265   struct ll *cli;
1266
1267   int n_contrasts = ll_count (&cmd->contrast_list);
1268   int n_cols = 2 + ws->actual_number_of_groups;
1269   int n_rows = 2 + n_contrasts;
1270
1271   struct tab_table *t;
1272
1273   const struct covariance *cov = ws->vws[0].cov ;
1274
1275   t = tab_create (n_cols, n_rows);
1276   tab_headers (t, 2, 0, 2, 0);
1277
1278   /* Put a frame around the entire box, and vertical lines inside */
1279   tab_box (t,
1280            TAL_2, TAL_2,
1281            -1, TAL_1,
1282            0, 0,
1283            n_cols - 1, n_rows - 1);
1284
1285   tab_box (t,
1286            -1, -1,
1287            TAL_0, TAL_0,
1288            2, 0,
1289            n_cols - 1, 0);
1290
1291   tab_box (t,
1292            -1, -1,
1293            TAL_0, TAL_0,
1294            0, 0,
1295            1, 1);
1296
1297   tab_hline (t, TAL_1, 2, n_cols - 1, 1);
1298   tab_hline (t, TAL_2, 0, n_cols - 1, 2);
1299
1300   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
1301
1302   tab_title (t, _("Contrast Coefficients"));
1303
1304   tab_text (t,  0, 2, TAB_LEFT | TAT_TITLE, _("Contrast"));
1305
1306
1307   tab_joint_text (t, 2, 0, n_cols - 1, 0, TAB_CENTER | TAT_TITLE,
1308                   var_to_string (cmd->indep_var));
1309
1310   for ( cli = ll_head (&cmd->contrast_list);
1311         cli != ll_null (&cmd->contrast_list);
1312         cli = ll_next (cli))
1313     {
1314       int count = 0;
1315       struct contrasts_node *cn = ll_data (cli, struct contrasts_node, ll);
1316       struct ll *coeffi ;
1317
1318       tab_text_format (t, 1, c_num + 2, TAB_CENTER, "%d", c_num + 1);
1319
1320       for (coeffi = ll_head (&cn->coefficient_list);
1321            coeffi != ll_null (&cn->coefficient_list);
1322            ++count, coeffi = ll_next (coeffi))
1323         {
1324           const struct categoricals *cats = covariance_get_categoricals (cov);
1325           const struct ccase *gcc = categoricals_get_case_by_category (cats, count);
1326           struct coeff_node *coeffn = ll_data (coeffi, struct coeff_node, ll);
1327           struct string vstr;
1328
1329           ds_init_empty (&vstr);
1330
1331           var_append_value_name (cmd->indep_var, case_data (gcc, cmd->indep_var), &vstr);
1332
1333           tab_text (t, count + 2, 1, TAB_CENTER | TAT_TITLE, ds_cstr (&vstr));
1334
1335           ds_destroy (&vstr);
1336
1337           tab_text_format (t, count + 2, c_num + 2, TAB_RIGHT, "%.*g",
1338                            DBL_DIG + 1, coeffn->coeff);
1339         }
1340       ++c_num;
1341     }
1342
1343   tab_submit (t);
1344 }
1345
1346
1347 /* Show the results of the contrast tests */
1348 static void
1349 show_contrast_tests (const struct oneway_spec *cmd, const struct oneway_workspace *ws)
1350 {
1351   int n_contrasts = ll_count (&cmd->contrast_list);
1352   size_t v;
1353   int n_cols = 8;
1354   size_t n_rows = 1 + cmd->n_vars * 2 * n_contrasts;
1355
1356   struct tab_table *t;
1357
1358   t = tab_create (n_cols, n_rows);
1359   tab_headers (t, 3, 0, 1, 0);
1360
1361   /* Put a frame around the entire box, and vertical lines inside */
1362   tab_box (t,
1363            TAL_2, TAL_2,
1364            -1, TAL_1,
1365            0, 0,
1366            n_cols - 1, n_rows - 1);
1367
1368   tab_box (t,
1369            -1, -1,
1370            TAL_0, TAL_0,
1371            0, 0,
1372            2, 0);
1373
1374   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
1375   tab_vline (t, TAL_2, 3, 0, n_rows - 1);
1376
1377   tab_title (t, _("Contrast Tests"));
1378
1379   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Contrast"));
1380   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Value of Contrast"));
1381   tab_text (t,  4, 0, TAB_CENTER | TAT_TITLE, _("Std. Error"));
1382   tab_text (t,  5, 0, TAB_CENTER | TAT_TITLE, _("t"));
1383   tab_text (t,  6, 0, TAB_CENTER | TAT_TITLE, _("df"));
1384   tab_text (t,  7, 0, TAB_CENTER | TAT_TITLE, _("Sig. (2-tailed)"));
1385
1386   for (v = 0; v < cmd->n_vars; ++v)
1387     {
1388       const struct per_var_ws *pvw = &ws->vws[v];
1389       const struct categoricals *cats = covariance_get_categoricals (pvw->cov);
1390       struct ll *cli;
1391       int i = 0;
1392       int lines_per_variable = 2 * n_contrasts;
1393
1394       tab_text (t,  0, (v * lines_per_variable) + 1, TAB_LEFT | TAT_TITLE,
1395                 var_to_string (cmd->vars[v]));
1396
1397       for ( cli = ll_head (&cmd->contrast_list);
1398             cli != ll_null (&cmd->contrast_list);
1399             ++i, cli = ll_next (cli))
1400         {
1401           struct contrasts_node *cn = ll_data (cli, struct contrasts_node, ll);
1402           struct ll *coeffi ;
1403           int ci = 0;
1404           double contrast_value = 0.0;
1405           double coef_msq = 0.0;
1406
1407           double T;
1408           double std_error_contrast;
1409           double df;
1410           double sec_vneq = 0.0;
1411
1412           /* Note: The calculation of the degrees of freedom in the
1413              "variances not equal" case is painfull!!
1414              The following formula may help to understand it:
1415              \frac{\left (\sum_{i=1}^k{c_i^2\frac{s_i^2}{n_i}}\right)^2}
1416              {
1417              \sum_{i=1}^k\left (
1418              \frac{\left (c_i^2\frac{s_i^2}{n_i}\right)^2}  {n_i-1}
1419              \right)
1420              }
1421           */
1422
1423           double df_denominator = 0.0;
1424           double df_numerator = 0.0;
1425
1426           double grand_n;
1427           moments1_calculate (ws->dd_total[v]->mom, &grand_n, NULL, NULL, NULL, NULL);
1428           df = grand_n - pvw->n_groups;
1429
1430           if ( i == 0 )
1431             {
1432               tab_text (t,  1, (v * lines_per_variable) + i + 1,
1433                         TAB_LEFT | TAT_TITLE,
1434                         _("Assume equal variances"));
1435
1436               tab_text (t,  1, (v * lines_per_variable) + i + 1 + n_contrasts,
1437                         TAB_LEFT | TAT_TITLE,
1438                         _("Does not assume equal"));
1439             }
1440
1441           tab_text_format (t,  2, (v * lines_per_variable) + i + 1,
1442                            TAB_CENTER | TAT_TITLE, "%d", i + 1);
1443
1444
1445           tab_text_format (t,  2,
1446                            (v * lines_per_variable) + i + 1 + n_contrasts,
1447                            TAB_CENTER | TAT_TITLE, "%d", i + 1);
1448
1449           for (coeffi = ll_head (&cn->coefficient_list);
1450                coeffi != ll_null (&cn->coefficient_list);
1451                ++ci, coeffi = ll_next (coeffi))
1452             {
1453               double n, mean, variance;
1454               const struct descriptive_data *dd = categoricals_get_user_data_by_category (cats, ci);
1455               struct coeff_node *cn = ll_data (coeffi, struct coeff_node, ll);
1456               const double coef = cn->coeff; 
1457               double winv ;
1458
1459               moments1_calculate (dd->mom, &n, &mean, &variance, NULL, NULL);
1460
1461               winv = variance / n;
1462
1463               contrast_value += coef * mean;
1464
1465               coef_msq += (pow2 (coef)) / n;
1466
1467               sec_vneq += (pow2 (coef)) * variance / n;
1468
1469               df_numerator += (pow2 (coef)) * winv;
1470               df_denominator += pow2((pow2 (coef)) * winv) / (n - 1);
1471             }
1472
1473           sec_vneq = sqrt (sec_vneq);
1474
1475           df_numerator = pow2 (df_numerator);
1476
1477           tab_double (t,  3, (v * lines_per_variable) + i + 1,
1478                       TAB_RIGHT, contrast_value, NULL, RC_OTHER);
1479
1480           tab_double (t,  3, (v * lines_per_variable) + i + 1 +
1481                       n_contrasts,
1482                       TAB_RIGHT, contrast_value, NULL, RC_OTHER);
1483
1484           std_error_contrast = sqrt (pvw->mse * coef_msq);
1485
1486           /* Std. Error */
1487           tab_double (t,  4, (v * lines_per_variable) + i + 1,
1488                       TAB_RIGHT, std_error_contrast,
1489                       NULL, RC_OTHER);
1490
1491           T = fabs (contrast_value / std_error_contrast);
1492
1493           /* T Statistic */
1494
1495           tab_double (t,  5, (v * lines_per_variable) + i + 1,
1496                       TAB_RIGHT, T,
1497                       NULL, RC_OTHER);
1498
1499
1500           /* Degrees of Freedom */
1501           tab_double (t,  6, (v * lines_per_variable) + i + 1,
1502                      TAB_RIGHT,  df, NULL, RC_INTEGER);
1503
1504
1505           /* Significance TWO TAILED !!*/
1506           tab_double (t,  7, (v * lines_per_variable) + i + 1,
1507                       TAB_RIGHT,  2 * gsl_cdf_tdist_Q (T, df),
1508                       NULL, RC_PVALUE);
1509
1510           /* Now for the Variances NOT Equal case */
1511
1512           /* Std. Error */
1513           tab_double (t,  4,
1514                       (v * lines_per_variable) + i + 1 + n_contrasts,
1515                       TAB_RIGHT, sec_vneq,
1516                       NULL, RC_OTHER);
1517
1518           T = contrast_value / sec_vneq;
1519           tab_double (t,  5,
1520                       (v * lines_per_variable) + i + 1 + n_contrasts,
1521                       TAB_RIGHT, T,
1522                       NULL, RC_OTHER);
1523
1524           df = df_numerator / df_denominator;
1525
1526           tab_double (t,  6,
1527                       (v * lines_per_variable) + i + 1 + n_contrasts,
1528                       TAB_RIGHT, df,
1529                       NULL, RC_OTHER);
1530
1531           {
1532             double p = gsl_cdf_tdist_P (T, df);
1533             double q = gsl_cdf_tdist_Q (T, df);
1534
1535             /* The Significance */
1536             tab_double (t, 7, (v * lines_per_variable) + i + 1 + n_contrasts,
1537                         TAB_RIGHT,  2 * ((T > 0) ? q : p),
1538                         NULL, RC_PVALUE);
1539           }
1540         }
1541
1542       if ( v > 0 )
1543         tab_hline (t, TAL_1, 0, n_cols - 1, (v * lines_per_variable) + 1);
1544     }
1545
1546   tab_submit (t);
1547 }
1548
1549
1550
1551 static void
1552 show_comparisons (const struct oneway_spec *cmd, const struct oneway_workspace *ws, int v)
1553 {
1554   const int n_cols = 8;
1555   const int heading_rows = 2;
1556   const int heading_cols = 3;
1557
1558   int p;
1559   int r = heading_rows ;
1560
1561   const struct per_var_ws *pvw = &ws->vws[v];
1562   const struct categoricals *cat = pvw->cat;
1563   const int n_rows = heading_rows + cmd->n_posthoc * pvw->n_groups * (pvw->n_groups - 1);
1564
1565   struct tab_table *t = tab_create (n_cols, n_rows);
1566
1567   tab_headers (t, heading_cols, 0, heading_rows, 0);
1568
1569   /* Put a frame around the entire box, and vertical lines inside */
1570   tab_box (t,
1571            TAL_2, TAL_2,
1572            -1, -1,
1573            0, 0,
1574            n_cols - 1, n_rows - 1);
1575
1576   tab_box (t,
1577            -1, -1,
1578            -1, TAL_1,
1579            heading_cols, 0,
1580            n_cols - 1, n_rows - 1);
1581
1582   tab_vline (t, TAL_2, heading_cols, 0, n_rows - 1);
1583
1584   tab_title (t, _("Multiple Comparisons (%s)"), var_to_string (cmd->vars[v]));
1585
1586   tab_text_format (t,  1, 1, TAB_LEFT | TAT_TITLE, _("(I) %s"), var_to_string (cmd->indep_var));
1587   tab_text_format (t,  2, 1, TAB_LEFT | TAT_TITLE, _("(J) %s"), var_to_string (cmd->indep_var));
1588   tab_text (t,  3, 0, TAB_CENTER | TAT_TITLE, _("Mean Difference"));
1589   tab_text (t,  3, 1, TAB_CENTER | TAT_TITLE, _("(I - J)"));
1590   tab_text (t,  4, 1, TAB_CENTER | TAT_TITLE, _("Std. Error"));
1591   tab_text (t,  5, 1, TAB_CENTER | TAT_TITLE, _("Sig."));
1592
1593   tab_joint_text_format (t, 6, 0, 7, 0, TAB_CENTER | TAT_TITLE,
1594                          _("%g%% Confidence Interval"),
1595                          (1 - cmd->alpha) * 100.0);
1596
1597   tab_text (t,  6, 1, TAB_CENTER | TAT_TITLE, _("Lower Bound"));
1598   tab_text (t,  7, 1, TAB_CENTER | TAT_TITLE, _("Upper Bound"));
1599
1600
1601   for (p = 0; p < cmd->n_posthoc; ++p)
1602     {
1603       int i;
1604       const struct posthoc *ph = &ph_tests[cmd->posthoc[p]];
1605
1606       tab_hline (t, TAL_2, 0, n_cols - 1, r);
1607
1608       tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, gettext (ph->label));
1609
1610       for (i = 0; i < pvw->n_groups ; ++i)
1611         {
1612           double weight_i, mean_i, var_i;
1613           int rx = 0;
1614           struct string vstr;
1615           int j;
1616           struct descriptive_data *dd_i = categoricals_get_user_data_by_category (cat, i);
1617           const struct ccase *gcc = categoricals_get_case_by_category (cat, i);
1618           
1619
1620           ds_init_empty (&vstr);
1621           var_append_value_name (cmd->indep_var, case_data (gcc, cmd->indep_var), &vstr);
1622
1623           if ( i != 0)
1624             tab_hline (t, TAL_1, 1, n_cols - 1, r);
1625           tab_text (t, 1, r, TAB_LEFT | TAT_TITLE, ds_cstr (&vstr));
1626
1627           moments1_calculate (dd_i->mom, &weight_i, &mean_i, &var_i, 0, 0);
1628
1629           for (j = 0 ; j < pvw->n_groups; ++j)
1630             {
1631               double std_err;
1632               double weight_j, mean_j, var_j;
1633               double half_range;
1634               const struct ccase *cc;
1635               struct descriptive_data *dd_j = categoricals_get_user_data_by_category (cat, j);
1636               if (j == i)
1637                 continue;
1638
1639               ds_clear (&vstr);
1640               cc = categoricals_get_case_by_category (cat, j);
1641               var_append_value_name (cmd->indep_var, case_data (cc, cmd->indep_var), &vstr);
1642               tab_text (t, 2, r + rx, TAB_LEFT | TAT_TITLE, ds_cstr (&vstr));
1643
1644               moments1_calculate (dd_j->mom, &weight_j, &mean_j, &var_j, 0, 0);
1645
1646               tab_double  (t, 3, r + rx, 0, mean_i - mean_j, NULL, RC_OTHER);
1647
1648               std_err = pvw->mse;
1649               std_err *= weight_i + weight_j;
1650               std_err /= weight_i * weight_j;
1651               std_err = sqrt (std_err);
1652
1653               tab_double  (t, 4, r + rx, 0, std_err, NULL, RC_OTHER);
1654           
1655               tab_double (t, 5, r + rx, 0, 2 * multiple_comparison_sig (std_err, pvw, dd_i, dd_j, ph), NULL, RC_PVALUE);
1656
1657               half_range = mc_half_range (cmd, pvw, std_err, dd_i, dd_j, ph);
1658
1659               tab_double (t, 6, r + rx, 0,
1660                           (mean_i - mean_j) - half_range, NULL, RC_OTHER);
1661
1662               tab_double (t, 7, r + rx, 0,
1663                           (mean_i - mean_j) + half_range, NULL, RC_OTHER);
1664
1665               rx++;
1666             }
1667           ds_destroy (&vstr);
1668           r += pvw->n_groups - 1;
1669         }
1670     }
1671
1672   tab_submit (t);
1673 }