1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2010, 2011, 2012 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/assertion.h"
37 #include "libpspp/ll.h"
38 #include "libpspp/message.h"
39 #include "libpspp/misc.h"
40 #include "libpspp/taint.h"
41 #include "linreg/sweep.h"
42 #include "math/categoricals.h"
43 #include "math/covariance.h"
44 #include "math/interaction.h"
45 #include "math/moments.h"
46 #include "output/tab.h"
49 #define _(msgid) gettext (msgid)
54 const struct variable **dep_vars;
57 const struct variable **factor_vars;
59 size_t n_interactions;
60 struct interaction **interactions;
62 enum mv_class exclude;
64 /* The weight variable */
65 const struct variable *wv;
67 const struct dictionary *dict;
80 struct moments *totals;
82 struct categoricals *cats;
85 Sums of squares due to different variables. Element 0 is the SSE
86 for the entire model. For i > 0, element i is the SS due to
93 /* Default design: all possible interactions */
95 design_full (struct glm_spec *glm)
99 glm->n_interactions = (1 << glm->n_factor_vars) - 1;
101 glm->interactions = xcalloc (glm->n_interactions, sizeof *glm->interactions);
103 /* All subsets, with exception of the empty set, of [0, glm->n_factor_vars) */
104 for (sz = 1; sz <= glm->n_factor_vars; ++sz)
106 gsl_combination *c = gsl_combination_calloc (glm->n_factor_vars, sz);
110 struct interaction *iact = interaction_create (NULL);
112 for (e = 0 ; e < gsl_combination_k (c); ++e)
113 interaction_add_variable (iact, glm->factor_vars [gsl_combination_get (c, e)]);
115 glm->interactions[i++] = iact;
117 while (gsl_combination_next (c) == GSL_SUCCESS);
119 gsl_combination_free (c);
123 static void output_glm (const struct glm_spec *,
124 const struct glm_workspace *ws);
125 static void run_glm (struct glm_spec *cmd, struct casereader *input,
126 const struct dataset *ds);
129 static bool parse_design_spec (struct lexer *lexer, struct glm_spec *glm);
133 cmd_glm (struct lexer *lexer, struct dataset *ds)
136 struct const_var_set *factors = NULL;
139 glm.dict = dataset_dict (ds);
141 glm.n_factor_vars = 0;
142 glm.n_interactions = 0;
143 glm.interactions = NULL;
145 glm.factor_vars = NULL;
146 glm.exclude = MV_ANY;
147 glm.intercept = true;
148 glm.wv = dict_get_weight (glm.dict);
150 glm.dump_coding = false;
153 if (!parse_variables_const (lexer, glm.dict,
154 &glm.dep_vars, &glm.n_dep_vars,
155 PV_NO_DUPLICATE | PV_NUMERIC))
158 lex_force_match (lexer, T_BY);
160 if (!parse_variables_const (lexer, glm.dict,
161 &glm.factor_vars, &glm.n_factor_vars,
162 PV_NO_DUPLICATE | PV_NUMERIC))
165 if (glm.n_dep_vars > 1)
167 msg (ME, _("Multivariate analysis is not yet implemented"));
172 const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
174 while (lex_token (lexer) != T_ENDCMD)
176 lex_match (lexer, T_SLASH);
178 if (lex_match_id (lexer, "MISSING"))
180 lex_match (lexer, T_EQUALS);
181 while (lex_token (lexer) != T_ENDCMD
182 && lex_token (lexer) != T_SLASH)
184 if (lex_match_id (lexer, "INCLUDE"))
186 glm.exclude = MV_SYSTEM;
188 else if (lex_match_id (lexer, "EXCLUDE"))
190 glm.exclude = MV_ANY;
194 lex_error (lexer, NULL);
199 else if (lex_match_id (lexer, "INTERCEPT"))
201 lex_match (lexer, T_EQUALS);
202 while (lex_token (lexer) != T_ENDCMD
203 && lex_token (lexer) != T_SLASH)
205 if (lex_match_id (lexer, "INCLUDE"))
207 glm.intercept = true;
209 else if (lex_match_id (lexer, "EXCLUDE"))
211 glm.intercept = false;
215 lex_error (lexer, NULL);
220 else if (lex_match_id (lexer, "CRITERIA"))
222 lex_match (lexer, T_EQUALS);
223 if (lex_match_id (lexer, "ALPHA"))
225 if (lex_force_match (lexer, T_LPAREN))
227 if (! lex_force_num (lexer))
229 lex_error (lexer, NULL);
233 glm.alpha = lex_number (lexer);
235 if ( ! lex_force_match (lexer, T_RPAREN))
237 lex_error (lexer, NULL);
244 lex_error (lexer, NULL);
248 else if (lex_match_id (lexer, "METHOD"))
250 lex_match (lexer, T_EQUALS);
251 if ( !lex_force_match_id (lexer, "SSTYPE"))
253 lex_error (lexer, NULL);
257 if ( ! lex_force_match (lexer, T_LPAREN))
259 lex_error (lexer, NULL);
263 if ( ! lex_force_int (lexer))
265 lex_error (lexer, NULL);
269 glm.ss_type = lex_integer (lexer);
270 if (1 > glm.ss_type && 3 < glm.ss_type )
272 msg (ME, _("Only types 1, 2 & 3 sums of squares are currently implemented"));
278 if ( ! lex_force_match (lexer, T_RPAREN))
280 lex_error (lexer, NULL);
284 else if (lex_match_id (lexer, "DESIGN"))
286 lex_match (lexer, T_EQUALS);
288 if (! parse_design_spec (lexer, &glm))
291 if (glm.n_interactions > 0)
294 else if (lex_match_id (lexer, "SHOWCODES"))
295 /* Undocumented debug option */
297 lex_match (lexer, T_EQUALS);
299 glm.dump_coding = true;
303 lex_error (lexer, NULL);
314 struct casegrouper *grouper;
315 struct casereader *group;
318 grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
319 while (casegrouper_get_next_group (grouper, &group))
320 run_glm (&glm, group, ds);
321 ok = casegrouper_destroy (grouper);
322 ok = proc_commit (ds) && ok;
325 const_var_set_destroy (factors);
326 free (glm.factor_vars);
327 for (i = 0 ; i < glm.n_interactions; ++i)
328 interaction_destroy (glm.interactions[i]);
330 free (glm.interactions);
338 const_var_set_destroy (factors);
339 free (glm.factor_vars);
340 for (i = 0 ; i < glm.n_interactions; ++i)
341 interaction_destroy (glm.interactions[i]);
343 free (glm.interactions);
350 not_dropped (size_t j, const bool *ff)
356 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
363 for (i = 0; i < cov->size1; i++)
365 if (not_dropped (i, dropped_f))
368 for (j = 0; j < cov->size2; j++)
370 if (not_dropped (j, dropped_f))
372 gsl_matrix_set (submatrix, n, m,
373 gsl_matrix_get (cov, i, j));
384 Type 1 sums of squares.
385 Populate SSQ with the Type 1 sums of squares according to COV
388 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
390 gsl_matrix *cm = covariance_calculate_unnormalized (cov);
393 bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
394 bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
395 const struct categoricals *cats = covariance_get_categoricals (cov);
397 size_t n_dropped_model = 0;
398 size_t n_dropped_submodel = 0;
400 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
403 n_dropped_submodel++;
404 model_dropped[i] = true;
405 submodel_dropped[i] = true;
408 for (k = 0; k < cmd->n_interactions; k++)
410 gsl_matrix *model_cov = NULL;
411 gsl_matrix *submodel_cov = NULL;
413 n_dropped_submodel = n_dropped_model;
414 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
416 submodel_dropped[i] = model_dropped[i];
419 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
421 const struct interaction * x =
422 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
424 if ( x == cmd->interactions [k])
426 model_dropped[i] = false;
431 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
432 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
434 fill_submatrix (cm, model_cov, model_dropped);
435 fill_submatrix (cm, submodel_cov, submodel_dropped);
437 reg_sweep (model_cov, 0);
438 reg_sweep (submodel_cov, 0);
440 gsl_vector_set (ssq, k + 1,
441 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
444 gsl_matrix_free (model_cov);
445 gsl_matrix_free (submodel_cov);
448 free (model_dropped);
449 free (submodel_dropped);
450 gsl_matrix_free (cm);
454 Type 2 sums of squares.
455 Populate SSQ with the Type 2 sums of squares according to COV
458 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
460 gsl_matrix *cm = covariance_calculate_unnormalized (cov);
463 bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
464 bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
465 const struct categoricals *cats = covariance_get_categoricals (cov);
467 for (k = 0; k < cmd->n_interactions; k++)
469 gsl_matrix *model_cov = NULL;
470 gsl_matrix *submodel_cov = NULL;
471 size_t n_dropped_model = 0;
472 size_t n_dropped_submodel = 0;
473 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
475 const struct interaction * x =
476 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
478 model_dropped[i] = false;
479 submodel_dropped[i] = false;
480 if (interaction_is_subset (cmd->interactions [k], x))
482 assert (n_dropped_submodel < covariance_dim (cov));
483 n_dropped_submodel++;
484 submodel_dropped[i] = true;
486 if ( cmd->interactions [k]->n_vars < x->n_vars)
488 assert (n_dropped_model < covariance_dim (cov));
490 model_dropped[i] = true;
495 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
496 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
498 fill_submatrix (cm, model_cov, model_dropped);
499 fill_submatrix (cm, submodel_cov, submodel_dropped);
501 reg_sweep (model_cov, 0);
502 reg_sweep (submodel_cov, 0);
504 gsl_vector_set (ssq, k + 1,
505 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
508 gsl_matrix_free (model_cov);
509 gsl_matrix_free (submodel_cov);
512 free (model_dropped);
513 free (submodel_dropped);
514 gsl_matrix_free (cm);
518 Type 3 sums of squares.
519 Populate SSQ with the Type 2 sums of squares according to COV
522 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
524 gsl_matrix *cm = covariance_calculate_unnormalized (cov);
527 bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
528 bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
529 const struct categoricals *cats = covariance_get_categoricals (cov);
532 gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
533 fill_submatrix (cm, submodel_cov, submodel_dropped);
534 reg_sweep (submodel_cov, 0);
535 ss0 = gsl_matrix_get (submodel_cov, 0, 0);
536 gsl_matrix_free (submodel_cov);
537 free (submodel_dropped);
539 for (k = 0; k < cmd->n_interactions; k++)
541 gsl_matrix *model_cov = NULL;
542 size_t n_dropped_model = 0;
544 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
546 const struct interaction * x =
547 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
549 model_dropped[i] = false;
551 if ( cmd->interactions [k] == x)
553 assert (n_dropped_model < covariance_dim (cov));
555 model_dropped[i] = true;
559 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
561 fill_submatrix (cm, model_cov, model_dropped);
563 reg_sweep (model_cov, 0);
565 gsl_vector_set (ssq, k + 1,
566 gsl_matrix_get (model_cov, 0, 0) - ss0);
568 gsl_matrix_free (model_cov);
570 free (model_dropped);
572 gsl_matrix_free (cm);
577 //static void dump_matrix (const gsl_matrix *m);
580 run_glm (struct glm_spec *cmd, struct casereader *input,
581 const struct dataset *ds)
583 bool warn_bad_weight = true;
586 struct dictionary *dict = dataset_dict (ds);
587 struct casereader *reader;
590 struct glm_workspace ws;
591 struct covariance *cov;
593 ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
594 cmd->wv, cmd->exclude, MV_ANY);
596 cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
597 ws.cats, cmd->wv, cmd->exclude);
600 c = casereader_peek (input, 0);
603 casereader_destroy (input);
606 output_split_file_values (ds, c);
609 taint = taint_clone (casereader_get_taint (input));
611 ws.totals = moments_create (MOMENT_VARIANCE);
613 for (reader = casereader_clone (input);
614 (c = casereader_read (reader)) != NULL; case_unref (c))
616 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
618 for (v = 0; v < cmd->n_dep_vars; ++v)
619 moments_pass_one (ws.totals, case_data (c, cmd->dep_vars[v])->f,
622 covariance_accumulate_pass1 (cov, c);
624 casereader_destroy (reader);
626 if (cmd->dump_coding)
627 reader = casereader_clone (input);
632 (c = casereader_read (reader)) != NULL; case_unref (c))
634 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
636 for (v = 0; v < cmd->n_dep_vars; ++v)
637 moments_pass_two (ws.totals, case_data (c, cmd->dep_vars[v])->f,
640 covariance_accumulate_pass2 (cov, c);
642 casereader_destroy (reader);
645 if (cmd->dump_coding)
647 struct tab_table *t =
648 covariance_dump_enc_header (cov,
649 1 + casereader_count_cases (input));
651 (c = casereader_read (reader)) != NULL; case_unref (c))
653 covariance_dump_enc (cov, c, t);
655 casereader_destroy (reader);
660 gsl_matrix *cm = covariance_calculate_unnormalized (cov);
664 ws.total_ssq = gsl_matrix_get (cm, 0, 0);
669 Store the overall SSE.
671 ws.ssq = gsl_vector_alloc (cm->size1);
672 gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
673 switch (cmd->ss_type)
676 ssq_type1 (cov, ws.ssq, cmd);
679 ssq_type2 (cov, ws.ssq, cmd);
682 ssq_type3 (cov, ws.ssq, cmd);
690 gsl_matrix_free (cm);
693 if (!taint_has_tainted_successor (taint))
694 output_glm (cmd, &ws);
696 gsl_vector_free (ws.ssq);
698 covariance_destroy (cov);
699 moments_destroy (ws.totals);
701 taint_destroy (taint);
704 static const char *roman[] =
706 "", /* The Romans had no concept of zero */
714 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
716 const struct fmt_spec *wfmt =
717 cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
719 double intercept_ssq;
721 double n_total, mean;
722 double df_corr = 1.0;
727 const int heading_columns = 1;
728 const int heading_rows = 1;
732 int nr = heading_rows + 3 + cmd->n_interactions;
736 msg (MW, "GLM is experimental. Do not rely on these results.");
737 t = tab_create (nc, nr);
738 tab_title (t, _("Tests of Between-Subjects Effects"));
740 tab_headers (t, heading_columns, 0, heading_rows, 0);
742 tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
744 tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
745 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
747 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Source"));
749 /* TRANSLATORS: The parameter is a roman numeral */
750 tab_text_format (t, 1, 0, TAB_CENTER | TAT_TITLE,
751 _("Type %s Sum of Squares"),
752 roman[cmd->ss_type]);
753 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("df"));
754 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
755 tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("F"));
756 tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("Sig."));
758 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
760 df_corr += categoricals_df_total (ws->cats);
764 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Corrected Model"));
766 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Model"));
770 mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
772 intercept_ssq = pow2 (mean * n_total) / n_total;
777 const double df = 1.0;
778 const double F = intercept_ssq / df / mse;
779 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Intercept"));
780 tab_double (t, 1, r, 0, intercept_ssq, NULL);
781 tab_double (t, 2, r, 0, 1.00, wfmt);
782 tab_double (t, 3, r, 0, intercept_ssq / df, NULL);
783 tab_double (t, 4, r, 0, F, NULL);
784 tab_double (t, 5, r, 0, gsl_cdf_fdist_Q (F, df, n_total - df_corr),
789 for (f = 0; f < cmd->n_interactions; ++f)
791 struct string str = DS_EMPTY_INITIALIZER;
792 double df = categoricals_df (ws->cats, f);
794 double ssq = gsl_vector_get (ws->ssq, f + 1);
799 if (! cmd->intercept)
802 ssq += intercept_ssq;
806 interaction_to_string (cmd->interactions[f], &str);
807 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, ds_cstr (&str));
810 tab_double (t, 1, r, 0, ssq, NULL);
811 tab_double (t, 2, r, 0, df, wfmt);
812 tab_double (t, 3, r, 0, ssq / df, NULL);
813 tab_double (t, 4, r, 0, F, NULL);
815 tab_double (t, 5, r, 0, gsl_cdf_fdist_Q (F, df, n_total - df_corr),
821 /* Model / Corrected Model */
823 double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
826 if ( cmd->intercept )
829 ssq += intercept_ssq;
832 tab_double (t, 1, heading_rows, 0, ssq, NULL);
833 tab_double (t, 2, heading_rows, 0, df, wfmt);
834 tab_double (t, 3, heading_rows, 0, ssq / df, NULL);
835 tab_double (t, 4, heading_rows, 0, F, NULL);
837 tab_double (t, 5, heading_rows, 0,
838 gsl_cdf_fdist_Q (F, df, n_total - df_corr), NULL);
842 const double df = n_total - df_corr;
843 const double ssq = gsl_vector_get (ws->ssq, 0);
844 const double mse = ssq / df;
845 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Error"));
846 tab_double (t, 1, r, 0, ssq, NULL);
847 tab_double (t, 2, r, 0, df, wfmt);
848 tab_double (t, 3, r++, 0, mse, NULL);
852 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Total"));
853 tab_double (t, 1, r, 0, ws->total_ssq + intercept_ssq, NULL);
854 tab_double (t, 2, r, 0, n_total, wfmt);
861 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Corrected Total"));
862 tab_double (t, 1, r, 0, ws->total_ssq, NULL);
863 tab_double (t, 2, r, 0, n_total - 1.0, wfmt);
871 dump_matrix (const gsl_matrix * m)
874 for (i = 0; i < m->size1; ++i)
876 for (j = 0; j < m->size2; ++j)
878 double x = gsl_matrix_get (m, i, j);
890 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
892 const struct variable *v = NULL;
893 if ( ! lex_match_variable (lexer, glm->dict, &v))
896 if (lex_match (lexer, T_LPAREN))
898 if ( ! parse_nested_variable (lexer, glm))
901 if ( ! lex_force_match (lexer, T_RPAREN))
905 lex_error (lexer, "Nested variables are not yet implemented"); return false;
909 /* A design term is an interaction OR a nested variable */
911 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
913 struct interaction *iact = NULL;
914 if (parse_design_interaction (lexer, glm->dict, &iact))
916 /* Interaction parsing successful. Add to list of interactions */
917 glm->interactions = xrealloc (glm->interactions, sizeof *glm->interactions * ++glm->n_interactions);
918 glm->interactions[glm->n_interactions - 1] = iact;
922 if ( parse_nested_variable (lexer, glm))
930 /* Parse a complete DESIGN specification.
931 A design spec is a design term, optionally followed by a comma,
932 and another design spec.
935 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
937 if (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
940 if ( ! parse_design_term (lexer, glm))
943 lex_match (lexer, T_COMMA);
945 return parse_design_spec (lexer, glm);