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