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