Replace regression.q with regression.c
[pspp] / src / language / stats / regression.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2005, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include <stdbool.h>
20
21 #include <gsl/gsl_cdf.h>
22 #include <gsl/gsl_matrix.h>
23
24 #include <data/dataset.h>
25
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"
30
31
32 #include "data/casegrouper.h"
33 #include "data/casereader.h"
34 #include "data/dictionary.h"
35
36 #include "math/covariance.h"
37 #include "math/linreg.h"
38 #include "math/moments.h"
39
40 #include "libpspp/message.h"
41 #include "libpspp/taint.h"
42
43 #include "output/tab.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47 #define N_(msgid) msgid
48
49
50 #include <gl/intprops.h>
51
52 #define REG_LARGE_DATA 1000
53
54 struct regression
55 {
56   struct dataset *ds;
57
58   const struct variable **vars;
59   size_t n_vars;
60
61   const struct variable **dep_vars;
62   size_t n_dep_vars;
63
64   bool r;
65   bool coeff;
66   bool anova;
67   bool bcov;
68
69
70   bool resid;
71   bool pred;
72
73   linreg **models;
74 };
75
76
77 static void run_regression (const struct regression *cmd, struct casereader *input);
78
79
80
81 /*
82   Transformations for saving predicted values
83   and residuals, etc.
84 */
85 struct reg_trns
86 {
87   int n_trns;                   /* Number of transformations. */
88   int trns_id;                  /* Which trns is this one? */
89   linreg *c;            /* Linear model for this trns. */
90 };
91
92 /*
93   Gets the predicted values.
94 */
95 static int
96 regression_trns_pred_proc (void *t_, struct ccase **c,
97                            casenumber case_idx UNUSED)
98 {
99   size_t i;
100   size_t n_vals;
101   struct reg_trns *trns = t_;
102   linreg *model;
103   union value *output = NULL;
104   const union value *tmp;
105   double *vals;
106   const struct variable **vars = NULL;
107
108   assert (trns != NULL);
109   model = trns->c;
110   assert (model != NULL);
111   assert (model->depvar != NULL);
112   assert (model->pred != NULL);
113
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);
118
119   output = case_data_rw (*c, model->pred);
120
121   for (i = 0; i < n_vals; i++)
122     {
123       tmp = case_data (*c, vars[i]);
124       vals[i] = tmp->f;
125     }
126   output->f = linreg_predict (model, vals, n_vals);
127   free (vals);
128   return TRNS_CONTINUE;
129 }
130
131 /*
132   Gets the residuals.
133 */
134 static int
135 regression_trns_resid_proc (void *t_, struct ccase **c,
136                             casenumber case_idx UNUSED)
137 {
138   size_t i;
139   size_t n_vals;
140   struct reg_trns *trns = t_;
141   linreg *model;
142   union value *output = NULL;
143   const union value *tmp;
144   double *vals = NULL;
145   double obs;
146   const struct variable **vars = NULL;
147
148   assert (trns != NULL);
149   model = trns->c;
150   assert (model != NULL);
151   assert (model->depvar != NULL);
152   assert (model->resid != NULL);
153
154   vars = linreg_get_vars (model);
155   n_vals = linreg_n_coeffs (model);
156
157   vals = xnmalloc (n_vals, sizeof (*vals));
158   *c = case_unshare (*c);
159   output = case_data_rw (*c, model->resid);
160   assert (output != NULL);
161
162   for (i = 0; i < n_vals; i++)
163     {
164       tmp = case_data (*c, vars[i]);
165       vals[i] = tmp->f;
166     }
167   tmp = case_data (*c, model->depvar);
168   obs = tmp->f;
169   output->f = linreg_residual (model, obs, vals, n_vals);
170   free (vals);
171
172   return TRNS_CONTINUE;
173 }
174
175
176 static char *
177 reg_get_name (const struct dictionary *dict, const char *prefix)
178 {
179   char *name;
180   int i;
181
182   /* XXX handle too-long prefixes */
183   name = xmalloc (strlen (prefix) + INT_BUFSIZE_BOUND (i) + 1);
184   for (i = 1; ; i++)
185     {
186       sprintf (name, "%s%d", prefix, i);
187       if (dict_lookup_var (dict, name) == NULL)
188         return name;
189     }
190 }
191
192 /*
193   Free the transformation. Free its linear model if this
194   transformation is the last one.
195 */
196 static bool
197 regression_trns_free (void *t_)
198 {
199   bool result = true;
200   struct reg_trns *t = t_;
201
202   if (t->trns_id == t->n_trns)
203     {
204       result = linreg_free (t->c);
205     }
206   free (t);
207
208   return result;
209 }
210
211 static void
212 reg_save_var (struct dataset *ds, const char *prefix, trns_proc_func * f,
213               linreg * c, struct variable **v, int n_trns)
214 {
215   struct dictionary *dict = dataset_dict (ds);
216   static int trns_index = 1;
217   char *name;
218   struct variable *new_var;
219   struct reg_trns *t = NULL;
220
221   t = xmalloc (sizeof (*t));
222   t->trns_id = trns_index;
223   t->n_trns = n_trns;
224   t->c = c;
225
226   name = reg_get_name (dict, prefix);
227   new_var = dict_create_var_assert (dict, name, 0);
228   free (name);
229
230   *v = new_var;
231   add_transformation (ds, f, regression_trns_free, t);
232   trns_index++;
233 }
234
235 static void
236 subcommand_save (const struct regression *cmd)
237 {
238   linreg **lc;
239   int n_trns = 0;
240
241   if ( cmd->resid ) n_trns++;
242   if ( cmd->pred ) n_trns++;
243
244   n_trns *= cmd->n_dep_vars;
245
246   for (lc = cmd->models; lc < cmd->models + cmd->n_dep_vars; lc++)
247     {
248       if (*lc != NULL)
249         {
250           if ((*lc)->depvar != NULL)
251             {
252               if (cmd->resid)
253                 {
254                   reg_save_var (cmd->ds, "RES", regression_trns_resid_proc, *lc,
255                                 &(*lc)->resid, n_trns);
256                 }
257               if (cmd->pred)
258                 {
259                   reg_save_var (cmd->ds, "PRED", regression_trns_pred_proc, *lc,
260                                 &(*lc)->pred, n_trns);
261                 }
262             }
263         }
264     }
265 }
266
267 int
268 cmd_regression (struct lexer *lexer, struct dataset *ds)
269 {
270   struct regression regression;
271   const struct dictionary *dict = dataset_dict (ds);
272
273   memset (&regression, 0, sizeof (struct regression));
274
275   regression.anova = true;
276   regression.coeff = true;
277   regression.r = true;
278
279   regression.pred = false;
280   regression.resid = false;
281
282   regression.ds = ds;
283
284   /* Accept an optional, completely pointless "/VARIABLES=" */
285   lex_match (lexer, T_SLASH);
286   if (lex_match_id  (lexer, "VARIABLES"))
287     {
288       if (! lex_force_match (lexer, T_EQUALS) )
289         goto error;
290     }
291
292   if (!parse_variables_const (lexer, dict,
293                               &regression.vars, &regression.n_vars,
294                               PV_NO_DUPLICATE | PV_NUMERIC))
295     goto error;
296
297
298   while (lex_token (lexer) != T_ENDCMD)
299     {
300       lex_match (lexer, T_SLASH);
301
302       if (lex_match_id  (lexer, "DEPENDENT"))
303         {
304           if (! lex_force_match (lexer, T_EQUALS) )
305             goto error;
306
307           if (!parse_variables_const (lexer, dict,
308                                       &regression.dep_vars, &regression.n_dep_vars,
309                                       PV_NO_DUPLICATE | PV_NUMERIC))
310             goto error;
311         }
312       else if (lex_match_id (lexer, "METHOD"))
313         {
314           lex_match (lexer, T_EQUALS);
315
316           if (!lex_force_match_id (lexer, "ENTER"))
317             {
318               goto error;
319             }
320         }
321       else if (lex_match_id (lexer, "STATISTICS"))
322         {
323           lex_match (lexer, T_EQUALS);
324
325           while (lex_token (lexer) != T_ENDCMD
326                  && lex_token (lexer) != T_SLASH)
327             {
328               if (lex_match (lexer, T_ALL))
329                 {
330                 }
331               else if (lex_match_id (lexer, "DEFAULTS"))
332                 {
333                 }
334               else if (lex_match_id (lexer, "R"))
335                 {
336                 }
337               else if (lex_match_id (lexer, "COEFF"))
338                 {
339                 }
340               else if (lex_match_id (lexer, "ANOVA"))
341                 {
342                 }
343               else if (lex_match_id (lexer, "BCOV"))
344                 {
345                 }
346               else
347                 {
348                   lex_error (lexer, NULL);
349                   goto error;
350                 }
351             }
352         }
353       else if (lex_match_id (lexer, "SAVE"))
354         {
355           lex_match (lexer, T_EQUALS);
356
357           while (lex_token (lexer) != T_ENDCMD
358                  && lex_token (lexer) != T_SLASH)
359             {
360               if (lex_match_id (lexer, "PRED"))
361                 {
362                   regression.pred = true;
363                 }
364               else if (lex_match_id (lexer, "RESID"))
365                 {
366                   regression.resid = true;
367                 }
368               else
369                 {
370                   lex_error (lexer, NULL);
371                   goto error;
372                 }
373             }
374         }
375       else
376         {
377           lex_error (lexer, NULL);
378           goto error;
379         }
380     }
381
382   if (!regression.vars)
383     {
384       dict_get_vars (dict, &regression.vars, &regression.n_vars, 0);
385     }
386
387
388   regression.models = xcalloc (regression.n_dep_vars, sizeof *regression.models);
389
390   {
391     struct casegrouper *grouper;
392     struct casereader *group;
393     bool ok;
394     
395     grouper = casegrouper_create_splits (proc_open (ds), dict);
396     while (casegrouper_get_next_group (grouper, &group))
397       run_regression (&regression, group);
398     ok = casegrouper_destroy (grouper);
399     ok = proc_commit (ds) && ok;
400   }
401
402   if (regression.pred || regression.resid )
403     subcommand_save (&regression);
404  
405
406   return CMD_SUCCESS;
407   
408  error:
409   return CMD_FAILURE;
410 }
411
412
413 static size_t
414 get_n_all_vars (const struct regression *cmd)
415 {
416   size_t result = cmd->n_vars;
417   size_t i;
418   size_t j;
419
420   result += cmd->n_dep_vars;
421   for (i = 0; i < cmd->n_dep_vars; i++)
422     {
423       for (j = 0; j < cmd->n_vars; j++)
424         {
425           if (cmd->vars[j] == cmd->dep_vars[i])
426             {
427               result--;
428             }
429         }
430     }
431   return result;
432 }
433
434 static void
435 fill_all_vars (const struct variable **vars, const struct regression *cmd)
436 {
437   size_t i;
438   size_t j;
439   bool absent;
440   
441   for (i = 0; i < cmd->n_vars; i++)
442     {
443       vars[i] = cmd->vars[i];
444     }
445   for (i = 0; i < cmd->n_dep_vars; i++)
446     {
447       absent = true;
448       for (j = 0; j < cmd->n_vars; j++)
449         {
450           if (cmd->dep_vars[i] == cmd->vars[j])
451             {
452               absent = false;
453               break;
454             }
455         }
456       if (absent)
457         {
458           vars[i + cmd->n_vars] = cmd->dep_vars[i];
459         }
460     }
461 }
462
463 /*
464   Is variable k the dependent variable?
465 */
466 static bool
467 is_depvar (const struct regression *cmd, size_t k, const struct variable *v)
468 {
469   return v == cmd->vars[k];
470 }
471
472
473 /* Identify the explanatory variables in v_variables.  Returns
474    the number of independent variables. */
475 static int
476 identify_indep_vars (const struct regression *cmd, 
477                      const struct variable **indep_vars,
478                      const struct variable *depvar)
479 {
480   int n_indep_vars = 0;
481   int i;
482
483   for (i = 0; i < cmd->n_vars; i++)
484     if (!is_depvar (cmd, i, depvar))
485       indep_vars[n_indep_vars++] = cmd->vars[i];
486   if ((n_indep_vars < 1) && is_depvar (cmd, 0, depvar))
487     {
488       /*
489         There is only one independent variable, and it is the same
490         as the dependent variable. Print a warning and continue.
491       */
492       msg (SE,
493            gettext ("The dependent variable is equal to the independent variable." 
494                     "The least squares line is therefore Y=X." 
495                     "Standard errors and related statistics may be meaningless."));
496       n_indep_vars = 1;
497       indep_vars[0] = cmd->vars[0];
498     }
499   return n_indep_vars;
500 }
501
502
503 static double
504 fill_covariance (gsl_matrix *cov, struct covariance *all_cov, 
505                  const struct variable **vars,
506                  size_t n_vars, const struct variable *dep_var, 
507                  const struct variable **all_vars, size_t n_all_vars,
508                  double *means)
509 {
510   size_t i;
511   size_t j;
512   size_t dep_subscript;
513   size_t *rows;
514   const gsl_matrix *ssizes;
515   const gsl_matrix *mean_matrix;
516   const gsl_matrix *ssize_matrix;
517   double result = 0.0;
518   
519   gsl_matrix *cm = covariance_calculate_unnormalized (all_cov);
520
521   if ( cm == NULL)
522     return 0;
523
524   rows = xnmalloc (cov->size1 - 1, sizeof (*rows));
525   
526   for (i = 0; i < n_all_vars; i++)
527     {
528       for (j = 0; j < n_vars; j++)
529         {
530           if (vars[j] == all_vars[i])
531             {
532               rows[j] = i;
533             }
534         }
535       if (all_vars[i] == dep_var)
536         {
537           dep_subscript = i;
538         }
539     }
540   mean_matrix = covariance_moments (all_cov, MOMENT_MEAN);
541   ssize_matrix = covariance_moments (all_cov, MOMENT_NONE);
542   for (i = 0; i < cov->size1 - 1; i++)
543     {
544       means[i] = gsl_matrix_get (mean_matrix, rows[i], 0)
545         / gsl_matrix_get (ssize_matrix, rows[i], 0);
546       for (j = 0; j < cov->size2 - 1; j++)
547         {
548           gsl_matrix_set (cov, i, j, gsl_matrix_get (cm, rows[i], rows[j]));
549           gsl_matrix_set (cov, j, i, gsl_matrix_get (cm, rows[j], rows[i]));
550         }
551     }
552   means[cov->size1 - 1] = gsl_matrix_get (mean_matrix, dep_subscript, 0)
553     / gsl_matrix_get (ssize_matrix, dep_subscript, 0);
554   ssizes = covariance_moments (all_cov, MOMENT_NONE);
555   result = gsl_matrix_get (ssizes, dep_subscript, rows[0]);
556   for (i = 0; i < cov->size1 - 1; i++)
557     {
558       gsl_matrix_set (cov, i, cov->size1 - 1, 
559                       gsl_matrix_get (cm, rows[i], dep_subscript));
560       gsl_matrix_set (cov, cov->size1 - 1, i, 
561                       gsl_matrix_get (cm, rows[i], dep_subscript));
562       if (result > gsl_matrix_get (ssizes, rows[i], dep_subscript))
563         {
564           result = gsl_matrix_get (ssizes, rows[i], dep_subscript);
565         }
566     }
567   gsl_matrix_set (cov, cov->size1 - 1, cov->size1 - 1, 
568                   gsl_matrix_get (cm, dep_subscript, dep_subscript));
569   free (rows);
570   gsl_matrix_free (cm);
571   return result;
572 }
573
574
575 /*
576   STATISTICS subcommand output functions.
577 */
578 static void reg_stats_r (linreg *, void *);
579 static void reg_stats_coeff (linreg *, void *);
580 static void reg_stats_anova (linreg *, void *);
581 static void reg_stats_bcov (linreg *, void *);
582
583 static void statistics_keyword_output (void (*)(linreg *, void *),
584                                        bool, linreg *, void *);
585
586
587
588 static void
589 subcommand_statistics (const struct regression *cmd , linreg * c, void *aux)
590 {
591   statistics_keyword_output (reg_stats_r, cmd->r, c, aux);
592   statistics_keyword_output (reg_stats_anova, cmd->anova, c, aux);
593   statistics_keyword_output (reg_stats_coeff, cmd->coeff, c, aux);
594   statistics_keyword_output (reg_stats_bcov, cmd->bcov, c, aux);
595 }
596
597
598 static void
599 run_regression (const struct regression *cmd, struct casereader *input)
600 {
601   size_t i;
602   int n_indep = 0;
603   int k;
604   double *means;
605   struct ccase *c;
606   struct covariance *cov;
607   const struct variable **vars;
608   const struct variable **all_vars;
609   const struct variable *dep_var;
610   struct casereader *reader;
611   size_t n_all_vars;
612
613   linreg **models = cmd->models;
614
615   n_all_vars = get_n_all_vars (cmd);
616   all_vars = xnmalloc (n_all_vars, sizeof (*all_vars));
617   fill_all_vars (all_vars, cmd);
618   vars = xnmalloc (cmd->n_vars, sizeof (*vars));
619   means  = xnmalloc (n_all_vars, sizeof (*means));
620   cov = covariance_1pass_create (n_all_vars, all_vars,
621                                  dict_get_weight (dataset_dict (cmd->ds)), MV_ANY);
622
623   reader = casereader_clone (input);
624   reader = casereader_create_filter_missing (reader, all_vars, n_all_vars,
625                                              MV_ANY, NULL, NULL);
626
627
628   for (; (c = casereader_read (reader)) != NULL; case_unref (c))
629     {
630       covariance_accumulate (cov, c);
631     }
632
633   for (k = 0; k < cmd->n_dep_vars; k++)
634     {
635       double n_data;
636
637       gsl_matrix *this_cm;
638       dep_var = cmd->dep_vars[k];
639       n_indep = identify_indep_vars (cmd, vars, dep_var);
640       
641       this_cm = gsl_matrix_alloc (n_indep + 1, n_indep + 1);
642       n_data = fill_covariance (this_cm, cov, vars, n_indep, 
643                                 dep_var, all_vars, n_all_vars, means);
644       models[k] = linreg_alloc (dep_var, (const struct variable **) vars,
645                                 n_data, n_indep);
646       models[k]->depvar = dep_var;
647       for (i = 0; i < n_indep; i++)
648         {
649           linreg_set_indep_variable_mean (models[k], i, means[i]);
650         }
651       linreg_set_depvar_mean (models[k], means[i]);
652       /*
653         For large data sets, use QR decomposition.
654       */
655       if (n_data > sqrt (n_indep) && n_data > REG_LARGE_DATA)
656         {
657           models[k]->method = LINREG_QR;
658         }
659
660       if (n_data > 0)
661         {
662           /*
663             Find the least-squares estimates and other statistics.
664           */
665           linreg_fit (this_cm, models[k]);
666           
667           if (!taint_has_tainted_successor (casereader_get_taint (input)))
668             {
669               subcommand_statistics (cmd, models[k], this_cm);
670             }
671         }
672       else
673         {
674           msg (SE,
675                _("No valid data found. This command was skipped."));
676           linreg_free (models[k]);
677           models[k] = NULL;
678         }
679       gsl_matrix_free (this_cm);
680     }
681   
682   casereader_destroy (reader);
683   free (vars);
684   free (all_vars);
685   free (means);
686   casereader_destroy (input);
687   covariance_destroy (cov);
688 }
689
690
691 \f
692
693
694 static void
695 reg_stats_r (linreg *c, void *aux UNUSED)
696 {
697   struct tab_table *t;
698   int n_rows = 2;
699   int n_cols = 5;
700   double rsq;
701   double adjrsq;
702   double std_error;
703
704   assert (c != NULL);
705   rsq = linreg_ssreg (c) / linreg_sst (c);
706   adjrsq = 1.0 - (1.0 - rsq) * (linreg_n_obs (c) - 1.0) / (linreg_n_obs (c) - linreg_n_coeffs (c));
707   std_error = sqrt (linreg_mse (c));
708   t = tab_create (n_cols, n_rows);
709   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
710   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
711   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
712   tab_vline (t, TAL_0, 1, 0, 0);
713
714   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("R"));
715   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("R Square"));
716   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Adjusted R Square"));
717   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Std. Error of the Estimate"));
718   tab_double (t, 1, 1, TAB_RIGHT, sqrt (rsq), NULL);
719   tab_double (t, 2, 1, TAB_RIGHT, rsq, NULL);
720   tab_double (t, 3, 1, TAB_RIGHT, adjrsq, NULL);
721   tab_double (t, 4, 1, TAB_RIGHT, std_error, NULL);
722   tab_title (t, _("Model Summary"));
723   tab_submit (t);
724 }
725
726 /*
727   Table showing estimated regression coefficients.
728 */
729 static void
730 reg_stats_coeff (linreg * c, void *aux_)
731 {
732   size_t j;
733   int n_cols = 7;
734   int n_rows;
735   int this_row;
736   double t_stat;
737   double pval;
738   double std_err;
739   double beta;
740   const char *label;
741
742   const struct variable *v;
743   struct tab_table *t;
744   gsl_matrix *cov = aux_;
745
746   assert (c != NULL);
747   n_rows = linreg_n_coeffs (c) + 3;
748
749   t = tab_create (n_cols, n_rows);
750   tab_headers (t, 2, 0, 1, 0);
751   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
752   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
753   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
754   tab_vline (t, TAL_0, 1, 0, 0);
755
756   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("B"));
757   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Std. Error"));
758   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Beta"));
759   tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("t"));
760   tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
761   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("(Constant)"));
762   tab_double (t, 2, 1, 0, linreg_intercept (c), NULL);
763   std_err = sqrt (gsl_matrix_get (linreg_cov (c), 0, 0));
764   tab_double (t, 3, 1, 0, std_err, NULL);
765   tab_double (t, 4, 1, 0, 0.0, NULL);
766   t_stat = linreg_intercept (c) / std_err;
767   tab_double (t, 5, 1, 0, t_stat, NULL);
768   pval = 2 * gsl_cdf_tdist_Q (fabs (t_stat), (double) (linreg_n_obs (c) - linreg_n_coeffs (c)));
769   tab_double (t, 6, 1, 0, pval, NULL);
770   for (j = 0; j < linreg_n_coeffs (c); j++)
771     {
772       struct string tstr;
773       ds_init_empty (&tstr);
774       this_row = j + 2;
775
776       v = linreg_indep_var (c, j);
777       label = var_to_string (v);
778       /* Do not overwrite the variable's name. */
779       ds_put_cstr (&tstr, label);
780       tab_text (t, 1, this_row, TAB_CENTER, ds_cstr (&tstr));
781       /*
782         Regression coefficients.
783       */
784       tab_double (t, 2, this_row, 0, linreg_coeff (c, j), NULL);
785       /*
786         Standard error of the coefficients.
787       */
788       std_err = sqrt (gsl_matrix_get (linreg_cov (c), j + 1, j + 1));
789       tab_double (t, 3, this_row, 0, std_err, NULL);
790       /*
791         Standardized coefficient, i.e., regression coefficient
792         if all variables had unit variance.
793       */
794       beta = sqrt (gsl_matrix_get (cov, j, j));
795       beta *= linreg_coeff (c, j) / 
796         sqrt (gsl_matrix_get (cov, cov->size1 - 1, cov->size2 - 1));
797       tab_double (t, 4, this_row, 0, beta, NULL);
798
799       /*
800         Test statistic for H0: coefficient is 0.
801       */
802       t_stat = linreg_coeff (c, j) / std_err;
803       tab_double (t, 5, this_row, 0, t_stat, NULL);
804       /*
805         P values for the test statistic above.
806       */
807       pval =
808         2 * gsl_cdf_tdist_Q (fabs (t_stat),
809                              (double) (linreg_n_obs (c) - linreg_n_coeffs (c)));
810       tab_double (t, 6, this_row, 0, pval, NULL);
811       ds_destroy (&tstr);
812     }
813   tab_title (t, _("Coefficients"));
814   tab_submit (t);
815 }
816
817 /*
818   Display the ANOVA table.
819 */
820 static void
821 reg_stats_anova (linreg * c, void *aux UNUSED)
822 {
823   int n_cols = 7;
824   int n_rows = 4;
825   const double msm = linreg_ssreg (c) / linreg_dfmodel (c);
826   const double mse = linreg_mse (c);
827   const double F = msm / mse;
828   const double pval = gsl_cdf_fdist_Q (F, c->dfm, c->dfe);
829
830   struct tab_table *t;
831
832   assert (c != NULL);
833   t = tab_create (n_cols, n_rows);
834   tab_headers (t, 2, 0, 1, 0);
835
836   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
837
838   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
839   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
840   tab_vline (t, TAL_0, 1, 0, 0);
841
842   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Sum of Squares"));
843   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("df"));
844   tab_text (t, 4, 0, TAB_CENTER | TAT_TITLE, _("Mean Square"));
845   tab_text (t, 5, 0, TAB_CENTER | TAT_TITLE, _("F"));
846   tab_text (t, 6, 0, TAB_CENTER | TAT_TITLE, _("Significance"));
847
848   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Regression"));
849   tab_text (t, 1, 2, TAB_LEFT | TAT_TITLE, _("Residual"));
850   tab_text (t, 1, 3, TAB_LEFT | TAT_TITLE, _("Total"));
851
852   /* Sums of Squares */
853   tab_double (t, 2, 1, 0, linreg_ssreg (c), NULL);
854   tab_double (t, 2, 3, 0, linreg_sst (c), NULL);
855   tab_double (t, 2, 2, 0, linreg_sse (c), NULL);
856
857
858   /* Degrees of freedom */
859   tab_text_format (t, 3, 1, TAB_RIGHT, "%g", c->dfm);
860   tab_text_format (t, 3, 2, TAB_RIGHT, "%g", c->dfe);
861   tab_text_format (t, 3, 3, TAB_RIGHT, "%g", c->dft);
862
863   /* Mean Squares */
864   tab_double (t, 4, 1, TAB_RIGHT, msm, NULL);
865   tab_double (t, 4, 2, TAB_RIGHT, mse, NULL);
866
867   tab_double (t, 5, 1, 0, F, NULL);
868
869   tab_double (t, 6, 1, 0, pval, NULL);
870
871   tab_title (t, _("ANOVA"));
872   tab_submit (t);
873 }
874
875
876 static void
877 reg_stats_bcov (linreg * c, void *aux UNUSED)
878 {
879   int n_cols;
880   int n_rows;
881   int i;
882   int k;
883   int row;
884   int col;
885   const char *label;
886   struct tab_table *t;
887
888   assert (c != NULL);
889   n_cols = c->n_indeps + 1 + 2;
890   n_rows = 2 * (c->n_indeps + 1);
891   t = tab_create (n_cols, n_rows);
892   tab_headers (t, 2, 0, 1, 0);
893   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, n_cols - 1, n_rows - 1);
894   tab_hline (t, TAL_2, 0, n_cols - 1, 1);
895   tab_vline (t, TAL_2, 2, 0, n_rows - 1);
896   tab_vline (t, TAL_0, 1, 0, 0);
897   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Model"));
898   tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Covariances"));
899   for (i = 0; i < linreg_n_coeffs (c); i++)
900     {
901       const struct variable *v = linreg_indep_var (c, i);
902       label = var_to_string (v);
903       tab_text (t, 2, i, TAB_CENTER, label);
904       tab_text (t, i + 2, 0, TAB_CENTER, label);
905       for (k = 1; k < linreg_n_coeffs (c); k++)
906         {
907           col = (i <= k) ? k : i;
908           row = (i <= k) ? i : k;
909           tab_double (t, k + 2, i, TAB_CENTER,
910                       gsl_matrix_get (c->cov, row, col), NULL);
911         }
912     }
913   tab_title (t, _("Coefficient Correlations"));
914   tab_submit (t);
915 }
916
917 static void
918 statistics_keyword_output (void (*function) (linreg *, void *),
919                            bool keyword, linreg * c, void *aux)
920 {
921   if (keyword)
922     {
923       (*function) (c, aux);
924     }
925 }