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