Fix memory leak in error path of LOGISTIC REGRESSION
[pspp] / src / language / stats / logistic.c
1 /* pspp - a program for statistical analysis.
2    Copyright (C) 2012 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
18 /* 
19    References: 
20    1. "Coding Logistic Regression with Newton-Raphson", James McCaffrey
21    http://msdn.microsoft.com/en-us/magazine/jj618304.aspx
22
23    2. "SPSS Statistical Algorithms" Chapter LOGISTIC REGRESSION Algorithms
24
25
26    The Newton Raphson method finds successive approximations to $\bf b$ where 
27    approximation ${\bf b}_t$ is (hopefully) better than the previous ${\bf b}_{t-1}$.
28
29    $ {\bf b}_t = {\bf b}_{t -1} + ({\bf X}^T{\bf W}_{t-1}{\bf X})^{-1}{\bf X}^T({\bf y} - {\bf \pi}_{t-1})$
30    where:
31
32    $\bf X$ is the $n \times p$ design matrix, $n$ being the number of cases, 
33    $p$ the number of parameters, \par
34    $\bf W$ is the diagonal matrix whose diagonal elements are
35    $\hat{\pi}_0(1 - \hat{\pi}_0), \, \hat{\pi}_1(1 - \hat{\pi}_2)\dots \hat{\pi}_{n-1}(1 - \hat{\pi}_{n-1})$
36    \par
37
38 */
39
40 #include <config.h>
41
42 #include <gsl/gsl_blas.h> 
43
44 #include <gsl/gsl_linalg.h>
45 #include <gsl/gsl_cdf.h>
46 #include <gsl/gsl_matrix.h>
47 #include <gsl/gsl_vector.h>
48 #include <math.h>
49
50 #include "data/case.h"
51 #include "data/casegrouper.h"
52 #include "data/casereader.h"
53 #include "data/dataset.h"
54 #include "data/dictionary.h"
55 #include "data/format.h"
56 #include "data/value.h"
57 #include "language/command.h"
58 #include "language/dictionary/split-file.h"
59 #include "language/lexer/lexer.h"
60 #include "language/lexer/value-parser.h"
61 #include "language/lexer/variable-parser.h"
62 #include "libpspp/assertion.h"
63 #include "libpspp/ll.h"
64 #include "libpspp/message.h"
65 #include "libpspp/misc.h"
66 #include "math/categoricals.h"
67 #include "math/interaction.h"
68 #include "libpspp/hmap.h"
69 #include "libpspp/hash-functions.h"
70
71 #include "output/tab.h"
72
73 #include "gettext.h"
74 #define _(msgid) gettext (msgid)
75
76
77
78
79 #define   PRINT_EACH_STEP  0x01
80 #define   PRINT_SUMMARY    0x02
81 #define   PRINT_CORR       0x04
82 #define   PRINT_ITER       0x08
83 #define   PRINT_GOODFIT    0x10
84 #define   PRINT_CI         0x20
85
86
87 #define PRINT_DEFAULT (PRINT_SUMMARY | PRINT_EACH_STEP)
88
89 /*
90   The constant parameters of the procedure.
91   That is, those which are set by the user.
92 */
93 struct lr_spec
94 {
95   /* The dependent variable */
96   const struct variable *dep_var;
97
98   /* The predictor variables (excluding categorical ones) */
99   const struct variable **predictor_vars;
100   size_t n_predictor_vars;
101
102   /* The categorical predictors */
103   struct interaction **cat_predictors;
104   size_t n_cat_predictors;
105
106
107   /* The union of the categorical and non-categorical variables */
108   const struct variable **indep_vars;
109   size_t n_indep_vars;
110
111
112   /* Which classes of missing vars are to be excluded */
113   enum mv_class exclude;
114
115   /* The weight variable */
116   const struct variable *wv;
117
118   /* The dictionary of the dataset */
119   const struct dictionary *dict;
120
121   /* True iff the constant (intercept) is to be included in the model */
122   bool constant;
123
124   /* Ths maximum number of iterations */
125   int max_iter;
126
127   /* Other iteration limiting conditions */
128   double bcon;
129   double min_epsilon;
130   double lcon;
131
132   /* The confidence interval (in percent) */
133   int confidence;
134
135   /* What results should be presented */
136   unsigned int print;
137
138   /* Inverse logit of the cut point */
139   double ilogit_cut_point;
140 };
141
142
143 /* The results and intermediate result of the procedure.
144    These are mutated as the procedure runs. Used for
145    temporary variables etc.
146 */
147 struct lr_result
148 {
149   /* Used to indicate if a pass should flag a warning when 
150      invalid (ie negative or missing) weight values are encountered */
151   bool warn_bad_weight;
152
153   /* The two values of the dependent variable. */
154   union value y0;
155   union value y1;
156
157
158   /* The sum of caseweights */
159   double cc;
160
161   /* The number of missing and nonmissing cases */
162   casenumber n_missing;
163   casenumber n_nonmissing;
164
165
166   gsl_matrix *hessian;
167
168   /* The categoricals and their payload. Null if  the analysis has no
169    categorical predictors */
170   struct categoricals *cats;
171   struct payload cp;
172
173
174   /* The estimates of the predictor coefficients */
175   gsl_vector *beta_hat;
176
177   /* The predicted classifications: 
178      True Negative, True Positive, False Negative, False Positive */
179   double tn, tp, fn, fp;
180 };
181
182
183 /*
184   Convert INPUT into a dichotomous scalar, according to how the dependent variable's
185   values are mapped.
186   For simple cases, this is a 1:1 mapping
187   The return value is always either 0 or 1
188 */
189 static double
190 map_dependent_var (const struct lr_spec *cmd, const struct lr_result *res, const union value *input)
191 {
192   const int width = var_get_width (cmd->dep_var);
193   if (value_equal (input, &res->y0, width))
194     return 0;
195
196   if (value_equal (input, &res->y1, width))
197     return 1;
198
199   /* This should never happen.  If it does,  then y0 and/or y1 have probably not been set */
200   NOT_REACHED ();
201
202   return SYSMIS;
203 }
204
205 static void output_classification_table (const struct lr_spec *cmd, const struct lr_result *res);
206
207 static void output_categories (const struct lr_spec *cmd, const struct lr_result *res);
208
209 static void output_depvarmap (const struct lr_spec *cmd, const struct lr_result *);
210
211 static void output_variables (const struct lr_spec *cmd, 
212                               const struct lr_result *);
213
214 static void output_model_summary (const struct lr_result *,
215                                   double initial_likelihood, double likelihood);
216
217 static void case_processing_summary (const struct lr_result *);
218
219
220 /* Return the value of case C corresponding to the INDEX'th entry in the
221    model */
222 static double
223 predictor_value (const struct ccase *c, 
224                     const struct variable **x, size_t n_x, 
225                     const struct categoricals *cats,
226                     size_t index)
227 {
228   /* Values of the scalar predictor variables */
229   if (index < n_x) 
230     return case_data (c, x[index])->f;
231
232   /* Coded values of categorical predictor variables (or interactions) */
233   if (cats && index - n_x  < categoricals_df_total (cats))
234     {
235       double x = categoricals_get_dummy_code_for_case (cats, index - n_x, c);
236       return x;
237     }
238
239   /* The constant term */
240   return 1.0;
241 }
242
243
244 /*
245   Return the probability beta_hat (that is the estimator logit(y) )
246   corresponding to the coefficient estimator for case C
247 */
248 static double 
249 pi_hat (const struct lr_spec *cmd, 
250         const struct lr_result *res,
251         const struct variable **x, size_t n_x,
252         const struct ccase *c)
253 {
254   int v0;
255   double pi = 0;
256   size_t n_coeffs = res->beta_hat->size;
257
258   if (cmd->constant)
259     {
260       pi += gsl_vector_get (res->beta_hat, res->beta_hat->size - 1);
261       n_coeffs--;
262     }
263   
264   for (v0 = 0; v0 < n_coeffs; ++v0)
265     {
266       pi += gsl_vector_get (res->beta_hat, v0) * 
267         predictor_value (c, x, n_x, res->cats, v0);
268     }
269
270   pi = 1.0 / (1.0 + exp(-pi));
271
272   return pi;
273 }
274
275
276 /*
277   Calculates the Hessian matrix X' V  X,
278   where: X is the n by N_X matrix comprising the n cases in INPUT
279   V is a diagonal matrix { (pi_hat_0)(1 - pi_hat_0), (pi_hat_1)(1 - pi_hat_1), ... (pi_hat_{N-1})(1 - pi_hat_{N-1})} 
280   (the partial derivative of the predicted values)
281
282   If ALL predicted values derivatives are close to zero or one, then CONVERGED
283   will be set to true.
284 */
285 static void
286 hessian (const struct lr_spec *cmd, 
287          struct lr_result *res,
288          struct casereader *input,
289          const struct variable **x, size_t n_x,
290          bool *converged)
291 {
292   struct casereader *reader;
293   struct ccase *c;
294
295   double max_w = -DBL_MAX;
296
297   gsl_matrix_set_zero (res->hessian);
298
299   for (reader = casereader_clone (input);
300        (c = casereader_read (reader)) != NULL; case_unref (c))
301     {
302       int v0, v1;
303       double pi = pi_hat (cmd, res, x, n_x, c);
304
305       double weight = dict_get_case_weight (cmd->dict, c, &res->warn_bad_weight);
306       double w = pi * (1 - pi);
307       if (w > max_w)
308         max_w = w;
309       w *= weight;
310
311       for (v0 = 0; v0 < res->beta_hat->size; ++v0)
312         {
313           double in0 = predictor_value (c, x, n_x, res->cats, v0);
314           for (v1 = 0; v1 < res->beta_hat->size; ++v1)
315             {
316               double in1 = predictor_value (c, x, n_x, res->cats, v1);
317               double *o = gsl_matrix_ptr (res->hessian, v0, v1);
318               *o += in0 * w * in1;
319             }
320         }
321     }
322   casereader_destroy (reader);
323
324   if ( max_w < cmd->min_epsilon)
325     {
326       *converged = true;
327       msg (MN, _("All predicted values are either 1 or 0"));
328     }
329 }
330
331
332 /* Calculates the value  X' (y - pi)
333    where X is the design model, 
334    y is the vector of observed independent variables
335    pi is the vector of estimates for y
336
337    Side effects:
338      the likelihood is stored in LIKELIHOOD;
339      the predicted values are placed in the respective tn, fn, tp fp values in RES
340 */
341 static gsl_vector *
342 xt_times_y_pi (const struct lr_spec *cmd,
343                struct lr_result *res,
344                struct casereader *input,
345                const struct variable **x, size_t n_x,
346                const struct variable *y_var,
347                double *llikelihood)
348 {
349   struct casereader *reader;
350   struct ccase *c;
351   gsl_vector *output = gsl_vector_calloc (res->beta_hat->size);
352
353   *llikelihood = 0.0;
354   res->tn = res->tp = res->fn = res->fp = 0;
355   for (reader = casereader_clone (input);
356        (c = casereader_read (reader)) != NULL; case_unref (c))
357     {
358       double pred_y = 0;
359       int v0;
360       double pi = pi_hat (cmd, res, x, n_x, c);
361       double weight = dict_get_case_weight (cmd->dict, c, &res->warn_bad_weight);
362
363
364       double y = map_dependent_var (cmd, res, case_data (c, y_var));
365
366       *llikelihood += (weight * y) * log (pi) + log (1 - pi) * weight * (1 - y);
367
368       for (v0 = 0; v0 < res->beta_hat->size; ++v0)
369         {
370           double in0 = predictor_value (c, x, n_x, res->cats, v0);
371           double *o = gsl_vector_ptr (output, v0);
372           *o += in0 * (y - pi) * weight;
373           pred_y += gsl_vector_get (res->beta_hat, v0) * in0;
374         }
375
376       /* Count the number of cases which would be correctly/incorrectly classified by this
377          estimated model */
378       if (pred_y <= cmd->ilogit_cut_point)
379         {
380           if (y == 0)
381             res->tn += weight;
382           else
383             res->fn += weight;
384         }
385       else
386         {
387           if (y == 0)
388             res->fp += weight;
389           else
390             res->tp += weight;
391         }
392     }
393
394   casereader_destroy (reader);
395
396   return output;
397 }
398
399 \f
400
401 /* "payload" functions for the categoricals.
402    The only function is to accumulate the frequency of each
403    category.
404  */
405
406 static void *
407 frq_create  (const void *aux1 UNUSED, void *aux2 UNUSED)
408 {
409   return xzalloc (sizeof (double));
410 }
411
412 static void
413 frq_update  (const void *aux1 UNUSED, void *aux2 UNUSED,
414              void *ud, const struct ccase *c UNUSED , double weight)
415 {
416   double *freq = ud;
417   *freq += weight;
418 }
419
420 static void 
421 frq_destroy (const void *aux1 UNUSED, void *aux2 UNUSED, void *user_data UNUSED)
422 {
423   free (user_data);
424 }
425
426 \f
427
428 /* 
429    Makes an initial pass though the data, doing the following:
430
431    * Checks that the dependent variable is  dichotomous,
432    * Creates and initialises the categoricals,
433    * Accumulates summary results,
434    * Calculates necessary initial values.
435    * Creates an initial value for \hat\beta the vector of beta_hats of \beta
436
437    Returns true if successful
438 */
439 static bool
440 initial_pass (const struct lr_spec *cmd, struct lr_result *res, struct casereader *input)
441 {
442   const int width = var_get_width (cmd->dep_var);
443
444   struct ccase *c;
445   struct casereader *reader;
446
447   double sum;
448   double sumA = 0.0;
449   double sumB = 0.0;
450
451   bool v0set = false;
452   bool v1set = false;
453
454   size_t n_coefficients = cmd->n_predictor_vars;
455   if (cmd->constant)
456     n_coefficients++;
457
458   /* Create categoricals if appropriate */
459   if (cmd->n_cat_predictors > 0)
460     {
461       res->cp.create = frq_create;
462       res->cp.update = frq_update;
463       res->cp.calculate = NULL;
464       res->cp.destroy = frq_destroy;
465
466       res->cats = categoricals_create (cmd->cat_predictors, cmd->n_cat_predictors,
467                                        cmd->wv, cmd->exclude, MV_ANY);
468
469       categoricals_set_payload (res->cats, &res->cp, cmd, res);
470     }
471
472   res->cc = 0;
473   for (reader = casereader_clone (input);
474        (c = casereader_read (reader)) != NULL; case_unref (c))
475     {
476       int v;
477       bool missing = false;
478       double weight = dict_get_case_weight (cmd->dict, c, &res->warn_bad_weight);
479       const union value *depval = case_data (c, cmd->dep_var);
480
481       if (var_is_value_missing (cmd->dep_var, depval, cmd->exclude))
482         {
483           missing = true;
484         }
485       else 
486       for (v = 0; v < cmd->n_indep_vars; ++v)
487         {
488           const union value *val = case_data (c, cmd->indep_vars[v]);
489           if (var_is_value_missing (cmd->indep_vars[v], val, cmd->exclude))
490             {
491               missing = true;
492               break;
493             }
494         }
495
496       /* Accumulate the missing and non-missing counts */
497       if (missing)
498         {
499           res->n_missing++;
500           continue;
501         }
502       res->n_nonmissing++;
503
504       /* Find the values of the dependent variable */
505       if (!v0set)
506         {
507           value_clone (&res->y0, depval, width);
508           v0set = true;
509         }
510       else if (!v1set)
511         {
512           if ( !value_equal (&res->y0, depval, width))
513             {
514               value_clone (&res->y1, depval, width);
515               v1set = true;
516             }
517         }
518       else
519         {
520           if (! value_equal (&res->y0, depval, width)
521               &&
522               ! value_equal (&res->y1, depval, width)
523               )
524             {
525               msg (ME, _("Dependent variable's values are not dichotomous."));
526               goto error;
527             }
528         }
529
530       if (v0set && value_equal (&res->y0, depval, width))
531           sumA += weight;
532
533       if (v1set && value_equal (&res->y1, depval, width))
534           sumB += weight;
535
536
537       res->cc += weight;
538
539       categoricals_update (res->cats, c);
540     }
541   casereader_destroy (reader);
542
543   categoricals_done (res->cats);
544
545   sum = sumB;
546
547   /* Ensure that Y0 is less than Y1.  Otherwise the mapping gets
548      inverted, which is confusing to users */
549   if (var_is_numeric (cmd->dep_var) && value_compare_3way (&res->y0, &res->y1, width) > 0)
550     {
551       union value tmp;
552       value_clone (&tmp, &res->y0, width);
553       value_copy (&res->y0, &res->y1, width);
554       value_copy (&res->y1, &tmp, width);
555       value_destroy (&tmp, width);
556       sum = sumA;
557     }
558
559   n_coefficients += categoricals_df_total (res->cats);
560   res->beta_hat = gsl_vector_calloc (n_coefficients);
561
562   if (cmd->constant)
563     {
564       double mean = sum / res->cc;
565       gsl_vector_set (res->beta_hat, res->beta_hat->size - 1, log (mean / (1 - mean)));
566     }
567
568   return true;
569
570  error:
571   casereader_destroy (reader);
572   return false;
573 }
574
575
576
577 /* Start of the logistic regression routine proper */
578 static bool
579 run_lr (const struct lr_spec *cmd, struct casereader *input,
580         const struct dataset *ds UNUSED)
581 {
582   int i;
583
584   bool converged = false;
585
586   /* Set the log likelihoods to a sentinel value */
587   double log_likelihood = SYSMIS;
588   double prev_log_likelihood = SYSMIS;
589   double initial_log_likelihood = SYSMIS;
590
591   struct lr_result work;
592   work.n_missing = 0;
593   work.n_nonmissing = 0;
594   work.warn_bad_weight = true;
595   work.cats = NULL;
596   work.beta_hat = NULL;
597   work.hessian = NULL;
598
599   /* Get the initial estimates of \beta and their standard errors.
600      And perform other auxilliary initialisation.  */
601   if (! initial_pass (cmd, &work, input))
602     goto error;
603   
604   for (i = 0; i < cmd->n_cat_predictors; ++i)
605     {
606       if (1 >= categoricals_n_count (work.cats, i))
607         {
608           struct string str;
609           ds_init_empty (&str);
610           
611           interaction_to_string (cmd->cat_predictors[i], &str);
612
613           msg (ME, _("Category %s does not have at least two distinct values. Logistic regression will not be run."),
614                ds_cstr(&str));
615           ds_destroy (&str);
616           goto error;
617         }
618     }
619
620   output_depvarmap (cmd, &work);
621
622   case_processing_summary (&work);
623
624
625   input = casereader_create_filter_missing (input,
626                                             cmd->indep_vars,
627                                             cmd->n_indep_vars,
628                                             cmd->exclude,
629                                             NULL,
630                                             NULL);
631
632   input = casereader_create_filter_missing (input,
633                                             &cmd->dep_var,
634                                             1,
635                                             cmd->exclude,
636                                             NULL,
637                                             NULL);
638
639   work.hessian = gsl_matrix_calloc (work.beta_hat->size, work.beta_hat->size);
640
641   /* Start the Newton Raphson iteration process... */
642   for( i = 0 ; i < cmd->max_iter ; ++i)
643     {
644       double min, max;
645       gsl_vector *v ;
646
647       
648       hessian (cmd, &work, input,
649                cmd->predictor_vars, cmd->n_predictor_vars,
650                &converged);
651
652       gsl_linalg_cholesky_decomp (work.hessian);
653       gsl_linalg_cholesky_invert (work.hessian);
654
655       v = xt_times_y_pi (cmd, &work, input,
656                          cmd->predictor_vars, cmd->n_predictor_vars,
657                          cmd->dep_var,
658                          &log_likelihood);
659
660       {
661         /* delta = M.v */
662         gsl_vector *delta = gsl_vector_alloc (v->size);
663         gsl_blas_dgemv (CblasNoTrans, 1.0, work.hessian, v, 0, delta);
664         gsl_vector_free (v);
665
666
667         gsl_vector_add (work.beta_hat, delta);
668
669         gsl_vector_minmax (delta, &min, &max);
670
671         if ( fabs (min) < cmd->bcon && fabs (max) < cmd->bcon)
672           {
673             msg (MN, _("Estimation terminated at iteration number %d because parameter estimates changed by less than %g"),
674                  i + 1, cmd->bcon);
675             converged = true;
676           }
677
678         gsl_vector_free (delta);
679       }
680
681       if (i > 0)
682         {
683           if (-log_likelihood > -(1.0 - cmd->lcon) * prev_log_likelihood)
684             {
685               msg (MN, _("Estimation terminated at iteration number %d because Log Likelihood decreased by less than %g%%"), i + 1, 100 * cmd->lcon);
686               converged = true;
687             }
688         }
689       if (i == 0)
690         initial_log_likelihood = log_likelihood;
691       prev_log_likelihood = log_likelihood;
692
693       if (converged)
694         break;
695     }
696
697
698
699   if ( ! converged) 
700     msg (MW, _("Estimation terminated at iteration number %d because maximum iterations has been reached"), i );
701
702
703   output_model_summary (&work, initial_log_likelihood, log_likelihood);
704
705   if (work.cats)
706     output_categories (cmd, &work);
707
708   output_classification_table (cmd, &work);
709   output_variables (cmd, &work);
710
711   casereader_destroy (input);
712   gsl_matrix_free (work.hessian);
713   gsl_vector_free (work.beta_hat); 
714   categoricals_destroy (work.cats);
715
716   return true;
717
718  error:
719   casereader_destroy (input);
720   gsl_matrix_free (work.hessian);
721   gsl_vector_free (work.beta_hat); 
722   categoricals_destroy (work.cats);
723
724   return false;
725 }
726
727 struct variable_node
728 {
729   struct hmap_node node;      /* Node in hash map. */
730   const struct variable *var; /* The variable */
731 };
732
733 static struct variable_node *
734 lookup_variable (const struct hmap *map, const struct variable *var, unsigned int hash)
735 {
736   struct variable_node *vn = NULL;
737   HMAP_FOR_EACH_WITH_HASH (vn, struct variable_node, node, hash, map)
738     {
739       if (vn->var == var)
740         break;
741       
742       fprintf (stderr, "Warning: Hash table collision\n");
743     }
744   
745   return vn;
746 }
747
748
749 /* Parse the LOGISTIC REGRESSION command syntax */
750 int
751 cmd_logistic (struct lexer *lexer, struct dataset *ds)
752 {
753   int i;
754   /* Temporary location for the predictor variables.
755      These may or may not include the categorical predictors */
756   const struct variable **pred_vars;
757   size_t n_pred_vars;
758   double cp = 0.5;
759
760   int v, x;
761   struct lr_spec lr;
762   lr.dict = dataset_dict (ds);
763   lr.n_predictor_vars = 0;
764   lr.predictor_vars = NULL;
765   lr.exclude = MV_ANY;
766   lr.wv = dict_get_weight (lr.dict);
767   lr.max_iter = 20;
768   lr.lcon = 0.0000;
769   lr.bcon = 0.001;
770   lr.min_epsilon = 0.00000001;
771   lr.constant = true;
772   lr.confidence = 95;
773   lr.print = PRINT_DEFAULT;
774   lr.cat_predictors = NULL;
775   lr.n_cat_predictors = 0;
776   lr.indep_vars = NULL;
777
778
779   if (lex_match_id (lexer, "VARIABLES"))
780     lex_match (lexer, T_EQUALS);
781
782   if (! (lr.dep_var = parse_variable_const (lexer, lr.dict)))
783     goto error;
784
785   lex_force_match (lexer, T_WITH);
786
787   if (!parse_variables_const (lexer, lr.dict,
788                               &pred_vars, &n_pred_vars,
789                               PV_NO_DUPLICATE))
790     goto error;
791
792
793   while (lex_token (lexer) != T_ENDCMD)
794     {
795       lex_match (lexer, T_SLASH);
796
797       if (lex_match_id (lexer, "MISSING"))
798         {
799           lex_match (lexer, T_EQUALS);
800           while (lex_token (lexer) != T_ENDCMD
801                  && lex_token (lexer) != T_SLASH)
802             {
803               if (lex_match_id (lexer, "INCLUDE"))
804                 {
805                   lr.exclude = MV_SYSTEM;
806                 }
807               else if (lex_match_id (lexer, "EXCLUDE"))
808                 {
809                   lr.exclude = MV_ANY;
810                 }
811               else
812                 {
813                   lex_error (lexer, NULL);
814                   goto error;
815                 }
816             }
817         }
818       else if (lex_match_id (lexer, "ORIGIN"))
819         {
820           lr.constant = false;
821         }
822       else if (lex_match_id (lexer, "NOORIGIN"))
823         {
824           lr.constant = true;
825         }
826       else if (lex_match_id (lexer, "NOCONST"))
827         {
828           lr.constant = false;
829         }
830       else if (lex_match_id (lexer, "EXTERNAL"))
831         {
832           /* This is for compatibility.  It does nothing */
833         }
834       else if (lex_match_id (lexer, "CATEGORICAL"))
835         {
836           lex_match (lexer, T_EQUALS);
837           do
838             {
839               lr.cat_predictors = xrealloc (lr.cat_predictors,
840                                   sizeof (*lr.cat_predictors) * ++lr.n_cat_predictors);
841               lr.cat_predictors[lr.n_cat_predictors - 1] = 0;
842             }
843           while (parse_design_interaction (lexer, lr.dict, 
844                                            lr.cat_predictors + lr.n_cat_predictors - 1));
845           lr.n_cat_predictors--;
846         }
847       else if (lex_match_id (lexer, "PRINT"))
848         {
849           lex_match (lexer, T_EQUALS);
850           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
851             {
852               if (lex_match_id (lexer, "DEFAULT"))
853                 {
854                   lr.print |= PRINT_DEFAULT;
855                 }
856               else if (lex_match_id (lexer, "SUMMARY"))
857                 {
858                   lr.print |= PRINT_SUMMARY;
859                 }
860 #if 0
861               else if (lex_match_id (lexer, "CORR"))
862                 {
863                   lr.print |= PRINT_CORR;
864                 }
865               else if (lex_match_id (lexer, "ITER"))
866                 {
867                   lr.print |= PRINT_ITER;
868                 }
869               else if (lex_match_id (lexer, "GOODFIT"))
870                 {
871                   lr.print |= PRINT_GOODFIT;
872                 }
873 #endif
874               else if (lex_match_id (lexer, "CI"))
875                 {
876                   lr.print |= PRINT_CI;
877                   if (lex_force_match (lexer, T_LPAREN))
878                     {
879                       if (! lex_force_int (lexer))
880                         {
881                           lex_error (lexer, NULL);
882                           goto error;
883                         }
884                       lr.confidence = lex_integer (lexer);
885                       lex_get (lexer);
886                       if ( ! lex_force_match (lexer, T_RPAREN))
887                         {
888                           lex_error (lexer, NULL);
889                           goto error;
890                         }
891                     }
892                 }
893               else if (lex_match_id (lexer, "ALL"))
894                 {
895                   lr.print = ~0x0000;
896                 }
897               else
898                 {
899                   lex_error (lexer, NULL);
900                   goto error;
901                 }
902             }
903         }
904       else if (lex_match_id (lexer, "CRITERIA"))
905         {
906           lex_match (lexer, T_EQUALS);
907           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
908             {
909               if (lex_match_id (lexer, "BCON"))
910                 {
911                   if (lex_force_match (lexer, T_LPAREN))
912                     {
913                       if (! lex_force_num (lexer))
914                         {
915                           lex_error (lexer, NULL);
916                           goto error;
917                         }
918                       lr.bcon = lex_number (lexer);
919                       lex_get (lexer);
920                       if ( ! lex_force_match (lexer, T_RPAREN))
921                         {
922                           lex_error (lexer, NULL);
923                           goto error;
924                         }
925                     }
926                 }
927               else if (lex_match_id (lexer, "ITERATE"))
928                 {
929                   if (lex_force_match (lexer, T_LPAREN))
930                     {
931                       if (! lex_force_int (lexer))
932                         {
933                           lex_error (lexer, NULL);
934                           goto error;
935                         }
936                       lr.max_iter = lex_integer (lexer);
937                       lex_get (lexer);
938                       if ( ! lex_force_match (lexer, T_RPAREN))
939                         {
940                           lex_error (lexer, NULL);
941                           goto error;
942                         }
943                     }
944                 }
945               else if (lex_match_id (lexer, "LCON"))
946                 {
947                   if (lex_force_match (lexer, T_LPAREN))
948                     {
949                       if (! lex_force_num (lexer))
950                         {
951                           lex_error (lexer, NULL);
952                           goto error;
953                         }
954                       lr.lcon = lex_number (lexer);
955                       lex_get (lexer);
956                       if ( ! lex_force_match (lexer, T_RPAREN))
957                         {
958                           lex_error (lexer, NULL);
959                           goto error;
960                         }
961                     }
962                 }
963               else if (lex_match_id (lexer, "EPS"))
964                 {
965                   if (lex_force_match (lexer, T_LPAREN))
966                     {
967                       if (! lex_force_num (lexer))
968                         {
969                           lex_error (lexer, NULL);
970                           goto error;
971                         }
972                       lr.min_epsilon = lex_number (lexer);
973                       lex_get (lexer);
974                       if ( ! lex_force_match (lexer, T_RPAREN))
975                         {
976                           lex_error (lexer, NULL);
977                           goto error;
978                         }
979                     }
980                 }
981               else if (lex_match_id (lexer, "CUT"))
982                 {
983                   if (lex_force_match (lexer, T_LPAREN))
984                     {
985                       if (! lex_force_num (lexer))
986                         {
987                           lex_error (lexer, NULL);
988                           goto error;
989                         }
990                       cp = lex_number (lexer);
991                       
992                       if (cp < 0 || cp > 1.0)
993                         {
994                           msg (ME, _("Cut point value must be in the range [0,1]"));
995                           goto error;
996                         }
997                       lex_get (lexer);
998                       if ( ! lex_force_match (lexer, T_RPAREN))
999                         {
1000                           lex_error (lexer, NULL);
1001                           goto error;
1002                         }
1003                     }
1004                 }
1005               else
1006                 {
1007                   lex_error (lexer, NULL);
1008                   goto error;
1009                 }
1010             }
1011         }
1012       else
1013         {
1014           lex_error (lexer, NULL);
1015           goto error;
1016         }
1017     }
1018
1019   lr.ilogit_cut_point = - log (1/cp - 1);
1020   
1021
1022   /* Copy the predictor variables from the temporary location into the 
1023      final one, dropping any categorical variables which appear there.
1024      FIXME: This is O(NxM).
1025   */
1026   {
1027   struct variable_node *vn, *next;
1028   struct hmap allvars;
1029   hmap_init (&allvars);
1030   for (v = x = 0; v < n_pred_vars; ++v)
1031     {
1032       bool drop = false;
1033       const struct variable *var = pred_vars[v];
1034       int cv = 0;
1035
1036       unsigned int hash = hash_pointer (var, 0);
1037       struct variable_node *vn = lookup_variable (&allvars, var, hash);
1038       if (vn == NULL)
1039         {
1040           vn = xmalloc (sizeof *vn);
1041           vn->var = var;
1042           hmap_insert (&allvars, &vn->node,  hash);
1043         }
1044
1045       for (cv = 0; cv < lr.n_cat_predictors ; ++cv)
1046         {
1047           int iv;
1048           const struct interaction *iact = lr.cat_predictors[cv];
1049           for (iv = 0 ; iv < iact->n_vars ; ++iv)
1050             {
1051               const struct variable *ivar = iact->vars[iv];
1052               unsigned int hash = hash_pointer (ivar, 0);
1053               struct variable_node *vn = lookup_variable (&allvars, ivar, hash);
1054               if (vn == NULL)
1055                 {
1056                   vn = xmalloc (sizeof *vn);
1057                   vn->var = ivar;
1058                   
1059                   hmap_insert (&allvars, &vn->node,  hash);
1060                 }
1061
1062               if (var == ivar)
1063                 {
1064                   drop = true;
1065                 }
1066             }
1067         }
1068
1069       if (drop)
1070         continue;
1071
1072       lr.predictor_vars = xrealloc (lr.predictor_vars, sizeof *lr.predictor_vars * (x + 1));
1073       lr.predictor_vars[x++] = var;
1074       lr.n_predictor_vars++;
1075     }
1076   free (pred_vars);
1077
1078   lr.n_indep_vars = hmap_count (&allvars);
1079   lr.indep_vars = xmalloc (lr.n_indep_vars * sizeof *lr.indep_vars);
1080
1081   /* Interate over each variable and push it into the array */
1082   x = 0;
1083   HMAP_FOR_EACH_SAFE (vn, next, struct variable_node, node, &allvars)
1084     {
1085       lr.indep_vars[x++] = vn->var;
1086       free (vn);
1087     }
1088   hmap_destroy (&allvars);
1089   }  
1090
1091
1092   /* logistical regression for each split group */
1093   {
1094     struct casegrouper *grouper;
1095     struct casereader *group;
1096     bool ok;
1097
1098     grouper = casegrouper_create_splits (proc_open (ds), lr.dict);
1099     while (casegrouper_get_next_group (grouper, &group))
1100       ok = run_lr (&lr, group, ds);
1101     ok = casegrouper_destroy (grouper);
1102     ok = proc_commit (ds) && ok;
1103   }
1104
1105   for (i = 0 ; i < lr.n_cat_predictors; ++i)
1106     {
1107       interaction_destroy (lr.cat_predictors[i]);
1108     }
1109   free (lr.predictor_vars);
1110   free (lr.cat_predictors);
1111   free (lr.indep_vars);
1112
1113   return CMD_SUCCESS;
1114
1115  error:
1116
1117   for (i = 0 ; i < lr.n_cat_predictors; ++i)
1118     {
1119       interaction_destroy (lr.cat_predictors[i]);
1120     }
1121   free (lr.predictor_vars);
1122   free (lr.cat_predictors);
1123   free (lr.indep_vars);
1124
1125   return CMD_FAILURE;
1126 }
1127
1128
1129 \f
1130
1131 /* Show the Dependent Variable Encoding box.
1132    This indicates how the dependent variable
1133    is mapped to the internal zero/one values.
1134 */
1135 static void
1136 output_depvarmap (const struct lr_spec *cmd, const struct lr_result *res)
1137 {
1138   const int heading_columns = 0;
1139   const int heading_rows = 1;
1140   struct tab_table *t;
1141   struct string str;
1142
1143   const int nc = 2;
1144   int nr = heading_rows + 2;
1145
1146   t = tab_create (nc, nr);
1147   tab_title (t, _("Dependent Variable Encoding"));
1148
1149   tab_headers (t, heading_columns, 0, heading_rows, 0);
1150
1151   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
1152
1153   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
1154   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1155
1156   tab_text (t,  0, 0, TAB_CENTER | TAT_TITLE, _("Original Value"));
1157   tab_text (t,  1, 0, TAB_CENTER | TAT_TITLE, _("Internal Value"));
1158
1159
1160
1161   ds_init_empty (&str);
1162   var_append_value_name (cmd->dep_var, &res->y0, &str);
1163   tab_text (t,  0, 0 + heading_rows,  0, ds_cstr (&str));
1164
1165   ds_clear (&str);
1166   var_append_value_name (cmd->dep_var, &res->y1, &str);
1167   tab_text (t,  0, 1 + heading_rows,  0, ds_cstr (&str));
1168
1169
1170   tab_double (t, 1, 0 + heading_rows, 0, map_dependent_var (cmd, res, &res->y0), &F_8_0);
1171   tab_double (t, 1, 1 + heading_rows, 0, map_dependent_var (cmd, res, &res->y1), &F_8_0);
1172   ds_destroy (&str);
1173
1174   tab_submit (t);
1175 }
1176
1177
1178 /* Show the Variables in the Equation box */
1179 static void
1180 output_variables (const struct lr_spec *cmd, 
1181                   const struct lr_result *res)
1182 {
1183   int row = 0;
1184   const int heading_columns = 1;
1185   int heading_rows = 1;
1186   struct tab_table *t;
1187
1188   int nc = 8;
1189   int nr ;
1190   int i = 0;
1191   int ivar = 0;
1192   int idx_correction = 0;
1193
1194   if (cmd->print & PRINT_CI)
1195     {
1196       nc += 2;
1197       heading_rows += 1;
1198       row++;
1199     }
1200   nr = heading_rows + cmd->n_predictor_vars;
1201   if (cmd->constant)
1202     nr++;
1203
1204   if (res->cats)
1205     nr += categoricals_df_total (res->cats) + cmd->n_cat_predictors;
1206
1207   t = tab_create (nc, nr);
1208   tab_title (t, _("Variables in the Equation"));
1209
1210   tab_headers (t, heading_columns, 0, heading_rows, 0);
1211
1212   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
1213
1214   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
1215   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1216
1217   tab_text (t,  0, row + 1, TAB_CENTER | TAT_TITLE, _("Step 1"));
1218
1219   tab_text (t,  2, row, TAB_CENTER | TAT_TITLE, _("B"));
1220   tab_text (t,  3, row, TAB_CENTER | TAT_TITLE, _("S.E."));
1221   tab_text (t,  4, row, TAB_CENTER | TAT_TITLE, _("Wald"));
1222   tab_text (t,  5, row, TAB_CENTER | TAT_TITLE, _("df"));
1223   tab_text (t,  6, row, TAB_CENTER | TAT_TITLE, _("Sig."));
1224   tab_text (t,  7, row, TAB_CENTER | TAT_TITLE, _("Exp(B)"));
1225
1226   if (cmd->print & PRINT_CI)
1227     {
1228       tab_joint_text_format (t, 8, 0, 9, 0,
1229                              TAB_CENTER | TAT_TITLE, _("%d%% CI for Exp(B)"), cmd->confidence);
1230
1231       tab_text (t,  8, row, TAB_CENTER | TAT_TITLE, _("Lower"));
1232       tab_text (t,  9, row, TAB_CENTER | TAT_TITLE, _("Upper"));
1233     }
1234  
1235   for (row = heading_rows ; row < nr; ++row)
1236     {
1237       const int idx = row - heading_rows - idx_correction;
1238
1239       const double b = gsl_vector_get (res->beta_hat, idx);
1240       const double sigma2 = gsl_matrix_get (res->hessian, idx, idx);
1241       const double wald = pow2 (b) / sigma2;
1242       const double df = 1;
1243
1244       if (idx < cmd->n_predictor_vars)
1245         {
1246           tab_text (t, 1, row, TAB_LEFT | TAT_TITLE, 
1247                     var_to_string (cmd->predictor_vars[idx]));
1248         }
1249       else if (i < cmd->n_cat_predictors)
1250         {
1251           double wald;
1252           bool summary = false;
1253           struct string str;
1254           const struct interaction *cat_predictors = cmd->cat_predictors[i];
1255           const int df = categoricals_df (res->cats, i);
1256
1257           ds_init_empty (&str);
1258           interaction_to_string (cat_predictors, &str);
1259
1260           if (ivar == 0)
1261             {
1262               /* Calculate the Wald statistic,
1263                  which is \beta' C^-1 \beta .
1264                  where \beta is the vector of the coefficient estimates comprising this
1265                  categorial variable. and C is the corresponding submatrix of the 
1266                  hessian matrix.
1267               */
1268               gsl_matrix_const_view mv =
1269                 gsl_matrix_const_submatrix (res->hessian, idx, idx, df, df);
1270               gsl_matrix *subhessian = gsl_matrix_alloc (mv.matrix.size1, mv.matrix.size2);
1271               gsl_vector_const_view vv = gsl_vector_const_subvector (res->beta_hat, idx, df);
1272               gsl_vector *temp = gsl_vector_alloc (df);
1273
1274               gsl_matrix_memcpy (subhessian, &mv.matrix);
1275               gsl_linalg_cholesky_decomp (subhessian);
1276               gsl_linalg_cholesky_invert (subhessian);
1277
1278               gsl_blas_dgemv (CblasTrans, 1.0, subhessian, &vv.vector, 0, temp);
1279               gsl_blas_ddot (temp, &vv.vector, &wald);
1280
1281               tab_double (t, 4, row, 0, wald, 0);
1282               tab_double (t, 5, row, 0, df, &F_8_0);
1283               tab_double (t, 6, row, 0, gsl_cdf_chisq_Q (wald, df), 0);
1284
1285               idx_correction ++;
1286               summary = true;
1287               gsl_matrix_free (subhessian);
1288               gsl_vector_free (temp);
1289             }
1290           else
1291             {
1292               ds_put_format (&str, "(%d)", ivar);
1293             }
1294
1295           tab_text (t, 1, row, TAB_LEFT | TAT_TITLE, ds_cstr (&str));
1296           if (ivar++ == df)
1297             {
1298               ++i; /* next interaction */
1299               ivar = 0;
1300             }
1301
1302           ds_destroy (&str);
1303
1304           if (summary)
1305             continue;
1306         }
1307       else
1308         {
1309           tab_text (t, 1, row, TAB_LEFT | TAT_TITLE, _("Constant"));
1310         }
1311
1312       tab_double (t, 2, row, 0, b, 0);
1313       tab_double (t, 3, row, 0, sqrt (sigma2), 0);
1314       tab_double (t, 4, row, 0, wald, 0);
1315       tab_double (t, 5, row, 0, df, &F_8_0);
1316       tab_double (t, 6, row, 0, gsl_cdf_chisq_Q (wald, df), 0);
1317       tab_double (t, 7, row, 0, exp (b), 0);
1318
1319       if (cmd->print & PRINT_CI)
1320         {
1321           int last_ci = nr;
1322           double wc = gsl_cdf_ugaussian_Pinv (0.5 + cmd->confidence / 200.0);
1323           wc *= sqrt (sigma2);
1324
1325           if (cmd->constant)
1326             last_ci--;
1327
1328           if (row < last_ci)
1329             {
1330               tab_double (t, 8, row, 0, exp (b - wc), 0);
1331               tab_double (t, 9, row, 0, exp (b + wc), 0);
1332             }
1333         }
1334     }
1335
1336   tab_submit (t);
1337 }
1338
1339
1340 /* Show the model summary box */
1341 static void
1342 output_model_summary (const struct lr_result *res,
1343                       double initial_log_likelihood, double log_likelihood)
1344 {
1345   const int heading_columns = 0;
1346   const int heading_rows = 1;
1347   struct tab_table *t;
1348
1349   const int nc = 4;
1350   int nr = heading_rows + 1;
1351   double cox;
1352
1353   t = tab_create (nc, nr);
1354   tab_title (t, _("Model Summary"));
1355
1356   tab_headers (t, heading_columns, 0, heading_rows, 0);
1357
1358   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
1359
1360   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
1361   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1362
1363   tab_text (t,  0, 0, TAB_LEFT | TAT_TITLE, _("Step 1"));
1364   tab_text (t,  1, 0, TAB_CENTER | TAT_TITLE, _("-2 Log likelihood"));
1365   tab_double (t,  1, 1, 0, -2 * log_likelihood, 0);
1366
1367
1368   tab_text (t,  2, 0, TAB_CENTER | TAT_TITLE, _("Cox & Snell R Square"));
1369   cox =  1.0 - exp((initial_log_likelihood - log_likelihood) * (2 / res->cc));
1370   tab_double (t,  2, 1, 0, cox, 0);
1371
1372   tab_text (t,  3, 0, TAB_CENTER | TAT_TITLE, _("Nagelkerke R Square"));
1373   tab_double (t,  3, 1, 0, cox / ( 1.0 - exp(initial_log_likelihood * (2 / res->cc))), 0);
1374
1375
1376   tab_submit (t);
1377 }
1378
1379 /* Show the case processing summary box */
1380 static void
1381 case_processing_summary (const struct lr_result *res)
1382 {
1383   const int heading_columns = 1;
1384   const int heading_rows = 1;
1385   struct tab_table *t;
1386
1387   const int nc = 3;
1388   const int nr = heading_rows + 3;
1389   casenumber total;
1390
1391   t = tab_create (nc, nr);
1392   tab_title (t, _("Case Processing Summary"));
1393
1394   tab_headers (t, heading_columns, 0, heading_rows, 0);
1395
1396   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
1397
1398   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
1399   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1400
1401   tab_text (t,  0, 0, TAB_LEFT | TAT_TITLE, _("Unweighted Cases"));
1402   tab_text (t,  1, 0, TAB_CENTER | TAT_TITLE, _("N"));
1403   tab_text (t,  2, 0, TAB_CENTER | TAT_TITLE, _("Percent"));
1404
1405
1406   tab_text (t,  0, 1, TAB_LEFT | TAT_TITLE, _("Included in Analysis"));
1407   tab_text (t,  0, 2, TAB_LEFT | TAT_TITLE, _("Missing Cases"));
1408   tab_text (t,  0, 3, TAB_LEFT | TAT_TITLE, _("Total"));
1409
1410   tab_double (t,  1, 1, 0, res->n_nonmissing, &F_8_0);
1411   tab_double (t,  1, 2, 0, res->n_missing, &F_8_0);
1412
1413   total = res->n_nonmissing + res->n_missing;
1414   tab_double (t,  1, 3, 0, total , &F_8_0);
1415
1416   tab_double (t,  2, 1, 0, 100 * res->n_nonmissing / (double) total, 0);
1417   tab_double (t,  2, 2, 0, 100 * res->n_missing / (double) total, 0);
1418   tab_double (t,  2, 3, 0, 100 * total / (double) total, 0);
1419
1420   tab_submit (t);
1421 }
1422
1423 static void
1424 output_categories (const struct lr_spec *cmd, const struct lr_result *res)
1425 {
1426   const struct fmt_spec *wfmt =
1427     cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
1428
1429   int cumulative_df;
1430   int i = 0;
1431   const int heading_columns = 2;
1432   const int heading_rows = 2;
1433   struct tab_table *t;
1434
1435   int nc ;
1436   int nr ;
1437
1438   int v;
1439   int r = 0;
1440
1441   int max_df = 0;
1442   int total_cats = 0;
1443   for (i = 0; i < cmd->n_cat_predictors; ++i)
1444     {
1445       size_t n = categoricals_n_count (res->cats, i);
1446       size_t df = categoricals_df (res->cats, i);
1447       if (max_df < df)
1448         max_df = df;
1449       total_cats += n;
1450     }
1451
1452   nc = heading_columns + 1 + max_df;
1453   nr = heading_rows + total_cats;
1454
1455   t = tab_create (nc, nr);
1456   tab_title (t, _("Categorical Variables' Codings"));
1457
1458   tab_headers (t, heading_columns, 0, heading_rows, 0);
1459
1460   tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
1461
1462   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
1463   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1464
1465
1466   tab_text (t, heading_columns, 1, TAB_CENTER | TAT_TITLE, _("Frequency"));
1467
1468   tab_joint_text_format (t, heading_columns + 1, 0, nc - 1, 0,
1469                          TAB_CENTER | TAT_TITLE, _("Parameter coding"));
1470
1471
1472   for (i = 0; i < max_df; ++i)
1473     {
1474       int c = heading_columns + 1 + i;
1475       tab_text_format (t,  c, 1, TAB_CENTER | TAT_TITLE, _("(%d)"), i + 1);
1476     }
1477
1478   cumulative_df = 0;
1479   for (v = 0; v < cmd->n_cat_predictors; ++v)
1480     {
1481       int cat;
1482       const struct interaction *cat_predictors = cmd->cat_predictors[v];
1483       int df =  categoricals_df (res->cats, v);
1484       struct string str;
1485       ds_init_empty (&str);
1486
1487       interaction_to_string (cat_predictors, &str);
1488
1489       tab_text (t, 0, heading_rows + r, TAB_LEFT | TAT_TITLE, ds_cstr (&str) );
1490
1491       ds_destroy (&str);
1492
1493       for (cat = 0; cat < categoricals_n_count (res->cats, v) ; ++cat)
1494         {
1495           struct string str;
1496           const struct ccase *c = categoricals_get_case_by_category_real (res->cats, v, cat);
1497           const double *freq = categoricals_get_user_data_by_category_real (res->cats, v, cat);
1498           
1499           int x;
1500           ds_init_empty (&str);
1501
1502           for (x = 0; x < cat_predictors->n_vars; ++x)
1503             {
1504               const union value *val = case_data (c, cat_predictors->vars[x]);
1505               var_append_value_name (cat_predictors->vars[x], val, &str);
1506
1507               if (x < cat_predictors->n_vars - 1)
1508                 ds_put_cstr (&str, " ");
1509             }
1510           
1511           tab_text   (t, 1, heading_rows + r, 0, ds_cstr (&str));
1512           ds_destroy (&str);
1513           tab_double (t, 2, heading_rows + r, 0, *freq, wfmt);
1514
1515           for (x = 0; x < df; ++x)
1516             {
1517               tab_double (t, heading_columns + 1 + x, heading_rows + r, 0, (cat == x), &F_8_0);
1518             }
1519           ++r;
1520         }
1521       cumulative_df += df;
1522     }
1523
1524   tab_submit (t);
1525
1526 }
1527
1528
1529 static void 
1530 output_classification_table (const struct lr_spec *cmd, const struct lr_result *res)
1531 {
1532   const struct fmt_spec *wfmt =
1533     cmd->wv ? var_get_print_format (cmd->wv) : &F_8_0;
1534
1535   const int heading_columns = 3;
1536   const int heading_rows = 3;
1537
1538   struct string sv0, sv1;
1539
1540   const int nc = heading_columns + 3;
1541   const int nr = heading_rows + 3;
1542
1543   struct tab_table *t = tab_create (nc, nr);
1544
1545   ds_init_empty (&sv0);
1546   ds_init_empty (&sv1);
1547
1548   tab_title (t, _("Classification Table"));
1549
1550   tab_headers (t, heading_columns, 0, heading_rows, 0);
1551
1552   tab_box (t, TAL_2, TAL_2, -1, -1, 0, 0, nc - 1, nr - 1);
1553   tab_box (t, -1, -1, -1, TAL_1, heading_columns, 0, nc - 1, nr - 1);
1554
1555   tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
1556   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1557
1558   tab_text (t,  0, heading_rows, TAB_CENTER | TAT_TITLE, _("Step 1"));
1559
1560
1561   tab_joint_text (t, heading_columns, 0, nc - 1, 0,
1562                   TAB_CENTER | TAT_TITLE, _("Predicted"));
1563
1564   tab_joint_text (t, heading_columns, 1, heading_columns + 1, 1, 
1565                   0, var_to_string (cmd->dep_var) );
1566
1567   tab_joint_text (t, 1, 2, 2, 2,
1568                   TAB_LEFT | TAT_TITLE, _("Observed"));
1569
1570   tab_text (t, 1, 3, TAB_LEFT, var_to_string (cmd->dep_var) );
1571
1572
1573   tab_joint_text (t, nc - 1, 1, nc - 1, 2,
1574                   TAB_CENTER | TAT_TITLE, _("Percentage\nCorrect"));
1575
1576
1577   tab_joint_text (t, 1, nr - 1, 2, nr - 1,
1578                   TAB_LEFT | TAT_TITLE, _("Overall Percentage"));
1579
1580
1581   tab_hline (t, TAL_1, 1, nc - 1, nr - 1);
1582
1583   var_append_value_name (cmd->dep_var, &res->y0, &sv0);
1584   var_append_value_name (cmd->dep_var, &res->y1, &sv1);
1585
1586   tab_text (t, 2, heading_rows,     TAB_LEFT,  ds_cstr (&sv0));
1587   tab_text (t, 2, heading_rows + 1, TAB_LEFT,  ds_cstr (&sv1));
1588
1589   tab_text (t, heading_columns,     2, 0,  ds_cstr (&sv0));
1590   tab_text (t, heading_columns + 1, 2, 0,  ds_cstr (&sv1));
1591
1592   ds_destroy (&sv0);
1593   ds_destroy (&sv1);
1594
1595   tab_double (t, heading_columns, 3,     0, res->tn, wfmt);
1596   tab_double (t, heading_columns + 1, 4, 0, res->tp, wfmt);
1597
1598   tab_double (t, heading_columns + 1, 3, 0, res->fp, wfmt);
1599   tab_double (t, heading_columns,     4, 0, res->fn, wfmt);
1600
1601   tab_double (t, heading_columns + 2, 3, 0, 100 * res->tn / (res->tn + res->fp), 0);
1602   tab_double (t, heading_columns + 2, 4, 0, 100 * res->tp / (res->tp + res->fn), 0);
1603
1604   tab_double (t, heading_columns + 2, 5, 0, 
1605               100 * (res->tp + res->tn) / (res->tp  + res->tn + res->fp + res->fn), 0);
1606
1607
1608   tab_submit (t);
1609 }