1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2005, 2009, 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/>. */
21 #include <gsl/gsl_cdf.h>
22 #include <gsl/gsl_matrix.h>
24 #include <data/dataset.h>
26 #include "language/command.h"
27 #include "language/lexer/lexer.h"
28 #include "language/lexer/value-parser.h"
29 #include "language/lexer/variable-parser.h"
32 #include "data/casegrouper.h"
33 #include "data/casereader.h"
34 #include "data/dictionary.h"
36 #include "math/covariance.h"
37 #include "math/linreg.h"
38 #include "math/moments.h"
40 #include "libpspp/message.h"
41 #include "libpspp/taint.h"
43 #include "output/tab.h"
46 #define _(msgid) gettext (msgid)
47 #define N_(msgid) msgid
50 #include <gl/intprops.h>
52 #define REG_LARGE_DATA 1000
58 const struct variable **vars;
61 const struct variable **dep_vars;
77 static void run_regression (const struct regression *cmd, struct casereader *input);
82 Transformations for saving predicted values
87 int n_trns; /* Number of transformations. */
88 int trns_id; /* Which trns is this one? */
89 linreg *c; /* Linear model for this trns. */
93 Gets the predicted values.
96 regression_trns_pred_proc (void *t_, struct ccase **c,
97 casenumber case_idx UNUSED)
101 struct reg_trns *trns = t_;
103 union value *output = NULL;
104 const union value *tmp;
106 const struct variable **vars = NULL;
108 assert (trns != NULL);
110 assert (model != NULL);
111 assert (model->depvar != NULL);
112 assert (model->pred != NULL);
114 vars = linreg_get_vars (model);
115 n_vals = linreg_n_coeffs (model);
116 vals = xnmalloc (n_vals, sizeof (*vals));
117 *c = case_unshare (*c);
119 output = case_data_rw (*c, model->pred);
121 for (i = 0; i < n_vals; i++)
123 tmp = case_data (*c, vars[i]);
126 output->f = linreg_predict (model, vals, n_vals);
128 return TRNS_CONTINUE;
135 regression_trns_resid_proc (void *t_, struct ccase **c,
136 casenumber case_idx UNUSED)
140 struct reg_trns *trns = t_;
142 union value *output = NULL;
143 const union value *tmp;
146 const struct variable **vars = NULL;
148 assert (trns != NULL);
150 assert (model != NULL);
151 assert (model->depvar != NULL);
152 assert (model->resid != NULL);
154 vars = linreg_get_vars (model);
155 n_vals = linreg_n_coeffs (model);
157 vals = xnmalloc (n_vals, sizeof (*vals));
158 *c = case_unshare (*c);
159 output = case_data_rw (*c, model->resid);
160 assert (output != NULL);
162 for (i = 0; i < n_vals; i++)
164 tmp = case_data (*c, vars[i]);
167 tmp = case_data (*c, model->depvar);
169 output->f = linreg_residual (model, obs, vals, n_vals);
172 return TRNS_CONTINUE;
177 reg_get_name (const struct dictionary *dict, const char *prefix)
182 /* XXX handle too-long prefixes */
183 name = xmalloc (strlen (prefix) + INT_BUFSIZE_BOUND (i) + 1);
186 sprintf (name, "%s%d", prefix, i);
187 if (dict_lookup_var (dict, name) == NULL)
193 Free the transformation. Free its linear model if this
194 transformation is the last one.
197 regression_trns_free (void *t_)
200 struct reg_trns *t = t_;
202 if (t->trns_id == t->n_trns)
204 result = linreg_free (t->c);
212 reg_save_var (struct dataset *ds, const char *prefix, trns_proc_func * f,
213 linreg * c, struct variable **v, int n_trns)
215 struct dictionary *dict = dataset_dict (ds);
216 static int trns_index = 1;
218 struct variable *new_var;
219 struct reg_trns *t = NULL;
221 t = xmalloc (sizeof (*t));
222 t->trns_id = trns_index;
226 name = reg_get_name (dict, prefix);
227 new_var = dict_create_var_assert (dict, name, 0);
231 add_transformation (ds, f, regression_trns_free, t);
236 subcommand_save (const struct regression *cmd)
241 if ( cmd->resid ) n_trns++;
242 if ( cmd->pred ) n_trns++;
244 n_trns *= cmd->n_dep_vars;
246 for (lc = cmd->models; lc < cmd->models + cmd->n_dep_vars; lc++)
250 if ((*lc)->depvar != NULL)
254 reg_save_var (cmd->ds, "RES", regression_trns_resid_proc, *lc,
255 &(*lc)->resid, n_trns);
259 reg_save_var (cmd->ds, "PRED", regression_trns_pred_proc, *lc,
260 &(*lc)->pred, n_trns);
268 cmd_regression (struct lexer *lexer, struct dataset *ds)
270 struct regression regression;
271 const struct dictionary *dict = dataset_dict (ds);
273 memset (®ression, 0, sizeof (struct regression));
275 regression.anova = true;
276 regression.coeff = true;
279 regression.pred = false;
280 regression.resid = false;
284 /* Accept an optional, completely pointless "/VARIABLES=" */
285 lex_match (lexer, T_SLASH);
286 if (lex_match_id (lexer, "VARIABLES"))
288 if (! lex_force_match (lexer, T_EQUALS) )
292 if (!parse_variables_const (lexer, dict,
293 ®ression.vars, ®ression.n_vars,
294 PV_NO_DUPLICATE | PV_NUMERIC))
298 while (lex_token (lexer) != T_ENDCMD)
300 lex_match (lexer, T_SLASH);
302 if (lex_match_id (lexer, "DEPENDENT"))
304 if (! lex_force_match (lexer, T_EQUALS) )
307 if (!parse_variables_const (lexer, dict,
308 ®ression.dep_vars, ®ression.n_dep_vars,
309 PV_NO_DUPLICATE | PV_NUMERIC))
312 else if (lex_match_id (lexer, "METHOD"))
314 lex_match (lexer, T_EQUALS);
316 if (!lex_force_match_id (lexer, "ENTER"))
321 else if (lex_match_id (lexer, "STATISTICS"))
323 lex_match (lexer, T_EQUALS);
325 while (lex_token (lexer) != T_ENDCMD
326 && lex_token (lexer) != T_SLASH)
328 if (lex_match (lexer, T_ALL))
331 else if (lex_match_id (lexer, "DEFAULTS"))
334 else if (lex_match_id (lexer, "R"))
337 else if (lex_match_id (lexer, "COEFF"))
340 else if (lex_match_id (lexer, "ANOVA"))
343 else if (lex_match_id (lexer, "BCOV"))
348 lex_error (lexer, NULL);
353 else if (lex_match_id (lexer, "SAVE"))
355 lex_match (lexer, T_EQUALS);
357 while (lex_token (lexer) != T_ENDCMD
358 && lex_token (lexer) != T_SLASH)
360 if (lex_match_id (lexer, "PRED"))
362 regression.pred = true;
364 else if (lex_match_id (lexer, "RESID"))
366 regression.resid = true;
370 lex_error (lexer, NULL);
377 lex_error (lexer, NULL);
382 if (!regression.vars)
384 dict_get_vars (dict, ®ression.vars, ®ression.n_vars, 0);
388 regression.models = xcalloc (regression.n_dep_vars, sizeof *regression.models);
391 struct casegrouper *grouper;
392 struct casereader *group;
395 grouper = casegrouper_create_splits (proc_open (ds), dict);
396 while (casegrouper_get_next_group (grouper, &group))
397 run_regression (®ression, group);
398 ok = casegrouper_destroy (grouper);
399 ok = proc_commit (ds) && ok;
402 if (regression.pred || regression.resid )
403 subcommand_save (®ression);
406 free (regression.models);
407 free (regression.vars);
408 free (regression.dep_vars);
412 free (regression.models);
413 free (regression.vars);
414 free (regression.dep_vars);
420 get_n_all_vars (const struct regression *cmd)
422 size_t result = cmd->n_vars;
426 result += cmd->n_dep_vars;
427 for (i = 0; i < cmd->n_dep_vars; i++)
429 for (j = 0; j < cmd->n_vars; j++)
431 if (cmd->vars[j] == cmd->dep_vars[i])
441 fill_all_vars (const struct variable **vars, const struct regression *cmd)
447 for (i = 0; i < cmd->n_vars; i++)
449 vars[i] = cmd->vars[i];
451 for (i = 0; i < cmd->n_dep_vars; i++)
454 for (j = 0; j < cmd->n_vars; j++)
456 if (cmd->dep_vars[i] == cmd->vars[j])
464 vars[i + cmd->n_vars] = cmd->dep_vars[i];
470 Is variable k the dependent variable?
473 is_depvar (const struct regression *cmd, size_t k, const struct variable *v)
475 return v == cmd->vars[k];
479 /* Identify the explanatory variables in v_variables. Returns
480 the number of independent variables. */
482 identify_indep_vars (const struct regression *cmd,
483 const struct variable **indep_vars,
484 const struct variable *depvar)
486 int n_indep_vars = 0;
489 for (i = 0; i < cmd->n_vars; i++)
490 if (!is_depvar (cmd, i, depvar))
491 indep_vars[n_indep_vars++] = cmd->vars[i];
492 if ((n_indep_vars < 1) && is_depvar (cmd, 0, depvar))
495 There is only one independent variable, and it is the same
496 as the dependent variable. Print a warning and continue.
499 gettext ("The dependent variable is equal to the independent variable."
500 "The least squares line is therefore Y=X."
501 "Standard errors and related statistics may be meaningless."));
503 indep_vars[0] = cmd->vars[0];
510 fill_covariance (gsl_matrix *cov, struct covariance *all_cov,
511 const struct variable **vars,
512 size_t n_vars, const struct variable *dep_var,
513 const struct variable **all_vars, size_t n_all_vars,
518 size_t dep_subscript;
520 const gsl_matrix *ssizes;
521 const gsl_matrix *mean_matrix;
522 const gsl_matrix *ssize_matrix;
525 gsl_matrix *cm = covariance_calculate_unnormalized (all_cov);
530 rows = xnmalloc (cov->size1 - 1, sizeof (*rows));
532 for (i = 0; i < n_all_vars; i++)
534 for (j = 0; j < n_vars; j++)
536 if (vars[j] == all_vars[i])
541 if (all_vars[i] == dep_var)
546 mean_matrix = covariance_moments (all_cov, MOMENT_MEAN);
547 ssize_matrix = covariance_moments (all_cov, MOMENT_NONE);
548 for (i = 0; i < cov->size1 - 1; i++)
550 means[i] = gsl_matrix_get (mean_matrix, rows[i], 0)
551 / gsl_matrix_get (ssize_matrix, rows[i], 0);
552 for (j = 0; j < cov->size2 - 1; j++)
554 gsl_matrix_set (cov, i, j, gsl_matrix_get (cm, rows[i], rows[j]));
555 gsl_matrix_set (cov, j, i, gsl_matrix_get (cm, rows[j], rows[i]));
558 means[cov->size1 - 1] = gsl_matrix_get (mean_matrix, dep_subscript, 0)
559 / gsl_matrix_get (ssize_matrix, dep_subscript, 0);
560 ssizes = covariance_moments (all_cov, MOMENT_NONE);
561 result = gsl_matrix_get (ssizes, dep_subscript, rows[0]);
562 for (i = 0; i < cov->size1 - 1; i++)
564 gsl_matrix_set (cov, i, cov->size1 - 1,
565 gsl_matrix_get (cm, rows[i], dep_subscript));
566 gsl_matrix_set (cov, cov->size1 - 1, i,
567 gsl_matrix_get (cm, rows[i], dep_subscript));
568 if (result > gsl_matrix_get (ssizes, rows[i], dep_subscript))
570 result = gsl_matrix_get (ssizes, rows[i], dep_subscript);
573 gsl_matrix_set (cov, cov->size1 - 1, cov->size1 - 1,
574 gsl_matrix_get (cm, dep_subscript, dep_subscript));
576 gsl_matrix_free (cm);
582 STATISTICS subcommand output functions.
584 static void reg_stats_r (linreg *, void *);
585 static void reg_stats_coeff (linreg *, void *);
586 static void reg_stats_anova (linreg *, void *);
587 static void reg_stats_bcov (linreg *, void *);
589 static void statistics_keyword_output (void (*)(linreg *, void *),
590 bool, linreg *, void *);
595 subcommand_statistics (const struct regression *cmd , linreg * c, void *aux)
597 statistics_keyword_output (reg_stats_r, cmd->r, c, aux);
598 statistics_keyword_output (reg_stats_anova, cmd->anova, c, aux);
599 statistics_keyword_output (reg_stats_coeff, cmd->coeff, c, aux);
600 statistics_keyword_output (reg_stats_bcov, cmd->bcov, c, aux);
605 run_regression (const struct regression *cmd, struct casereader *input)
612 struct covariance *cov;
613 const struct variable **vars;
614 const struct variable **all_vars;
615 const struct variable *dep_var;
616 struct casereader *reader;
619 linreg **models = cmd->models;
621 n_all_vars = get_n_all_vars (cmd);
622 all_vars = xnmalloc (n_all_vars, sizeof (*all_vars));
623 fill_all_vars (all_vars, cmd);
624 vars = xnmalloc (cmd->n_vars, sizeof (*vars));
625 means = xnmalloc (n_all_vars, sizeof (*means));
626 cov = covariance_1pass_create (n_all_vars, all_vars,
627 dict_get_weight (dataset_dict (cmd->ds)), MV_ANY);
629 reader = casereader_clone (input);
630 reader = casereader_create_filter_missing (reader, all_vars, n_all_vars,
634 for (; (c = casereader_read (reader)) != NULL; case_unref (c))
636 covariance_accumulate (cov, c);
639 for (k = 0; k < cmd->n_dep_vars; k++)
644 dep_var = cmd->dep_vars[k];
645 n_indep = identify_indep_vars (cmd, vars, dep_var);
647 this_cm = gsl_matrix_alloc (n_indep + 1, n_indep + 1);
648 n_data = fill_covariance (this_cm, cov, vars, n_indep,
649 dep_var, all_vars, n_all_vars, means);
650 models[k] = linreg_alloc (dep_var, (const struct variable **) vars,
652 models[k]->depvar = dep_var;
653 for (i = 0; i < n_indep; i++)
655 linreg_set_indep_variable_mean (models[k], i, means[i]);
657 linreg_set_depvar_mean (models[k], means[i]);
659 For large data sets, use QR decomposition.
661 if (n_data > sqrt (n_indep) && n_data > REG_LARGE_DATA)
663 models[k]->method = LINREG_QR;
669 Find the least-squares estimates and other statistics.
671 linreg_fit (this_cm, models[k]);
673 if (!taint_has_tainted_successor (casereader_get_taint (input)))
675 subcommand_statistics (cmd, models[k], this_cm);
681 _("No valid data found. This command was skipped."));
682 linreg_free (models[k]);
685 gsl_matrix_free (this_cm);
688 casereader_destroy (reader);
692 casereader_destroy (input);
693 covariance_destroy (cov);
701 reg_stats_r (linreg *c, void *aux UNUSED)
711 rsq = linreg_ssreg (c) / linreg_sst (c);
712 adjrsq = 1.0 - (1.0 - rsq) * (linreg_n_obs (c) - 1.0) / (linreg_n_obs (c) - linreg_n_coeffs (c));
713 std_error = sqrt (linreg_mse (c));
714 t = tab_create (n_cols, n_rows);
715 tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
716 tab_hline (t, TAL_2, 0, n_cols - 1, 1);
717 tab_vline (t, TAL_2, 2, 0, n_rows - 1);
718 tab_vline (t, TAL_0, 1, 0, 0);
720 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("R"));
721 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("R Square"));
722 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Adjusted R Square"));
723 tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Std. Error of the Estimate"));
724 tab_double (t, 1, 1, TAB_RIGHT, sqrt (rsq), NULL);
725 tab_double (t, 2, 1, TAB_RIGHT, rsq, NULL);
726 tab_double (t, 3, 1, TAB_RIGHT, adjrsq, NULL);
727 tab_double (t, 4, 1, TAB_RIGHT, std_error, NULL);
728 tab_title (t, _("Model Summary"));
733 Table showing estimated regression coefficients.
736 reg_stats_coeff (linreg * c, void *aux_)
748 const struct variable *v;
750 gsl_matrix *cov = aux_;
753 n_rows = linreg_n_coeffs (c) + 3;
755 t = tab_create (n_cols, n_rows);
756 tab_headers (t, 2, 0, 1, 0);
757 tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
758 tab_hline (t, TAL_2, 0, n_cols - 1, 1);
759 tab_vline (t, TAL_2, 2, 0, n_rows - 1);
760 tab_vline (t, TAL_0, 1, 0, 0);
762 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("B"));
763 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Std. Error"));
764 tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Beta"));
765 tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("t"));
766 tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
767 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("(Constant)"));
768 tab_double (t, 2, 1, 0, linreg_intercept (c), NULL);
769 std_err = sqrt (gsl_matrix_get (linreg_cov (c), 0, 0));
770 tab_double (t, 3, 1, 0, std_err, NULL);
771 tab_double (t, 4, 1, 0, 0.0, NULL);
772 t_stat = linreg_intercept (c) / std_err;
773 tab_double (t, 5, 1, 0, t_stat, NULL);
774 pval = 2 * gsl_cdf_tdist_Q (fabs (t_stat), (double) (linreg_n_obs (c) - linreg_n_coeffs (c)));
775 tab_double (t, 6, 1, 0, pval, NULL);
776 for (j = 0; j < linreg_n_coeffs (c); j++)
779 ds_init_empty (&tstr);
782 v = linreg_indep_var (c, j);
783 label = var_to_string (v);
784 /* Do not overwrite the variable's name. */
785 ds_put_cstr (&tstr, label);
786 tab_text (t, 1, this_row, TAB_CENTER, ds_cstr (&tstr));
788 Regression coefficients.
790 tab_double (t, 2, this_row, 0, linreg_coeff (c, j), NULL);
792 Standard error of the coefficients.
794 std_err = sqrt (gsl_matrix_get (linreg_cov (c), j + 1, j + 1));
795 tab_double (t, 3, this_row, 0, std_err, NULL);
797 Standardized coefficient, i.e., regression coefficient
798 if all variables had unit variance.
800 beta = sqrt (gsl_matrix_get (cov, j, j));
801 beta *= linreg_coeff (c, j) /
802 sqrt (gsl_matrix_get (cov, cov->size1 - 1, cov->size2 - 1));
803 tab_double (t, 4, this_row, 0, beta, NULL);
806 Test statistic for H0: coefficient is 0.
808 t_stat = linreg_coeff (c, j) / std_err;
809 tab_double (t, 5, this_row, 0, t_stat, NULL);
811 P values for the test statistic above.
814 2 * gsl_cdf_tdist_Q (fabs (t_stat),
815 (double) (linreg_n_obs (c) - linreg_n_coeffs (c)));
816 tab_double (t, 6, this_row, 0, pval, NULL);
819 tab_title (t, _("Coefficients"));
824 Display the ANOVA table.
827 reg_stats_anova (linreg * c, void *aux UNUSED)
831 const double msm = linreg_ssreg (c) / linreg_dfmodel (c);
832 const double mse = linreg_mse (c);
833 const double F = msm / mse;
834 const double pval = gsl_cdf_fdist_Q (F, c->dfm, c->dfe);
839 t = tab_create (n_cols, n_rows);
840 tab_headers (t, 2, 0, 1, 0);
842 tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
844 tab_hline (t, TAL_2, 0, n_cols - 1, 1);
845 tab_vline (t, TAL_2, 2, 0, n_rows - 1);
846 tab_vline (t, TAL_0, 1, 0, 0);
848 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Sum of Squares"));
849 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df"));
850 tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
851 tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("F"));
852 tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
854 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Regression"));
855 tab_text (t, 1, 2, TAB_LEFT | TAT_TITLE, _("Residual"));
856 tab_text (t, 1, 3, TAB_LEFT | TAT_TITLE, _("Total"));
858 /* Sums of Squares */
859 tab_double (t, 2, 1, 0, linreg_ssreg (c), NULL);
860 tab_double (t, 2, 3, 0, linreg_sst (c), NULL);
861 tab_double (t, 2, 2, 0, linreg_sse (c), NULL);
864 /* Degrees of freedom */
865 tab_text_format (t, 3, 1, TAB_RIGHT, "%g", c->dfm);
866 tab_text_format (t, 3, 2, TAB_RIGHT, "%g", c->dfe);
867 tab_text_format (t, 3, 3, TAB_RIGHT, "%g", c->dft);
870 tab_double (t, 4, 1, TAB_RIGHT, msm, NULL);
871 tab_double (t, 4, 2, TAB_RIGHT, mse, NULL);
873 tab_double (t, 5, 1, 0, F, NULL);
875 tab_double (t, 6, 1, 0, pval, NULL);
877 tab_title (t, _("ANOVA"));
883 reg_stats_bcov (linreg * c, void *aux UNUSED)
895 n_cols = c->n_indeps + 1 + 2;
896 n_rows = 2 * (c->n_indeps + 1);
897 t = tab_create (n_cols, n_rows);
898 tab_headers (t, 2, 0, 1, 0);
899 tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
900 tab_hline (t, TAL_2, 0, n_cols - 1, 1);
901 tab_vline (t, TAL_2, 2, 0, n_rows - 1);
902 tab_vline (t, TAL_0, 1, 0, 0);
903 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Model"));
904 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Covariances"));
905 for (i = 0; i < linreg_n_coeffs (c); i++)
907 const struct variable *v = linreg_indep_var (c, i);
908 label = var_to_string (v);
909 tab_text (t, 2, i, TAB_CENTER, label);
910 tab_text (t, i + 2, 0, TAB_CENTER, label);
911 for (k = 1; k < linreg_n_coeffs (c); k++)
913 col = (i <= k) ? k : i;
914 row = (i <= k) ? i : k;
915 tab_double (t, k + 2, i, TAB_CENTER,
916 gsl_matrix_get (c->cov, row, col), NULL);
919 tab_title (t, _("Coefficient Correlations"));
924 statistics_keyword_output (void (*function) (linreg *, void *),
925 bool keyword, linreg * c, void *aux)
929 (*function) (c, aux);