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 if (!parse_variables_const (lexer, glm.dict,
155 &glm.dep_vars, &glm.n_dep_vars,
156 PV_NO_DUPLICATE | PV_NUMERIC))
159 if (! lex_force_match (lexer, T_BY))
162 if (!parse_variables_const (lexer, glm.dict,
163 &glm.factor_vars, &glm.n_factor_vars,
164 PV_NO_DUPLICATE | PV_NUMERIC))
167 if (glm.n_dep_vars > 1)
169 msg (ME, _("Multivariate analysis is not yet implemented"));
174 const_var_set_create_from_array (glm.factor_vars, glm.n_factor_vars);
176 while (lex_token (lexer) != T_ENDCMD)
178 lex_match (lexer, T_SLASH);
180 if (lex_match_id (lexer, "MISSING"))
182 lex_match (lexer, T_EQUALS);
183 while (lex_token (lexer) != T_ENDCMD
184 && lex_token (lexer) != T_SLASH)
186 if (lex_match_id (lexer, "INCLUDE"))
188 glm.exclude = MV_SYSTEM;
190 else if (lex_match_id (lexer, "EXCLUDE"))
192 glm.exclude = MV_ANY;
196 lex_error (lexer, NULL);
201 else if (lex_match_id (lexer, "INTERCEPT"))
203 lex_match (lexer, T_EQUALS);
204 while (lex_token (lexer) != T_ENDCMD
205 && lex_token (lexer) != T_SLASH)
207 if (lex_match_id (lexer, "INCLUDE"))
209 glm.intercept = true;
211 else if (lex_match_id (lexer, "EXCLUDE"))
213 glm.intercept = false;
217 lex_error (lexer, NULL);
222 else if (lex_match_id (lexer, "CRITERIA"))
224 lex_match (lexer, T_EQUALS);
225 if (lex_match_id (lexer, "ALPHA"))
227 if (lex_force_match (lexer, T_LPAREN))
229 if (! lex_force_num (lexer))
231 lex_error (lexer, NULL);
235 glm.alpha = lex_number (lexer);
237 if (! lex_force_match (lexer, T_RPAREN))
239 lex_error (lexer, NULL);
246 lex_error (lexer, NULL);
250 else if (lex_match_id (lexer, "METHOD"))
252 lex_match (lexer, T_EQUALS);
253 if (!lex_force_match_id (lexer, "SSTYPE"))
255 lex_error (lexer, NULL);
259 if (! lex_force_match (lexer, T_LPAREN))
261 lex_error (lexer, NULL);
265 if (!lex_force_int_range (lexer, "SSTYPE", 1, 3))
267 lex_error (lexer, NULL);
271 glm.ss_type = lex_integer (lexer);
274 if (! lex_force_match (lexer, T_RPAREN))
276 lex_error (lexer, NULL);
280 else if (lex_match_id (lexer, "DESIGN"))
282 lex_match (lexer, T_EQUALS);
284 if (! parse_design_spec (lexer, &glm))
287 if (glm.n_interactions > 0)
290 else if (lex_match_id (lexer, "SHOWCODES"))
291 /* Undocumented debug option */
293 lex_match (lexer, T_EQUALS);
295 glm.dump_coding = true;
299 lex_error (lexer, NULL);
310 struct casegrouper *grouper;
311 struct casereader *group;
314 grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
315 while (casegrouper_get_next_group (grouper, &group))
316 run_glm (&glm, group, ds);
317 ok = casegrouper_destroy (grouper);
318 ok = proc_commit (ds) && ok;
321 const_var_set_destroy (factors);
322 free (glm.factor_vars);
323 for (i = 0 ; i < glm.n_interactions; ++i)
324 interaction_destroy (glm.interactions[i]);
326 free (glm.interactions);
334 const_var_set_destroy (factors);
335 free (glm.factor_vars);
336 for (i = 0 ; i < glm.n_interactions; ++i)
337 interaction_destroy (glm.interactions[i]);
339 free (glm.interactions);
346 not_dropped (size_t j, const bool *ff)
352 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
359 for (i = 0; i < cov->size1; i++)
361 if (not_dropped (i, dropped_f))
364 for (j = 0; j < cov->size2; j++)
366 if (not_dropped (j, dropped_f))
368 gsl_matrix_set (submatrix, n, m,
369 gsl_matrix_get (cov, i, j));
380 Type 1 sums of squares.
381 Populate SSQ with the Type 1 sums of squares according to COV
384 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
386 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
389 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
390 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
391 const struct categoricals *cats = covariance_get_categoricals (cov);
393 size_t n_dropped_model = 0;
394 size_t n_dropped_submodel = 0;
396 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
399 n_dropped_submodel++;
400 model_dropped[i] = true;
401 submodel_dropped[i] = true;
404 for (k = 0; k < cmd->n_interactions; k++)
406 gsl_matrix *model_cov = NULL;
407 gsl_matrix *submodel_cov = NULL;
409 n_dropped_submodel = n_dropped_model;
410 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
412 submodel_dropped[i] = model_dropped[i];
415 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
417 const struct interaction * x =
418 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
420 if (x == cmd->interactions [k])
422 model_dropped[i] = false;
427 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
428 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
430 fill_submatrix (cm, model_cov, model_dropped);
431 fill_submatrix (cm, submodel_cov, submodel_dropped);
433 reg_sweep (model_cov, 0);
434 reg_sweep (submodel_cov, 0);
436 gsl_vector_set (ssq, k + 1,
437 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
440 gsl_matrix_free (model_cov);
441 gsl_matrix_free (submodel_cov);
444 free (model_dropped);
445 free (submodel_dropped);
449 Type 2 sums of squares.
450 Populate SSQ with the Type 2 sums of squares according to COV
453 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
455 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
458 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
459 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
460 const struct categoricals *cats = covariance_get_categoricals (cov);
462 for (k = 0; k < cmd->n_interactions; k++)
464 gsl_matrix *model_cov = NULL;
465 gsl_matrix *submodel_cov = NULL;
466 size_t n_dropped_model = 0;
467 size_t n_dropped_submodel = 0;
468 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
470 const struct interaction * x =
471 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
473 model_dropped[i] = false;
474 submodel_dropped[i] = false;
475 if (interaction_is_subset (cmd->interactions [k], x))
477 assert (n_dropped_submodel < covariance_dim (cov));
478 n_dropped_submodel++;
479 submodel_dropped[i] = true;
481 if (cmd->interactions [k]->n_vars < x->n_vars)
483 assert (n_dropped_model < covariance_dim (cov));
485 model_dropped[i] = true;
490 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
491 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
493 fill_submatrix (cm, model_cov, model_dropped);
494 fill_submatrix (cm, submodel_cov, submodel_dropped);
496 reg_sweep (model_cov, 0);
497 reg_sweep (submodel_cov, 0);
499 gsl_vector_set (ssq, k + 1,
500 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
503 gsl_matrix_free (model_cov);
504 gsl_matrix_free (submodel_cov);
507 free (model_dropped);
508 free (submodel_dropped);
512 Type 3 sums of squares.
513 Populate SSQ with the Type 2 sums of squares according to COV
516 ssq_type3 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
518 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
521 bool *model_dropped = XCALLOC (covariance_dim (cov), bool);
522 bool *submodel_dropped = XCALLOC (covariance_dim (cov), bool);
523 const struct categoricals *cats = covariance_get_categoricals (cov);
526 gsl_matrix *submodel_cov = gsl_matrix_alloc (cm->size1, cm->size2);
527 fill_submatrix (cm, submodel_cov, submodel_dropped);
528 reg_sweep (submodel_cov, 0);
529 ss0 = gsl_matrix_get (submodel_cov, 0, 0);
530 gsl_matrix_free (submodel_cov);
531 free (submodel_dropped);
533 for (k = 0; k < cmd->n_interactions; k++)
535 gsl_matrix *model_cov = NULL;
536 size_t n_dropped_model = 0;
538 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
540 const struct interaction * x =
541 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
543 model_dropped[i] = false;
545 if (cmd->interactions [k] == x)
547 assert (n_dropped_model < covariance_dim (cov));
549 model_dropped[i] = true;
553 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
555 fill_submatrix (cm, model_cov, model_dropped);
557 reg_sweep (model_cov, 0);
559 gsl_vector_set (ssq, k + 1,
560 gsl_matrix_get (model_cov, 0, 0) - ss0);
562 gsl_matrix_free (model_cov);
564 free (model_dropped);
569 //static void dump_matrix (const gsl_matrix *m);
572 run_glm (struct glm_spec *cmd, struct casereader *input,
573 const struct dataset *ds)
575 bool warn_bad_weight = true;
578 struct dictionary *dict = dataset_dict (ds);
579 struct casereader *reader;
582 struct glm_workspace ws;
583 struct covariance *cov;
585 input = casereader_create_filter_missing (input,
586 cmd->dep_vars, cmd->n_dep_vars,
590 input = casereader_create_filter_missing (input,
591 cmd->factor_vars, cmd->n_factor_vars,
595 ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
598 cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
599 ws.cats, cmd->wv, cmd->exclude, true);
602 c = casereader_peek (input, 0);
605 casereader_destroy (input);
608 output_split_file_values (ds, c);
611 taint = taint_clone (casereader_get_taint (input));
613 ws.totals = moments_create (MOMENT_VARIANCE);
615 for (reader = casereader_clone (input);
616 (c = casereader_read (reader)) != NULL; case_unref (c))
618 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
620 for (v = 0; v < cmd->n_dep_vars; ++v)
621 moments_pass_one (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
623 covariance_accumulate_pass1 (cov, c);
625 casereader_destroy (reader);
627 if (cmd->dump_coding)
628 reader = casereader_clone (input);
633 (c = casereader_read (reader)) != NULL; case_unref (c))
635 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
637 for (v = 0; v < cmd->n_dep_vars; ++v)
638 moments_pass_two (ws.totals, case_num (c, cmd->dep_vars[v]), weight);
640 covariance_accumulate_pass2 (cov, c);
642 casereader_destroy (reader);
645 if (cmd->dump_coding)
647 struct pivot_table *t = covariance_dump_enc_header (cov);
649 (c = casereader_read (reader)) != NULL; case_unref (c))
651 covariance_dump_enc (cov, c, t);
654 pivot_table_submit (t);
658 const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
659 gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
660 gsl_matrix_memcpy (cm, ucm);
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);
689 gsl_matrix_free (cm);
692 if (!taint_has_tainted_successor (taint))
693 output_glm (cmd, &ws);
695 gsl_vector_free (ws.ssq);
697 covariance_destroy (cov);
698 moments_destroy (ws.totals);
700 taint_destroy (taint);
704 put_glm_row (struct pivot_table *table, int row,
705 double a, double b, double c, double d, double e)
707 double entries[] = { a, b, c, d, e };
709 for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
710 if (entries[col] != SYSMIS)
711 pivot_table_put2 (table, col, row,
712 pivot_value_new_number (entries[col]));
716 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
718 struct pivot_table *table = pivot_table_create (
719 N_("Tests of Between-Subjects Effects"));
721 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
722 (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
723 : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
724 : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
725 N_("df"), PIVOT_RC_COUNT,
726 N_("Mean Square"), PIVOT_RC_OTHER,
727 N_("F"), PIVOT_RC_OTHER,
728 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
730 struct pivot_dimension *source = pivot_dimension_create (
731 table, PIVOT_AXIS_ROW, N_("Source"),
732 cmd->intercept ? N_("Corrected Model") : N_("Model"));
734 double n_total, mean;
735 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
737 double df_corr = 1.0 + categoricals_df_total (ws->cats);
739 double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
740 double intercept_ssq = pow2 (mean * n_total) / n_total;
743 int row = pivot_category_create_leaf (
744 source->root, pivot_value_new_text (N_("Intercept")));
746 /* The intercept for unbalanced models is of limited use and
747 nobody knows how to calculate it properly */
748 if (categoricals_isbalanced (ws->cats))
750 const double df = 1.0;
751 const double F = intercept_ssq / df / mse;
752 put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
753 F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
757 double ssq_effects = 0.0;
758 for (int f = 0; f < cmd->n_interactions; ++f)
760 double df = categoricals_df (ws->cats, f);
761 double ssq = gsl_vector_get (ws->ssq, f + 1);
766 ssq += intercept_ssq;
768 double F = ssq / df / mse;
770 struct string str = DS_EMPTY_INITIALIZER;
771 interaction_to_string (cmd->interactions[f], &str);
772 int row = pivot_category_create_leaf (
773 source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
775 put_glm_row (table, row, ssq, df, ssq / df, F,
776 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
780 /* Model / Corrected Model */
782 double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
786 ssq += intercept_ssq;
787 double F = ssq / df / mse;
788 put_glm_row (table, 0, ssq, df, ssq / df, F,
789 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
793 int row = pivot_category_create_leaf (source->root,
794 pivot_value_new_text (N_("Error")));
795 const double df = n_total - df_corr;
796 const double ssq = gsl_vector_get (ws->ssq, 0);
797 const double mse = ssq / df;
798 put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
802 int row = pivot_category_create_leaf (source->root,
803 pivot_value_new_text (N_("Total")));
804 put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
805 SYSMIS, SYSMIS, SYSMIS);
810 int row = pivot_category_create_leaf (
811 source->root, pivot_value_new_text (N_("Corrected Total")));
812 put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
816 pivot_table_submit (table);
821 dump_matrix (const gsl_matrix * m)
824 for (i = 0; i < m->size1; ++i)
826 for (j = 0; j < m->size2; ++j)
828 double x = gsl_matrix_get (m, i, j);
840 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
842 const struct variable *v = NULL;
843 if (! lex_match_variable (lexer, glm->dict, &v))
846 if (lex_match (lexer, T_LPAREN))
848 if (! parse_nested_variable (lexer, glm))
851 if (! lex_force_match (lexer, T_RPAREN))
855 lex_error (lexer, "Nested variables are not yet implemented");
859 /* A design term is an interaction OR a nested variable */
861 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
863 struct interaction *iact = NULL;
864 if (parse_design_interaction (lexer, glm->dict, &iact))
866 /* Interaction parsing successful. Add to list of interactions */
867 glm->interactions = xrealloc (glm->interactions, sizeof (*glm->interactions) * ++glm->n_interactions);
868 glm->interactions[glm->n_interactions - 1] = iact;
872 if (parse_nested_variable (lexer, glm))
880 /* Parse a complete DESIGN specification.
881 A design spec is a design term, optionally followed by a comma,
882 and another design spec.
885 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
887 if (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
890 if (! parse_design_term (lexer, glm))
893 lex_match (lexer, T_COMMA);
895 return parse_design_spec (lexer, glm);