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 (lexer))
267 lex_error (lexer, NULL);
271 glm.ss_type = lex_integer (lexer);
272 if (1 > glm.ss_type || 3 < glm.ss_type)
274 msg (ME, _("Only types 1, 2 & 3 sums of squares are currently implemented"));
280 if (! lex_force_match (lexer, T_RPAREN))
282 lex_error (lexer, NULL);
286 else if (lex_match_id (lexer, "DESIGN"))
288 lex_match (lexer, T_EQUALS);
290 if (! parse_design_spec (lexer, &glm))
293 if (glm.n_interactions > 0)
296 else if (lex_match_id (lexer, "SHOWCODES"))
297 /* Undocumented debug option */
299 lex_match (lexer, T_EQUALS);
301 glm.dump_coding = true;
305 lex_error (lexer, NULL);
316 struct casegrouper *grouper;
317 struct casereader *group;
320 grouper = casegrouper_create_splits (proc_open (ds), glm.dict);
321 while (casegrouper_get_next_group (grouper, &group))
322 run_glm (&glm, group, ds);
323 ok = casegrouper_destroy (grouper);
324 ok = proc_commit (ds) && ok;
327 const_var_set_destroy (factors);
328 free (glm.factor_vars);
329 for (i = 0 ; i < glm.n_interactions; ++i)
330 interaction_destroy (glm.interactions[i]);
332 free (glm.interactions);
340 const_var_set_destroy (factors);
341 free (glm.factor_vars);
342 for (i = 0 ; i < glm.n_interactions; ++i)
343 interaction_destroy (glm.interactions[i]);
345 free (glm.interactions);
352 not_dropped (size_t j, const bool *ff)
358 fill_submatrix (const gsl_matrix * cov, gsl_matrix * submatrix, bool *dropped_f)
365 for (i = 0; i < cov->size1; i++)
367 if (not_dropped (i, dropped_f))
370 for (j = 0; j < cov->size2; j++)
372 if (not_dropped (j, dropped_f))
374 gsl_matrix_set (submatrix, n, m,
375 gsl_matrix_get (cov, i, j));
386 Type 1 sums of squares.
387 Populate SSQ with the Type 1 sums of squares according to COV
390 ssq_type1 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
392 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
395 bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
396 bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
397 const struct categoricals *cats = covariance_get_categoricals (cov);
399 size_t n_dropped_model = 0;
400 size_t n_dropped_submodel = 0;
402 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
405 n_dropped_submodel++;
406 model_dropped[i] = true;
407 submodel_dropped[i] = true;
410 for (k = 0; k < cmd->n_interactions; k++)
412 gsl_matrix *model_cov = NULL;
413 gsl_matrix *submodel_cov = NULL;
415 n_dropped_submodel = n_dropped_model;
416 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
418 submodel_dropped[i] = model_dropped[i];
421 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
423 const struct interaction * x =
424 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
426 if (x == cmd->interactions [k])
428 model_dropped[i] = false;
433 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
434 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
436 fill_submatrix (cm, model_cov, model_dropped);
437 fill_submatrix (cm, submodel_cov, submodel_dropped);
439 reg_sweep (model_cov, 0);
440 reg_sweep (submodel_cov, 0);
442 gsl_vector_set (ssq, k + 1,
443 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
446 gsl_matrix_free (model_cov);
447 gsl_matrix_free (submodel_cov);
450 free (model_dropped);
451 free (submodel_dropped);
455 Type 2 sums of squares.
456 Populate SSQ with the Type 2 sums of squares according to COV
459 ssq_type2 (struct covariance *cov, gsl_vector *ssq, const struct glm_spec *cmd)
461 const gsl_matrix *cm = covariance_calculate_unnormalized (cov);
464 bool *model_dropped = xcalloc (covariance_dim (cov), sizeof (*model_dropped));
465 bool *submodel_dropped = xcalloc (covariance_dim (cov), sizeof (*submodel_dropped));
466 const struct categoricals *cats = covariance_get_categoricals (cov);
468 for (k = 0; k < cmd->n_interactions; k++)
470 gsl_matrix *model_cov = NULL;
471 gsl_matrix *submodel_cov = NULL;
472 size_t n_dropped_model = 0;
473 size_t n_dropped_submodel = 0;
474 for (i = cmd->n_dep_vars; i < covariance_dim (cov); i++)
476 const struct interaction * x =
477 categoricals_get_interaction_by_subscript (cats, i - cmd->n_dep_vars);
479 model_dropped[i] = false;
480 submodel_dropped[i] = false;
481 if (interaction_is_subset (cmd->interactions [k], x))
483 assert (n_dropped_submodel < covariance_dim (cov));
484 n_dropped_submodel++;
485 submodel_dropped[i] = true;
487 if (cmd->interactions [k]->n_vars < x->n_vars)
489 assert (n_dropped_model < covariance_dim (cov));
491 model_dropped[i] = true;
496 model_cov = gsl_matrix_alloc (cm->size1 - n_dropped_model, cm->size2 - n_dropped_model);
497 submodel_cov = gsl_matrix_alloc (cm->size1 - n_dropped_submodel, cm->size2 - n_dropped_submodel);
499 fill_submatrix (cm, model_cov, model_dropped);
500 fill_submatrix (cm, submodel_cov, submodel_dropped);
502 reg_sweep (model_cov, 0);
503 reg_sweep (submodel_cov, 0);
505 gsl_vector_set (ssq, k + 1,
506 gsl_matrix_get (submodel_cov, 0, 0) - gsl_matrix_get (model_cov, 0, 0)
509 gsl_matrix_free (model_cov);
510 gsl_matrix_free (submodel_cov);
513 free (model_dropped);
514 free (submodel_dropped);
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 const 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);
575 //static void dump_matrix (const gsl_matrix *m);
578 run_glm (struct glm_spec *cmd, struct casereader *input,
579 const struct dataset *ds)
581 bool warn_bad_weight = true;
584 struct dictionary *dict = dataset_dict (ds);
585 struct casereader *reader;
588 struct glm_workspace ws;
589 struct covariance *cov;
591 input = casereader_create_filter_missing (input,
592 cmd->dep_vars, cmd->n_dep_vars,
596 input = casereader_create_filter_missing (input,
597 cmd->factor_vars, cmd->n_factor_vars,
601 ws.cats = categoricals_create (cmd->interactions, cmd->n_interactions,
604 cov = covariance_2pass_create (cmd->n_dep_vars, cmd->dep_vars,
605 ws.cats, cmd->wv, cmd->exclude, true);
608 c = casereader_peek (input, 0);
611 casereader_destroy (input);
614 output_split_file_values (ds, c);
617 taint = taint_clone (casereader_get_taint (input));
619 ws.totals = moments_create (MOMENT_VARIANCE);
621 for (reader = casereader_clone (input);
622 (c = casereader_read (reader)) != NULL; case_unref (c))
624 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
626 for (v = 0; v < cmd->n_dep_vars; ++v)
627 moments_pass_one (ws.totals, case_data (c, cmd->dep_vars[v])->f,
630 covariance_accumulate_pass1 (cov, c);
632 casereader_destroy (reader);
634 if (cmd->dump_coding)
635 reader = casereader_clone (input);
640 (c = casereader_read (reader)) != NULL; case_unref (c))
642 double weight = dict_get_case_weight (dict, c, &warn_bad_weight);
644 for (v = 0; v < cmd->n_dep_vars; ++v)
645 moments_pass_two (ws.totals, case_data (c, cmd->dep_vars[v])->f,
648 covariance_accumulate_pass2 (cov, c);
650 casereader_destroy (reader);
653 if (cmd->dump_coding)
655 struct pivot_table *t = covariance_dump_enc_header (cov);
657 (c = casereader_read (reader)) != NULL; case_unref (c))
659 covariance_dump_enc (cov, c, t);
662 pivot_table_submit (t);
666 const gsl_matrix *ucm = covariance_calculate_unnormalized (cov);
667 gsl_matrix *cm = gsl_matrix_alloc (ucm->size1, ucm->size2);
668 gsl_matrix_memcpy (cm, ucm);
672 ws.total_ssq = gsl_matrix_get (cm, 0, 0);
677 Store the overall SSE.
679 ws.ssq = gsl_vector_alloc (cm->size1);
680 gsl_vector_set (ws.ssq, 0, gsl_matrix_get (cm, 0, 0));
681 switch (cmd->ss_type)
684 ssq_type1 (cov, ws.ssq, cmd);
687 ssq_type2 (cov, ws.ssq, cmd);
690 ssq_type3 (cov, ws.ssq, cmd);
697 gsl_matrix_free (cm);
700 if (!taint_has_tainted_successor (taint))
701 output_glm (cmd, &ws);
703 gsl_vector_free (ws.ssq);
705 covariance_destroy (cov);
706 moments_destroy (ws.totals);
708 taint_destroy (taint);
712 put_glm_row (struct pivot_table *table, int row,
713 double a, double b, double c, double d, double e)
715 double entries[] = { a, b, c, d, e };
717 for (size_t col = 0; col < sizeof entries / sizeof *entries; col++)
718 if (entries[col] != SYSMIS)
719 pivot_table_put2 (table, col, row,
720 pivot_value_new_number (entries[col]));
724 output_glm (const struct glm_spec *cmd, const struct glm_workspace *ws)
726 struct pivot_table *table = pivot_table_create (
727 N_("Tests of Between-Subjects Effects"));
729 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
730 (cmd->ss_type == 1 ? N_("Type I Sum Of Squares")
731 : cmd->ss_type == 2 ? N_("Type II Sum Of Squares")
732 : N_("Type III Sum Of Squares")), PIVOT_RC_OTHER,
733 N_("df"), PIVOT_RC_COUNT,
734 N_("Mean Square"), PIVOT_RC_OTHER,
735 N_("F"), PIVOT_RC_OTHER,
736 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
738 struct pivot_dimension *source = pivot_dimension_create (
739 table, PIVOT_AXIS_ROW, N_("Source"),
740 cmd->intercept ? N_("Corrected Model") : N_("Model"));
742 double n_total, mean;
743 moments_calculate (ws->totals, &n_total, &mean, NULL, NULL, NULL);
745 double df_corr = 1.0 + categoricals_df_total (ws->cats);
747 double mse = gsl_vector_get (ws->ssq, 0) / (n_total - df_corr);
748 double intercept_ssq = pow2 (mean * n_total) / n_total;
751 int row = pivot_category_create_leaf (
752 source->root, pivot_value_new_text (N_("Intercept")));
754 /* The intercept for unbalanced models is of limited use and
755 nobody knows how to calculate it properly */
756 if (categoricals_isbalanced (ws->cats))
758 const double df = 1.0;
759 const double F = intercept_ssq / df / mse;
760 put_glm_row (table, row, intercept_ssq, 1.0, intercept_ssq / df,
761 F, gsl_cdf_fdist_Q (F, df, n_total - df_corr));
765 double ssq_effects = 0.0;
766 for (int f = 0; f < cmd->n_interactions; ++f)
768 double df = categoricals_df (ws->cats, f);
769 double ssq = gsl_vector_get (ws->ssq, f + 1);
774 ssq += intercept_ssq;
776 double F = ssq / df / mse;
778 struct string str = DS_EMPTY_INITIALIZER;
779 interaction_to_string (cmd->interactions[f], &str);
780 int row = pivot_category_create_leaf (
781 source->root, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
783 put_glm_row (table, row, ssq, df, ssq / df, F,
784 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
788 /* Model / Corrected Model */
790 double ssq = ws->total_ssq - gsl_vector_get (ws->ssq, 0);
794 ssq += intercept_ssq;
795 double F = ssq / df / mse;
796 put_glm_row (table, 0, ssq, df, ssq / df, F,
797 gsl_cdf_fdist_Q (F, df, n_total - df_corr));
801 int row = pivot_category_create_leaf (source->root,
802 pivot_value_new_text (N_("Error")));
803 const double df = n_total - df_corr;
804 const double ssq = gsl_vector_get (ws->ssq, 0);
805 const double mse = ssq / df;
806 put_glm_row (table, row, ssq, df, mse, SYSMIS, SYSMIS);
810 int row = pivot_category_create_leaf (source->root,
811 pivot_value_new_text (N_("Total")));
812 put_glm_row (table, row, ws->total_ssq + intercept_ssq, n_total,
813 SYSMIS, SYSMIS, SYSMIS);
818 int row = pivot_category_create_leaf (
819 source->root, pivot_value_new_text (N_("Corrected Total")));
820 put_glm_row (table, row, ws->total_ssq, n_total - 1.0, SYSMIS,
824 pivot_table_submit (table);
829 dump_matrix (const gsl_matrix * m)
832 for (i = 0; i < m->size1; ++i)
834 for (j = 0; j < m->size2; ++j)
836 double x = gsl_matrix_get (m, i, j);
848 parse_nested_variable (struct lexer *lexer, struct glm_spec *glm)
850 const struct variable *v = NULL;
851 if (! lex_match_variable (lexer, glm->dict, &v))
854 if (lex_match (lexer, T_LPAREN))
856 if (! parse_nested_variable (lexer, glm))
859 if (! lex_force_match (lexer, T_RPAREN))
863 lex_error (lexer, "Nested variables are not yet implemented"); return false;
867 /* A design term is an interaction OR a nested variable */
869 parse_design_term (struct lexer *lexer, struct glm_spec *glm)
871 struct interaction *iact = NULL;
872 if (parse_design_interaction (lexer, glm->dict, &iact))
874 /* Interaction parsing successful. Add to list of interactions */
875 glm->interactions = xrealloc (glm->interactions, sizeof *glm->interactions * ++glm->n_interactions);
876 glm->interactions[glm->n_interactions - 1] = iact;
880 if (parse_nested_variable (lexer, glm))
888 /* Parse a complete DESIGN specification.
889 A design spec is a design term, optionally followed by a comma,
890 and another design spec.
893 parse_design_spec (struct lexer *lexer, struct glm_spec *glm)
895 if (lex_token (lexer) == T_ENDCMD || lex_token (lexer) == T_SLASH)
898 if (! parse_design_term (lexer, glm))
901 lex_match (lexer, T_COMMA);
903 return parse_design_spec (lexer, glm);