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)
55 const struct variable **dep_vars;
58 const struct variable **factor_vars;
60 size_t n_interactions;
61 struct interaction **interactions;
63 enum mv_class exclude;
65 /* The weight variable */
66 const struct variable *wv;
68 const struct dictionary *dict;
81 struct moments *totals;
83 struct categoricals *cats;
86 Sums of squares due to different variables. Element 0 is the SSE
87 for the entire model. For i > 0, element i is the SS due to
94 /* Default design: all possible interactions */
96 design_full (struct glm_spec *glm)
100 glm->n_interactions = (1 << glm->n_factor_vars) - 1;
102 glm->interactions = xcalloc (glm->n_interactions, sizeof *glm->interactions);
104 /* All subsets, with exception of the empty set, of [0, glm->n_factor_vars) */
105 for (sz = 1; sz <= glm->n_factor_vars; ++sz)
107 gsl_combination *c = gsl_combination_calloc (glm->n_factor_vars, sz);
111 struct interaction *iact = interaction_create (NULL);
113 for (e = 0 ; e < gsl_combination_k (c); ++e)
114 interaction_add_variable (iact, glm->factor_vars [gsl_combination_get (c, e)]);
116 glm->interactions[i++] = iact;
118 while (gsl_combination_next (c) == GSL_SUCCESS);
120 gsl_combination_free (c);
124 static void output_glm (const struct glm_spec *,
125 const struct glm_workspace *ws);
126 static void run_glm (struct glm_spec *cmd, struct casereader *input,
127 const struct dataset *ds);
130 static bool parse_design_spec (struct lexer *lexer, struct glm_spec *glm);
134 cmd_glm (struct lexer *lexer, struct dataset *ds)
137 struct const_var_set *factors = NULL;
140 glm.dict = dataset_dict (ds);
142 glm.n_factor_vars = 0;
143 glm.n_interactions = 0;
144 glm.interactions = NULL;
146 glm.factor_vars = NULL;
147 glm.exclude = MV_ANY;
148 glm.intercept = true;
149 glm.wv = dict_get_weight (glm.dict);
151 glm.dump_coding = false;
154 int dep_vars_start = lex_ofs (lexer);
155 if (!parse_variables_const (lexer, glm.dict,
156 &glm.dep_vars, &glm.n_dep_vars,
157 PV_NO_DUPLICATE | PV_NUMERIC))
159 int dep_vars_end = lex_ofs (lexer) - 1;
161 if (! lex_force_match (lexer, T_BY))
164 if (!parse_variables_const (lexer, glm.dict,
165 &glm.factor_vars, &glm.n_factor_vars,
166 PV_NO_DUPLICATE | PV_NUMERIC))
169 if (glm.n_dep_vars > 1)
171 lex_ofs_error (lexer, dep_vars_start, dep_vars_end,
172 _("Multivariate analysis is not yet implemented"));
177 const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
179 while (lex_token (lexer) != T_ENDCMD)
181 lex_match (lexer, T_SLASH);
183 if (lex_match_id (lexer, "MISSING"))
185 lex_match (lexer, T_EQUALS);
186 while (lex_token (lexer) != T_ENDCMD
187 && lex_token (lexer) != T_SLASH)
189 if (lex_match_id (lexer, "INCLUDE"))
191 glm.exclude = MV_SYSTEM;
193 else if (lex_match_id (lexer, "EXCLUDE"))
195 glm.exclude = MV_ANY;
199 lex_error (lexer, NULL);
204 else if (lex_match_id (lexer, "INTERCEPT"))
206 lex_match (lexer, T_EQUALS);
207 while (lex_token (lexer) != T_ENDCMD
208 && lex_token (lexer) != T_SLASH)
210 if (lex_match_id (lexer, "INCLUDE"))
212 glm.intercept = true;
214 else if (lex_match_id (lexer, "EXCLUDE"))
216 glm.intercept = false;
220 lex_error (lexer, NULL);
225 else if (lex_match_id (lexer, "CRITERIA"))
227 lex_match (lexer, T_EQUALS);
228 if (lex_match_id (lexer, "ALPHA"))
230 if (lex_force_match (lexer, T_LPAREN))
232 if (! lex_force_num (lexer))
234 lex_error (lexer, NULL);
238 glm.alpha = lex_number (lexer);
240 if (! lex_force_match (lexer, T_RPAREN))
242 lex_error (lexer, NULL);
249 lex_error (lexer, NULL);
253 else if (lex_match_id (lexer, "METHOD"))
255 lex_match (lexer, T_EQUALS);
256 if (!lex_force_match_id (lexer, "SSTYPE"))
258 lex_error (lexer, NULL);
262 if (! lex_force_match (lexer, T_LPAREN))
264 lex_error (lexer, NULL);
268 if (!lex_force_int_range (lexer, "SSTYPE", 1, 3))
270 lex_error (lexer, NULL);
274 glm.ss_type = lex_integer (lexer);
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]);
329 free (glm.interactions);
337 const_var_set_destroy (factors);
338 free (glm.factor_vars);
339 for (i = 0 ; i < glm.n_interactions; ++i)
340 interaction_destroy (glm.interactions[i]);
342 free (glm.interactions);
349 not_dropped (size_t j, const bool *ff)
355 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
362 for (i = 0; i < cov->size1; i++)
364 if (not_dropped (i, dropped_f))
367 for (j = 0; j < cov->size2; j++)
369 if (not_dropped (j, dropped_f))
371 gsl_matrix_set (submatrix, n, m,
372 gsl_matrix_get (cov, i, j));
383 Type 1 sums of squares.
384 Populate SSQ with the Type 1 sums of squares according to COV
387 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
389 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
392 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
393 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
394 const struct categoricals *cats = covariance_get_categoricals (cov);
396 size_t n_dropped_model = 0;
397 size_t n_dropped_submodel = 0;
399 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
402 n_dropped_submodel++;
403 model_dropped[i] = true;
404 submodel_dropped[i] = true;
407 for (k = 0; k < cmd->n_interactions; k++)
409 gsl_matrix *model_cov = NULL;
410 gsl_matrix *submodel_cov = NULL;
412 n_dropped_submodel = n_dropped_model;
413 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
415 submodel_dropped[i] = model_dropped[i];
418 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
420 const struct interaction * x =
421 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
423 if (x == cmd->interactions [k])
425 model_dropped[i] = false;
430 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
431 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
433 fill_submatrix (cm, model_cov, model_dropped);
434 fill_submatrix (cm, submodel_cov, submodel_dropped);
436 reg_sweep (model_cov, 0);
437 reg_sweep (submodel_cov, 0);
439 gsl_vector_set (ssq, k + 1,
440 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
443 gsl_matrix_free (model_cov);
444 gsl_matrix_free (submodel_cov);
447 free (model_dropped);
448 free (submodel_dropped);
452 Type 2 sums of squares.
453 Populate SSQ with the Type 2 sums of squares according to COV
456 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
458 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
461 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
462 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
463 const struct categoricals *cats = covariance_get_categoricals (cov);
465 for (k = 0; k < cmd->n_interactions; k++)
467 gsl_matrix *model_cov = NULL;
468 gsl_matrix *submodel_cov = NULL;
469 size_t n_dropped_model = 0;
470 size_t n_dropped_submodel = 0;
471 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
473 const struct interaction * x =
474 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
476 model_dropped[i] = false;
477 submodel_dropped[i] = false;
478 if (interaction_is_subset (cmd->interactions [k], x))
480 assert (n_dropped_submodel < covariance_dim (cov));
481 n_dropped_submodel++;
482 submodel_dropped[i] = true;
484 if (cmd->interactions [k]->n_vars < x->n_vars)
486 assert (n_dropped_model < covariance_dim (cov));
488 model_dropped[i] = true;
493 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
494 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
496 fill_submatrix (cm, model_cov, model_dropped);
497 fill_submatrix (cm, submodel_cov, submodel_dropped);
499 reg_sweep (model_cov, 0);
500 reg_sweep (submodel_cov, 0);
502 gsl_vector_set (ssq, k + 1,
503 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
506 gsl_matrix_free (model_cov);
507 gsl_matrix_free (submodel_cov);
510 free (model_dropped);
511 free (submodel_dropped);
515 Type 3 sums of squares.
516 Populate SSQ with the Type 2 sums of squares according to COV
519 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
521 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
524 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
525 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
526 const struct categoricals *cats = covariance_get_categoricals (cov);
529 gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
530 fill_submatrix (cm, submodel_cov, submodel_dropped);
531 reg_sweep (submodel_cov, 0);
532 ss0 = gsl_matrix_get (submodel_cov, 0, 0);
533 gsl_matrix_free (submodel_cov);
534 free (submodel_dropped);
536 for (k = 0; k < cmd->n_interactions; k++)
538 gsl_matrix *model_cov = NULL;
539 size_t n_dropped_model = 0;
541 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
543 const struct interaction * x =
544 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
546 model_dropped[i] = false;
548 if (cmd->interactions [k] == x)
550 assert (n_dropped_model < covariance_dim (cov));
552 model_dropped[i] = true;
556 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
558 fill_submatrix (cm, model_cov, model_dropped);
560 reg_sweep (model_cov, 0);
562 gsl_vector_set (ssq, k + 1,
563 gsl_matrix_get (model_cov, 0, 0) - ss0);
565 gsl_matrix_free (model_cov);
567 free (model_dropped);
572 //static void dump_matrix (const gsl_matrix *m);
575 run_glm (struct glm_spec *cmd, struct casereader *input,
576 const struct dataset *ds)
578 bool warn_bad_weight = true;
581 struct dictionary *dict = dataset_dict (ds);
582 struct casereader *reader;
585 struct glm_workspace ws;
586 struct covariance *cov;
588 input = casereader_create_filter_missing (input,
589 cmd->dep_vars, cmd->n_dep_vars,
593 input = casereader_create_filter_missing (input,
594 cmd->factor_vars, cmd->n_factor_vars,
598 ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
601 cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
602 ws.cats, cmd->wv, cmd->exclude, true);
605 c = casereader_peek (input, 0);
608 casereader_destroy (input);
611 output_split_file_values (ds, c);
614 taint = taint_clone (casereader_get_taint (input));
616 ws.totals = moments_create (MOMENT_VARIANCE);
618 for (reader = casereader_clone (input);
619 (c = casereader_read (reader)) != NULL; case_unref (c))
621 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
623 for (v = 0; v < cmd->n_dep_vars; ++v)
624 moments_pass_one (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
626 covariance_accumulate_pass1 (cov, c);
628 casereader_destroy (reader);
630 if (cmd->dump_coding)
631 reader = casereader_clone (input);
636 (c = casereader_read (reader)) != NULL; case_unref (c))
638 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
640 for (v = 0; v < cmd->n_dep_vars; ++v)
641 moments_pass_two (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
643 covariance_accumulate_pass2 (cov, c);
645 casereader_destroy (reader);
648 if (cmd->dump_coding)
650 struct pivot_table *t = covariance_dump_enc_header (cov);
652 (c = casereader_read (reader)) != NULL; case_unref (c))
654 covariance_dump_enc (cov, c, t);
657 pivot_table_submit (t);
661 const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
662 gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
663 gsl_matrix_memcpy (cm, ucm);
667 ws.total_ssq = gsl_matrix_get (cm, 0, 0);
672 Store the overall SSE.
674 ws.ssq = gsl_vector_alloc (cm->size1);
675 gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
676 switch (cmd->ss_type)
679 ssq_type1 (cov, ws.ssq, cmd);
682 ssq_type2 (cov, ws.ssq, cmd);
685 ssq_type3 (cov, ws.ssq, cmd);
692 gsl_matrix_free (cm);
695 if (!taint_has_tainted_successor (taint))
696 output_glm (cmd, &ws);
698 gsl_vector_free (ws.ssq);
700 covariance_destroy (cov);
701 moments_destroy (ws.totals);
703 taint_destroy (taint);
707 put_glm_row (struct pivot_table *table, int row,
708 double a, double b, double c, double d, double e)
710 double entries[] = { a, b, c, d, e };
712 for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
713 if (entries[col] != SYSMIS)
714 pivot_table_put2 (table, col, row,
715 pivot_value_new_number (entries[col]));
719 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
721 struct pivot_table *table = pivot_table_create (
722 N_("Tests of Between-Subjects Effects"));
724 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
725 (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
726 : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
727 : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
728 N_("df"), PIVOT_RC_COUNT,
729 N_("Mean Square"), PIVOT_RC_OTHER,
730 N_("F"), PIVOT_RC_OTHER,
731 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
733 struct pivot_dimension *source = pivot_dimension_create (
734 table, PIVOT_AXIS_ROW, N_("Source"),
735 cmd->intercept ? N_("Corrected Model") : N_("Model"));
737 double n_total, mean;
738 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
740 double df_corr = 1.0 + categoricals_df_total (ws->cats);
742 double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
743 double intercept_ssq = pow2 (mean * n_total) / n_total;
746 int row = pivot_category_create_leaf (
747 source->root, pivot_value_new_text (N_("Intercept")));
749 /* The intercept for unbalanced models is of limited use and
750 nobody knows how to calculate it properly */
751 if (categoricals_isbalanced (ws->cats))
753 const double df = 1.0;
754 const double F = intercept_ssq / df / mse;
755 put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
756 F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
760 double ssq_effects = 0.0;
761 for (int f = 0; f < cmd->n_interactions; ++f)
763 double df = categoricals_df (ws->cats, f);
764 double ssq = gsl_vector_get (ws->ssq, f + 1);
769 ssq += intercept_ssq;
771 double F = ssq / df / mse;
773 struct string str = DS_EMPTY_INITIALIZER;
774 interaction_to_string (cmd->interactions[f], &str);
775 int row = pivot_category_create_leaf (
776 source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
778 put_glm_row (table, row, ssq, df, ssq / df, F,
779 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
783 /* Model / Corrected Model */
785 double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
789 ssq += intercept_ssq;
790 double F = ssq / df / mse;
791 put_glm_row (table, 0, ssq, df, ssq / df, F,
792 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
796 int row = pivot_category_create_leaf (source->root,
797 pivot_value_new_text (N_("Error")));
798 const double df = n_total - df_corr;
799 const double ssq = gsl_vector_get (ws->ssq, 0);
800 const double mse = ssq / df;
801 put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
805 int row = pivot_category_create_leaf (source->root,
806 pivot_value_new_text (N_("Total")));
807 put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
808 SYSMIS, SYSMIS, SYSMIS);
813 int row = pivot_category_create_leaf (
814 source->root, pivot_value_new_text (N_("Corrected Total")));
815 put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
819 pivot_table_submit (table);
824 dump_matrix (const gsl_matrix * m)
827 for (i = 0; i < m->size1; ++i)
829 for (j = 0; j < m->size2; ++j)
831 double x = gsl_matrix_get (m, i, j);
843 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
845 const struct variable *v = NULL;
846 if (! lex_match_variable (lexer, glm->dict, &v))
849 if (lex_match (lexer, T_LPAREN))
851 if (! parse_nested_variable (lexer, glm))
854 if (! lex_force_match (lexer, T_RPAREN))
858 lex_error (lexer, "Nested variables are not yet implemented");
862 /* A design term is an interaction OR a nested variable */
864 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
866 struct interaction *iact = NULL;
867 if (parse_design_interaction (lexer, glm->dict, &iact))
869 /* Interaction parsing successful. Add to list of interactions */
870 glm->interactions = xrealloc (glm->interactions, sizeof (*glm->interactions) * ++glm->n_interactions);
871 glm->interactions[glm->n_interactions - 1] = iact;
875 if (parse_nested_variable (lexer, glm))
883 /* Parse a complete DESIGN specification.
884 A design spec is a design term, optionally followed by a comma,
885 and another design spec.
888 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
890 if (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
893 if (! parse_design_term (lexer, glm))
896 lex_match (lexer, T_COMMA);
898 return parse_design_spec (lexer, glm);