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