1002653a8438a347771c466853c4676ec9ff9588
[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   output_split_file_values_peek (ds, input);
543
544
545   taint = taint_clone (casereader_get_taint (input));
546
547   ws.totals = moments_create (MOMENT_VARIANCE);
548
549   for (reader = casereader_clone (input);
550        (c = casereader_read (reader)) != NULL; case_unref (c))
551     {
552       double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
553
554       for (v = 0; v < cmd->n_dep_vars; ++v)
555         moments_pass_one (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
556
557       covariance_accumulate_pass1 (cov, c);
558     }
559   casereader_destroy (reader);
560
561   if (cmd->dump_coding)
562     reader = casereader_clone (input);
563   else
564     reader = input;
565
566   for (;
567        (c = casereader_read (reader)) != NULL; case_unref (c))
568     {
569       double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
570
571       for (v = 0; v < cmd->n_dep_vars; ++v)
572         moments_pass_two (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
573
574       covariance_accumulate_pass2 (cov, c);
575     }
576   casereader_destroy (reader);
577
578
579   if (cmd->dump_coding)
580     {
581       struct pivot_table *t = covariance_dump_enc_header (cov);
582       for (reader = input;
583            (c = casereader_read (reader)) != NULL; case_unref (c))
584         {
585           covariance_dump_enc (cov, c, t);
586         }
587
588       pivot_table_submit (t);
589     }
590
591   {
592     const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
593     gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
594     gsl_matrix_memcpy (cm, ucm);
595
596     //    dump_matrix (cm);
597
598     ws.total_ssq = gsl_matrix_get (cm, 0, 0);
599
600     reg_sweep (cm, 0);
601
602     /*
603       Store the overall SSE.
604     */
605     ws.ssq = gsl_vector_alloc (cm->size1);
606     gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
607     switch (cmd->ss_type)
608       {
609       case 1:
610         ssq_type1 (cov, ws.ssq, cmd);
611         break;
612       case 2:
613         ssq_type2 (cov, ws.ssq, cmd);
614         break;
615       case 3:
616         ssq_type3 (cov, ws.ssq, cmd);
617         break;
618       default:
619         NOT_REACHED ();
620         break;
621       }
622     //    dump_matrix (cm);
623     gsl_matrix_free (cm);
624   }
625
626   if (!taint_has_tainted_successor (taint))
627     output_glm (cmd, &ws);
628
629   gsl_vector_free (ws.ssq);
630
631   covariance_destroy (cov);
632   moments_destroy (ws.totals);
633
634   taint_destroy (taint);
635 }
636
637 static void
638 put_glm_row (struct pivot_table *table, int row,
639              double a, double b, double c, double d, double e)
640 {
641   double entries[] = { a, b, c, d, e };
642
643   for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
644     if (entries[col] != SYSMIS)
645       pivot_table_put2 (table, col, row,
646                         pivot_value_new_number (entries[col]));
647 }
648
649 static void
650 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
651 {
652   struct pivot_table *table = pivot_table_create (
653     N_("Tests of Between-Subjects Effects"));
654
655   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
656                           (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
657                            : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
658                            : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
659                           N_("df"), PIVOT_RC_COUNT,
660                           N_("Mean Square"), PIVOT_RC_OTHER,
661                           N_("F"), PIVOT_RC_OTHER,
662                           N_("Sig."), PIVOT_RC_SIGNIFICANCE);
663
664   struct pivot_dimension *source = pivot_dimension_create (
665     table, PIVOT_AXIS_ROW, N_("Source"),
666     cmd->intercept ? N_("Corrected Model") : N_("Model"));
667
668   double n_total, mean;
669   moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
670
671   double df_corr = 1.0 + categoricals_df_total (ws->cats);
672
673   double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
674   double intercept_ssq = pow2 (mean * n_total) / n_total;
675   if (cmd->intercept)
676     {
677       int row = pivot_category_create_leaf (
678         source->root, pivot_value_new_text (N_("Intercept")));
679
680       /* The intercept for unbalanced models is of limited use and
681          nobody knows how to calculate it properly */
682       if (categoricals_isbalanced (ws->cats))
683         {
684           const double df = 1.0;
685           const double F = intercept_ssq / df / mse;
686           put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
687                        F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
688         }
689     }
690
691   double ssq_effects = 0.0;
692   for (int f = 0; f < cmd->n_interactions; ++f)
693     {
694       double df = categoricals_df (ws->cats, f);
695       double ssq = gsl_vector_get (ws->ssq, f + 1);
696       ssq_effects += ssq;
697       if (!cmd->intercept)
698         {
699           df++;
700           ssq += intercept_ssq;
701         }
702       double F = ssq / df / mse;
703
704       struct string str = DS_EMPTY_INITIALIZER;
705       interaction_to_string (cmd->interactions[f], &str);
706       int row = pivot_category_create_leaf (
707         source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
708
709       put_glm_row (table, row, ssq, df, ssq / df, F,
710                    gsl_cdf_fdist_Q (F, df, n_total - df_corr));
711     }
712
713   {
714     /* Model / Corrected Model */
715     double df = df_corr;
716     double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
717     if (cmd->intercept)
718       df--;
719     else
720       ssq += intercept_ssq;
721     double F = ssq / df / mse;
722     put_glm_row (table, 0, ssq, df, ssq / df, F,
723                  gsl_cdf_fdist_Q (F, df, n_total - df_corr));
724   }
725
726   {
727     int row = pivot_category_create_leaf (source->root,
728                                           pivot_value_new_text (N_("Error")));
729     const double df = n_total - df_corr;
730     const double ssq = gsl_vector_get (ws->ssq, 0);
731     const double mse = ssq / df;
732     put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
733   }
734
735   {
736     int row = pivot_category_create_leaf (source->root,
737                                           pivot_value_new_text (N_("Total")));
738     put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
739                  SYSMIS, SYSMIS, SYSMIS);
740   }
741
742   if (cmd->intercept)
743     {
744       int row = pivot_category_create_leaf (
745         source->root, pivot_value_new_text (N_("Corrected Total")));
746       put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
747                    SYSMIS, SYSMIS);
748     }
749
750   pivot_table_submit (table);
751 }
752
753 #if 0
754 static void
755 dump_matrix (const gsl_matrix * m)
756 {
757   size_t i, j;
758   for (i = 0; i < m->size1; ++i)
759     {
760       for (j = 0; j < m->size2; ++j)
761         {
762           double x = gsl_matrix_get (m, i, j);
763           printf ("%.3f ", x);
764         }
765       printf ("\n");
766     }
767   printf ("\n");
768 }
769 #endif
770
771
772 \f
773 static bool
774 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
775 {
776   const struct variable *v = NULL;
777   if (!lex_match_variable (lexer, glm->dict, &v))
778     return false;
779
780   if (lex_match (lexer, T_LPAREN))
781     {
782       if (!parse_nested_variable (lexer, glm))
783         return false;
784
785       if (!lex_force_match (lexer, T_RPAREN))
786         return false;
787     }
788
789   lex_error (lexer, "Nested variables are not yet implemented");
790   return false;
791 }
792
793 /* An interaction is a variable followed by {*, BY} followed by an interaction */
794 static bool
795 parse_internal_interaction (struct lexer *lexer, const struct dictionary *dict, struct interaction **iact, struct interaction **it)
796 {
797   const struct variable *v = NULL;
798   assert (iact);
799
800   switch  (lex_next_token (lexer, 1))
801     {
802     case T_ENDCMD:
803     case T_SLASH:
804     case T_COMMA:
805     case T_ID:
806     case T_BY:
807     case T_ASTERISK:
808       break;
809     default:
810       return false;
811       break;
812     }
813
814   if (! lex_match_variable (lexer, dict, &v))
815     {
816       if (it)
817         interaction_destroy (*it);
818       *iact = NULL;
819       return false;
820     }
821
822   assert (v);
823
824   if (*iact == NULL)
825     *iact = interaction_create (v);
826   else
827     interaction_add_variable (*iact, v);
828
829   if (lex_match (lexer, T_ASTERISK) || lex_match (lexer, T_BY))
830     {
831       return parse_internal_interaction (lexer, dict, iact, iact);
832     }
833
834   return true;
835 }
836
837 /* Parse an interaction.
838    If not successful return false.
839    Otherwise, a newly created interaction will be placed in IACT.
840    It is the caller's responsibility to destroy this interaction.
841  */
842 static bool
843 parse_design_interaction (struct lexer *lexer, const struct dictionary *dict, struct interaction **iact)
844 {
845   return parse_internal_interaction (lexer, dict, iact, NULL);
846 }
847
848 /* A design term is an interaction OR a nested variable */
849 static bool
850 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
851 {
852   struct interaction *iact = NULL;
853   if (parse_design_interaction (lexer, glm->dict, &iact))
854     {
855       /* Interaction parsing successful.  Add to list of interactions */
856       glm->interactions = xrealloc (glm->interactions, sizeof (*glm->interactions) * ++glm->n_interactions);
857       glm->interactions[glm->n_interactions - 1] = iact;
858       return true;
859     }
860
861   if (parse_nested_variable (lexer, glm))
862     return true;
863
864   return false;
865 }
866
867
868
869 /* Parse a complete DESIGN specification.
870    A design spec is a design term, optionally followed by a comma,
871    and another design spec.
872 */
873 static bool
874 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
875 {
876   if  (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
877     return true;
878
879   if (!parse_design_term (lexer, glm))
880     return false;
881
882   lex_match (lexer, T_COMMA);
883
884   return parse_design_spec (lexer, glm);
885 }