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