Rewrite PSPP output engine.
[pspp-builds.git] / src / language / stats / oneway.q
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <gsl/gsl_cdf.h>
20 #include <math.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23
24 #include <data/case.h>
25 #include <data/casegrouper.h>
26 #include <data/casereader.h>
27 #include <data/dictionary.h>
28 #include <data/procedure.h>
29 #include <data/value-labels.h>
30 #include <data/variable.h>
31 #include <language/command.h>
32 #include <language/dictionary/split-file.h>
33 #include <language/lexer/lexer.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/hash.h>
36 #include <libpspp/message.h>
37 #include <libpspp/misc.h>
38 #include <libpspp/str.h>
39 #include <libpspp/taint.h>
40 #include <math/group-proc.h>
41 #include <math/group.h>
42 #include <math/levene.h>
43 #include <output/tab.h>
44 #include "sort-criteria.h"
45 #include <data/format.h>
46
47 #include "xalloc.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51
52 /* (headers) */
53
54 /* (specification)
55    "ONEWAY" (oneway_):
56    *^variables=custom;
57    missing=miss:!analysis/listwise,
58    incl:include/!exclude;
59    +contrast= double list;
60    +statistics[st_]=descriptives,homogeneity.
61 */
62 /* (declarations) */
63 /* (functions) */
64
65 static struct cmd_oneway cmd;
66
67 /* The independent variable */
68 static const struct variable *indep_var;
69
70 /* Number of dependent variables */
71 static size_t n_vars;
72
73 /* The dependent variables */
74 static const struct variable **vars;
75
76
77 /* A  hash table containing all the distinct values of the independent
78    variables */
79 static struct hsh_table *global_group_hash;
80
81 /* The number of distinct values of the independent variable, when all
82    missing values are disregarded */
83 static int ostensible_number_of_groups = -1;
84
85
86 static void run_oneway (struct cmd_oneway *, struct casereader *,
87                         const struct dataset *);
88
89
90 /* Routines to show the output tables */
91 static void show_anova_table(void);
92 static void show_descriptives (const struct dictionary *dict);
93 static void show_homogeneity(void);
94
95 static void show_contrast_coeffs (short *);
96 static void show_contrast_tests (short *);
97
98
99 enum stat_table_t {STAT_DESC = 1, STAT_HOMO = 2};
100
101 static enum stat_table_t stat_tables;
102
103 static void output_oneway (const struct dictionary *dict);
104
105
106 int
107 cmd_oneway (struct lexer *lexer, struct dataset *ds)
108 {
109   struct casegrouper *grouper;
110   struct casereader *group;
111   int i;
112   bool ok;
113
114   if ( !parse_oneway (lexer, ds, &cmd, NULL))
115     return CMD_FAILURE;
116
117   /* What statistics were requested */
118   if ( cmd.sbc_statistics)
119     {
120
121       for (i = 0; i < ONEWAY_ST_count; ++i)
122         {
123           if (! cmd.a_statistics[i]) continue;
124
125           switch (i) 
126             {
127             case ONEWAY_ST_DESCRIPTIVES:
128               stat_tables |= STAT_DESC;
129               break;
130             case ONEWAY_ST_HOMOGENEITY:
131               stat_tables |= STAT_HOMO;
132               break;
133             }
134         }
135     }
136
137   /* Data pass.  FIXME: error handling. */
138   grouper = casegrouper_create_splits (proc_open (ds), dataset_dict (ds));
139   while (casegrouper_get_next_group (grouper, &group))
140     run_oneway (&cmd, group, ds);
141   ok = casegrouper_destroy (grouper);
142   ok = proc_commit (ds) && ok;
143
144   free (vars);
145   free_oneway (&cmd);
146
147   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
148 }
149
150
151 static void
152 output_oneway (const struct dictionary *dict)
153 {
154   size_t i;
155   short *bad_contrast;
156
157   bad_contrast = xnmalloc (cmd.sbc_contrast, sizeof *bad_contrast);
158
159   /* Check the sanity of the given contrast values */
160   for (i = 0; i < cmd.sbc_contrast; ++i)
161     {
162       int j;
163       double sum = 0;
164
165       bad_contrast[i] = 0;
166       if (subc_list_double_count (&cmd.dl_contrast[i]) !=
167           ostensible_number_of_groups)
168         {
169           msg (SW,
170                _("Number of contrast coefficients must equal the number of groups"));
171           bad_contrast[i] = 1;
172           continue;
173         }
174
175       for (j = 0; j < ostensible_number_of_groups; ++j)
176         sum += subc_list_double_at (&cmd.dl_contrast[i], j);
177
178       if ( sum != 0.0 )
179         msg (SW, _("Coefficients for contrast %zu do not total zero"), i + 1);
180     }
181
182   if ( stat_tables & STAT_DESC )
183     show_descriptives (dict);
184
185   if ( stat_tables & STAT_HOMO )
186     show_homogeneity ();
187
188   show_anova_table ();
189
190   if (cmd.sbc_contrast )
191     {
192       show_contrast_coeffs (bad_contrast);
193       show_contrast_tests (bad_contrast);
194     }
195
196   free (bad_contrast);
197
198   /* Clean up */
199   for (i = 0; i < n_vars; ++i )
200     {
201       struct hsh_table *group_hash = group_proc_get (vars[i])->group_hash;
202
203       hsh_destroy (group_hash);
204     }
205
206   hsh_destroy (global_group_hash);
207 }
208
209
210 /* Parser for the variables sub command */
211 static int
212 oneway_custom_variables (struct lexer *lexer,
213                          struct dataset *ds, struct cmd_oneway *cmd UNUSED,
214                          void *aux UNUSED)
215 {
216   struct dictionary *dict = dataset_dict (ds);
217
218   lex_match (lexer, '=');
219
220   if ((lex_token (lexer) != T_ID ||
221        dict_lookup_var (dict, lex_tokid (lexer)) == NULL)
222       && lex_token (lexer) != T_ALL)
223     return 2;
224
225   if (!parse_variables_const (lexer, dict, &vars, &n_vars,
226                               PV_DUPLICATE
227                               | PV_NUMERIC | PV_NO_SCRATCH) )
228     {
229       free (vars);
230       return 0;
231     }
232
233   assert (n_vars);
234
235   if ( ! lex_match (lexer, T_BY))
236     return 2;
237
238   indep_var = parse_variable (lexer, dict);
239
240   if ( !indep_var )
241     {
242       msg (SE, _("`%s' is not a variable name"), lex_tokid (lexer));
243       return 0;
244     }
245
246   return 1;
247 }
248
249
250 /* Show the ANOVA table */
251 static void
252 show_anova_table (void)
253 {
254   size_t i;
255   int n_cols =7;
256   size_t n_rows = n_vars * 3 + 1;
257
258   struct tab_table *t;
259
260
261   t = tab_create (n_cols, n_rows);
262   tab_headers (t, 2, 0, 1, 0);
263
264   tab_box (t,
265            TAL_2, TAL_2,
266            -1, TAL_1,
267            0, 0,
268            n_cols - 1, n_rows - 1);
269
270   tab_hline (t, TAL_2, 0, n_cols - 1, 1 );
271   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
272   tab_vline (t, TAL_0, 1, 0, 0);
273
274   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Sum of Squares"));
275   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df"));
276   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
277   tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("F"));
278   tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
279
280
281   for (i = 0; i < n_vars; ++i)
282     {
283       struct group_statistics *totals = &group_proc_get (vars[i])->ugs;
284       struct hsh_table *group_hash = group_proc_get (vars[i])->group_hash;
285       struct hsh_iterator g;
286       struct group_statistics *gs;
287       double ssa = 0;
288       const char *s = var_to_string (vars[i]);
289
290       for (gs =  hsh_first (group_hash, &g);
291            gs != 0;
292            gs = hsh_next (group_hash, &g))
293         {
294           ssa += pow2 (gs->sum) / gs->n;
295         }
296
297       ssa -= pow2 (totals->sum) / totals->n;
298
299       tab_text (t, 0, i * 3 + 1, TAB_LEFT | TAT_TITLE, s);
300       tab_text (t, 1, i * 3 + 1, TAB_LEFT | TAT_TITLE, _("Between Groups"));
301       tab_text (t, 1, i * 3 + 2, TAB_LEFT | TAT_TITLE, _("Within Groups"));
302       tab_text (t, 1, i * 3 + 3, TAB_LEFT | TAT_TITLE, _("Total"));
303
304       if (i > 0)
305         tab_hline (t, TAL_1, 0, n_cols - 1, i * 3 + 1);
306
307       {
308         struct group_proc *gp = group_proc_get (vars[i]);
309         const double sst = totals->ssq - pow2 (totals->sum) / totals->n;
310         const double df1 = gp->n_groups - 1;
311         const double df2 = totals->n - gp->n_groups;
312         const double msa = ssa / df1;
313
314         gp->mse  = (sst - ssa) / df2;
315
316
317         /* Sums of Squares */
318         tab_double (t, 2, i * 3 + 1, 0, ssa, NULL);
319         tab_double (t, 2, i * 3 + 3, 0, sst, NULL);
320         tab_double (t, 2, i * 3 + 2, 0, sst - ssa, NULL);
321
322
323         /* Degrees of freedom */
324         tab_fixed (t, 3, i * 3 + 1, 0, df1, 4, 0);
325         tab_fixed (t, 3, i * 3 + 2, 0, df2, 4, 0);
326         tab_fixed (t, 3, i * 3 + 3, 0, totals->n - 1, 4, 0);
327
328         /* Mean Squares */
329         tab_double (t, 4, i * 3 + 1, TAB_RIGHT, msa, NULL);
330         tab_double (t, 4, i * 3 + 2, TAB_RIGHT, gp->mse, NULL);
331
332         {
333           const double F = msa / gp->mse ;
334
335           /* The F value */
336           tab_double (t, 5, i * 3 + 1, 0,  F, NULL);
337
338           /* The significance */
339           tab_double (t, 6, i * 3 + 1, 0, gsl_cdf_fdist_Q (F, df1, df2), NULL);
340         }
341       }
342     }
343
344
345   tab_title (t, _("ANOVA"));
346   tab_submit (t);
347 }
348
349
350 /* Show the descriptives table */
351 static void
352 show_descriptives (const struct dictionary *dict)
353 {
354   size_t v;
355   int n_cols = 10;
356   struct tab_table *t;
357   int row;
358
359   const double confidence = 0.95;
360   const double q = (1.0 - confidence) / 2.0;
361
362   const struct variable *wv = dict_get_weight (dict);
363   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : & F_8_0;
364
365   int n_rows = 2;
366
367   for ( v = 0; v < n_vars; ++v )
368     n_rows += group_proc_get (vars[v])->n_groups + 1;
369
370   t = tab_create (n_cols, n_rows);
371   tab_headers (t, 2, 0, 2, 0);
372
373
374   /* Put a frame around the entire box, and vertical lines inside */
375   tab_box (t,
376            TAL_2, TAL_2,
377            -1, TAL_1,
378            0, 0,
379            n_cols - 1, n_rows - 1);
380
381   /* Underline headers */
382   tab_hline (t, TAL_2, 0, n_cols - 1, 2);
383   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
384
385   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("N"));
386   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Mean"));
387   tab_text (t, 4, 1, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
388   tab_text (t, 5, 1, TAB_CENTER | TAT_TITLE, _("Std. Error"));
389
390
391   tab_vline (t, TAL_0, 7, 0, 0);
392   tab_hline (t, TAL_1, 6, 7, 1);
393   tab_joint_text_format (t, 6, 0, 7, 0, TAB_CENTER | TAT_TITLE,
394                          _("%g%% Confidence Interval for Mean"),
395                          confidence*100.0);
396
397   tab_text (t, 6, 1, TAB_CENTER | TAT_TITLE, _("Lower Bound"));
398   tab_text (t, 7, 1, TAB_CENTER | TAT_TITLE, _("Upper Bound"));
399
400   tab_text (t, 8, 1, TAB_CENTER | TAT_TITLE, _("Minimum"));
401   tab_text (t, 9, 1, TAB_CENTER | TAT_TITLE, _("Maximum"));
402
403
404   tab_title (t, _("Descriptives"));
405
406
407   row = 2;
408   for (v = 0; v < n_vars; ++v)
409     {
410       double T;
411       double std_error;
412
413       struct group_proc *gp = group_proc_get (vars[v]);
414
415       struct group_statistics *gs;
416       struct group_statistics *totals = &gp->ugs;
417
418       const char *s = var_to_string (vars[v]);
419       const struct fmt_spec *fmt = var_get_print_format (vars[v]);
420
421       struct group_statistics *const *gs_array =
422         (struct group_statistics *const *) hsh_sort (gp->group_hash);
423       int count = 0;
424
425       tab_text (t, 0, row, TAB_LEFT | TAT_TITLE, s);
426       if ( v > 0)
427         tab_hline (t, TAL_1, 0, n_cols - 1, row);
428
429       for (count = 0; count < hsh_count (gp->group_hash); ++count)
430         {
431           struct string vstr;
432           ds_init_empty (&vstr);
433           gs = gs_array[count];
434
435           var_append_value_name (indep_var, &gs->id, &vstr);
436
437           tab_text (t, 1, row + count,
438                     TAB_LEFT | TAT_TITLE,
439                     ds_cstr (&vstr));
440
441           ds_destroy (&vstr);
442
443           /* Now fill in the numbers ... */
444
445           tab_fixed (t, 2, row + count, 0, gs->n, 8, 0);
446
447           tab_double (t, 3, row + count, 0, gs->mean, NULL);
448
449           tab_double (t, 4, row + count, 0, gs->std_dev, NULL);
450
451           std_error = gs->std_dev / sqrt (gs->n) ;
452           tab_double (t, 5, row + count, 0,
453                      std_error, NULL);
454
455           /* Now the confidence interval */
456
457           T = gsl_cdf_tdist_Qinv (q, gs->n - 1);
458
459           tab_double (t, 6, row + count, 0,
460                     gs->mean - T * std_error, NULL);
461
462           tab_double (t, 7, row + count, 0,
463                     gs->mean + T * std_error, NULL);
464
465           /* Min and Max */
466
467           tab_double (t, 8, row + count, 0,  gs->minimum, fmt);
468           tab_double (t, 9, row + count, 0,  gs->maximum, fmt);
469         }
470
471       tab_text (t, 1, row + count,
472                 TAB_LEFT | TAT_TITLE, _("Total"));
473
474       tab_double (t, 2, row + count, 0, totals->n, wfmt);
475
476       tab_double (t, 3, row + count, 0, totals->mean, NULL);
477
478       tab_double (t, 4, row + count, 0, totals->std_dev, NULL);
479
480       std_error = totals->std_dev / sqrt (totals->n) ;
481
482       tab_double (t, 5, row + count, 0, std_error, NULL);
483
484       /* Now the confidence interval */
485
486       T = gsl_cdf_tdist_Qinv (q, totals->n - 1);
487
488       tab_double (t, 6, row + count, 0,
489                   totals->mean - T * std_error, NULL);
490
491       tab_double (t, 7, row + count, 0,
492                   totals->mean + T * std_error, NULL);
493
494       /* Min and Max */
495
496       tab_double (t, 8, row + count, 0,  totals->minimum, fmt);
497       tab_double (t, 9, row + count, 0,  totals->maximum, fmt);
498
499       row += gp->n_groups + 1;
500     }
501
502   tab_submit (t);
503 }
504
505 /* Show the homogeneity table */
506 static void
507 show_homogeneity (void)
508 {
509   size_t v;
510   int n_cols = 5;
511   size_t n_rows = n_vars + 1;
512
513   struct tab_table *t;
514
515
516   t = tab_create (n_cols, n_rows);
517   tab_headers (t, 1, 0, 1, 0);
518
519
520   /* Put a frame around the entire box, and vertical lines inside */
521   tab_box (t,
522            TAL_2, TAL_2,
523            -1, TAL_1,
524            0, 0,
525            n_cols - 1, n_rows - 1);
526
527
528   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
529   tab_vline (t, TAL_2, 1, 0, n_rows - 1);
530
531
532   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Levene Statistic"));
533   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("df1"));
534   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df2"));
535   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
536
537   tab_title (t, _("Test of Homogeneity of Variances"));
538
539   for (v = 0; v < n_vars; ++v)
540     {
541       double F;
542       const struct variable *var = vars[v];
543       const struct group_proc *gp = group_proc_get (vars[v]);
544       const char *s = var_to_string (var);
545       const struct group_statistics *totals = &gp->ugs;
546
547       const double df1 = gp->n_groups - 1;
548       const double df2 = totals->n - gp->n_groups;
549
550       tab_text (t, 0, v + 1, TAB_LEFT | TAT_TITLE, s);
551
552       F = gp->levene;
553       tab_double (t, 1, v + 1, TAB_RIGHT, F, NULL);
554       tab_fixed (t, 2, v + 1, TAB_RIGHT, df1, 8, 0);
555       tab_fixed (t, 3, v + 1, TAB_RIGHT, df2, 8, 0);
556
557       /* Now the significance */
558       tab_double (t, 4, v + 1, TAB_RIGHT,gsl_cdf_fdist_Q (F, df1, df2), NULL);
559     }
560
561   tab_submit (t);
562 }
563
564
565 /* Show the contrast coefficients table */
566 static void
567 show_contrast_coeffs (short *bad_contrast)
568 {
569   int n_cols = 2 + ostensible_number_of_groups;
570   int n_rows = 2 + cmd.sbc_contrast;
571   int count = 0;
572   void *const *group_values;
573
574   struct tab_table *t;
575
576   t = tab_create (n_cols, n_rows);
577   tab_headers (t, 2, 0, 2, 0);
578
579   /* Put a frame around the entire box, and vertical lines inside */
580   tab_box (t,
581            TAL_2, TAL_2,
582            -1, TAL_1,
583            0, 0,
584            n_cols - 1, n_rows - 1);
585
586   tab_box (t,
587            -1, -1,
588            TAL_0, TAL_0,
589            2, 0,
590            n_cols - 1, 0);
591
592   tab_box (t,
593            -1, -1,
594            TAL_0, TAL_0,
595            0, 0,
596            1, 1);
597
598   tab_hline (t, TAL_1, 2, n_cols - 1, 1);
599   tab_hline (t, TAL_2, 0, n_cols - 1, 2);
600
601   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
602
603   tab_title (t, _("Contrast Coefficients"));
604
605   tab_text (t,  0, 2, TAB_LEFT | TAT_TITLE, _("Contrast"));
606
607
608   tab_joint_text (t, 2, 0, n_cols - 1, 0, TAB_CENTER | TAT_TITLE,
609                   var_to_string (indep_var));
610
611   group_values = hsh_sort (global_group_hash);
612   for (count = 0;
613        count < hsh_count (global_group_hash);
614        ++count)
615     {
616       double *group_value_p;
617       union value group_value;
618       int i;
619       struct string vstr;
620
621       ds_init_empty (&vstr);
622
623       group_value_p = group_values[count];
624       group_value.f = *group_value_p;
625       var_append_value_name (indep_var, &group_value, &vstr);
626
627       tab_text (t, count + 2, 1, TAB_CENTER | TAT_TITLE,
628                 ds_cstr (&vstr));
629
630       ds_destroy (&vstr);
631
632
633       for (i = 0; i < cmd.sbc_contrast; ++i )
634         {
635           tab_text_format (t, 1, i + 2, TAB_CENTER, "%d", i + 1);
636
637           if ( bad_contrast[i] )
638             tab_text (t, count + 2, i + 2, TAB_RIGHT, "?" );
639           else
640             tab_text_format (t, count + 2, i + 2, TAB_RIGHT, "%g",
641                              subc_list_double_at (&cmd.dl_contrast[i], count));
642         }
643     }
644
645   tab_submit (t);
646 }
647
648
649 /* Show the results of the contrast tests */
650 static void
651 show_contrast_tests (short *bad_contrast)
652 {
653   size_t v;
654   int n_cols = 8;
655   size_t n_rows = 1 + n_vars * 2 * cmd.sbc_contrast;
656
657   struct tab_table *t;
658
659   t = tab_create (n_cols, n_rows);
660   tab_headers (t, 3, 0, 1, 0);
661
662   /* Put a frame around the entire box, and vertical lines inside */
663   tab_box (t,
664            TAL_2, TAL_2,
665            -1, TAL_1,
666            0, 0,
667            n_cols - 1, n_rows - 1);
668
669   tab_box (t,
670            -1, -1,
671            TAL_0, TAL_0,
672            0, 0,
673            2, 0);
674
675   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
676   tab_vline (t, TAL_2, 3, 0, n_rows - 1);
677
678
679   tab_title (t, _("Contrast Tests"));
680
681   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Contrast"));
682   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Value of Contrast"));
683   tab_text (t,  4, 0, TAB_CENTER | TAT_TITLE, _("Std. Error"));
684   tab_text (t,  5, 0, TAB_CENTER | TAT_TITLE, _("t"));
685   tab_text (t,  6, 0, TAB_CENTER | TAT_TITLE, _("df"));
686   tab_text (t,  7, 0, TAB_CENTER | TAT_TITLE, _("Sig. (2-tailed)"));
687
688   for (v = 0; v < n_vars; ++v)
689     {
690       int i;
691       int lines_per_variable = 2 * cmd.sbc_contrast;
692
693
694       tab_text (t,  0, (v * lines_per_variable) + 1, TAB_LEFT | TAT_TITLE,
695                 var_to_string (vars[v]));
696
697       for (i = 0; i < cmd.sbc_contrast; ++i)
698         {
699           int ci;
700           double contrast_value = 0.0;
701           double coef_msq = 0.0;
702           struct group_proc *grp_data = group_proc_get (vars[v]);
703           struct hsh_table *group_hash = grp_data->group_hash;
704
705           void *const *group_stat_array;
706
707           double T;
708           double std_error_contrast;
709           double df;
710           double sec_vneq = 0.0;
711
712
713           /* Note: The calculation of the degrees of freedom in the
714              "variances not equal" case is painfull!!
715              The following formula may help to understand it:
716              \frac{\left (\sum_{i=1}^k{c_i^2\frac{s_i^2}{n_i}}\right)^2}
717              {
718              \sum_{i=1}^k\left (
719              \frac{\left (c_i^2\frac{s_i^2}{n_i}\right)^2}  {n_i-1}
720              \right)
721              }
722           */
723
724           double df_denominator = 0.0;
725           double df_numerator = 0.0;
726           if ( i == 0 )
727             {
728               tab_text (t,  1, (v * lines_per_variable) + i + 1,
729                         TAB_LEFT | TAT_TITLE,
730                         _("Assume equal variances"));
731
732               tab_text (t,  1, (v * lines_per_variable) + i + 1 + cmd.sbc_contrast,
733                         TAB_LEFT | TAT_TITLE,
734                         _("Does not assume equal"));
735             }
736
737           tab_text_format (t,  2, (v * lines_per_variable) + i + 1,
738                            TAB_CENTER | TAT_TITLE, "%d", i + 1);
739
740
741           tab_text_format (t,  2,
742                            (v * lines_per_variable) + i + 1 + cmd.sbc_contrast,
743                            TAB_CENTER | TAT_TITLE, "%d", i + 1);
744
745
746           if ( bad_contrast[i])
747             continue;
748
749           group_stat_array = hsh_sort (group_hash);
750
751           for (ci = 0; ci < hsh_count (group_hash);  ++ci)
752             {
753               const double coef = subc_list_double_at (&cmd.dl_contrast[i], ci);
754               struct group_statistics *gs = group_stat_array[ci];
755
756               const double winv = pow2 (gs->std_dev) / gs->n;
757
758               contrast_value += coef * gs->mean;
759
760               coef_msq += (coef * coef) / gs->n;
761
762               sec_vneq += (coef * coef) * pow2 (gs->std_dev) /gs->n;
763
764               df_numerator += (coef * coef) * winv;
765               df_denominator += pow2((coef * coef) * winv) / (gs->n - 1);
766             }
767           sec_vneq = sqrt (sec_vneq);
768
769           df_numerator = pow2 (df_numerator);
770
771           tab_double (t,  3, (v * lines_per_variable) + i + 1,
772                      TAB_RIGHT, contrast_value, NULL);
773
774           tab_double (t,  3, (v * lines_per_variable) + i + 1 +
775                      cmd.sbc_contrast,
776                      TAB_RIGHT, contrast_value, NULL);
777
778           std_error_contrast = sqrt (grp_data->mse * coef_msq);
779
780           /* Std. Error */
781           tab_double (t,  4, (v * lines_per_variable) + i + 1,
782                      TAB_RIGHT, std_error_contrast,
783                      NULL);
784
785           T = fabs (contrast_value / std_error_contrast);
786
787           /* T Statistic */
788
789           tab_double (t,  5, (v * lines_per_variable) + i + 1,
790                      TAB_RIGHT, T,
791                      NULL);
792
793           df = grp_data->ugs.n - grp_data->n_groups;
794
795           /* Degrees of Freedom */
796           tab_fixed (t,  6, (v * lines_per_variable) + i + 1,
797                      TAB_RIGHT,  df,
798                      8, 0);
799
800
801           /* Significance TWO TAILED !!*/
802           tab_double (t,  7, (v * lines_per_variable) + i + 1,
803                      TAB_RIGHT,  2 * gsl_cdf_tdist_Q (T, df),
804                      NULL);
805
806           /* Now for the Variances NOT Equal case */
807
808           /* Std. Error */
809           tab_double (t,  4,
810                      (v * lines_per_variable) + i + 1 + cmd.sbc_contrast,
811                      TAB_RIGHT, sec_vneq,
812                      NULL);
813
814           T = contrast_value / sec_vneq;
815           tab_double (t,  5,
816                      (v * lines_per_variable) + i + 1 + cmd.sbc_contrast,
817                      TAB_RIGHT, T,
818                      NULL);
819
820           df = df_numerator / df_denominator;
821
822           tab_double (t,  6,
823                      (v * lines_per_variable) + i + 1 + cmd.sbc_contrast,
824                      TAB_RIGHT, df,
825                      NULL);
826
827           /* The Significance */
828
829           tab_double (t, 7, (v * lines_per_variable) + i + 1 + cmd.sbc_contrast,
830                      TAB_RIGHT,  2 * gsl_cdf_tdist_Q (T,df),
831                      NULL);
832         }
833
834       if ( v > 0 )
835         tab_hline (t, TAL_1, 0, n_cols - 1, (v * lines_per_variable) + 1);
836     }
837
838   tab_submit (t);
839 }
840
841
842 /* ONEWAY ANOVA Calculations */
843
844 static void  postcalc (struct cmd_oneway *cmd UNUSED);
845
846 static void  precalc (struct cmd_oneway *cmd UNUSED);
847
848
849
850 /* Pre calculations */
851 static void
852 precalc (struct cmd_oneway *cmd UNUSED)
853 {
854   size_t i = 0;
855
856   for (i = 0; i < n_vars; ++i)
857     {
858       struct group_proc *gp = group_proc_get (vars[i]);
859       struct group_statistics *totals = &gp->ugs;
860
861       /* Create a hash for each of the dependent variables.
862          The hash contains a group_statistics structure,
863          and is keyed by value of the independent variable */
864
865       gp->group_hash = hsh_create (4, compare_group, hash_group,
866                                    (hsh_free_func *) free_group,
867                                    indep_var);
868
869       totals->sum = 0;
870       totals->n = 0;
871       totals->ssq = 0;
872       totals->sum_diff = 0;
873       totals->maximum = -DBL_MAX;
874       totals->minimum = DBL_MAX;
875     }
876 }
877
878 static int
879 compare_double_3way (const void *a_, const void *b_, const void *aux UNUSED)
880 {
881   const double *a = a_;
882   const double *b = b_;
883   return *a < *b ? -1 : *a > *b;
884 }
885
886 static unsigned
887 do_hash_double (const void *value_, const void *aux UNUSED)
888 {
889   const double *value = value_;
890   return hash_double (*value, 0);
891 }
892
893 static void
894 free_double (void *value_, const void *aux UNUSED)
895 {
896   double *value = value_;
897   free (value);
898 }
899
900 static void
901 run_oneway (struct cmd_oneway *cmd,
902             struct casereader *input,
903             const struct dataset *ds)
904 {
905   struct taint *taint;
906   struct dictionary *dict = dataset_dict (ds);
907   enum mv_class exclude;
908   struct casereader *reader;
909   struct ccase *c;
910
911   c = casereader_peek (input, 0);
912   if (c == NULL)
913     {
914       casereader_destroy (input);
915       return;
916     }
917   output_split_file_values (ds, c);
918   case_unref (c);
919
920   taint = taint_clone (casereader_get_taint (input));
921
922   global_group_hash = hsh_create (4,
923                                   compare_double_3way,
924                                   do_hash_double,
925                                   free_double,
926                                   indep_var);
927
928   precalc (cmd);
929
930   exclude = cmd->incl != ONEWAY_INCLUDE ? MV_ANY : MV_SYSTEM;
931   input = casereader_create_filter_missing (input, &indep_var, 1,
932                                             exclude, NULL, NULL);
933   if (cmd->miss == ONEWAY_LISTWISE)
934     input = casereader_create_filter_missing (input, vars, n_vars,
935                                               exclude, NULL, NULL);
936   input = casereader_create_filter_weight (input, dict, NULL, NULL);
937
938   reader = casereader_clone (input);
939   for (; (c = casereader_read (reader)) != NULL; case_unref (c))
940     {
941       size_t i;
942
943       const double weight = dict_get_case_weight (dict, c, NULL);
944
945       const union value *indep_val = case_data (c, indep_var);
946       void **p = hsh_probe (global_group_hash, &indep_val->f);
947       if (*p == NULL)
948         {
949           double *value = *p = xmalloc (sizeof *value);
950           *value = indep_val->f;
951         }
952
953       for (i = 0; i < n_vars; ++i)
954         {
955           const struct variable *v = vars[i];
956
957           const union value *val = case_data (c, v);
958
959           struct group_proc *gp = group_proc_get (vars[i]);
960           struct hsh_table *group_hash = gp->group_hash;
961
962           struct group_statistics *gs;
963
964           gs = hsh_find (group_hash, indep_val );
965
966           if ( ! gs )
967             {
968               gs = xmalloc (sizeof *gs);
969               gs->id = *indep_val;
970               gs->sum = 0;
971               gs->n = 0;
972               gs->ssq = 0;
973               gs->sum_diff = 0;
974               gs->minimum = DBL_MAX;
975               gs->maximum = -DBL_MAX;
976
977               hsh_insert ( group_hash, gs );
978             }
979
980           if (!var_is_value_missing (v, val, exclude))
981             {
982               struct group_statistics *totals = &gp->ugs;
983
984               totals->n += weight;
985               totals->sum += weight * val->f;
986               totals->ssq += weight * pow2 (val->f);
987
988               if ( val->f * weight  < totals->minimum )
989                 totals->minimum = val->f * weight;
990
991               if ( val->f * weight  > totals->maximum )
992                 totals->maximum = val->f * weight;
993
994               gs->n += weight;
995               gs->sum += weight * val->f;
996               gs->ssq += weight * pow2 (val->f);
997
998               if ( val->f * weight  < gs->minimum )
999                 gs->minimum = val->f * weight;
1000
1001               if ( val->f * weight  > gs->maximum )
1002                 gs->maximum = val->f * weight;
1003             }
1004
1005           gp->n_groups = hsh_count ( group_hash );
1006         }
1007
1008     }
1009   casereader_destroy (reader);
1010
1011   postcalc (cmd);
1012
1013
1014   if ( stat_tables & STAT_HOMO )
1015     levene (dict, casereader_clone (input), indep_var, n_vars, vars, exclude);
1016
1017   casereader_destroy (input);
1018
1019   ostensible_number_of_groups = hsh_count (global_group_hash);
1020
1021   if (!taint_has_tainted_successor (taint))
1022     output_oneway (dict);
1023
1024   taint_destroy (taint);
1025 }
1026
1027
1028 /* Post calculations for the ONEWAY command */
1029 void
1030 postcalc (  struct cmd_oneway *cmd UNUSED )
1031 {
1032   size_t i = 0;
1033
1034   for (i = 0; i < n_vars; ++i)
1035     {
1036       struct group_proc *gp = group_proc_get (vars[i]);
1037       struct hsh_table *group_hash = gp->group_hash;
1038       struct group_statistics *totals = &gp->ugs;
1039
1040       struct hsh_iterator g;
1041       struct group_statistics *gs;
1042
1043       for (gs =  hsh_first (group_hash, &g);
1044            gs != 0;
1045            gs = hsh_next (group_hash, &g))
1046         {
1047           gs->mean = gs->sum / gs->n;
1048           gs->s_std_dev = sqrt (gs->ssq / gs->n - pow2 (gs->mean));
1049
1050           gs->std_dev = sqrt (
1051                               gs->n / (gs->n - 1) *
1052                               ( gs->ssq / gs->n - pow2 (gs->mean))
1053                               );
1054
1055           gs->se_mean = gs->std_dev / sqrt (gs->n);
1056           gs->mean_diff = gs->sum_diff / gs->n;
1057         }
1058
1059       totals->mean = totals->sum / totals->n;
1060       totals->std_dev = sqrt (
1061                               totals->n / (totals->n - 1) *
1062                               (totals->ssq / totals->n - pow2 (totals->mean))
1063                               );
1064
1065       totals->se_mean = totals->std_dev / sqrt (totals->n);
1066     }
1067 }
1068
1069 /*
1070   Local Variables:
1071   mode: c
1072   End:
1073 */