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