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