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