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/commands/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/pivot-table.h"
49 #define N_(msgid) msgid
50 #define _(msgid) gettext (msgid)
54 const struct variable **dep_vars;
57 const struct variable **factor_vars;
60 struct interaction **interactions;
61 size_t n_interactions;
63 enum mv_class exclude;
65 const struct variable *wv; /* The weight variable */
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
92 /* Default design: all possible interactions */
94 design_full (struct glm_spec *glm)
96 size_t n = (1 << glm->n_factor_vars) - 1;
97 glm->interactions = xnmalloc (n, sizeof *glm->interactions);
99 /* All subsets, with exception of the empty set, of [0, glm->n_factor_vars) */
100 for (size_t sz = 1; sz <= glm->n_factor_vars; ++sz)
102 gsl_combination *c = gsl_combination_calloc (glm->n_factor_vars, sz);
106 struct interaction *iact = interaction_create (NULL);
107 for (int e = 0; e < gsl_combination_k (c); ++e)
108 interaction_add_variable (
109 iact, glm->factor_vars [gsl_combination_get (c, e)]);
111 glm->interactions[glm->n_interactions++] = iact;
113 while (gsl_combination_next (c) == GSL_SUCCESS);
115 gsl_combination_free (c);
117 assert (glm->n_interactions == n);
120 static void output_glm (const struct glm_spec *,
121 const struct glm_workspace *ws);
122 static void run_glm (struct glm_spec *cmd, struct casereader *input,
123 const struct dataset *ds);
125 static struct interaction *parse_design_term (struct lexer *,
126 const struct dictionary *);
129 cmd_glm (struct lexer *lexer, struct dataset *ds)
131 struct const_var_set *factors = NULL;
133 struct dictionary *dict = dataset_dict (ds);
134 struct glm_spec glm = {
138 .wv = dict_get_weight (dict),
143 int dep_vars_start = lex_ofs (lexer);
144 if (!parse_variables_const (lexer, glm.dict,
145 &glm.dep_vars, &glm.n_dep_vars,
146 PV_NO_DUPLICATE | PV_NUMERIC))
148 int dep_vars_end = lex_ofs (lexer) - 1;
150 if (!lex_force_match (lexer, T_BY))
153 if (!parse_variables_const (lexer, glm.dict,
154 &glm.factor_vars, &glm.n_factor_vars,
155 PV_NO_DUPLICATE | PV_NUMERIC))
158 if (glm.n_dep_vars > 1)
160 lex_ofs_error (lexer, dep_vars_start, dep_vars_end,
161 _("Multivariate analysis is not yet implemented."));
165 factors = const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
167 size_t allocated_interactions = 0;
168 while (lex_token (lexer) != T_ENDCMD)
170 lex_match (lexer, T_SLASH);
172 if (lex_match_id (lexer, "MISSING"))
174 lex_match (lexer, T_EQUALS);
175 while (lex_token (lexer) != T_ENDCMD
176 && lex_token (lexer) != T_SLASH)
178 if (lex_match_id (lexer, "INCLUDE"))
179 glm.exclude = MV_SYSTEM;
180 else if (lex_match_id (lexer, "EXCLUDE"))
181 glm.exclude = MV_ANY;
184 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
189 else if (lex_match_id (lexer, "INTERCEPT"))
191 lex_match (lexer, T_EQUALS);
192 while (lex_token (lexer) != T_ENDCMD
193 && lex_token (lexer) != T_SLASH)
195 if (lex_match_id (lexer, "INCLUDE"))
196 glm.intercept = true;
197 else if (lex_match_id (lexer, "EXCLUDE"))
198 glm.intercept = false;
201 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
206 else if (lex_match_id (lexer, "CRITERIA"))
208 lex_match (lexer, T_EQUALS);
209 if (!lex_force_match_phrase (lexer, "ALPHA(")
210 || !lex_force_num (lexer))
212 glm.alpha = lex_number (lexer);
214 if (!lex_force_match (lexer, T_RPAREN))
217 else if (lex_match_id (lexer, "METHOD"))
219 lex_match (lexer, T_EQUALS);
220 if (!lex_force_match_phrase (lexer, "SSTYPE(")
221 || !lex_force_int_range (lexer, "SSTYPE", 1, 3))
224 glm.ss_type = lex_integer (lexer);
227 if (!lex_force_match (lexer, T_RPAREN))
230 else if (lex_match_id (lexer, "DESIGN"))
232 lex_match (lexer, T_EQUALS);
236 struct interaction *iact = parse_design_term (lexer, glm.dict);
240 if (glm.n_interactions >= allocated_interactions)
241 glm.interactions = x2nrealloc (glm.interactions,
242 &allocated_interactions,
243 sizeof *glm.interactions);
244 glm.interactions[glm.n_interactions++] = iact;
246 lex_match (lexer, T_COMMA);
248 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH);
250 if (glm.n_interactions > 0)
253 else if (lex_match_id (lexer, "SHOWCODES"))
255 /* Undocumented debug option */
256 glm.dump_coding = true;
260 lex_error_expecting (lexer, "MISSING", "INTERCEPT", "CRITERIA",
269 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
270 struct casereader *group;
271 while (casegrouper_get_next_group (grouper, &group))
272 run_glm (&glm, group, ds);
273 bool ok = casegrouper_destroy (grouper);
274 ok = proc_commit (ds) && ok;
276 const_var_set_destroy (factors);
277 free (glm.factor_vars);
278 for (size_t i = 0; i < glm.n_interactions; ++i)
279 interaction_destroy (glm.interactions[i]);
281 free (glm.interactions);
287 const_var_set_destroy (factors);
288 free (glm.factor_vars);
289 for (size_t i = 0; i < glm.n_interactions; ++i)
290 interaction_destroy (glm.interactions[i]);
292 free (glm.interactions);
299 not_dropped (size_t j, const bool *ff)
305 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
312 for (i = 0; i < cov->size1; i++)
314 if (not_dropped (i, dropped_f))
317 for (j = 0; j < cov->size2; j++)
319 if (not_dropped (j, dropped_f))
321 gsl_matrix_set (submatrix, n, m,
322 gsl_matrix_get (cov, i, j));
333 Type 1 sums of squares.
334 Populate SSQ with the Type 1 sums of squares according to COV
337 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
339 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
342 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
343 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
344 const struct categoricals *cats = covariance_get_categoricals (cov);
346 size_t n_dropped_model = 0;
347 size_t n_dropped_submodel = 0;
349 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
352 n_dropped_submodel++;
353 model_dropped[i] = true;
354 submodel_dropped[i] = true;
357 for (k = 0; k < cmd->n_interactions; k++)
359 gsl_matrix *model_cov = NULL;
360 gsl_matrix *submodel_cov = NULL;
362 n_dropped_submodel = n_dropped_model;
363 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
364 submodel_dropped[i] = model_dropped[i];
366 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
368 const struct interaction * x =
369 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
371 if (x == cmd->interactions [k])
373 model_dropped[i] = false;
378 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
379 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
381 fill_submatrix (cm, model_cov, model_dropped);
382 fill_submatrix (cm, submodel_cov, submodel_dropped);
384 reg_sweep (model_cov, 0);
385 reg_sweep (submodel_cov, 0);
387 gsl_vector_set (ssq, k + 1,
388 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
391 gsl_matrix_free (model_cov);
392 gsl_matrix_free (submodel_cov);
395 free (model_dropped);
396 free (submodel_dropped);
400 Type 2 sums of squares.
401 Populate SSQ with the Type 2 sums of squares according to COV
404 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
406 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
407 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
408 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
409 const struct categoricals *cats = covariance_get_categoricals (cov);
411 for (size_t k = 0; k < cmd->n_interactions; k++)
413 gsl_matrix *model_cov = NULL;
414 gsl_matrix *submodel_cov = NULL;
415 size_t n_dropped_model = 0;
416 size_t n_dropped_submodel = 0;
417 for (size_t i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
419 const struct interaction * x =
420 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
422 model_dropped[i] = false;
423 submodel_dropped[i] = false;
424 if (interaction_is_subset (cmd->interactions [k], x))
426 assert (n_dropped_submodel < covariance_dim (cov));
427 n_dropped_submodel++;
428 submodel_dropped[i] = true;
430 if (cmd->interactions [k]->n_vars < x->n_vars)
432 assert (n_dropped_model < covariance_dim (cov));
434 model_dropped[i] = true;
439 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
440 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
442 fill_submatrix (cm, model_cov, model_dropped);
443 fill_submatrix (cm, submodel_cov, submodel_dropped);
445 reg_sweep (model_cov, 0);
446 reg_sweep (submodel_cov, 0);
448 gsl_vector_set (ssq, k + 1,
449 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
452 gsl_matrix_free (model_cov);
453 gsl_matrix_free (submodel_cov);
456 free (model_dropped);
457 free (submodel_dropped);
461 Type 3 sums of squares.
462 Populate SSQ with the Type 2 sums of squares according to COV
465 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
467 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
468 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
469 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
470 const struct categoricals *cats = covariance_get_categoricals (cov);
472 gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
473 fill_submatrix (cm, submodel_cov, submodel_dropped);
474 reg_sweep (submodel_cov, 0);
475 double ss0 = gsl_matrix_get (submodel_cov, 0, 0);
476 gsl_matrix_free (submodel_cov);
477 free (submodel_dropped);
479 for (size_t k = 0; k < cmd->n_interactions; k++)
481 size_t n_dropped_model = 0;
482 for (size_t i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
484 const struct interaction * x =
485 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
487 model_dropped[i] = false;
489 if (cmd->interactions [k] == x)
491 assert (n_dropped_model < covariance_dim (cov));
493 model_dropped[i] = true;
497 gsl_matrix *model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model,
498 cm->size2 - n_dropped_model);
500 fill_submatrix (cm, model_cov, model_dropped);
502 reg_sweep (model_cov, 0);
504 gsl_vector_set (ssq, k + 1, gsl_matrix_get (model_cov, 0, 0) - ss0);
506 gsl_matrix_free (model_cov);
508 free (model_dropped);
512 run_glm (struct glm_spec *cmd, struct casereader *input,
513 const struct dataset *ds)
515 bool warn_bad_weight = true;
516 struct dictionary *dict = dataset_dict (ds);
519 input = casereader_create_filter_missing (input,
520 cmd->dep_vars, cmd->n_dep_vars,
524 input = casereader_create_filter_missing (input,
525 cmd->factor_vars, cmd->n_factor_vars,
529 struct glm_workspace ws = {
530 .cats = categoricals_create (cmd->interactions, cmd->n_interactions,
534 struct covariance *cov = covariance_2pass_create (
535 cmd->n_dep_vars, cmd->dep_vars, ws.cats, cmd->wv, cmd->exclude, true);
537 output_split_file_values_peek (ds, input);
539 struct taint *taint = taint_clone (casereader_get_taint (input));
541 ws.totals = moments_create (MOMENT_VARIANCE);
543 struct casereader *reader = casereader_clone (input);
545 for (; (c = casereader_read (reader)) != NULL; case_unref (c))
547 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
549 for (int v = 0; v < cmd->n_dep_vars; ++v)
550 moments_pass_one (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
552 covariance_accumulate_pass1 (cov, c);
554 casereader_destroy (reader);
556 if (cmd->dump_coding)
557 reader = casereader_clone (input);
561 for (; (c = casereader_read (reader)) != NULL; case_unref (c))
563 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
565 for (size_t v = 0; v < cmd->n_dep_vars; ++v)
566 moments_pass_two (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
568 covariance_accumulate_pass2 (cov, c);
570 casereader_destroy (reader);
573 if (cmd->dump_coding)
575 struct pivot_table *t = covariance_dump_enc_header (cov);
577 (c = casereader_read (reader)) != NULL; case_unref (c))
579 covariance_dump_enc (cov, c, t);
582 pivot_table_submit (t);
586 const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
587 gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
588 gsl_matrix_memcpy (cm, ucm);
592 ws.total_ssq = gsl_matrix_get (cm, 0, 0);
597 Store the overall SSE.
599 ws.ssq = gsl_vector_alloc (cm->size1);
600 gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
601 switch (cmd->ss_type)
604 ssq_type1 (cov, ws.ssq, cmd);
607 ssq_type2 (cov, ws.ssq, cmd);
610 ssq_type3 (cov, ws.ssq, cmd);
617 gsl_matrix_free (cm);
620 if (!taint_has_tainted_successor (taint))
621 output_glm (cmd, &ws);
623 gsl_vector_free (ws.ssq);
625 covariance_destroy (cov);
626 moments_destroy (ws.totals);
628 taint_destroy (taint);
632 put_glm_row (struct pivot_table *table, int row,
633 double a, double b, double c, double d, double e)
635 double entries[] = { a, b, c, d, e };
637 for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
638 if (entries[col] != SYSMIS)
639 pivot_table_put2 (table, col, row,
640 pivot_value_new_number (entries[col]));
644 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
646 struct pivot_table *table = pivot_table_create (
647 N_("Tests of Between-Subjects Effects"));
649 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
650 (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
651 : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
652 : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
653 N_("df"), PIVOT_RC_COUNT,
654 N_("Mean Square"), PIVOT_RC_OTHER,
655 N_("F"), PIVOT_RC_OTHER,
656 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
658 struct pivot_dimension *source = pivot_dimension_create (
659 table, PIVOT_AXIS_ROW, N_("Source"),
660 cmd->intercept ? N_("Corrected Model") : N_("Model"));
662 double n_total, mean;
663 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
665 double df_corr = 1.0 + categoricals_df_total (ws->cats);
667 double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
668 double intercept_ssq = pow2 (mean * n_total) / n_total;
671 int row = pivot_category_create_leaf (
672 source->root, pivot_value_new_text (N_("Intercept")));
674 /* The intercept for unbalanced models is of limited use and
675 nobody knows how to calculate it properly */
676 if (categoricals_isbalanced (ws->cats))
678 const double df = 1.0;
679 const double F = intercept_ssq / df / mse;
680 put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
681 F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
685 double ssq_effects = 0.0;
686 for (int f = 0; f < cmd->n_interactions; ++f)
688 double df = categoricals_df (ws->cats, f);
689 double ssq = gsl_vector_get (ws->ssq, f + 1);
694 ssq += intercept_ssq;
696 double F = ssq / df / mse;
698 struct string str = DS_EMPTY_INITIALIZER;
699 interaction_to_string (cmd->interactions[f], &str);
700 int row = pivot_category_create_leaf (
701 source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
703 put_glm_row (table, row, ssq, df, ssq / df, F,
704 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
708 /* Model / Corrected Model */
710 double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
714 ssq += intercept_ssq;
715 double F = ssq / df / mse;
716 put_glm_row (table, 0, ssq, df, ssq / df, F,
717 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
721 int row = pivot_category_create_leaf (source->root,
722 pivot_value_new_text (N_("Error")));
723 const double df = n_total - df_corr;
724 const double ssq = gsl_vector_get (ws->ssq, 0);
725 const double mse = ssq / df;
726 put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
730 int row = pivot_category_create_leaf (source->root,
731 pivot_value_new_text (N_("Total")));
732 put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
733 SYSMIS, SYSMIS, SYSMIS);
738 int row = pivot_category_create_leaf (
739 source->root, pivot_value_new_text (N_("Corrected Total")));
740 put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
744 pivot_table_submit (table);
749 dump_matrix (const gsl_matrix * m)
752 for (i = 0; i < m->size1; ++i)
754 for (j = 0; j < m->size2; ++j)
756 double x = gsl_matrix_get (m, i, j);
767 static struct interaction *
768 parse_design_term (struct lexer *lexer, const struct dictionary *dict)
770 struct interaction *iact = interaction_create (NULL);
773 struct variable *var = parse_variable (lexer, dict);
776 interaction_add_variable (iact, var);
778 if (lex_match (lexer, T_LPAREN) || lex_match_id (lexer, "WITHIN"))
780 lex_next_error (lexer, -1, -1,
781 "Nested variables are not yet implemented.");
785 while (lex_match (lexer, T_ASTERISK));
790 interaction_destroy (iact);