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