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