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