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/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
93 /* Default design: all possible interactions */
95 design_full (struct glm_spec *glm)
97 glm->n_interactions = (1 << glm->n_factor_vars) - 1;
98 glm->interactions = xcalloc (glm->n_interactions, sizeof *glm->interactions);
100 /* All subsets, with exception of the empty set, of [0, glm->n_factor_vars) */
102 for (size_t sz = 1; sz <= glm->n_factor_vars; ++sz)
104 gsl_combination *c = gsl_combination_calloc (glm->n_factor_vars, sz);
108 struct interaction *iact = interaction_create (NULL);
110 for (e = 0; e < gsl_combination_k (c); ++e)
111 interaction_add_variable (iact, glm->factor_vars [gsl_combination_get (c, e)]);
113 glm->interactions[i++] = iact;
115 while (gsl_combination_next (c) == GSL_SUCCESS);
117 gsl_combination_free (c);
121 static void output_glm (const struct glm_spec *,
122 const struct glm_workspace *ws);
123 static void run_glm (struct glm_spec *cmd, struct casereader *input,
124 const struct dataset *ds);
127 static bool parse_design_spec (struct lexer *lexer, struct glm_spec *glm);
131 cmd_glm (struct lexer *lexer, struct dataset *ds)
133 struct const_var_set *factors = NULL;
135 struct dictionary *dict = dataset_dict (ds);
136 struct glm_spec glm = {
140 .wv = dict_get_weight (dict),
145 int dep_vars_start = lex_ofs (lexer);
146 if (!parse_variables_const (lexer, glm.dict,
147 &glm.dep_vars, &glm.n_dep_vars,
148 PV_NO_DUPLICATE | PV_NUMERIC))
150 int dep_vars_end = lex_ofs (lexer) - 1;
152 if (!lex_force_match (lexer, T_BY))
155 if (!parse_variables_const (lexer, glm.dict,
156 &glm.factor_vars, &glm.n_factor_vars,
157 PV_NO_DUPLICATE | PV_NUMERIC))
160 if (glm.n_dep_vars > 1)
162 lex_ofs_error (lexer, dep_vars_start, dep_vars_end,
163 _("Multivariate analysis is not yet implemented"));
167 factors = const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
169 while (lex_token (lexer) != T_ENDCMD)
171 lex_match (lexer, T_SLASH);
173 if (lex_match_id (lexer, "MISSING"))
175 lex_match (lexer, T_EQUALS);
176 while (lex_token (lexer) != T_ENDCMD
177 && lex_token (lexer) != T_SLASH)
179 if (lex_match_id (lexer, "INCLUDE"))
180 glm.exclude = MV_SYSTEM;
181 else if (lex_match_id (lexer, "EXCLUDE"))
182 glm.exclude = MV_ANY;
185 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
190 else if (lex_match_id (lexer, "INTERCEPT"))
192 lex_match (lexer, T_EQUALS);
193 while (lex_token (lexer) != T_ENDCMD
194 && lex_token (lexer) != T_SLASH)
196 if (lex_match_id (lexer, "INCLUDE"))
197 glm.intercept = true;
198 else if (lex_match_id (lexer, "EXCLUDE"))
199 glm.intercept = false;
202 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
207 else if (lex_match_id (lexer, "CRITERIA"))
209 lex_match (lexer, T_EQUALS);
210 if (!lex_force_match_phrase (lexer, "ALPHA(")
211 || !lex_force_num (lexer))
213 glm.alpha = lex_number (lexer);
215 if (!lex_force_match (lexer, T_RPAREN))
218 else if (lex_match_id (lexer, "METHOD"))
220 lex_match (lexer, T_EQUALS);
221 if (!lex_force_match_phrase (lexer, "SSTYPE(")
222 || !lex_force_int_range (lexer, "SSTYPE", 1, 3))
225 glm.ss_type = lex_integer (lexer);
228 if (!lex_force_match (lexer, T_RPAREN))
231 else if (lex_match_id (lexer, "DESIGN"))
233 lex_match (lexer, T_EQUALS);
235 if (!parse_design_spec (lexer, &glm))
238 if (glm.n_interactions > 0)
241 else if (lex_match_id (lexer, "SHOWCODES"))
243 /* Undocumented debug option */
244 glm.dump_coding = true;
248 lex_error_expecting (lexer, "MISSING", "INTERCEPT", "CRITERIA",
257 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
258 struct casereader *group;
259 while (casegrouper_get_next_group (grouper, &group))
260 run_glm (&glm, group, ds);
261 bool ok = casegrouper_destroy (grouper);
262 ok = proc_commit (ds) && ok;
264 const_var_set_destroy (factors);
265 free (glm.factor_vars);
266 for (size_t i = 0; i < glm.n_interactions; ++i)
267 interaction_destroy (glm.interactions[i]);
269 free (glm.interactions);
275 const_var_set_destroy (factors);
276 free (glm.factor_vars);
277 for (size_t i = 0; i < glm.n_interactions; ++i)
278 interaction_destroy (glm.interactions[i]);
280 free (glm.interactions);
287 not_dropped (size_t j, const bool *ff)
293 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
300 for (i = 0; i < cov->size1; i++)
302 if (not_dropped (i, dropped_f))
305 for (j = 0; j < cov->size2; j++)
307 if (not_dropped (j, dropped_f))
309 gsl_matrix_set (submatrix, n, m,
310 gsl_matrix_get (cov, i, j));
321 Type 1 sums of squares.
322 Populate SSQ with the Type 1 sums of squares according to COV
325 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
327 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
330 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
331 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
332 const struct categoricals *cats = covariance_get_categoricals (cov);
334 size_t n_dropped_model = 0;
335 size_t n_dropped_submodel = 0;
337 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
340 n_dropped_submodel++;
341 model_dropped[i] = true;
342 submodel_dropped[i] = true;
345 for (k = 0; k < cmd->n_interactions; k++)
347 gsl_matrix *model_cov = NULL;
348 gsl_matrix *submodel_cov = NULL;
350 n_dropped_submodel = n_dropped_model;
351 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
353 submodel_dropped[i] = model_dropped[i];
356 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
358 const struct interaction * x =
359 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
361 if (x == cmd->interactions [k])
363 model_dropped[i] = false;
368 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
369 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
371 fill_submatrix (cm, model_cov, model_dropped);
372 fill_submatrix (cm, submodel_cov, submodel_dropped);
374 reg_sweep (model_cov, 0);
375 reg_sweep (submodel_cov, 0);
377 gsl_vector_set (ssq, k + 1,
378 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
381 gsl_matrix_free (model_cov);
382 gsl_matrix_free (submodel_cov);
385 free (model_dropped);
386 free (submodel_dropped);
390 Type 2 sums of squares.
391 Populate SSQ with the Type 2 sums of squares according to COV
394 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
396 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
399 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
400 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
401 const struct categoricals *cats = covariance_get_categoricals (cov);
403 for (k = 0; k < cmd->n_interactions; k++)
405 gsl_matrix *model_cov = NULL;
406 gsl_matrix *submodel_cov = NULL;
407 size_t n_dropped_model = 0;
408 size_t n_dropped_submodel = 0;
409 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
411 const struct interaction * x =
412 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
414 model_dropped[i] = false;
415 submodel_dropped[i] = false;
416 if (interaction_is_subset (cmd->interactions [k], x))
418 assert (n_dropped_submodel < covariance_dim (cov));
419 n_dropped_submodel++;
420 submodel_dropped[i] = true;
422 if (cmd->interactions [k]->n_vars < x->n_vars)
424 assert (n_dropped_model < covariance_dim (cov));
426 model_dropped[i] = true;
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);
453 Type 3 sums of squares.
454 Populate SSQ with the Type 2 sums of squares according to COV
457 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
459 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
462 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
463 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
464 const struct categoricals *cats = covariance_get_categoricals (cov);
467 gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
468 fill_submatrix (cm, submodel_cov, submodel_dropped);
469 reg_sweep (submodel_cov, 0);
470 ss0 = gsl_matrix_get (submodel_cov, 0, 0);
471 gsl_matrix_free (submodel_cov);
472 free (submodel_dropped);
474 for (k = 0; k < cmd->n_interactions; k++)
476 gsl_matrix *model_cov = NULL;
477 size_t n_dropped_model = 0;
479 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
481 const struct interaction * x =
482 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
484 model_dropped[i] = false;
486 if (cmd->interactions [k] == x)
488 assert (n_dropped_model < covariance_dim (cov));
490 model_dropped[i] = true;
494 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
496 fill_submatrix (cm, model_cov, model_dropped);
498 reg_sweep (model_cov, 0);
500 gsl_vector_set (ssq, k + 1,
501 gsl_matrix_get (model_cov, 0, 0) - ss0);
503 gsl_matrix_free (model_cov);
505 free (model_dropped);
510 //static void dump_matrix (const gsl_matrix *m);
513 run_glm (struct glm_spec *cmd, struct casereader *input,
514 const struct dataset *ds)
516 bool warn_bad_weight = true;
519 struct dictionary *dict = dataset_dict (ds);
520 struct casereader *reader;
523 struct glm_workspace ws;
524 struct covariance *cov;
526 input = casereader_create_filter_missing (input,
527 cmd->dep_vars, cmd->n_dep_vars,
531 input = casereader_create_filter_missing (input,
532 cmd->factor_vars, cmd->n_factor_vars,
536 ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
539 cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
540 ws.cats, cmd->wv, cmd->exclude, true);
542 output_split_file_values_peek (ds, input);
545 taint = taint_clone (casereader_get_taint (input));
547 ws.totals = moments_create (MOMENT_VARIANCE);
549 for (reader = casereader_clone (input);
550 (c = casereader_read (reader)) != NULL; case_unref (c))
552 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
554 for (v = 0; v < cmd->n_dep_vars; ++v)
555 moments_pass_one (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
557 covariance_accumulate_pass1 (cov, c);
559 casereader_destroy (reader);
561 if (cmd->dump_coding)
562 reader = casereader_clone (input);
567 (c = casereader_read (reader)) != NULL; case_unref (c))
569 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
571 for (v = 0; v < cmd->n_dep_vars; ++v)
572 moments_pass_two (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
574 covariance_accumulate_pass2 (cov, c);
576 casereader_destroy (reader);
579 if (cmd->dump_coding)
581 struct pivot_table *t = covariance_dump_enc_header (cov);
583 (c = casereader_read (reader)) != NULL; case_unref (c))
585 covariance_dump_enc (cov, c, t);
588 pivot_table_submit (t);
592 const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
593 gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
594 gsl_matrix_memcpy (cm, ucm);
598 ws.total_ssq = gsl_matrix_get (cm, 0, 0);
603 Store the overall SSE.
605 ws.ssq = gsl_vector_alloc (cm->size1);
606 gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
607 switch (cmd->ss_type)
610 ssq_type1 (cov, ws.ssq, cmd);
613 ssq_type2 (cov, ws.ssq, cmd);
616 ssq_type3 (cov, ws.ssq, cmd);
623 gsl_matrix_free (cm);
626 if (!taint_has_tainted_successor (taint))
627 output_glm (cmd, &ws);
629 gsl_vector_free (ws.ssq);
631 covariance_destroy (cov);
632 moments_destroy (ws.totals);
634 taint_destroy (taint);
638 put_glm_row (struct pivot_table *table, int row,
639 double a, double b, double c, double d, double e)
641 double entries[] = { a, b, c, d, e };
643 for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
644 if (entries[col] != SYSMIS)
645 pivot_table_put2 (table, col, row,
646 pivot_value_new_number (entries[col]));
650 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
652 struct pivot_table *table = pivot_table_create (
653 N_("Tests of Between-Subjects Effects"));
655 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
656 (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
657 : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
658 : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
659 N_("df"), PIVOT_RC_COUNT,
660 N_("Mean Square"), PIVOT_RC_OTHER,
661 N_("F"), PIVOT_RC_OTHER,
662 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
664 struct pivot_dimension *source = pivot_dimension_create (
665 table, PIVOT_AXIS_ROW, N_("Source"),
666 cmd->intercept ? N_("Corrected Model") : N_("Model"));
668 double n_total, mean;
669 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
671 double df_corr = 1.0 + categoricals_df_total (ws->cats);
673 double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
674 double intercept_ssq = pow2 (mean * n_total) / n_total;
677 int row = pivot_category_create_leaf (
678 source->root, pivot_value_new_text (N_("Intercept")));
680 /* The intercept for unbalanced models is of limited use and
681 nobody knows how to calculate it properly */
682 if (categoricals_isbalanced (ws->cats))
684 const double df = 1.0;
685 const double F = intercept_ssq / df / mse;
686 put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
687 F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
691 double ssq_effects = 0.0;
692 for (int f = 0; f < cmd->n_interactions; ++f)
694 double df = categoricals_df (ws->cats, f);
695 double ssq = gsl_vector_get (ws->ssq, f + 1);
700 ssq += intercept_ssq;
702 double F = ssq / df / mse;
704 struct string str = DS_EMPTY_INITIALIZER;
705 interaction_to_string (cmd->interactions[f], &str);
706 int row = pivot_category_create_leaf (
707 source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
709 put_glm_row (table, row, ssq, df, ssq / df, F,
710 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
714 /* Model / Corrected Model */
716 double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
720 ssq += intercept_ssq;
721 double F = ssq / df / mse;
722 put_glm_row (table, 0, ssq, df, ssq / df, F,
723 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
727 int row = pivot_category_create_leaf (source->root,
728 pivot_value_new_text (N_("Error")));
729 const double df = n_total - df_corr;
730 const double ssq = gsl_vector_get (ws->ssq, 0);
731 const double mse = ssq / df;
732 put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
736 int row = pivot_category_create_leaf (source->root,
737 pivot_value_new_text (N_("Total")));
738 put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
739 SYSMIS, SYSMIS, SYSMIS);
744 int row = pivot_category_create_leaf (
745 source->root, pivot_value_new_text (N_("Corrected Total")));
746 put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
750 pivot_table_submit (table);
755 dump_matrix (const gsl_matrix * m)
758 for (i = 0; i < m->size1; ++i)
760 for (j = 0; j < m->size2; ++j)
762 double x = gsl_matrix_get (m, i, j);
774 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
776 const struct variable *v = NULL;
777 if (!lex_match_variable (lexer, glm->dict, &v))
780 if (lex_match (lexer, T_LPAREN))
782 if (!parse_nested_variable (lexer, glm))
785 if (!lex_force_match (lexer, T_RPAREN))
789 lex_error (lexer, "Nested variables are not yet implemented");
793 /* An interaction is a variable followed by {*, BY} followed by an interaction */
795 parse_internal_interaction (struct lexer *lexer, const struct dictionary *dict, struct interaction **iact, struct interaction **it)
797 const struct variable *v = NULL;
800 switch (lex_next_token (lexer, 1))
814 if (! lex_match_variable (lexer, dict, &v))
817 interaction_destroy (*it);
825 *iact = interaction_create (v);
827 interaction_add_variable (*iact, v);
829 if (lex_match (lexer, T_ASTERISK) || lex_match (lexer, T_BY))
831 return parse_internal_interaction (lexer, dict, iact, iact);
837 /* Parse an interaction.
838 If not successful return false.
839 Otherwise, a newly created interaction will be placed in IACT.
840 It is the caller's responsibility to destroy this interaction.
843 parse_design_interaction (struct lexer *lexer, const struct dictionary *dict, struct interaction **iact)
845 return parse_internal_interaction (lexer, dict, iact, NULL);
848 /* A design term is an interaction OR a nested variable */
850 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
852 struct interaction *iact = NULL;
853 if (parse_design_interaction (lexer, glm->dict, &iact))
855 /* Interaction parsing successful. Add to list of interactions */
856 glm->interactions = xrealloc (glm->interactions, sizeof (*glm->interactions) * ++glm->n_interactions);
857 glm->interactions[glm->n_interactions - 1] = iact;
861 if (parse_nested_variable (lexer, glm))
869 /* Parse a complete DESIGN specification.
870 A design spec is a design term, optionally followed by a comma,
871 and another design spec.
874 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
876 if (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
879 if (!parse_design_term (lexer, glm))
882 lex_match (lexer, T_COMMA);
884 return parse_design_spec (lexer, glm);