src/language/stats/glm.c: Fix compiler warnings
[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_range (lexer, "SSTYPE", 1, 3))
266             {
267               lex_error (lexer, NULL);
268               goto error;
269             }
270
271           glm.ss_type = lex_integer (lexer);
272           lex_get (lexer);
273
274           if (! lex_force_match (lexer, T_RPAREN))
275             {
276               lex_error (lexer, NULL);
277               goto error;
278             }
279         }
280       else if (lex_match_id (lexer, "DESIGN"))
281         {
282           lex_match (lexer, T_EQUALS);
283
284           if (! parse_design_spec (lexer, &glm))
285             goto error;
286
287           if (glm.n_interactions > 0)
288             design = true;
289         }
290       else if (lex_match_id (lexer, "SHOWCODES"))
291         /* Undocumented debug option */
292         {
293           lex_match (lexer, T_EQUALS);
294
295           glm.dump_coding = true;
296         }
297       else
298         {
299           lex_error (lexer, NULL);
300           goto error;
301         }
302     }
303
304   if (! design)
305     {
306       design_full (&glm);
307     }
308
309   {
310     struct casegrouper *grouper;
311     struct casereader *group;
312     bool ok;
313
314     grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
315     while (casegrouper_get_next_group (grouper, &group))
316       run_glm (&glm, group, ds);
317     ok = casegrouper_destroy (grouper);
318     ok = proc_commit (ds) && ok;
319   }
320
321   const_var_set_destroy (factors);
322   free (glm.factor_vars);
323   for (i = 0 ; i < glm.n_interactions; ++i)
324     interaction_destroy (glm.interactions[i]);
325
326   free (glm.interactions);
327   free (glm.dep_vars);
328
329
330   return CMD_SUCCESS;
331
332 error:
333
334   const_var_set_destroy (factors);
335   free (glm.factor_vars);
336   for (i = 0 ; i < glm.n_interactions; ++i)
337     interaction_destroy (glm.interactions[i]);
338
339   free (glm.interactions);
340   free (glm.dep_vars);
341
342   return CMD_FAILURE;
343 }
344
345 static inline bool
346 not_dropped (size_t j, const bool *ff)
347 {
348   return ! ff[j];
349 }
350
351 static void
352 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
353 {
354   size_t i;
355   size_t j;
356   size_t n = 0;
357   size_t m = 0;
358
359   for (i = 0; i < cov->size1; i++)
360     {
361       if (not_dropped (i, dropped_f))
362         {
363           m = 0;
364           for (j = 0; j < cov->size2; j++)
365             {
366               if (not_dropped (j, dropped_f))
367                 {
368                   gsl_matrix_set (submatrix, n, m,
369                                   gsl_matrix_get (cov, i, j));
370                   m++;
371                 }
372             }
373           n++;
374         }
375     }
376 }
377
378
379 /*
380    Type 1 sums of squares.
381    Populate SSQ with the Type 1 sums of squares according to COV
382  */
383 static void
384 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
385 {
386   const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
387   size_t i;
388   size_t k;
389   bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
390   bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
391   const struct categoricals *cats = covariance_get_categoricals (cov);
392
393   size_t n_dropped_model = 0;
394   size_t n_dropped_submodel = 0;
395
396   for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
397     {
398       n_dropped_model++;
399       n_dropped_submodel++;
400       model_dropped[i] = true;
401       submodel_dropped[i] = true;
402     }
403
404   for (k = 0; k < cmd->n_interactions; k++)
405     {
406       gsl_matrix *model_cov = NULL;
407       gsl_matrix *submodel_cov = NULL;
408
409       n_dropped_submodel = n_dropped_model;
410       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
411         {
412           submodel_dropped[i] = model_dropped[i];
413         }
414
415       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
416         {
417           const struct interaction * x =
418             categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
419
420           if (x == cmd->interactions [k])
421             {
422               model_dropped[i] = false;
423               n_dropped_model--;
424             }
425         }
426
427       model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
428       submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
429
430       fill_submatrix (cm, model_cov,    model_dropped);
431       fill_submatrix (cm, submodel_cov, submodel_dropped);
432
433       reg_sweep (model_cov, 0);
434       reg_sweep (submodel_cov, 0);
435
436       gsl_vector_set (ssq, k + 1,
437                       gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
438                 );
439
440       gsl_matrix_free (model_cov);
441       gsl_matrix_free (submodel_cov);
442     }
443
444   free (model_dropped);
445   free (submodel_dropped);
446 }
447
448 /*
449    Type 2 sums of squares.
450    Populate SSQ with the Type 2 sums of squares according to COV
451  */
452 static void
453 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
454 {
455   const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
456   size_t i;
457   size_t k;
458   bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
459   bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
460   const struct categoricals *cats = covariance_get_categoricals (cov);
461
462   for (k = 0; k < cmd->n_interactions; k++)
463     {
464       gsl_matrix *model_cov = NULL;
465       gsl_matrix *submodel_cov = NULL;
466       size_t n_dropped_model = 0;
467       size_t n_dropped_submodel = 0;
468       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
469         {
470           const struct interaction * x =
471             categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
472
473           model_dropped[i] = false;
474           submodel_dropped[i] = false;
475           if (interaction_is_subset (cmd->interactions [k], x))
476             {
477               assert (n_dropped_submodel < covariance_dim (cov));
478               n_dropped_submodel++;
479               submodel_dropped[i] = true;
480
481               if (cmd->interactions [k]->n_vars < x->n_vars)
482                 {
483                   assert (n_dropped_model < covariance_dim (cov));
484                   n_dropped_model++;
485                   model_dropped[i] = true;
486                 }
487             }
488         }
489
490       model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
491       submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
492
493       fill_submatrix (cm, model_cov,    model_dropped);
494       fill_submatrix (cm, submodel_cov, submodel_dropped);
495
496       reg_sweep (model_cov, 0);
497       reg_sweep (submodel_cov, 0);
498
499       gsl_vector_set (ssq, k + 1,
500                       gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
501                 );
502
503       gsl_matrix_free (model_cov);
504       gsl_matrix_free (submodel_cov);
505     }
506
507   free (model_dropped);
508   free (submodel_dropped);
509 }
510
511 /*
512    Type 3 sums of squares.
513    Populate SSQ with the Type 2 sums of squares according to COV
514  */
515 static void
516 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
517 {
518   const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
519   size_t i;
520   size_t k;
521   bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
522   bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
523   const struct categoricals *cats = covariance_get_categoricals (cov);
524
525   double ss0;
526   gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
527   fill_submatrix (cm, submodel_cov, submodel_dropped);
528   reg_sweep (submodel_cov, 0);
529   ss0 = gsl_matrix_get (submodel_cov, 0, 0);
530   gsl_matrix_free (submodel_cov);
531   free (submodel_dropped);
532
533   for (k = 0; k < cmd->n_interactions; k++)
534     {
535       gsl_matrix *model_cov = NULL;
536       size_t n_dropped_model = 0;
537
538       for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
539         {
540           const struct interaction * x =
541             categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
542
543           model_dropped[i] = false;
544
545           if (cmd->interactions [k] == x)
546             {
547               assert (n_dropped_model < covariance_dim (cov));
548               n_dropped_model++;
549               model_dropped[i] = true;
550             }
551         }
552
553       model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
554
555       fill_submatrix (cm, model_cov,    model_dropped);
556
557       reg_sweep (model_cov, 0);
558
559       gsl_vector_set (ssq, k + 1,
560                       gsl_matrix_get (model_cov, 0, 0) - ss0);
561
562       gsl_matrix_free (model_cov);
563     }
564   free (model_dropped);
565 }
566
567
568
569 //static  void dump_matrix (const gsl_matrix *m);
570
571 static void
572 run_glm (struct glm_spec *cmd, struct casereader *input,
573          const struct dataset *ds)
574 {
575   bool warn_bad_weight = true;
576   int v;
577   struct taint *taint;
578   struct dictionary *dict = dataset_dict (ds);
579   struct casereader *reader;
580   struct ccase *c;
581
582   struct glm_workspace ws;
583   struct covariance *cov;
584
585   input  = casereader_create_filter_missing (input,
586                                              cmd->dep_vars, cmd->n_dep_vars,
587                                              cmd->exclude,
588                                              NULL,  NULL);
589
590   input  = casereader_create_filter_missing (input,
591                                              cmd->factor_vars, cmd->n_factor_vars,
592                                              cmd->exclude,
593                                              NULL,  NULL);
594
595   ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
596                                  cmd->wv, MV_ANY);
597
598   cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
599                                  ws.cats, cmd->wv, cmd->exclude, true);
600
601
602   c = casereader_peek (input, 0);
603   if (c == NULL)
604     {
605       casereader_destroy (input);
606       return;
607     }
608   output_split_file_values (ds, c);
609   case_unref (c);
610
611   taint = taint_clone (casereader_get_taint (input));
612
613   ws.totals = moments_create (MOMENT_VARIANCE);
614
615   for (reader = casereader_clone (input);
616        (c = casereader_read (reader)) != NULL; case_unref (c))
617     {
618       double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
619
620       for (v = 0; v < cmd->n_dep_vars; ++v)
621         moments_pass_one (ws.totals, case_data (c, cmd->dep_vars[v])->f,
622                           weight);
623
624       covariance_accumulate_pass1 (cov, c);
625     }
626   casereader_destroy (reader);
627
628   if (cmd->dump_coding)
629     reader = casereader_clone (input);
630   else
631     reader = input;
632
633   for (;
634        (c = casereader_read (reader)) != NULL; case_unref (c))
635     {
636       double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
637
638       for (v = 0; v < cmd->n_dep_vars; ++v)
639         moments_pass_two (ws.totals, case_data (c, cmd->dep_vars[v])->f,
640                           weight);
641
642       covariance_accumulate_pass2 (cov, c);
643     }
644   casereader_destroy (reader);
645
646
647   if (cmd->dump_coding)
648     {
649       struct pivot_table *t = covariance_dump_enc_header (cov);
650       for (reader = input;
651            (c = casereader_read (reader)) != NULL; case_unref (c))
652         {
653           covariance_dump_enc (cov, c, t);
654         }
655
656       pivot_table_submit (t);
657     }
658
659   {
660     const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
661     gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
662     gsl_matrix_memcpy (cm, ucm);
663
664     //    dump_matrix (cm);
665
666     ws.total_ssq = gsl_matrix_get (cm, 0, 0);
667
668     reg_sweep (cm, 0);
669
670     /*
671       Store the overall SSE.
672     */
673     ws.ssq = gsl_vector_alloc (cm->size1);
674     gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
675     switch (cmd->ss_type)
676       {
677       case 1:
678         ssq_type1 (cov, ws.ssq, cmd);
679         break;
680       case 2:
681         ssq_type2 (cov, ws.ssq, cmd);
682         break;
683       case 3:
684         ssq_type3 (cov, ws.ssq, cmd);
685         break;
686       default:
687         NOT_REACHED ();
688         break;
689       }
690     //    dump_matrix (cm);
691     gsl_matrix_free (cm);
692   }
693
694   if (!taint_has_tainted_successor (taint))
695     output_glm (cmd, &ws);
696
697   gsl_vector_free (ws.ssq);
698
699   covariance_destroy (cov);
700   moments_destroy (ws.totals);
701
702   taint_destroy (taint);
703 }
704
705 static void
706 put_glm_row (struct pivot_table *table, int row,
707              double a, double b, double c, double d, double e)
708 {
709   double entries[] = { a, b, c, d, e };
710
711   for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
712     if (entries[col] != SYSMIS)
713       pivot_table_put2 (table, col, row,
714                         pivot_value_new_number (entries[col]));
715 }
716
717 static void
718 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
719 {
720   struct pivot_table *table = pivot_table_create (
721     N_("Tests of Between-Subjects Effects"));
722
723   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
724                           (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
725                            : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
726                            : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
727                           N_("df"), PIVOT_RC_COUNT,
728                           N_("Mean Square"), PIVOT_RC_OTHER,
729                           N_("F"), PIVOT_RC_OTHER,
730                           N_("Sig."), PIVOT_RC_SIGNIFICANCE);
731
732   struct pivot_dimension *source = pivot_dimension_create (
733     table, PIVOT_AXIS_ROW, N_("Source"),
734     cmd->intercept ? N_("Corrected Model") : N_("Model"));
735
736   double n_total, mean;
737   moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
738
739   double df_corr = 1.0 + categoricals_df_total (ws->cats);
740
741   double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
742   double intercept_ssq = pow2 (mean * n_total) / n_total;
743   if (cmd->intercept)
744     {
745       int row = pivot_category_create_leaf (
746         source->root, pivot_value_new_text (N_("Intercept")));
747
748       /* The intercept for unbalanced models is of limited use and
749          nobody knows how to calculate it properly */
750       if (categoricals_isbalanced (ws->cats))
751         {
752           const double df = 1.0;
753           const double F = intercept_ssq / df / mse;
754           put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
755                        F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
756         }
757     }
758
759   double ssq_effects = 0.0;
760   for (int f = 0; f < cmd->n_interactions; ++f)
761     {
762       double df = categoricals_df (ws->cats, f);
763       double ssq = gsl_vector_get (ws->ssq, f + 1);
764       ssq_effects += ssq;
765       if (!cmd->intercept)
766         {
767           df++;
768           ssq += intercept_ssq;
769         }
770       double F = ssq / df / mse;
771
772       struct string str = DS_EMPTY_INITIALIZER;
773       interaction_to_string (cmd->interactions[f], &str);
774       int row = pivot_category_create_leaf (
775         source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
776
777       put_glm_row (table, row, ssq, df, ssq / df, F,
778                    gsl_cdf_fdist_Q (F, df, n_total - df_corr));
779     }
780
781   {
782     /* Model / Corrected Model */
783     double df = df_corr;
784     double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
785     if (cmd->intercept)
786       df--;
787     else
788       ssq += intercept_ssq;
789     double F = ssq / df / mse;
790     put_glm_row (table, 0, ssq, df, ssq / df, F,
791                  gsl_cdf_fdist_Q (F, df, n_total - df_corr));
792   }
793
794   {
795     int row = pivot_category_create_leaf (source->root,
796                                           pivot_value_new_text (N_("Error")));
797     const double df = n_total - df_corr;
798     const double ssq = gsl_vector_get (ws->ssq, 0);
799     const double mse = ssq / df;
800     put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
801   }
802
803   {
804     int row = pivot_category_create_leaf (source->root,
805                                           pivot_value_new_text (N_("Total")));
806     put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
807                  SYSMIS, SYSMIS, SYSMIS);
808   }
809
810   if (cmd->intercept)
811     {
812       int row = pivot_category_create_leaf (
813         source->root, pivot_value_new_text (N_("Corrected Total")));
814       put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
815                    SYSMIS, SYSMIS);
816     }
817
818   pivot_table_submit (table);
819 }
820
821 #if 0
822 static void
823 dump_matrix (const gsl_matrix * m)
824 {
825   size_t i, j;
826   for (i = 0; i < m->size1; ++i)
827     {
828       for (j = 0; j < m->size2; ++j)
829         {
830           double x = gsl_matrix_get (m, i, j);
831           printf ("%.3f ", x);
832         }
833       printf ("\n");
834     }
835   printf ("\n");
836 }
837 #endif
838
839
840 \f
841 static bool
842 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
843 {
844   const struct variable *v = NULL;
845   if (! lex_match_variable (lexer, glm->dict, &v))
846     return false;
847
848   if (lex_match (lexer, T_LPAREN))
849     {
850       if (! parse_nested_variable (lexer, glm))
851         return false;
852
853       if (! lex_force_match (lexer, T_RPAREN))
854         return false;
855     }
856
857   lex_error (lexer, "Nested variables are not yet implemented");
858   return false;
859 }
860
861 /* A design term is an interaction OR a nested variable */
862 static bool
863 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
864 {
865   struct interaction *iact = NULL;
866   if (parse_design_interaction (lexer, glm->dict, &iact))
867     {
868       /* Interaction parsing successful.  Add to list of interactions */
869       glm->interactions = xrealloc (glm->interactions, sizeof (*glm->interactions) * ++glm->n_interactions);
870       glm->interactions[glm->n_interactions - 1] = iact;
871       return true;
872     }
873
874   if (parse_nested_variable (lexer, glm))
875     return true;
876
877   return false;
878 }
879
880
881
882 /* Parse a complete DESIGN specification.
883    A design spec is a design term, optionally followed by a comma,
884    and another design spec.
885 */
886 static bool
887 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
888 {
889   if  (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
890     return true;
891
892   if (! parse_design_term (lexer, glm))
893     return false;
894
895   lex_match (lexer, T_COMMA);
896
897   return parse_design_spec (lexer, glm);
898 }