output: Introduce pivot tables.
[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/hash-functions.h"
64 #include "libpspp/hmap.h"
65 #include "libpspp/ll.h"
66 #include "libpspp/message.h"
67 #include "libpspp/misc.h"
68 #include "math/categoricals.h"
69 #include "math/interaction.h"
70 #include "output/pivot-table.h"
71
72 #include "gettext.h"
73 #define N_(msgid) msgid
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, 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               case_unref (c);
527               goto error;
528             }
529         }
530
531       if (v0set && value_equal (&res->y0, depval, width))
532           sumA += weight;
533
534       if (v1set && value_equal (&res->y1, depval, width))
535           sumB += weight;
536
537
538       res->cc += weight;
539
540       categoricals_update (res->cats, c);
541     }
542   casereader_destroy (reader);
543
544   categoricals_done (res->cats);
545
546   sum = sumB;
547
548   /* Ensure that Y0 is less than Y1.  Otherwise the mapping gets
549      inverted, which is confusing to users */
550   if (var_is_numeric (cmd->dep_var) && value_compare_3way (&res->y0, &res->y1, width) > 0)
551     {
552       union value tmp;
553       value_clone (&tmp, &res->y0, width);
554       value_copy (&res->y0, &res->y1, width);
555       value_copy (&res->y1, &tmp, width);
556       value_destroy (&tmp, width);
557       sum = sumA;
558     }
559
560   n_coefficients += categoricals_df_total (res->cats);
561   res->beta_hat = gsl_vector_calloc (n_coefficients);
562
563   if (cmd->constant)
564     {
565       double mean = sum / res->cc;
566       gsl_vector_set (res->beta_hat, res->beta_hat->size - 1, log (mean / (1 - mean)));
567     }
568
569   return true;
570
571  error:
572   casereader_destroy (reader);
573   return false;
574 }
575
576
577
578 /* Start of the logistic regression routine proper */
579 static bool
580 run_lr (const struct lr_spec *cmd, struct casereader *input,
581         const struct dataset *ds UNUSED)
582 {
583   int i;
584
585   bool converged = false;
586
587   /* Set the log likelihoods to a sentinel value */
588   double log_likelihood = SYSMIS;
589   double prev_log_likelihood = SYSMIS;
590   double initial_log_likelihood = SYSMIS;
591
592   struct lr_result work;
593   work.n_missing = 0;
594   work.n_nonmissing = 0;
595   work.warn_bad_weight = true;
596   work.cats = NULL;
597   work.beta_hat = NULL;
598   work.hessian = NULL;
599
600   /* Get the initial estimates of \beta and their standard errors.
601      And perform other auxiliary initialisation.  */
602   if (! initial_pass (cmd, &work, input))
603     goto error;
604
605   for (i = 0; i < cmd->n_cat_predictors; ++i)
606     {
607       if (1 >= categoricals_n_count (work.cats, i))
608         {
609           struct string str;
610           ds_init_empty (&str);
611
612           interaction_to_string (cmd->cat_predictors[i], &str);
613
614           msg (ME, _("Category %s does not have at least two distinct values. Logistic regression will not be run."),
615                ds_cstr(&str));
616           ds_destroy (&str);
617           goto error;
618         }
619     }
620
621   output_depvarmap (cmd, &work);
622
623   case_processing_summary (&work);
624
625
626   input = casereader_create_filter_missing (input,
627                                             cmd->indep_vars,
628                                             cmd->n_indep_vars,
629                                             cmd->exclude,
630                                             NULL,
631                                             NULL);
632
633   input = casereader_create_filter_missing (input,
634                                             &cmd->dep_var,
635                                             1,
636                                             cmd->exclude,
637                                             NULL,
638                                             NULL);
639
640   work.hessian = gsl_matrix_calloc (work.beta_hat->size, work.beta_hat->size);
641
642   /* Start the Newton Raphson iteration process... */
643   for( i = 0 ; i < cmd->max_iter ; ++i)
644     {
645       double min, max;
646       gsl_vector *v ;
647
648
649       hessian (cmd, &work, input,
650                cmd->predictor_vars, cmd->n_predictor_vars,
651                &converged);
652
653       gsl_linalg_cholesky_decomp (work.hessian);
654       gsl_linalg_cholesky_invert (work.hessian);
655
656       v = xt_times_y_pi (cmd, &work, input,
657                          cmd->predictor_vars, cmd->n_predictor_vars,
658                          cmd->dep_var,
659                          &log_likelihood);
660
661       {
662         /* delta = M.v */
663         gsl_vector *delta = gsl_vector_alloc (v->size);
664         gsl_blas_dgemv (CblasNoTrans, 1.0, work.hessian, v, 0, delta);
665         gsl_vector_free (v);
666
667
668         gsl_vector_add (work.beta_hat, delta);
669
670         gsl_vector_minmax (delta, &min, &max);
671
672         if ( fabs (min) < cmd->bcon && fabs (max) < cmd->bcon)
673           {
674             msg (MN, _("Estimation terminated at iteration number %d because parameter estimates changed by less than %g"),
675                  i + 1, cmd->bcon);
676             converged = true;
677           }
678
679         gsl_vector_free (delta);
680       }
681
682       if (i > 0)
683         {
684           if (-log_likelihood > -(1.0 - cmd->lcon) * prev_log_likelihood)
685             {
686               msg (MN, _("Estimation terminated at iteration number %d because Log Likelihood decreased by less than %g%%"), i + 1, 100 * cmd->lcon);
687               converged = true;
688             }
689         }
690       if (i == 0)
691         initial_log_likelihood = log_likelihood;
692       prev_log_likelihood = log_likelihood;
693
694       if (converged)
695         break;
696     }
697
698
699
700   if ( ! converged)
701     msg (MW, _("Estimation terminated at iteration number %d because maximum iterations has been reached"), i );
702
703
704   output_model_summary (&work, initial_log_likelihood, log_likelihood);
705
706   if (work.cats)
707     output_categories (cmd, &work);
708
709   output_classification_table (cmd, &work);
710   output_variables (cmd, &work);
711
712   casereader_destroy (input);
713   gsl_matrix_free (work.hessian);
714   gsl_vector_free (work.beta_hat);
715   categoricals_destroy (work.cats);
716
717   return true;
718
719  error:
720   casereader_destroy (input);
721   gsl_matrix_free (work.hessian);
722   gsl_vector_free (work.beta_hat);
723   categoricals_destroy (work.cats);
724
725   return false;
726 }
727
728 struct variable_node
729 {
730   struct hmap_node node;      /* Node in hash map. */
731   const struct variable *var; /* The variable */
732 };
733
734 static struct variable_node *
735 lookup_variable (const struct hmap *map, const struct variable *var, unsigned int hash)
736 {
737   struct variable_node *vn = NULL;
738   HMAP_FOR_EACH_WITH_HASH (vn, struct variable_node, node, hash, map)
739     {
740       if (vn->var == var)
741         break;
742
743       fprintf (stderr, "Warning: Hash table collision\n");
744     }
745
746   return vn;
747 }
748
749
750 /* Parse the LOGISTIC REGRESSION command syntax */
751 int
752 cmd_logistic (struct lexer *lexer, struct dataset *ds)
753 {
754   int i;
755   /* Temporary location for the predictor variables.
756      These may or may not include the categorical predictors */
757   const struct variable **pred_vars;
758   size_t n_pred_vars;
759   double cp = 0.5;
760
761   int v, x;
762   struct lr_spec lr;
763   lr.dict = dataset_dict (ds);
764   lr.n_predictor_vars = 0;
765   lr.predictor_vars = NULL;
766   lr.exclude = MV_ANY;
767   lr.wv = dict_get_weight (lr.dict);
768   lr.max_iter = 20;
769   lr.lcon = 0.0000;
770   lr.bcon = 0.001;
771   lr.min_epsilon = 0.00000001;
772   lr.constant = true;
773   lr.confidence = 95;
774   lr.print = PRINT_DEFAULT;
775   lr.cat_predictors = NULL;
776   lr.n_cat_predictors = 0;
777   lr.indep_vars = NULL;
778
779
780   if (lex_match_id (lexer, "VARIABLES"))
781     lex_match (lexer, T_EQUALS);
782
783   if (! (lr.dep_var = parse_variable_const (lexer, lr.dict)))
784     goto error;
785
786   if (! lex_force_match (lexer, T_WITH))
787     goto error;
788
789   if (!parse_variables_const (lexer, lr.dict,
790                               &pred_vars, &n_pred_vars,
791                               PV_NO_DUPLICATE))
792     goto error;
793
794
795   while (lex_token (lexer) != T_ENDCMD)
796     {
797       lex_match (lexer, T_SLASH);
798
799       if (lex_match_id (lexer, "MISSING"))
800         {
801           lex_match (lexer, T_EQUALS);
802           while (lex_token (lexer) != T_ENDCMD
803                  && lex_token (lexer) != T_SLASH)
804             {
805               if (lex_match_id (lexer, "INCLUDE"))
806                 {
807                   lr.exclude = MV_SYSTEM;
808                 }
809               else if (lex_match_id (lexer, "EXCLUDE"))
810                 {
811                   lr.exclude = MV_ANY;
812                 }
813               else
814                 {
815                   lex_error (lexer, NULL);
816                   goto error;
817                 }
818             }
819         }
820       else if (lex_match_id (lexer, "ORIGIN"))
821         {
822           lr.constant = false;
823         }
824       else if (lex_match_id (lexer, "NOORIGIN"))
825         {
826           lr.constant = true;
827         }
828       else if (lex_match_id (lexer, "NOCONST"))
829         {
830           lr.constant = false;
831         }
832       else if (lex_match_id (lexer, "EXTERNAL"))
833         {
834           /* This is for compatibility.  It does nothing */
835         }
836       else if (lex_match_id (lexer, "CATEGORICAL"))
837         {
838           lex_match (lexer, T_EQUALS);
839           do
840             {
841               lr.cat_predictors = xrealloc (lr.cat_predictors,
842                                   sizeof (*lr.cat_predictors) * ++lr.n_cat_predictors);
843               lr.cat_predictors[lr.n_cat_predictors - 1] = 0;
844             }
845           while (parse_design_interaction (lexer, lr.dict,
846                                            lr.cat_predictors + lr.n_cat_predictors - 1));
847           lr.n_cat_predictors--;
848         }
849       else if (lex_match_id (lexer, "PRINT"))
850         {
851           lex_match (lexer, T_EQUALS);
852           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
853             {
854               if (lex_match_id (lexer, "DEFAULT"))
855                 {
856                   lr.print |= PRINT_DEFAULT;
857                 }
858               else if (lex_match_id (lexer, "SUMMARY"))
859                 {
860                   lr.print |= PRINT_SUMMARY;
861                 }
862 #if 0
863               else if (lex_match_id (lexer, "CORR"))
864                 {
865                   lr.print |= PRINT_CORR;
866                 }
867               else if (lex_match_id (lexer, "ITER"))
868                 {
869                   lr.print |= PRINT_ITER;
870                 }
871               else if (lex_match_id (lexer, "GOODFIT"))
872                 {
873                   lr.print |= PRINT_GOODFIT;
874                 }
875 #endif
876               else if (lex_match_id (lexer, "CI"))
877                 {
878                   lr.print |= PRINT_CI;
879                   if (lex_force_match (lexer, T_LPAREN))
880                     {
881                       if (! lex_force_num (lexer))
882                         {
883                           lex_error (lexer, NULL);
884                           goto error;
885                         }
886                       lr.confidence = lex_number (lexer);
887                       lex_get (lexer);
888                       if ( ! lex_force_match (lexer, T_RPAREN))
889                         {
890                           lex_error (lexer, NULL);
891                           goto error;
892                         }
893                     }
894                 }
895               else if (lex_match_id (lexer, "ALL"))
896                 {
897                   lr.print = ~0x0000;
898                 }
899               else
900                 {
901                   lex_error (lexer, NULL);
902                   goto error;
903                 }
904             }
905         }
906       else if (lex_match_id (lexer, "CRITERIA"))
907         {
908           lex_match (lexer, T_EQUALS);
909           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
910             {
911               if (lex_match_id (lexer, "BCON"))
912                 {
913                   if (lex_force_match (lexer, T_LPAREN))
914                     {
915                       if (! lex_force_num (lexer))
916                         {
917                           lex_error (lexer, NULL);
918                           goto error;
919                         }
920                       lr.bcon = lex_number (lexer);
921                       lex_get (lexer);
922                       if ( ! lex_force_match (lexer, T_RPAREN))
923                         {
924                           lex_error (lexer, NULL);
925                           goto error;
926                         }
927                     }
928                 }
929               else if (lex_match_id (lexer, "ITERATE"))
930                 {
931                   if (lex_force_match (lexer, T_LPAREN))
932                     {
933                       if (! lex_force_int (lexer))
934                         {
935                           lex_error (lexer, NULL);
936                           goto error;
937                         }
938                       lr.max_iter = lex_integer (lexer);
939                       lex_get (lexer);
940                       if ( ! lex_force_match (lexer, T_RPAREN))
941                         {
942                           lex_error (lexer, NULL);
943                           goto error;
944                         }
945                     }
946                 }
947               else if (lex_match_id (lexer, "LCON"))
948                 {
949                   if (lex_force_match (lexer, T_LPAREN))
950                     {
951                       if (! lex_force_num (lexer))
952                         {
953                           lex_error (lexer, NULL);
954                           goto error;
955                         }
956                       lr.lcon = lex_number (lexer);
957                       lex_get (lexer);
958                       if ( ! lex_force_match (lexer, T_RPAREN))
959                         {
960                           lex_error (lexer, NULL);
961                           goto error;
962                         }
963                     }
964                 }
965               else if (lex_match_id (lexer, "EPS"))
966                 {
967                   if (lex_force_match (lexer, T_LPAREN))
968                     {
969                       if (! lex_force_num (lexer))
970                         {
971                           lex_error (lexer, NULL);
972                           goto error;
973                         }
974                       lr.min_epsilon = lex_number (lexer);
975                       lex_get (lexer);
976                       if ( ! lex_force_match (lexer, T_RPAREN))
977                         {
978                           lex_error (lexer, NULL);
979                           goto error;
980                         }
981                     }
982                 }
983               else if (lex_match_id (lexer, "CUT"))
984                 {
985                   if (lex_force_match (lexer, T_LPAREN))
986                     {
987                       if (! lex_force_num (lexer))
988                         {
989                           lex_error (lexer, NULL);
990                           goto error;
991                         }
992                       cp = lex_number (lexer);
993
994                       if (cp < 0 || cp > 1.0)
995                         {
996                           msg (ME, _("Cut point value must be in the range [0,1]"));
997                           goto error;
998                         }
999                       lex_get (lexer);
1000                       if ( ! lex_force_match (lexer, T_RPAREN))
1001                         {
1002                           lex_error (lexer, NULL);
1003                           goto error;
1004                         }
1005                     }
1006                 }
1007               else
1008                 {
1009                   lex_error (lexer, NULL);
1010                   goto error;
1011                 }
1012             }
1013         }
1014       else
1015         {
1016           lex_error (lexer, NULL);
1017           goto error;
1018         }
1019     }
1020
1021   lr.ilogit_cut_point = - log (1/cp - 1);
1022
1023
1024   /* Copy the predictor variables from the temporary location into the
1025      final one, dropping any categorical variables which appear there.
1026      FIXME: This is O(NxM).
1027   */
1028   {
1029   struct variable_node *vn, *next;
1030   struct hmap allvars;
1031   hmap_init (&allvars);
1032   for (v = x = 0; v < n_pred_vars; ++v)
1033     {
1034       bool drop = false;
1035       const struct variable *var = pred_vars[v];
1036       int cv = 0;
1037
1038       unsigned int hash = hash_pointer (var, 0);
1039       struct variable_node *vn = lookup_variable (&allvars, var, hash);
1040       if (vn == NULL)
1041         {
1042           vn = xmalloc (sizeof *vn);
1043           vn->var = var;
1044           hmap_insert (&allvars, &vn->node,  hash);
1045         }
1046
1047       for (cv = 0; cv < lr.n_cat_predictors ; ++cv)
1048         {
1049           int iv;
1050           const struct interaction *iact = lr.cat_predictors[cv];
1051           for (iv = 0 ; iv < iact->n_vars ; ++iv)
1052             {
1053               const struct variable *ivar = iact->vars[iv];
1054               unsigned int hash = hash_pointer (ivar, 0);
1055               struct variable_node *vn = lookup_variable (&allvars, ivar, hash);
1056               if (vn == NULL)
1057                 {
1058                   vn = xmalloc (sizeof *vn);
1059                   vn->var = ivar;
1060
1061                   hmap_insert (&allvars, &vn->node,  hash);
1062                 }
1063
1064               if (var == ivar)
1065                 {
1066                   drop = true;
1067                 }
1068             }
1069         }
1070
1071       if (drop)
1072         continue;
1073
1074       lr.predictor_vars = xrealloc (lr.predictor_vars, sizeof *lr.predictor_vars * (x + 1));
1075       lr.predictor_vars[x++] = var;
1076       lr.n_predictor_vars++;
1077     }
1078   free (pred_vars);
1079
1080   lr.n_indep_vars = hmap_count (&allvars);
1081   lr.indep_vars = xmalloc (lr.n_indep_vars * sizeof *lr.indep_vars);
1082
1083   /* Interate over each variable and push it into the array */
1084   x = 0;
1085   HMAP_FOR_EACH_SAFE (vn, next, struct variable_node, node, &allvars)
1086     {
1087       lr.indep_vars[x++] = vn->var;
1088       free (vn);
1089     }
1090   hmap_destroy (&allvars);
1091   }
1092
1093
1094   /* logistical regression for each split group */
1095   {
1096     struct casegrouper *grouper;
1097     struct casereader *group;
1098     bool ok;
1099
1100     grouper = casegrouper_create_splits (proc_open (ds), lr.dict);
1101     while (casegrouper_get_next_group (grouper, &group))
1102       ok = run_lr (&lr, group, ds);
1103     ok = casegrouper_destroy (grouper);
1104     ok = proc_commit (ds) && ok;
1105   }
1106
1107   for (i = 0 ; i < lr.n_cat_predictors; ++i)
1108     {
1109       interaction_destroy (lr.cat_predictors[i]);
1110     }
1111   free (lr.predictor_vars);
1112   free (lr.cat_predictors);
1113   free (lr.indep_vars);
1114
1115   return CMD_SUCCESS;
1116
1117  error:
1118
1119   for (i = 0 ; i < lr.n_cat_predictors; ++i)
1120     {
1121       interaction_destroy (lr.cat_predictors[i]);
1122     }
1123   free (lr.predictor_vars);
1124   free (lr.cat_predictors);
1125   free (lr.indep_vars);
1126
1127   return CMD_FAILURE;
1128 }
1129
1130
1131 \f
1132
1133 /* Show the Dependent Variable Encoding box.
1134    This indicates how the dependent variable
1135    is mapped to the internal zero/one values.
1136 */
1137 static void
1138 output_depvarmap (const struct lr_spec *cmd, const struct lr_result *res)
1139 {
1140   struct pivot_table *table = pivot_table_create (
1141     N_("Dependent Variable Encoding"));
1142
1143   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Mapping"),
1144                           N_("Internal Value"));
1145
1146   struct pivot_dimension *original = pivot_dimension_create (
1147     table, PIVOT_AXIS_ROW, N_("Original Value"));
1148   original->root->show_label = true;
1149
1150   for (int i = 0; i < 2; i++)
1151     {
1152       const union value *v = i ? &res->y1 : &res->y0;
1153       int orig_idx = pivot_category_create_leaf (
1154         original->root, pivot_value_new_var_value (cmd->dep_var, v));
1155       pivot_table_put2 (table, 0, orig_idx, pivot_value_new_number (
1156                           map_dependent_var (cmd, res, v)));
1157     }
1158
1159   pivot_table_submit (table);
1160 }
1161
1162
1163 /* Show the Variables in the Equation box */
1164 static void
1165 output_variables (const struct lr_spec *cmd,
1166                   const struct lr_result *res)
1167 {
1168   struct pivot_table *table = pivot_table_create (
1169     N_("Variables in the Equation"));
1170
1171   struct pivot_dimension *statistics = pivot_dimension_create (
1172     table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1173     N_("B"), PIVOT_RC_OTHER,
1174     N_("S.E."), PIVOT_RC_OTHER,
1175     N_("Wald"), PIVOT_RC_OTHER,
1176     N_("df"), PIVOT_RC_INTEGER,
1177     N_("Sig."), PIVOT_RC_SIGNIFICANCE,
1178     N_("Exp(B)"), PIVOT_RC_OTHER);
1179   if (cmd->print & PRINT_CI)
1180     {
1181       struct pivot_category *group = pivot_category_create_group__ (
1182         statistics->root,
1183         pivot_value_new_text_format (N_("%d%% CI for Exp(B)"),
1184                                      cmd->confidence));
1185       pivot_category_create_leaves (group, N_("Lower"), N_("Upper"));
1186     }
1187
1188   struct pivot_dimension *variables = pivot_dimension_create (
1189     table, PIVOT_AXIS_ROW, N_("Variables"));
1190   struct pivot_category *step1 = pivot_category_create_group (
1191     variables->root, N_("Step 1"));
1192
1193   int ivar = 0;
1194   int idx_correction = 0;
1195   int i = 0;
1196
1197   int nr = cmd->n_predictor_vars;
1198   if (cmd->constant)
1199     nr++;
1200   if (res->cats)
1201     nr += categoricals_df_total (res->cats) + cmd->n_cat_predictors;
1202
1203   for (int row = 0; row < nr; row++)
1204     {
1205       const int idx = row - idx_correction;
1206
1207       int var_idx;
1208       if (idx < cmd->n_predictor_vars)
1209         var_idx = pivot_category_create_leaf (
1210           step1, pivot_value_new_variable (cmd->predictor_vars[idx]));
1211       else if (i < cmd->n_cat_predictors)
1212         {
1213           const struct interaction *cat_predictors = cmd->cat_predictors[i];
1214           struct string str = DS_EMPTY_INITIALIZER;
1215           interaction_to_string (cat_predictors, &str);
1216           if (ivar != 0)
1217             ds_put_format (&str, "(%d)", ivar);
1218           var_idx = pivot_category_create_leaf (
1219             step1, pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
1220
1221           int df = categoricals_df (res->cats, i);
1222           bool summary = ivar == 0;
1223           if (summary)
1224             {
1225               /* Calculate the Wald statistic,
1226                  which is \beta' C^-1 \beta .
1227                  where \beta is the vector of the coefficient estimates comprising this
1228                  categorial variable. and C is the corresponding submatrix of the
1229                  hessian matrix.
1230               */
1231               gsl_matrix_const_view mv =
1232                 gsl_matrix_const_submatrix (res->hessian, idx, idx, df, df);
1233               gsl_matrix *subhessian = gsl_matrix_alloc (mv.matrix.size1, mv.matrix.size2);
1234               gsl_vector_const_view vv = gsl_vector_const_subvector (res->beta_hat, idx, df);
1235               gsl_vector *temp = gsl_vector_alloc (df);
1236
1237               gsl_matrix_memcpy (subhessian, &mv.matrix);
1238               gsl_linalg_cholesky_decomp (subhessian);
1239               gsl_linalg_cholesky_invert (subhessian);
1240
1241               gsl_blas_dgemv (CblasTrans, 1.0, subhessian, &vv.vector, 0, temp);
1242               double wald;
1243               gsl_blas_ddot (temp, &vv.vector, &wald);
1244
1245               double entries[] = { wald, df, gsl_cdf_chisq_Q (wald, df) };
1246               for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1247                 pivot_table_put2 (table, j + 2, var_idx,
1248                                   pivot_value_new_number (entries[j]));
1249
1250               idx_correction++;
1251               gsl_matrix_free (subhessian);
1252               gsl_vector_free (temp);
1253             }
1254
1255           if (ivar++ == df)
1256             {
1257               ++i; /* next interaction */
1258               ivar = 0;
1259             }
1260
1261           if (summary)
1262             continue;
1263         }
1264       else
1265         var_idx = pivot_category_create_leaves (step1, N_("Constant"));
1266
1267       double b = gsl_vector_get (res->beta_hat, idx);
1268       double sigma2 = gsl_matrix_get (res->hessian, idx, idx);
1269       double wald = pow2 (b) / sigma2;
1270       double df = 1;
1271       double wc = (gsl_cdf_ugaussian_Pinv (0.5 + cmd->confidence / 200.0)
1272                    * sqrt (sigma2));
1273       bool show_ci = cmd->print & PRINT_CI && row < nr - cmd->constant;
1274
1275       double entries[] = {
1276         b,
1277         sqrt (sigma2),
1278         wald,
1279         df,
1280         gsl_cdf_chisq_Q (wald, df),
1281         exp (b),
1282         show_ci ? exp (b - wc) : SYSMIS,
1283         show_ci ? exp (b + wc) : SYSMIS,
1284       };
1285       for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1286         if (entries[j] != SYSMIS)
1287           pivot_table_put2 (table, j, var_idx,
1288                             pivot_value_new_number (entries[j]));
1289     }
1290
1291   pivot_table_submit (table);
1292 }
1293
1294
1295 /* Show the model summary box */
1296 static void
1297 output_model_summary (const struct lr_result *res,
1298                       double initial_log_likelihood, double log_likelihood)
1299 {
1300   struct pivot_table *table = pivot_table_create (N_("Model Summary"));
1301
1302   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1303                           N_("-2 Log likelihood"), PIVOT_RC_OTHER,
1304                           N_("Cox & Snell R Square"), PIVOT_RC_OTHER,
1305                           N_("Nagelkerke R Square"), PIVOT_RC_OTHER);
1306
1307   struct pivot_dimension *step = pivot_dimension_create (
1308     table, PIVOT_AXIS_ROW, N_("Step"));
1309   step->root->show_label = true;
1310   pivot_category_create_leaf (step->root, pivot_value_new_integer (1));
1311
1312   double cox = (1.0 - exp ((initial_log_likelihood - log_likelihood)
1313                            * (2 / res->cc)));
1314   double entries[] = {
1315     -2 * log_likelihood,
1316     cox,
1317     cox / ( 1.0 - exp(initial_log_likelihood * (2 / res->cc)))
1318   };
1319   for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1320     pivot_table_put2 (table, i, 0, pivot_value_new_number (entries[i]));
1321
1322   pivot_table_submit (table);
1323 }
1324
1325 /* Show the case processing summary box */
1326 static void
1327 case_processing_summary (const struct lr_result *res)
1328 {
1329   struct pivot_table *table = pivot_table_create (
1330     N_("Case Processing Summary"));
1331
1332   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1333                           N_("N"), PIVOT_RC_COUNT,
1334                           N_("Percent"), PIVOT_RC_PERCENT);
1335
1336   struct pivot_dimension *cases = pivot_dimension_create (
1337     table, PIVOT_AXIS_ROW, N_("Unweighted Cases"),
1338     N_("Included in Analysis"), N_("Missing Cases"), N_("Total"));
1339   cases->root->show_label = true;
1340
1341   double total = res->n_nonmissing + res->n_missing;
1342   struct entry
1343     {
1344       int stat_idx;
1345       int case_idx;
1346       double x;
1347     }
1348   entries[] = {
1349     { 0, 0, res->n_nonmissing },
1350     { 0, 1, res->n_missing },
1351     { 0, 2, total },
1352     { 1, 0, 100.0 * res->n_nonmissing / total },
1353     { 1, 1, 100.0 * res->n_missing / total },
1354     { 1, 2, 100.0 },
1355   };
1356   for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1357     pivot_table_put2 (table, entries[i].stat_idx, entries[i].case_idx,
1358                       pivot_value_new_number (entries[i].x));
1359
1360   pivot_table_submit (table);
1361 }
1362
1363 static void
1364 output_categories (const struct lr_spec *cmd, const struct lr_result *res)
1365 {
1366   struct pivot_table *table = pivot_table_create (
1367     N_("Categorical Variables' Codings"));
1368   pivot_table_set_weight_var (table, dict_get_weight (cmd->dict));
1369
1370   int max_df = 0;
1371   int total_cats = 0;
1372   for (int i = 0; i < cmd->n_cat_predictors; ++i)
1373     {
1374       size_t n = categoricals_n_count (res->cats, i);
1375       size_t df = categoricals_df (res->cats, i);
1376       if (max_df < df)
1377         max_df = df;
1378       total_cats += n;
1379     }
1380
1381   struct pivot_dimension *codings = pivot_dimension_create (
1382     table, PIVOT_AXIS_COLUMN, N_("Codings"),
1383     N_("Frequency"), PIVOT_RC_COUNT);
1384   struct pivot_category *coding_group = pivot_category_create_group (
1385     codings->root, N_("Parameter coding"));
1386   for (int i = 0; i < max_df; ++i)
1387     pivot_category_create_leaf_rc (
1388       coding_group,
1389       pivot_value_new_user_text_nocopy (xasprintf ("(%d)", i + 1)),
1390       PIVOT_RC_INTEGER);
1391
1392   struct pivot_dimension *categories = pivot_dimension_create (
1393     table, PIVOT_AXIS_ROW, N_("Categories"));
1394
1395   int cumulative_df = 0;
1396   for (int v = 0; v < cmd->n_cat_predictors; ++v)
1397     {
1398       int cat;
1399       const struct interaction *cat_predictors = cmd->cat_predictors[v];
1400       int df = categoricals_df (res->cats, v);
1401
1402       struct string str = DS_EMPTY_INITIALIZER;
1403       interaction_to_string (cat_predictors, &str);
1404       struct pivot_category *var_group = pivot_category_create_group__ (
1405         categories->root,
1406         pivot_value_new_user_text_nocopy (ds_steal_cstr (&str)));
1407
1408       for (cat = 0; cat < categoricals_n_count (res->cats, v) ; ++cat)
1409         {
1410           const struct ccase *c = categoricals_get_case_by_category_real (
1411             res->cats, v, cat);
1412           struct string label = DS_EMPTY_INITIALIZER;
1413           for (int x = 0; x < cat_predictors->n_vars; ++x)
1414             {
1415               if (!ds_is_empty (&label))
1416                 ds_put_byte (&label, ' ');
1417
1418               const union value *val = case_data (c, cat_predictors->vars[x]);
1419               var_append_value_name (cat_predictors->vars[x], val, &label);
1420             }
1421           int cat_idx = pivot_category_create_leaf (
1422             var_group,
1423             pivot_value_new_user_text_nocopy (ds_steal_cstr (&label)));
1424
1425           double *freq = categoricals_get_user_data_by_category_real (
1426             res->cats, v, cat);
1427           pivot_table_put2 (table, 0, cat_idx, pivot_value_new_number (*freq));
1428
1429           for (int x = 0; x < df; ++x)
1430             pivot_table_put2 (table, x + 1, cat_idx,
1431                               pivot_value_new_number (cat == x));
1432         }
1433       cumulative_df += df;
1434     }
1435
1436   pivot_table_submit (table);
1437 }
1438
1439 static void
1440 create_classification_dimension (const struct lr_spec *cmd,
1441                                  const struct lr_result *res,
1442                                  struct pivot_table *table,
1443                                  enum pivot_axis_type axis_type,
1444                                  const char *label, const char *total)
1445 {
1446   struct pivot_dimension *d = pivot_dimension_create (
1447     table, axis_type, label);
1448   d->root->show_label = true;
1449   struct pivot_category *pred_group = pivot_category_create_group__ (
1450     d->root, pivot_value_new_variable (cmd->dep_var));
1451   for (int i = 0; i < 2; i++)
1452     {
1453       const union value *y = i ? &res->y1 : &res->y0;
1454       pivot_category_create_leaf_rc (
1455         pred_group, pivot_value_new_var_value (cmd->dep_var, y),
1456         PIVOT_RC_COUNT);
1457     }
1458   pivot_category_create_leaves (d->root, total, PIVOT_RC_PERCENT);
1459 }
1460
1461 static void
1462 output_classification_table (const struct lr_spec *cmd, const struct lr_result *res)
1463 {
1464   struct pivot_table *table = pivot_table_create (N_("Classification Table"));
1465   pivot_table_set_weight_var (table, cmd->wv);
1466
1467   create_classification_dimension (cmd, res, table, PIVOT_AXIS_COLUMN,
1468                                    N_("Predicted"), N_("Percentage Correct"));
1469   create_classification_dimension (cmd, res, table, PIVOT_AXIS_ROW,
1470                                    N_("Observed"), N_("Overall Percentage"));
1471
1472   pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Step"), N_("Step 1"));
1473
1474   struct entry
1475     {
1476       int pred_idx;
1477       int obs_idx;
1478       double x;
1479     }
1480   entries[] = {
1481     { 0, 0, res->tn },
1482     { 0, 1, res->fn },
1483     { 1, 0, res->fp },
1484     { 1, 1, res->tp },
1485     { 2, 0, 100 * res->tn / (res->tn + res->fp) },
1486     { 2, 1, 100 * res->tp / (res->tp + res->fn) },
1487     { 2, 2,
1488       100 * (res->tp + res->tn) / (res->tp  + res->tn + res->fp + res->fn)},
1489   };
1490   for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1491     {
1492       const struct entry *e = &entries[i];
1493       pivot_table_put3 (table, e->pred_idx, e->obs_idx, 0,
1494                         pivot_value_new_number (e->x));
1495     }
1496
1497   pivot_table_submit (table);
1498 }