1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2010, 2011 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include <gsl/gsl_cdf.h>
20 #include <gsl/gsl_matrix.h>
21 #include <gsl/gsl_combination.h>
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"
48 #define _(msgid) gettext (msgid)
53 const struct variable **dep_vars;
56 const struct variable **factor_vars;
58 size_t n_interactions;
59 struct interaction **interactions;
61 enum mv_class exclude;
63 /* The weight variable */
64 const struct variable *wv;
66 const struct dictionary *dict;
79 struct moments *totals;
81 struct categoricals *cats;
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
92 /* Default design: all possible interactions */
94 design_full (struct glm_spec *glm)
98 glm->n_interactions = (1 << glm->n_factor_vars) - 1;
100 glm->interactions = xcalloc (glm->n_interactions, sizeof *glm->interactions);
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)
105 gsl_combination *c = gsl_combination_calloc (glm->n_factor_vars, sz);
109 struct interaction *iact = interaction_create (NULL);
111 for (e = 0 ; e < gsl_combination_k (c); ++e)
112 interaction_add_variable (iact, glm->factor_vars [gsl_combination_get (c, e)]);
114 glm->interactions[i++] = iact;
116 while (gsl_combination_next (c) == GSL_SUCCESS);
118 gsl_combination_free (c);
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);
128 static bool parse_design_spec (struct lexer *lexer, struct glm_spec *glm);
132 cmd_glm (struct lexer *lexer, struct dataset *ds)
135 struct const_var_set *factors = NULL;
138 glm.dict = dataset_dict (ds);
140 glm.n_factor_vars = 0;
141 glm.n_interactions = 0;
142 glm.interactions = NULL;
144 glm.factor_vars = NULL;
145 glm.exclude = MV_ANY;
146 glm.intercept = true;
147 glm.wv = dict_get_weight (glm.dict);
149 glm.dump_coding = false;
152 if (!parse_variables_const (lexer, glm.dict,
153 &glm.dep_vars, &glm.n_dep_vars,
154 PV_NO_DUPLICATE | PV_NUMERIC))
157 lex_force_match (lexer, T_BY);
159 if (!parse_variables_const (lexer, glm.dict,
160 &glm.factor_vars, &glm.n_factor_vars,
161 PV_NO_DUPLICATE | PV_NUMERIC))
164 if (glm.n_dep_vars > 1)
166 msg (ME, _("Multivariate analysis is not yet implemented"));
171 const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
173 while (lex_token (lexer) != T_ENDCMD)
175 lex_match (lexer, T_SLASH);
177 if (lex_match_id (lexer, "MISSING"))
179 lex_match (lexer, T_EQUALS);
180 while (lex_token (lexer) != T_ENDCMD
181 && lex_token (lexer) != T_SLASH)
183 if (lex_match_id (lexer, "INCLUDE"))
185 glm.exclude = MV_SYSTEM;
187 else if (lex_match_id (lexer, "EXCLUDE"))
189 glm.exclude = MV_ANY;
193 lex_error (lexer, NULL);
198 else if (lex_match_id (lexer, "INTERCEPT"))
200 lex_match (lexer, T_EQUALS);
201 while (lex_token (lexer) != T_ENDCMD
202 && lex_token (lexer) != T_SLASH)
204 if (lex_match_id (lexer, "INCLUDE"))
206 glm.intercept = true;
208 else if (lex_match_id (lexer, "EXCLUDE"))
210 glm.intercept = false;
214 lex_error (lexer, NULL);
219 else if (lex_match_id (lexer, "CRITERIA"))
221 lex_match (lexer, T_EQUALS);
222 if (lex_match_id (lexer, "ALPHA"))
224 if (lex_force_match (lexer, T_LPAREN))
226 if (! lex_force_num (lexer))
228 lex_error (lexer, NULL);
232 glm.alpha = lex_number (lexer);
234 if ( ! lex_force_match (lexer, T_RPAREN))
236 lex_error (lexer, NULL);
243 lex_error (lexer, NULL);
247 else if (lex_match_id (lexer, "METHOD"))
249 lex_match (lexer, T_EQUALS);
250 if ( !lex_force_match_id (lexer, "SSTYPE"))
252 lex_error (lexer, NULL);
256 if ( ! lex_force_match (lexer, T_LPAREN))
258 lex_error (lexer, NULL);
262 if ( ! lex_force_int (lexer))
264 lex_error (lexer, NULL);
268 glm.ss_type = lex_integer (lexer);
269 if (1 != glm.ss_type && 2 != glm.ss_type )
271 msg (ME, _("Only types 1 & 2 sum of squares are currently implemented"));
277 if ( ! lex_force_match (lexer, T_RPAREN))
279 lex_error (lexer, NULL);
283 else if (lex_match_id (lexer, "DESIGN"))
285 lex_match (lexer, T_EQUALS);
287 if (! parse_design_spec (lexer, &glm))
290 if (glm.n_interactions > 0)
293 else if (lex_match_id (lexer, "SHOWCODES"))
294 /* Undocumented debug option */
296 lex_match (lexer, T_EQUALS);
298 glm.dump_coding = true;
302 lex_error (lexer, NULL);
313 struct casegrouper *grouper;
314 struct casereader *group;
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;
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);
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]);
341 free (glm.interactions);
347 static void get_ssq (struct covariance *, gsl_vector *,
348 const struct glm_spec *);
351 not_dropped (size_t j, const bool *ff)
357 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
364 for (i = 0; i < cov->size1; i++)
366 if (not_dropped (i, dropped_f))
369 for (j = 0; j < cov->size2; j++)
371 if (not_dropped (j, dropped_f))
373 gsl_matrix_set (submatrix, n, m,
374 gsl_matrix_get (cov, i, j));
384 get_ssq (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
386 gsl_matrix *cm = covariance_calculate_unnormalized (cov);
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);
393 for (k = 0; k < cmd->n_interactions; k++)
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++)
401 const struct interaction * x =
402 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
404 model_dropped[i] = false;
405 submodel_dropped[i] = false;
406 if (interaction_is_subset (cmd->interactions [k], x))
408 assert (n_dropped_submodel < covariance_dim (cov));
409 n_dropped_submodel++;
410 submodel_dropped[i] = true;
412 if ( cmd->interactions [k]->n_vars < x->n_vars)
414 assert (n_dropped_model < covariance_dim (cov));
416 model_dropped[i] = true;
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);
424 fill_submatrix (cm, model_cov, model_dropped);
425 fill_submatrix (cm, submodel_cov, submodel_dropped);
427 reg_sweep (model_cov, 0);
428 reg_sweep (submodel_cov, 0);
430 gsl_vector_set (ssq, k + 1,
431 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
434 gsl_matrix_free (model_cov);
435 gsl_matrix_free (submodel_cov);
438 free (model_dropped);
439 free (submodel_dropped);
440 gsl_matrix_free (cm);
443 //static void dump_matrix (const gsl_matrix *m);
446 run_glm (struct glm_spec *cmd, struct casereader *input,
447 const struct dataset *ds)
449 bool warn_bad_weight = true;
452 struct dictionary *dict = dataset_dict (ds);
453 struct casereader *reader;
456 struct glm_workspace ws;
457 struct covariance *cov;
459 ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
460 cmd->wv, cmd->exclude,
461 NULL, NULL, NULL, NULL);
463 cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
464 ws.cats, cmd->wv, cmd->exclude);
467 c = casereader_peek (input, 0);
470 casereader_destroy (input);
473 output_split_file_values (ds, c);
476 taint = taint_clone (casereader_get_taint (input));
478 ws.totals = moments_create (MOMENT_VARIANCE);
480 for (reader = casereader_clone (input);
481 (c = casereader_read (reader)) != NULL; case_unref (c))
483 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
485 for (v = 0; v < cmd->n_dep_vars; ++v)
486 moments_pass_one (ws.totals, case_data (c, cmd->dep_vars[v])->f,
489 covariance_accumulate_pass1 (cov, c);
491 casereader_destroy (reader);
493 if (cmd->dump_coding)
494 reader = casereader_clone (input);
499 (c = casereader_read (reader)) != NULL; case_unref (c))
501 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
503 for (v = 0; v < cmd->n_dep_vars; ++v)
504 moments_pass_two (ws.totals, case_data (c, cmd->dep_vars[v])->f,
507 covariance_accumulate_pass2 (cov, c);
509 casereader_destroy (reader);
512 if (cmd->dump_coding)
514 struct tab_table *t =
515 covariance_dump_enc_header (cov,
516 1 + casereader_count_cases (input));
518 (c = casereader_read (reader)) != NULL; case_unref (c))
520 covariance_dump_enc (cov, c, t);
522 casereader_destroy (reader);
527 gsl_matrix *cm = covariance_calculate_unnormalized (cov);
531 ws.total_ssq = gsl_matrix_get (cm, 0, 0);
536 Store the overall SSE.
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);
543 gsl_matrix_free (cm);
546 if (!taint_has_tainted_successor (taint))
547 output_glm (cmd, &ws);
549 gsl_vector_free (ws.ssq);
551 covariance_destroy (cov);
552 moments_destroy (ws.totals);
554 taint_destroy (taint);
557 static const char *roman[] =
559 "", /* The Romans had no concept of zero */
567 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
569 const struct fmt_spec *wfmt =
570 cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
572 double n_total, mean;
573 double df_corr = 0.0;
578 const int heading_columns = 1;
579 const int heading_rows = 1;
583 int nr = heading_rows + 4 + cmd->n_interactions;
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"));
591 tab_headers (t, heading_columns, 0, heading_rows, 0);
593 tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
595 tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
596 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
598 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Source"));
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."));
609 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
614 df_corr += categoricals_df_total (ws->cats);
616 mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
619 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Corrected Model"));
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),
638 for (f = 0; f < cmd->n_interactions; ++f)
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));
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);
653 tab_double (t, 5, r, 0, gsl_cdf_fdist_Q (F, df, n_total - df_corr),
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);
668 tab_double (t, 5, heading_rows, 0,
669 gsl_cdf_fdist_Q (F, df, n_total - df_corr), NULL);
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);
684 const double intercept = pow2 (mean * n_total) / n_total;
685 const double ssq = intercept + ws->total_ssq;
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);
694 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Corrected Total"));
697 tab_double (t, 1, r, 0, ws->total_ssq, NULL);
698 tab_double (t, 2, r, 0, n_total - 1.0, wfmt);
705 dump_matrix (const gsl_matrix * m)
708 for (i = 0; i < m->size1; ++i)
710 for (j = 0; j < m->size2; ++j)
712 double x = gsl_matrix_get (m, i, j);
725 If the match succeeds, the variable will be placed in VAR.
726 Returns true if successful */
728 lex_match_variable (struct lexer *lexer, const struct glm_spec *glm, const struct variable **var)
730 if (lex_token (lexer) != T_ID)
733 *var = parse_variable_const (lexer, glm->dict);
740 /* An interaction is a variable followed by {*, BY} followed by an interaction */
742 parse_design_interaction (struct lexer *lexer, struct glm_spec *glm, struct interaction **iact)
744 const struct variable *v = NULL;
747 switch (lex_next_token (lexer, 1))
761 if (! lex_match_variable (lexer, glm, &v))
763 interaction_destroy (*iact);
771 *iact = interaction_create (v);
773 interaction_add_variable (*iact, v);
775 if ( lex_match (lexer, T_ASTERISK) || lex_match (lexer, T_BY))
777 return parse_design_interaction (lexer, glm, iact);
784 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
786 const struct variable *v = NULL;
787 if ( ! lex_match_variable (lexer, glm, &v))
790 if (lex_match (lexer, T_LPAREN))
792 if ( ! parse_nested_variable (lexer, glm))
795 if ( ! lex_force_match (lexer, T_RPAREN))
799 lex_error (lexer, "Nested variables are not yet implemented"); return false;
803 /* A design term is an interaction OR a nested variable */
805 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
807 struct interaction *iact = NULL;
808 if (parse_design_interaction (lexer, glm, &iact))
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;
816 if ( parse_nested_variable (lexer, glm))
824 /* Parse a complete DESIGN specification.
825 A design spec is a design term, optionally followed by a comma,
826 and another design spec.
829 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
831 if (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
834 if ( ! parse_design_term (lexer, glm))
837 lex_match (lexer, T_COMMA);
839 return parse_design_spec (lexer, glm);