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