5c46b1843706722c908b0f2e5b4aa91ced0031f4
[pspp] / src / language / stats / glm.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 2011, 2012 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 <gsl/gsl_matrix.h>
21 #include <gsl/gsl_combination.h>
22 #include <math.h>
23
24 #include "data/case.h"
25 #include "data/casegrouper.h"
26 #include "data/casereader.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/value.h"
31 #include "language/command.h"
32 #include "language/dictionary/split-file.h"
33 #include "language/lexer/lexer.h"
34 #include "language/lexer/value-parser.h"
35 #include "language/lexer/variable-parser.h"
36 #include "libpspp/assertion.h"
37 #include "libpspp/ll.h"
38 #include "libpspp/message.h"
39 #include "libpspp/misc.h"
40 #include "libpspp/taint.h"
41 #include "linreg/sweep.h"
42 #include "math/categoricals.h"
43 #include "math/covariance.h"
44 #include "math/interaction.h"
45 #include "math/moments.h"
46 #include "output/tab.h"
47
48 #include "gettext.h"
49 #define _(msgid) gettext (msgid)
50
51 struct glm_spec
52 {
53   size_t n_dep_vars;
54   const struct variable **dep_vars;
55
56   size_t n_factor_vars;
57   const struct variable **factor_vars;
58
59   size_t n_interactions;
60   struct interaction **interactions;
61
62   enum mv_class exclude;
63
64   /* The weight variable */
65   const struct variable *wv;
66
67   const struct dictionary *dict;
68
69   int ss_type;
70   bool intercept;
71
72   double alpha;
73
74   bool dump_coding;
75 };
76
77 struct glm_workspace
78 {
79   double total_ssq;
80   struct moments *totals;
81
82   struct categoricals *cats;
83
84   /*
85      Sums of squares due to different variables. Element 0 is the SSE
86      for the entire model. For i > 0, element i is the SS due to
87      variable i.
88    */
89   gsl_vector *ssq;
90 };
91
92
93 /* Default design: all possible interactions */
94 static void
95 design_full (struct glm_spec *glm)
96 {
97   int sz;
98   int i = 0;
99   glm->n_interactions = (1 << glm->n_factor_vars) - 1;
100
101   glm->interactions = xcalloc (glm->n_interactions, sizeof *glm->interactions);
102
103   /* All subsets, with exception of the empty set, of [0, glm->n_factor_vars) */
104   for (sz = 1; sz <= glm->n_factor_vars; ++sz)
105     {
106       gsl_combination *c = gsl_combination_calloc (glm->n_factor_vars, sz);
107
108       do
109         {
110           struct interaction *iact = interaction_create (NULL);
111           int e;
112           for (e = 0 ; e < gsl_combination_k (c); ++e)
113             interaction_add_variable (iact, glm->factor_vars [gsl_combination_get (c, e)]);
114
115           glm->interactions[i++] = iact;
116         }
117       while (gsl_combination_next (c) == GSL_SUCCESS);
118
119       gsl_combination_free (c);
120     }
121 }
122
123 static void output_glm (const struct glm_spec *,
124                         const struct glm_workspace *ws);
125 static void run_glm (struct glm_spec *cmd, struct casereader *input,
126                      const struct dataset *ds);
127
128
129 static bool parse_design_spec (struct lexer *lexer, struct glm_spec *glm);
130
131
132 int
133 cmd_glm (struct lexer *lexer, struct dataset *ds)
134 {
135   int i;
136   struct const_var_set *factors = NULL;
137   struct glm_spec glm;
138   bool design = false;
139   glm.dict = dataset_dict (ds);
140   glm.n_dep_vars = 0;
141   glm.n_factor_vars = 0;
142   glm.n_interactions = 0;
143   glm.interactions = NULL;
144   glm.dep_vars = NULL;
145   glm.factor_vars = NULL;
146   glm.exclude = MV_ANY;
147   glm.intercept = true;
148   glm.wv = dict_get_weight (glm.dict);
149   glm.alpha = 0.05;
150   glm.dump_coding = false;
151   glm.ss_type = 3;
152
153   if (!parse_variables_const (lexer, glm.dict,
154                               &glm.dep_vars, &glm.n_dep_vars,
155                               PV_NO_DUPLICATE | PV_NUMERIC))
156     goto error;
157
158   if (! lex_force_match (lexer, T_BY))
159     goto error;
160
161   if (!parse_variables_const (lexer, glm.dict,
162                               &glm.factor_vars, &glm.n_factor_vars,
163                               PV_NO_DUPLICATE | PV_NUMERIC))
164     goto error;
165
166   if (glm.n_dep_vars > 1)
167     {
168       msg (ME, _("Multivariate analysis is not yet implemented"));
169       return CMD_FAILURE;
170     }
171
172   factors =
173     const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
174
175   while (lex_token (lexer) != T_ENDCMD)
176     {
177       lex_match (lexer, T_SLASH);
178
179       if (lex_match_id (lexer, "MISSING"))
180         {
181           lex_match (lexer, T_EQUALS);
182           while (lex_token (lexer) != T_ENDCMD
183                  && lex_token (lexer) != T_SLASH)
184             {
185               if (lex_match_id (lexer, "INCLUDE"))
186                 {
187                   glm.exclude = MV_SYSTEM;
188                 }
189               else if (lex_match_id (lexer, "EXCLUDE"))
190                 {
191                   glm.exclude = MV_ANY;
192                 }
193               else
194                 {
195                   lex_error (lexer, NULL);
196                   goto error;
197                 }
198             }
199         }
200       else if (lex_match_id (lexer, "INTERCEPT"))
201         {
202           lex_match (lexer, T_EQUALS);
203           while (lex_token (lexer) != T_ENDCMD
204                  && lex_token (lexer) != T_SLASH)
205             {
206               if (lex_match_id (lexer, "INCLUDE"))
207                 {
208                   glm.intercept = true;
209                 }
210               else if (lex_match_id (lexer, "EXCLUDE"))
211                 {
212                   glm.intercept = false;
213                 }
214               else
215                 {
216                   lex_error (lexer, NULL);
217                   goto error;
218                 }
219             }
220         }
221       else if (lex_match_id (lexer, "CRITERIA"))
222         {
223           lex_match (lexer, T_EQUALS);
224           if (lex_match_id (lexer, "ALPHA"))
225             {
226               if (lex_force_match (lexer, T_LPAREN))
227                 {
228                   if (! lex_force_num (lexer))
229                     {
230                       lex_error (lexer, NULL);
231                       goto error;
232                     }
233
234                   glm.alpha = lex_number (lexer);
235                   lex_get (lexer);
236                   if ( ! lex_force_match (lexer, T_RPAREN))
237                     {
238                       lex_error (lexer, NULL);
239                       goto error;
240                     }
241                 }
242             }
243           else
244             {
245               lex_error (lexer, NULL);
246               goto error;
247             }
248         }
249       else if (lex_match_id (lexer, "METHOD"))
250         {
251           lex_match (lexer, T_EQUALS);
252           if ( !lex_force_match_id (lexer, "SSTYPE"))
253             {
254               lex_error (lexer, NULL);
255               goto error;
256             }
257
258           if ( ! lex_force_match (lexer, T_LPAREN))
259             {
260               lex_error (lexer, NULL);
261               goto error;
262             }
263
264           if ( ! lex_force_int (lexer))
265             {
266               lex_error (lexer, NULL);
267               goto error;
268             }
269
270           glm.ss_type = lex_integer (lexer);
271           if (1 > glm.ss_type  ||  3 < glm.ss_type )
272             {
273               msg (ME, _("Only types 1, 2 & 3 sums of squares are currently implemented"));
274               goto error;
275             }
276
277           lex_get (lexer);
278
279           if ( ! lex_force_match (lexer, T_RPAREN))
280             {
281               lex_error (lexer, NULL);
282               goto error;
283             }
284         }
285       else if (lex_match_id (lexer, "DESIGN"))
286         {
287           lex_match (lexer, T_EQUALS);
288
289           if (! parse_design_spec (lexer, &glm))
290             goto error;
291
292           if (glm.n_interactions > 0)
293             design = true;
294         }
295       else if (lex_match_id (lexer, "SHOWCODES"))
296         /* Undocumented debug option */
297         {
298           lex_match (lexer, T_EQUALS);
299
300           glm.dump_coding = true;
301         }
302       else
303         {
304           lex_error (lexer, NULL);
305           goto error;
306         }
307     }
308
309   if ( ! design )
310     {
311       design_full (&glm);
312     }
313
314   {
315     struct casegrouper *grouper;
316     struct casereader *group;
317     bool ok;
318
319     grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
320     while (casegrouper_get_next_group (grouper, &group))
321       run_glm (&glm, group, ds);
322     ok = casegrouper_destroy (grouper);
323     ok = proc_commit (ds) && ok;
324   }
325
326   const_var_set_destroy (factors);
327   free (glm.factor_vars);
328   for (i = 0 ; i < glm.n_interactions; ++i)
329     interaction_destroy (glm.interactions[i]);
330
331   free (glm.interactions);
332   free (glm.dep_vars);
333
334
335   return CMD_SUCCESS;
336
337 error:
338
339   const_var_set_destroy (factors);
340   free (glm.factor_vars);
341   for (i = 0 ; i < glm.n_interactions; ++i)
342     interaction_destroy (glm.interactions[i]);
343
344   free (glm.interactions);
345   free (glm.dep_vars);
346
347   return CMD_FAILURE;
348 }
349
350 static inline bool
351 not_dropped (size_t j, const bool *ff)
352 {
353   return ! ff[j];
354 }
355
356 static void
357 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
358 {
359   size_t i;
360   size_t j;
361   size_t n = 0;
362   size_t m = 0;
363
364   for (i = 0; i < cov->size1; i++)
365     {
366       if (not_dropped (i, dropped_f))
367         {
368           m = 0;
369           for (j = 0; j < cov->size2; j++)
370             {
371               if (not_dropped (j, dropped_f))
372                 {
373                   gsl_matrix_set (submatrix, n, m,
374                                   gsl_matrix_get (cov, i, j));
375                   m++;
376                 }
377             }
378           n++;
379         }
380     }
381 }
382
383
384 /*
385    Type 1 sums of squares.
386    Populate SSQ with the Type 1 sums of squares according to COV
387  */
388 static void
389 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
390 {
391   const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
392   size_t i;
393   size_t k;
394   bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
395   bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
396   const struct categoricals *cats = covariance_get_categoricals (cov);
397
398   size_t n_dropped_model = 0;
399   size_t n_dropped_submodel = 0;
400
401   for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
402     {
403       n_dropped_model++;
404       n_dropped_submodel++;
405       model_dropped[i] = true;
406       submodel_dropped[i] = true;
407     }
408
409   for (k = 0; k < cmd->n_interactions; k++)
410     {
411       gsl_matrix *model_cov = NULL;
412       gsl_matrix *submodel_cov = NULL;
413
414       n_dropped_submodel = n_dropped_model;
415       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
416         {
417           submodel_dropped[i] = model_dropped[i];
418         }
419
420       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
421         {
422           const struct interaction * x =
423             categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
424
425           if ( x == cmd->interactions [k])
426             {
427               model_dropped[i] = false;
428               n_dropped_model--;
429             }
430         }
431
432       model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
433       submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
434
435       fill_submatrix (cm, model_cov,    model_dropped);
436       fill_submatrix (cm, submodel_cov, submodel_dropped);
437
438       reg_sweep (model_cov, 0);
439       reg_sweep (submodel_cov, 0);
440
441       gsl_vector_set (ssq, k + 1,
442                       gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
443                       );
444
445       gsl_matrix_free (model_cov);
446       gsl_matrix_free (submodel_cov);
447     }
448
449   free (model_dropped);
450   free (submodel_dropped);
451 }
452
453 /*
454    Type 2 sums of squares.
455    Populate SSQ with the Type 2 sums of squares according to COV
456  */
457 static void
458 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
459 {
460   const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
461   size_t i;
462   size_t k;
463   bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
464   bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
465   const struct categoricals *cats = covariance_get_categoricals (cov);
466
467   for (k = 0; k < cmd->n_interactions; k++)
468     {
469       gsl_matrix *model_cov = NULL;
470       gsl_matrix *submodel_cov = NULL;
471       size_t n_dropped_model = 0;
472       size_t n_dropped_submodel = 0;
473       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
474         {
475           const struct interaction * x =
476             categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
477
478           model_dropped[i] = false;
479           submodel_dropped[i] = false;
480           if (interaction_is_subset (cmd->interactions [k], x))
481             {
482               assert (n_dropped_submodel < covariance_dim (cov));
483               n_dropped_submodel++;
484               submodel_dropped[i] = true;
485
486               if ( cmd->interactions [k]->n_vars < x->n_vars)
487                 {
488                   assert (n_dropped_model < covariance_dim (cov));
489                   n_dropped_model++;
490                   model_dropped[i] = true;
491                 }
492             }
493         }
494
495       model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
496       submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
497
498       fill_submatrix (cm, model_cov,    model_dropped);
499       fill_submatrix (cm, submodel_cov, submodel_dropped);
500
501       reg_sweep (model_cov, 0);
502       reg_sweep (submodel_cov, 0);
503
504       gsl_vector_set (ssq, k + 1,
505                       gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
506                       );
507
508       gsl_matrix_free (model_cov);
509       gsl_matrix_free (submodel_cov);
510     }
511
512   free (model_dropped);
513   free (submodel_dropped);
514 }
515
516 /*
517    Type 3 sums of squares.
518    Populate SSQ with the Type 2 sums of squares according to COV
519  */
520 static void
521 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
522 {
523   const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
524   size_t i;
525   size_t k;
526   bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
527   bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
528   const struct categoricals *cats = covariance_get_categoricals (cov);
529
530   double ss0;
531   gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
532   fill_submatrix (cm, submodel_cov, submodel_dropped);
533   reg_sweep (submodel_cov, 0);
534   ss0 = gsl_matrix_get (submodel_cov, 0, 0);
535   gsl_matrix_free (submodel_cov);
536   free (submodel_dropped);
537
538   for (k = 0; k < cmd->n_interactions; k++)
539     {
540       gsl_matrix *model_cov = NULL;
541       size_t n_dropped_model = 0;
542
543       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
544         {
545           const struct interaction * x =
546             categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
547
548           model_dropped[i] = false;
549
550           if ( cmd->interactions [k] == x)
551             {
552               assert (n_dropped_model < covariance_dim (cov));
553               n_dropped_model++;
554               model_dropped[i] = true;
555             }
556         }
557
558       model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
559
560       fill_submatrix (cm, model_cov,    model_dropped);
561
562       reg_sweep (model_cov, 0);
563
564       gsl_vector_set (ssq, k + 1,
565                       gsl_matrix_get (model_cov, 0, 0) - ss0);
566
567       gsl_matrix_free (model_cov);
568     }
569   free (model_dropped);
570 }
571
572
573
574 //static  void dump_matrix (const gsl_matrix *m);
575
576 static void
577 run_glm (struct glm_spec *cmd, struct casereader *input,
578          const struct dataset *ds)
579 {
580   bool warn_bad_weight = true;
581   int v;
582   struct taint *taint;
583   struct dictionary *dict = dataset_dict (ds);
584   struct casereader *reader;
585   struct ccase *c;
586
587   struct glm_workspace ws;
588   struct covariance *cov;
589
590   input  = casereader_create_filter_missing (input,
591                                              cmd->dep_vars, cmd->n_dep_vars,
592                                              cmd->exclude,
593                                              NULL,  NULL);
594
595   input  = casereader_create_filter_missing (input,
596                                              cmd->factor_vars, cmd->n_factor_vars,
597                                              cmd->exclude,
598                                              NULL,  NULL);
599
600   ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
601                                  cmd->wv, MV_ANY);
602
603   cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
604                                  ws.cats, cmd->wv, cmd->exclude, true);
605
606
607   c = casereader_peek (input, 0);
608   if (c == NULL)
609     {
610       casereader_destroy (input);
611       return;
612     }
613   output_split_file_values (ds, c);
614   case_unref (c);
615
616   taint = taint_clone (casereader_get_taint (input));
617
618   ws.totals = moments_create (MOMENT_VARIANCE);
619
620   for (reader = casereader_clone (input);
621        (c = casereader_read (reader)) != NULL; case_unref (c))
622     {
623       double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
624
625       for (v = 0; v < cmd->n_dep_vars; ++v)
626         moments_pass_one (ws.totals, case_data (c, cmd->dep_vars[v])->f,
627                           weight);
628
629       covariance_accumulate_pass1 (cov, c);
630     }
631   casereader_destroy (reader);
632
633   if (cmd->dump_coding)
634     reader = casereader_clone (input);
635   else
636     reader = input;
637
638   for (;
639        (c = casereader_read (reader)) != NULL; case_unref (c))
640     {
641       double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
642
643       for (v = 0; v < cmd->n_dep_vars; ++v)
644         moments_pass_two (ws.totals, case_data (c, cmd->dep_vars[v])->f,
645                           weight);
646
647       covariance_accumulate_pass2 (cov, c);
648     }
649   casereader_destroy (reader);
650
651
652   if (cmd->dump_coding)
653     {
654       struct tab_table *t =
655         covariance_dump_enc_header (cov,
656                                     1 + casereader_count_cases (input));
657       for (reader = input;
658            (c = casereader_read (reader)) != NULL; case_unref (c))
659         {
660           covariance_dump_enc (cov, c, t);
661         }
662       casereader_destroy (reader);
663       tab_submit (t);
664     }
665
666   {
667     const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
668     gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
669     gsl_matrix_memcpy (cm, ucm);
670
671     //    dump_matrix (cm);
672
673     ws.total_ssq = gsl_matrix_get (cm, 0, 0);
674
675     reg_sweep (cm, 0);
676
677     /*
678       Store the overall SSE.
679     */
680     ws.ssq = gsl_vector_alloc (cm->size1);
681     gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
682     switch (cmd->ss_type)
683       {
684       case 1:
685         ssq_type1 (cov, ws.ssq, cmd);
686         break;
687       case 2:
688         ssq_type2 (cov, ws.ssq, cmd);
689         break;
690       case 3:
691         ssq_type3 (cov, ws.ssq, cmd);
692         break;
693       default:
694         NOT_REACHED ();
695         break;
696       }
697     //    dump_matrix (cm);
698     gsl_matrix_free (cm);
699   }
700
701   if (!taint_has_tainted_successor (taint))
702     output_glm (cmd, &ws);
703
704   gsl_vector_free (ws.ssq);
705
706   covariance_destroy (cov);
707   moments_destroy (ws.totals);
708
709   taint_destroy (taint);
710 }
711
712 static const char *roman[] =
713   {
714     "", /* The Romans had no concept of zero */
715     "I",
716     "II",
717     "III",
718     "IV"
719   };
720
721 static void
722 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
723 {
724   const struct fmt_spec *wfmt =
725     cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
726
727   double intercept_ssq;
728   double ssq_effects;
729   double n_total, mean;
730   double df_corr = 1.0;
731   double mse = 0;
732
733   int f;
734   int r;
735   const int heading_columns = 1;
736   const int heading_rows = 1;
737   struct tab_table *t;
738
739   const int nc = 6;
740   int nr = heading_rows + 3 + cmd->n_interactions;
741   if (cmd->intercept)
742     nr += 2;
743
744   t = tab_create (nc, nr);
745   tab_set_format (t, RC_WEIGHT, wfmt);
746   tab_title (t, _("Tests of Between-Subjects Effects"));
747
748   tab_headers (t, heading_columns, 0, heading_rows, 0);
749
750   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
751
752   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
753   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
754
755   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Source"));
756
757   /* TRANSLATORS: The parameter is a roman numeral */
758   tab_text_format (t, 1, 0, TAB_CENTER | TAT_TITLE,
759                    _("Type %s Sum of Squares"),
760                    roman[cmd->ss_type]);
761   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("df"));
762   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
763   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("F"));
764   tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("Sig."));
765
766   moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
767
768   df_corr += categoricals_df_total (ws->cats);
769
770   r = heading_rows;
771   if (cmd->intercept)
772     tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Corrected Model"));
773   else
774     tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Model"));
775
776   r++;
777
778   mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
779
780   intercept_ssq = pow2 (mean * n_total) / n_total;
781
782   ssq_effects = 0.0;
783   if (cmd->intercept)
784     {
785       const double df = 1.0;
786       const double F = intercept_ssq / df / mse;
787       tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Intercept"));
788       /* The intercept for unbalanced models is of limited use and
789          nobody knows how to calculate it properly */
790       if (categoricals_isbalanced (ws->cats))
791         {
792           tab_double (t, 1, r, 0, intercept_ssq, NULL, RC_OTHER);
793           tab_double (t, 2, r, 0, 1.00, NULL, RC_WEIGHT);
794           tab_double (t, 3, r, 0, intercept_ssq / df, NULL, RC_OTHER);
795           tab_double (t, 4, r, 0, F, NULL, RC_OTHER);
796           tab_double (t, 5, r, 0, gsl_cdf_fdist_Q (F, df, n_total - df_corr),
797                       NULL, RC_PVALUE);
798         }
799       r++;
800     }
801
802   for (f = 0; f < cmd->n_interactions; ++f)
803     {
804       struct string str = DS_EMPTY_INITIALIZER;
805       double df = categoricals_df (ws->cats, f);
806
807       double ssq = gsl_vector_get (ws->ssq, f + 1);
808       double F;
809
810       ssq_effects += ssq;
811
812       if (! cmd->intercept)
813         {
814           df++;
815           ssq += intercept_ssq;
816         }
817
818       F = ssq / df / mse;
819       interaction_to_string (cmd->interactions[f], &str);
820       tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, ds_cstr (&str));
821       ds_destroy (&str);
822
823       tab_double (t, 1, r, 0, ssq, NULL, RC_OTHER);
824       tab_double (t, 2, r, 0, df, NULL, RC_WEIGHT);
825       tab_double (t, 3, r, 0, ssq / df, NULL, RC_OTHER);
826       tab_double (t, 4, r, 0, F, NULL, RC_OTHER);
827
828       tab_double (t, 5, r, 0, gsl_cdf_fdist_Q (F, df, n_total - df_corr),
829                   NULL, RC_PVALUE);
830       r++;
831     }
832
833   {
834     /* Model / Corrected Model */
835     double df = df_corr;
836     double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
837     double F;
838
839     if ( cmd->intercept )
840       df --;
841     else
842       ssq += intercept_ssq;
843
844     F = ssq / df / mse;
845     tab_double (t, 1, heading_rows, 0, ssq, NULL, RC_OTHER);
846     tab_double (t, 2, heading_rows, 0, df, NULL, RC_WEIGHT);
847     tab_double (t, 3, heading_rows, 0, ssq / df, NULL, RC_OTHER);
848     tab_double (t, 4, heading_rows, 0, F, NULL, RC_OTHER);
849
850     tab_double (t, 5, heading_rows, 0,
851                 gsl_cdf_fdist_Q (F, df, n_total - df_corr), NULL, RC_PVALUE);
852   }
853
854   {
855     const double df = n_total - df_corr;
856     const double ssq = gsl_vector_get (ws->ssq, 0);
857     const double mse = ssq / df;
858     tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Error"));
859     tab_double (t, 1, r, 0, ssq, NULL, RC_OTHER);
860     tab_double (t, 2, r, 0, df, NULL, RC_WEIGHT);
861     tab_double (t, 3, r++, 0, mse, NULL, RC_OTHER);
862   }
863
864   {
865     tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Total"));
866     tab_double (t, 1, r, 0, ws->total_ssq + intercept_ssq, NULL, RC_OTHER);
867     tab_double (t, 2, r, 0, n_total, NULL, RC_WEIGHT);
868
869     r++;
870   }
871
872   if (cmd->intercept)
873     {
874       tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Corrected Total"));
875       tab_double (t, 1, r, 0, ws->total_ssq, NULL, RC_OTHER);
876       tab_double (t, 2, r, 0, n_total - 1.0, NULL, RC_WEIGHT);
877     }
878
879   tab_submit (t);
880 }
881
882 #if 0
883 static void
884 dump_matrix (const gsl_matrix * m)
885 {
886   size_t i, j;
887   for (i = 0; i < m->size1; ++i)
888     {
889       for (j = 0; j < m->size2; ++j)
890         {
891           double x = gsl_matrix_get (m, i, j);
892           printf ("%.3f ", x);
893         }
894       printf ("\n");
895     }
896   printf ("\n");
897 }
898 #endif
899
900
901 \f
902 static bool
903 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
904 {
905   const struct variable *v = NULL;
906   if ( ! lex_match_variable (lexer, glm->dict, &v))
907     return false;
908
909   if (lex_match (lexer, T_LPAREN))
910     {
911       if ( ! parse_nested_variable (lexer, glm))
912         return false;
913
914       if ( ! lex_force_match (lexer, T_RPAREN))
915         return false;
916     }
917
918   lex_error (lexer, "Nested variables are not yet implemented"); return false;
919   return true;
920 }
921
922 /* A design term is an interaction OR a nested variable */
923 static bool
924 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
925 {
926   struct interaction *iact = NULL;
927   if (parse_design_interaction (lexer, glm->dict, &iact))
928     {
929       /* Interaction parsing successful.  Add to list of interactions */
930       glm->interactions = xrealloc (glm->interactions, sizeof *glm->interactions * ++glm->n_interactions);
931       glm->interactions[glm->n_interactions - 1] = iact;
932       return true;
933     }
934
935   if ( parse_nested_variable (lexer, glm))
936     return true;
937
938   return false;
939 }
940
941
942
943 /* Parse a complete DESIGN specification.
944    A design spec is a design term, optionally followed by a comma,
945    and another design spec.
946 */
947 static bool
948 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
949 {
950   if  (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
951     return true;
952
953   if ( ! parse_design_term (lexer, glm))
954     return false;
955
956   lex_match (lexer, T_COMMA);
957
958   return parse_design_spec (lexer, glm);
959 }
960