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