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