CROSSTABS: Always cite all the dimensions if there are too many.
[pspp] / src / language / commands / crosstabs.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 /* FIXME:
18
19    - How to calculate significance of some symmetric and directional measures?
20    - How to calculate ASE for symmetric Somers ' d?
21    - How to calculate ASE for Goodman and Kruskal's tau?
22    - How to calculate approx. T of symmetric uncertainty coefficient?
23
24 */
25
26 #include <config.h>
27
28 #include <ctype.h>
29 #include <float.h>
30 #include <gsl/gsl_cdf.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33
34 #include "data/case.h"
35 #include "data/casegrouper.h"
36 #include "data/casereader.h"
37 #include "data/data-out.h"
38 #include "data/dataset.h"
39 #include "data/dictionary.h"
40 #include "data/format.h"
41 #include "data/value-labels.h"
42 #include "data/variable.h"
43 #include "language/command.h"
44 #include "language/commands/freq.h"
45 #include "language/commands/split-file.h"
46 #include "language/lexer/lexer.h"
47 #include "language/lexer/variable-parser.h"
48 #include "libpspp/array.h"
49 #include "libpspp/assertion.h"
50 #include "libpspp/compiler.h"
51 #include "libpspp/hash-functions.h"
52 #include "libpspp/hmap.h"
53 #include "libpspp/hmapx.h"
54 #include "libpspp/message.h"
55 #include "libpspp/misc.h"
56 #include "libpspp/pool.h"
57 #include "libpspp/str.h"
58 #include "output/pivot-table.h"
59 #include "output/charts/barchart.h"
60
61 #include "gl/minmax.h"
62 #include "gl/xalloc-oversized.h"
63 #include "gl/xalloc.h"
64 #include "gl/xsize.h"
65
66 #include "gettext.h"
67 #define _(msgid) gettext (msgid)
68 #define N_(msgid) msgid
69
70 /* Kinds of cells in the crosstabulation. */
71 #define CRS_CELLS                                               \
72     C(COUNT, N_("Count"), PIVOT_RC_COUNT)                       \
73     C(EXPECTED, N_("Expected"), PIVOT_RC_OTHER)                 \
74     C(ROW, N_("Row %"), PIVOT_RC_PERCENT)                       \
75     C(COLUMN, N_("Column %"), PIVOT_RC_PERCENT)                 \
76     C(TOTAL, N_("Total %"), PIVOT_RC_PERCENT)                   \
77     C(RESIDUAL, N_("Residual"), PIVOT_RC_RESIDUAL)              \
78     C(SRESIDUAL, N_("Std. Residual"), PIVOT_RC_RESIDUAL)        \
79     C(ASRESIDUAL, N_("Adjusted Residual"), PIVOT_RC_RESIDUAL)
80 enum crs_cell
81   {
82 #define C(KEYWORD, STRING, RC) CRS_CL_##KEYWORD,
83     CRS_CELLS
84 #undef C
85   };
86 enum {
87 #define C(KEYWORD, STRING, RC) + 1
88   CRS_N_CELLS = CRS_CELLS
89 #undef C
90 };
91 #define CRS_ALL_CELLS ((1u << CRS_N_CELLS) - 1)
92
93 /* Kinds of statistics. */
94 #define CRS_STATISTICS                          \
95     S(CHISQ)                                    \
96     S(PHI)                                      \
97     S(CC)                                       \
98     S(LAMBDA)                                   \
99     S(UC)                                       \
100     S(BTAU)                                     \
101     S(CTAU)                                     \
102     S(RISK)                                     \
103     S(GAMMA)                                    \
104     S(D)                                        \
105     S(KAPPA)                                    \
106     S(ETA)                                      \
107     S(CORR)
108 enum crs_statistic_index {
109 #define S(KEYWORD) CRS_ST_##KEYWORD##_INDEX,
110   CRS_STATISTICS
111 #undef S
112 };
113 enum crs_statistic_bit {
114 #define S(KEYWORD) CRS_ST_##KEYWORD = 1u << CRS_ST_##KEYWORD##_INDEX,
115   CRS_STATISTICS
116 #undef S
117 };
118 enum {
119 #define S(KEYWORD) + 1
120   CRS_N_STATISTICS = CRS_STATISTICS
121 #undef S
122 };
123 #define CRS_ALL_STATISTICS ((1u << CRS_N_STATISTICS) - 1)
124
125 /* Number of chi-square statistics. */
126 #define N_CHISQ 5
127
128 /* Number of symmetric statistics. */
129 #define N_SYMMETRIC 9
130
131 /* Number of directional statistics. */
132 #define N_DIRECTIONAL 13
133
134 /* Indexes into the 'vars' member of struct crosstabulation and
135    struct crosstab member. */
136 enum
137   {
138     ROW_VAR = 0,                /* Row variable. */
139     COL_VAR = 1                 /* Column variable. */
140     /* Higher indexes cause multiple tables to be output. */
141   };
142
143 struct xtab_var
144   {
145     const struct variable *var;
146     union value *values;
147     size_t n_values;
148   };
149
150 /* A crosstabulation of 2 or more variables. */
151 struct crosstabulation
152   {
153     struct crosstabs_proc *proc;
154     struct fmt_spec weight_format; /* Format for weight variable. */
155     double missing;             /* Weight of missing cases. */
156
157     /* Variables (2 or more). */
158     size_t n_vars;
159     struct xtab_var *vars;
160
161     /* Constants (0 or more). */
162     size_t n_consts;
163     struct xtab_var *const_vars;
164     size_t *const_indexes;
165
166     /* Data. */
167     struct hmap data;
168     struct freq **entries;
169     size_t n_entries;
170
171     /* Number of statistically interesting columns/rows
172        (columns/rows with data in them). */
173     size_t ns_cols, ns_rows;
174
175     /* Matrix contents. */
176     double *mat;                /* Matrix proper. */
177     double *row_tot;            /* Row totals. */
178     double *col_tot;            /* Column totals. */
179     double total;               /* Grand total. */
180
181     /* Syntax. */
182     int start_ofs;
183     int end_ofs;
184   };
185
186 /* Integer mode variable info. */
187 struct var_range
188   {
189     struct hmap_node hmap_node; /* In struct crosstabs_proc var_ranges map. */
190     const struct variable *var; /* The variable. */
191     int min;                    /* Minimum value. */
192     int max;                    /* Maximum value + 1. */
193     int count;                  /* max - min. */
194   };
195
196 struct crosstabs_proc
197   {
198     const struct dictionary *dict;
199     enum { INTEGER, GENERAL } mode;
200     enum mv_class exclude;
201     bool barchart;
202     bool bad_warn;
203     struct fmt_spec weight_format;
204
205     /* Variables specifies on VARIABLES. */
206     const struct variable **variables;
207     size_t n_variables;
208     struct hmap var_ranges;
209
210     /* TABLES. */
211     struct crosstabulation *pivots;
212     size_t n_pivots;
213
214     /* CELLS. */
215     size_t n_cells;             /* Number of cells requested. */
216     unsigned int cells;         /* Bit k is 1 if cell k is requested. */
217     int a_cells[CRS_N_CELLS];   /* 0...n_cells-1 are the requested cells. */
218
219     /* Rounding of cells. */
220     bool round_case_weights;    /* Round case weights? */
221     bool round_cells;           /* If !round_case_weights, round cells? */
222     bool round_down;            /* Round down? (otherwise to nearest) */
223
224     /* STATISTICS. */
225     unsigned int statistics;    /* Bit k is 1 if statistic k is requested. */
226
227     bool descending;            /* True if descending sort order is requested. */
228   };
229
230 static bool parse_crosstabs_tables (struct lexer *, struct dataset *,
231                                     struct crosstabs_proc *);
232 static bool parse_crosstabs_variables (struct lexer *, struct dataset *,
233                                        struct crosstabs_proc *);
234
235 static const struct var_range *get_var_range (const struct crosstabs_proc *,
236                                               const struct variable *);
237
238 static bool should_tabulate_case (const struct crosstabulation *,
239                                   const struct ccase *, enum mv_class exclude);
240 static void tabulate_general_case (struct crosstabulation *, const struct ccase *,
241                                    double weight);
242 static void tabulate_integer_case (struct crosstabulation *, const struct ccase *,
243                                    double weight);
244 static void postcalc (struct crosstabs_proc *, struct lexer *);
245
246 static double
247 round_weight (const struct crosstabs_proc *proc, double weight)
248 {
249   return proc->round_down ? floor (weight) : floor (weight + 0.5);
250 }
251
252 #define FOR_EACH_POPULATED_COLUMN(C, XT) \
253   for (size_t C = next_populated_column (0, XT); \
254        C < (XT)->vars[COL_VAR].n_values;      \
255        C = next_populated_column (C + 1, XT))
256 static size_t
257 next_populated_column (size_t c, const struct crosstabulation *xt)
258 {
259   size_t n_columns = xt->vars[COL_VAR].n_values;
260   for (; c < n_columns; c++)
261     if (xt->col_tot[c])
262       break;
263   return c;
264 }
265
266 #define FOR_EACH_POPULATED_ROW(R, XT) \
267   for (size_t R = next_populated_row (0, XT); R < (XT)->vars[ROW_VAR].n_values; \
268        R = next_populated_row (R + 1, XT))
269 static size_t
270 next_populated_row (size_t r, const struct crosstabulation *xt)
271 {
272   size_t n_rows = xt->vars[ROW_VAR].n_values;
273   for (; r < n_rows; r++)
274     if (xt->row_tot[r])
275       break;
276   return r;
277 }
278
279 /* Parses and executes the CROSSTABS procedure. */
280 int
281 cmd_crosstabs (struct lexer *lexer, struct dataset *ds)
282 {
283   int result = CMD_FAILURE;
284
285   struct crosstabs_proc proc = {
286     .dict = dataset_dict (ds),
287     .mode = GENERAL,
288     .exclude = MV_ANY,
289     .barchart = false,
290     .bad_warn = true,
291     .weight_format = *dict_get_weight_format (dataset_dict (ds)),
292
293     .variables = NULL,
294     .n_variables = 0,
295     .var_ranges = HMAP_INITIALIZER (proc.var_ranges),
296
297     .pivots = NULL,
298     .n_pivots = 0,
299
300     .cells = 1u << CRS_CL_COUNT,
301     /* n_cells and a_cells will be filled in later. */
302
303     .round_case_weights = false,
304     .round_cells = false,
305     .round_down = false,
306
307     .statistics = 0,
308
309     .descending = false,
310   };
311   bool show_tables = true;
312   int exclude_ofs = 0;
313   lex_match (lexer, T_SLASH);
314   for (;;)
315     {
316       if (lex_match_id (lexer, "VARIABLES"))
317         {
318           if (!parse_crosstabs_variables (lexer, ds, &proc))
319             goto exit;
320         }
321       else if (lex_match_id (lexer, "MISSING"))
322         {
323           lex_match (lexer, T_EQUALS);
324           exclude_ofs = lex_ofs (lexer);
325           if (lex_match_id (lexer, "TABLE"))
326             proc.exclude = MV_ANY;
327           else if (lex_match_id (lexer, "INCLUDE"))
328             proc.exclude = MV_SYSTEM;
329           else if (lex_match_id (lexer, "REPORT"))
330             proc.exclude = 0;
331           else
332             {
333               lex_error_expecting (lexer, "TABLE", "INCLUDE", "REPORT");
334               goto exit;
335             }
336         }
337       else if (lex_match_id (lexer, "COUNT"))
338         {
339           lex_match (lexer, T_EQUALS);
340
341           /* Default is CELL. */
342           proc.round_case_weights = false;
343           proc.round_cells = true;
344
345           while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
346             {
347               if (lex_match_id (lexer, "ASIS"))
348                 {
349                   proc.round_case_weights = false;
350                   proc.round_cells = false;
351                 }
352               else if (lex_match_id (lexer, "CASE"))
353                 {
354                   proc.round_case_weights = true;
355                   proc.round_cells = false;
356                 }
357               else if (lex_match_id (lexer, "CELL"))
358                 {
359                   proc.round_case_weights = false;
360                   proc.round_cells = true;
361                 }
362               else if (lex_match_id (lexer, "ROUND"))
363                 proc.round_down = false;
364               else if (lex_match_id (lexer, "TRUNCATE"))
365                 proc.round_down = true;
366               else
367                 {
368                   lex_error_expecting (lexer, "ASIS", "CASE", "CELL",
369                                        "ROUND", "TRUNCATE");
370                   goto exit;
371                 }
372               lex_match (lexer, T_COMMA);
373             }
374         }
375       else if (lex_match_id (lexer, "FORMAT"))
376         {
377           lex_match (lexer, T_EQUALS);
378           while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
379             {
380               if (lex_match_id (lexer, "AVALUE"))
381                 proc.descending = false;
382               else if (lex_match_id (lexer, "DVALUE"))
383                 proc.descending = true;
384               else if (lex_match_id (lexer, "TABLES"))
385                 show_tables = true;
386               else if (lex_match_id (lexer, "NOTABLES"))
387                 show_tables = false;
388               else
389                 {
390                   lex_error_expecting (lexer, "AVALUE", "DVALUE",
391                                        "TABLES", "NOTABLES");
392                   goto exit;
393                 }
394               lex_match (lexer, T_COMMA);
395             }
396         }
397       else if (lex_match_id (lexer, "BARCHART"))
398         proc.barchart = true;
399       else if (lex_match_id (lexer, "CELLS"))
400         {
401           lex_match (lexer, T_EQUALS);
402
403           if (lex_match_id (lexer, "NONE"))
404             proc.cells = 0;
405           else if (lex_match (lexer, T_ALL))
406             proc.cells = CRS_ALL_CELLS;
407           else
408             {
409               proc.cells = 0;
410               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
411                 {
412 #define C(KEYWORD, STRING, RC)                                  \
413                   if (lex_match_id (lexer, #KEYWORD))           \
414                     {                                           \
415                       proc.cells |= 1u << CRS_CL_##KEYWORD;     \
416                       continue;                                 \
417                     }
418                   CRS_CELLS
419 #undef C
420
421                   static const char *cells[] =
422                     {
423 #define C(KEYWORD, STRING, RC) #KEYWORD,
424                       CRS_CELLS
425 #undef C
426                     };
427                   lex_error_expecting_array (lexer, cells,
428                                              sizeof cells / sizeof *cells);
429                   goto exit;
430                 }
431               if (!proc.cells)
432                 proc.cells = ((1u << CRS_CL_COUNT) | (1u << CRS_CL_ROW)
433                               | (1u << CRS_CL_COLUMN) | (1u << CRS_CL_TOTAL));
434             }
435         }
436       else if (lex_match_id (lexer, "STATISTICS"))
437         {
438           lex_match (lexer, T_EQUALS);
439
440           if (lex_match_id (lexer, "NONE"))
441             proc.statistics = 0;
442           else if (lex_match (lexer, T_ALL))
443             proc.statistics = CRS_ALL_STATISTICS;
444           else
445             {
446               proc.statistics = 0;
447               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
448                 {
449 #define S(KEYWORD)                                              \
450                   if (lex_match_id (lexer, #KEYWORD))           \
451                     {                                           \
452                       proc.statistics |= CRS_ST_##KEYWORD;      \
453                       continue;                                 \
454                     }
455                   CRS_STATISTICS
456 #undef S
457                   static const char *stats[] =
458                     {
459 #define S(KEYWORD) #KEYWORD,
460                       CRS_STATISTICS
461 #undef S
462                     };
463                   lex_error_expecting_array (lexer, stats,
464                                              sizeof stats / sizeof *stats);
465                   goto exit;
466                 }
467               if (!proc.statistics)
468                 proc.statistics = CRS_ST_CHISQ;
469             }
470         }
471       else if (!parse_crosstabs_tables (lexer, ds, &proc))
472         goto exit;
473
474       if (!lex_match (lexer, T_SLASH))
475         break;
476     }
477   if (!lex_end_of_command (lexer))
478     goto exit;
479
480   if (!proc.n_pivots)
481     {
482       msg (SE, _("At least one crosstabulation must be requested (using "
483                  "the TABLES subcommand)."));
484       goto exit;
485     }
486
487   /* Cells. */
488   if (!show_tables)
489     proc.cells = 0;
490   for (size_t i = 0; i < CRS_N_CELLS; i++)
491     if (proc.cells & (1u << i))
492       proc.a_cells[proc.n_cells++] = i;
493   assert (proc.n_cells < CRS_N_CELLS);
494
495   /* Missing values. */
496   if (proc.mode == GENERAL && !proc.exclude)
497     {
498       lex_ofs_msg (lexer, SW, exclude_ofs, exclude_ofs,
499                    _("Missing mode %s not allowed in general mode.  "
500                      "Assuming %s."), "REPORT", "MISSING=TABLE");
501       proc.exclude = MV_ANY;
502     }
503
504   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
505                                                               dataset_dict (ds),
506                                                               NULL, NULL);
507   struct casegrouper *grouper = casegrouper_create_splits (input, dataset_dict (ds));
508   struct casereader *group;
509   while (casegrouper_get_next_group (grouper, &group))
510     {
511       output_split_file_values_peek (ds, group);
512
513       /* Initialize hash tables. */
514       for (struct crosstabulation *xt = &proc.pivots[0];
515            xt < &proc.pivots[proc.n_pivots]; xt++)
516         hmap_init (&xt->data);
517
518       /* Tabulate. */
519       struct ccase *c;
520       for (; (c = casereader_read (group)) != NULL; case_unref (c))
521         for (struct crosstabulation *xt = &proc.pivots[0];
522              xt < &proc.pivots[proc.n_pivots]; xt++)
523           {
524             double weight = dict_get_case_weight (dataset_dict (ds), c,
525                                                   &proc.bad_warn);
526             if (proc.round_case_weights)
527               {
528                 weight = round_weight (&proc, weight);
529                 if (weight == 0.)
530                   continue;
531               }
532             if (should_tabulate_case (xt, c, proc.exclude))
533               {
534                 if (proc.mode == GENERAL)
535                   tabulate_general_case (xt, c, weight);
536                 else
537                   tabulate_integer_case (xt, c, weight);
538               }
539             else
540               xt->missing += weight;
541           }
542       casereader_destroy (group);
543
544       /* Output. */
545       postcalc (&proc, lexer);
546     }
547   bool ok = casegrouper_destroy (grouper);
548   ok = proc_commit (ds) && ok;
549
550   result = ok ? CMD_SUCCESS : CMD_FAILURE;
551
552 exit:
553   free (proc.variables);
554
555   struct var_range *range, *next_range;
556   HMAP_FOR_EACH_SAFE (range, next_range, struct var_range, hmap_node,
557                       &proc.var_ranges)
558     {
559       hmap_delete (&proc.var_ranges, &range->hmap_node);
560       free (range);
561     }
562   for (struct crosstabulation *xt = &proc.pivots[0];
563        xt < &proc.pivots[proc.n_pivots]; xt++)
564     {
565       free (xt->vars);
566       free (xt->const_vars);
567       free (xt->const_indexes);
568     }
569   free (proc.pivots);
570
571   return result;
572 }
573
574 /* Parses the TABLES subcommand. */
575 static bool
576 parse_crosstabs_tables (struct lexer *lexer, struct dataset *ds,
577                         struct crosstabs_proc *proc)
578 {
579   const struct variable ***by = NULL;
580   size_t *by_nvar = NULL;
581   bool ok = false;
582
583   /* Ensure that this is a TABLES subcommand. */
584   if (!lex_match_id (lexer, "TABLES")
585       && (lex_token (lexer) != T_ID ||
586           dict_lookup_var (dataset_dict (ds), lex_tokcstr (lexer)) == NULL)
587       && lex_token (lexer) != T_ALL)
588     {
589       lex_error (lexer, _("Syntax error expecting subcommand name or "
590                           "variable name."));
591       return false;
592     }
593   lex_match (lexer, T_EQUALS);
594
595   struct const_var_set *var_set
596     = (proc->variables
597        ? const_var_set_create_from_array (proc->variables,
598                                           proc->n_variables)
599        : const_var_set_create_from_dict (dataset_dict (ds)));
600
601   size_t nx = 1;
602   size_t n_by = 0;
603   int vars_start = lex_ofs (lexer);
604   bool overflow = false;
605   do
606     {
607       by = xnrealloc (by, n_by + 1, sizeof *by);
608       by_nvar = xnrealloc (by_nvar, n_by + 1, sizeof *by_nvar);
609       if (!parse_const_var_set_vars (lexer, var_set, &by[n_by], &by_nvar[n_by],
610                                      PV_NO_DUPLICATE | PV_NO_SCRATCH))
611         goto done;
612       size_t n = by_nvar[n_by++];
613       if (xalloc_oversized (nx, n))
614         overflow = true;
615       nx *= n;
616     }
617   while (lex_match (lexer, T_BY));
618   if (overflow)
619     {
620       lex_ofs_error (lexer, vars_start, lex_ofs (lexer) - 1,
621                      _("Too many cross-tabulation variables or dimensions."));
622       goto done;
623     }
624   if (n_by < 2)
625     {
626       bool unused UNUSED = lex_force_match (lexer, T_BY);
627       goto done;
628     }
629   int vars_end = lex_ofs (lexer) - 1;
630
631   size_t *by_iter = XCALLOC (n_by, size_t);
632   proc->pivots = xnrealloc (proc->pivots,
633                             proc->n_pivots + nx, sizeof *proc->pivots);
634   for (size_t i = 0; i < nx; i++)
635     {
636       struct crosstabulation *xt = &proc->pivots[proc->n_pivots++];
637
638       *xt = (struct crosstabulation) {
639         .proc = proc,
640         .weight_format = proc->weight_format,
641         .missing = 0.,
642         .n_vars = n_by,
643         .vars = xcalloc (n_by, sizeof *xt->vars),
644         .n_consts = 0,
645         .const_vars = NULL,
646         .const_indexes = NULL,
647         .start_ofs = vars_start,
648         .end_ofs = vars_end,
649       };
650
651       for (size_t j = 0; j < n_by; j++)
652         xt->vars[j].var = by[j][by_iter[j]];
653
654       for (int j = n_by - 1; j >= 0; j--)
655         {
656           if (++by_iter[j] < by_nvar[j])
657             break;
658           by_iter[j] = 0;
659         }
660     }
661   free (by_iter);
662   ok = true;
663
664 done:
665   /* All return paths lead here. */
666   for (size_t i = 0; i < n_by; i++)
667     free (by[i]);
668   free (by);
669   free (by_nvar);
670
671   const_var_set_destroy (var_set);
672
673   return ok;
674 }
675
676 /* Parses the VARIABLES subcommand. */
677 static bool
678 parse_crosstabs_variables (struct lexer *lexer, struct dataset *ds,
679                            struct crosstabs_proc *proc)
680 {
681   if (proc->n_pivots)
682     {
683       lex_next_error (lexer, -1, -1, _("%s must be specified before %s."),
684                       "VARIABLES", "TABLES");
685       return false;
686     }
687
688   lex_match (lexer, T_EQUALS);
689
690   for (;;)
691     {
692       size_t orig_nv = proc->n_variables;
693
694       if (!parse_variables_const (lexer, dataset_dict (ds),
695                                   &proc->variables, &proc->n_variables,
696                                   (PV_APPEND | PV_NUMERIC
697                                    | PV_NO_DUPLICATE | PV_NO_SCRATCH)))
698         return false;
699
700       if (!lex_force_match (lexer, T_LPAREN))
701           goto error;
702
703       if (!lex_force_int (lexer))
704         goto error;
705       long min = lex_integer (lexer);
706       lex_get (lexer);
707
708       lex_match (lexer, T_COMMA);
709
710       if (!lex_force_int_range (lexer, NULL, min, LONG_MAX))
711         goto error;
712       long max = lex_integer (lexer);
713       lex_get (lexer);
714
715       if (!lex_force_match (lexer, T_RPAREN))
716         goto error;
717
718       for (size_t i = orig_nv; i < proc->n_variables; i++)
719         {
720           const struct variable *var = proc->variables[i];
721           struct var_range *vr = xmalloc (sizeof *vr);
722           *vr = (struct var_range) {
723             .var = var,
724             .min = min,
725             .max = max,
726             .count = max - min + 1,
727           };
728           hmap_insert (&proc->var_ranges, &vr->hmap_node,
729                        hash_pointer (var, 0));
730         }
731
732       if (lex_token (lexer) == T_SLASH)
733         break;
734     }
735
736   proc->mode = INTEGER;
737   return true;
738
739  error:
740   free (proc->variables);
741   proc->variables = NULL;
742   proc->n_variables = 0;
743   return false;
744 }
745 \f
746 /* Data file processing. */
747
748 static const struct var_range *
749 get_var_range (const struct crosstabs_proc *proc, const struct variable *var)
750 {
751   if (!hmap_is_empty (&proc->var_ranges))
752     {
753       const struct var_range *range;
754
755       HMAP_FOR_EACH_IN_BUCKET (range, struct var_range, hmap_node,
756                                hash_pointer (var, 0), &proc->var_ranges)
757         if (range->var == var)
758           return range;
759     }
760
761   return NULL;
762 }
763
764 static bool
765 should_tabulate_case (const struct crosstabulation *xt, const struct ccase *c,
766                       enum mv_class exclude)
767 {
768   for (size_t j = 0; j < xt->n_vars; j++)
769     {
770       const struct variable *var = xt->vars[j].var;
771       const struct var_range *range = get_var_range (xt->proc, var);
772
773       if (var_is_value_missing (var, case_data (c, var)) & exclude)
774         return false;
775
776       if (range != NULL)
777         {
778           double num = case_num (c, var);
779           if (num < range->min || num >= range->max + 1.)
780             return false;
781         }
782     }
783   return true;
784 }
785
786 static void
787 tabulate_integer_case (struct crosstabulation *xt, const struct ccase *c,
788                        double weight)
789 {
790   size_t hash = 0;
791   for (size_t j = 0; j < xt->n_vars; j++)
792     {
793       /* Throw away fractional parts of values. */
794       hash = hash_int (case_num (c, xt->vars[j].var), hash);
795     }
796
797   struct freq *te;
798   HMAP_FOR_EACH_WITH_HASH (te, struct freq, node, hash, &xt->data)
799     {
800       for (size_t j = 0; j < xt->n_vars; j++)
801         if ((int) case_num (c, xt->vars[j].var) != (int) te->values[j].f)
802           goto no_match;
803
804       /* Found an existing entry. */
805       te->count += weight;
806       return;
807
808     no_match: ;
809     }
810
811   /* No existing entry.  Create a new one. */
812   te = xmalloc (table_entry_size (xt->n_vars));
813   te->count = weight;
814   for (size_t j = 0; j < xt->n_vars; j++)
815     te->values[j].f = (int) case_num (c, xt->vars[j].var);
816   hmap_insert (&xt->data, &te->node, hash);
817 }
818
819 static void
820 tabulate_general_case (struct crosstabulation *xt, const struct ccase *c,
821                        double weight)
822 {
823   size_t hash = 0;
824   for (size_t j = 0; j < xt->n_vars; j++)
825     {
826       const struct variable *var = xt->vars[j].var;
827       hash = value_hash (case_data (c, var), var_get_width (var), hash);
828     }
829
830   struct freq *te;
831   HMAP_FOR_EACH_WITH_HASH (te, struct freq, node, hash, &xt->data)
832     {
833       for (size_t j = 0; j < xt->n_vars; j++)
834         {
835           const struct variable *var = xt->vars[j].var;
836           if (!value_equal (case_data (c, var), &te->values[j],
837                             var_get_width (var)))
838             goto no_match;
839         }
840
841       /* Found an existing entry. */
842       te->count += weight;
843       return;
844
845     no_match: ;
846     }
847
848   /* No existing entry.  Create a new one. */
849   te = xmalloc (table_entry_size (xt->n_vars));
850   te->count = weight;
851   for (size_t j = 0; j < xt->n_vars; j++)
852     {
853       const struct variable *var = xt->vars[j].var;
854       value_clone (&te->values[j], case_data (c, var), var_get_width (var));
855     }
856   hmap_insert (&xt->data, &te->node, hash);
857 }
858 \f
859 /* Post-data reading calculations. */
860
861 static int compare_table_entry_vars_3way (const struct freq *a,
862                                           const struct freq *b,
863                                           const struct crosstabulation *xt,
864                                           int idx0, int idx1);
865 static int compare_table_entry_3way (const void *ap_, const void *bp_,
866                                      const void *xt_);
867 static int compare_table_entry_3way_inv (const void *ap_, const void *bp_,
868                                      const void *xt_);
869
870 static void enum_var_values (const struct crosstabulation *, int var_idx,
871                              bool descending);
872 static void free_var_values (const struct crosstabulation *, int var_idx);
873 static void output_crosstabulation (struct crosstabs_proc *,
874                                     struct crosstabulation *,
875                                     struct lexer *);
876 static void make_crosstabulation_subset (struct crosstabulation *xt,
877                                      size_t row0, size_t row1,
878                                      struct crosstabulation *subset);
879 static void make_summary_table (struct crosstabs_proc *);
880 static bool find_crosstab (struct crosstabulation *, size_t *row0p,
881                            size_t *row1p);
882
883 static void
884 postcalc (struct crosstabs_proc *proc, struct lexer *lexer)
885 {
886   /* Round hash table entries, if requested
887
888      If this causes any of the cell counts to fall to zero, delete those
889      cells. */
890   if (proc->round_cells)
891     for (struct crosstabulation *xt = proc->pivots;
892          xt < &proc->pivots[proc->n_pivots]; xt++)
893       {
894         struct freq *e, *next;
895         HMAP_FOR_EACH_SAFE (e, next, struct freq, node, &xt->data)
896           {
897             e->count = round_weight (proc, e->count);
898             if (e->count == 0.0)
899               {
900                 hmap_delete (&xt->data, &e->node);
901                 free (e);
902               }
903           }
904       }
905
906   /* Convert hash tables into sorted arrays of entries. */
907   for (struct crosstabulation *xt = proc->pivots;
908        xt < &proc->pivots[proc->n_pivots]; xt++)
909     {
910       xt->n_entries = hmap_count (&xt->data);
911       xt->entries = xnmalloc (xt->n_entries, sizeof *xt->entries);
912
913       size_t i = 0;
914       struct freq *e;
915       HMAP_FOR_EACH (e, struct freq, node, &xt->data)
916         xt->entries[i++] = e;
917
918       hmap_destroy (&xt->data);
919
920       sort (xt->entries, xt->n_entries, sizeof *xt->entries,
921             proc->descending ? compare_table_entry_3way_inv : compare_table_entry_3way,
922             xt);
923     }
924
925   make_summary_table (proc);
926
927   /* Output each pivot table. */
928   for (struct crosstabulation *xt = proc->pivots;
929        xt < &proc->pivots[proc->n_pivots]; xt++)
930     {
931       output_crosstabulation (proc, xt, lexer);
932       if (proc->barchart)
933         {
934           int n_vars = (xt->n_vars > 2 ? 2 : xt->n_vars);
935           const struct variable **vars = XCALLOC (n_vars, const struct variable*);
936           for (size_t i = 0; i < n_vars; i++)
937             vars[i] = xt->vars[i].var;
938           chart_submit (barchart_create (vars, n_vars, _("Count"),
939                                          false,
940                                          xt->entries, xt->n_entries));
941           free (vars);
942         }
943     }
944
945   /* Free output and prepare for next split file. */
946   for (struct crosstabulation *xt = proc->pivots;
947        xt < &proc->pivots[proc->n_pivots]; xt++)
948     {
949       xt->missing = 0.0;
950
951       /* Free the members that were allocated in this function(and the values
952          owned by the entries.
953
954          The other pointer members are either both allocated and destroyed at a
955          lower level (in output_crosstabulation), or both allocated and
956          destroyed at a higher level (in crs_custom_tables and free_proc,
957          respectively). */
958       for (size_t i = 0; i < xt->n_vars; i++)
959         {
960           int width = var_get_width (xt->vars[i].var);
961           if (value_needs_init (width))
962             for (size_t j = 0; j < xt->n_entries; j++)
963               value_destroy (&xt->entries[j]->values[i], width);
964         }
965
966       for (size_t i = 0; i < xt->n_entries; i++)
967         free (xt->entries[i]);
968       free (xt->entries);
969     }
970 }
971
972 static void
973 make_crosstabulation_subset (struct crosstabulation *xt, size_t row0,
974                              size_t row1, struct crosstabulation *subset)
975 {
976   *subset = *xt;
977   if (xt->n_vars > 2)
978     {
979       assert (xt->n_consts == 0);
980       subset->n_vars = 2;
981       subset->vars = xt->vars;
982
983       subset->n_consts = xt->n_vars - 2;
984       subset->const_vars = xt->vars + 2;
985       subset->const_indexes = xcalloc (subset->n_consts,
986                                        sizeof *subset->const_indexes);
987       for (size_t i = 0; i < subset->n_consts; i++)
988         {
989           const union value *value = &xt->entries[row0]->values[2 + i];
990
991           for (size_t j = 0; j < xt->vars[2 + i].n_values; j++)
992             if (value_equal (&xt->vars[2 + i].values[j], value,
993                              var_get_width (xt->vars[2 + i].var)))
994               {
995                 subset->const_indexes[i] = j;
996                 goto found;
997               }
998           NOT_REACHED ();
999         found: ;
1000         }
1001     }
1002   subset->entries = &xt->entries[row0];
1003   subset->n_entries = row1 - row0;
1004 }
1005
1006 static int
1007 compare_table_entry_var_3way (const struct freq *a,
1008                               const struct freq *b,
1009                               const struct crosstabulation *xt,
1010                               int idx)
1011 {
1012   return value_compare_3way (&a->values[idx], &b->values[idx],
1013                              var_get_width (xt->vars[idx].var));
1014 }
1015
1016 static int
1017 compare_table_entry_vars_3way (const struct freq *a,
1018                                const struct freq *b,
1019                                const struct crosstabulation *xt,
1020                                int idx0, int idx1)
1021 {
1022   for (int i = idx1 - 1; i >= idx0; i--)
1023     {
1024       int cmp = compare_table_entry_var_3way (a, b, xt, i);
1025       if (cmp != 0)
1026         return cmp;
1027     }
1028   return 0;
1029 }
1030
1031 /* Compare the struct freq at *AP to the one at *BP and
1032    return a strcmp()-type result. */
1033 static int
1034 compare_table_entry_3way (const void *ap_, const void *bp_, const void *xt_)
1035 {
1036   const struct freq *const *ap = ap_;
1037   const struct freq *const *bp = bp_;
1038   const struct freq *a = *ap;
1039   const struct freq *b = *bp;
1040   const struct crosstabulation *xt = xt_;
1041
1042   int cmp = compare_table_entry_vars_3way (a, b, xt, 2, xt->n_vars);
1043   if (cmp != 0)
1044     return cmp;
1045
1046   cmp = compare_table_entry_var_3way (a, b, xt, ROW_VAR);
1047   if (cmp != 0)
1048     return cmp;
1049
1050   return compare_table_entry_var_3way (a, b, xt, COL_VAR);
1051 }
1052
1053 /* Inverted version of compare_table_entry_3way */
1054 static int
1055 compare_table_entry_3way_inv (const void *ap_, const void *bp_, const void *xt_)
1056 {
1057   return -compare_table_entry_3way (ap_, bp_, xt_);
1058 }
1059
1060 /* Output a table summarizing the cases processed. */
1061 static void
1062 make_summary_table (struct crosstabs_proc *proc)
1063 {
1064   struct pivot_table *table = pivot_table_create (N_("Summary"));
1065   pivot_table_set_weight_var (table, dict_get_weight (proc->dict));
1066
1067   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1068                           N_("N"), PIVOT_RC_COUNT,
1069                           N_("Percent"), PIVOT_RC_PERCENT);
1070
1071   struct pivot_dimension *cases = pivot_dimension_create (
1072     table, PIVOT_AXIS_COLUMN, N_("Cases"),
1073     N_("Valid"), N_("Missing"), N_("Total"));
1074   cases->root->show_label = true;
1075
1076   struct pivot_dimension *tables = pivot_dimension_create (
1077     table, PIVOT_AXIS_ROW, N_("Crosstabulation"));
1078   for (struct crosstabulation *xt = &proc->pivots[0];
1079        xt < &proc->pivots[proc->n_pivots]; xt++)
1080     {
1081       struct string name = DS_EMPTY_INITIALIZER;
1082       for (size_t i = 0; i < xt->n_vars; i++)
1083         {
1084           if (i > 0)
1085             ds_put_cstr (&name, " Ã— ");
1086           ds_put_cstr (&name, var_to_string (xt->vars[i].var));
1087         }
1088
1089       int row = pivot_category_create_leaf (
1090         tables->root,
1091         pivot_value_new_user_text_nocopy (ds_steal_cstr (&name)));
1092
1093       double valid = 0.;
1094       for (size_t i = 0; i < xt->n_entries; i++)
1095         valid += xt->entries[i]->count;
1096
1097       double n[3];
1098       n[0] = valid;
1099       n[1] = xt->missing;
1100       n[2] = n[0] + n[1];
1101       for (int i = 0; i < 3; i++)
1102         {
1103           pivot_table_put3 (table, 0, i, row, pivot_value_new_number (n[i]));
1104           pivot_table_put3 (table, 1, i, row,
1105                             pivot_value_new_number (n[i] / n[2] * 100.0));
1106         }
1107     }
1108
1109   pivot_table_submit (table);
1110 }
1111 \f
1112 /* Output. */
1113
1114 static struct pivot_table *create_crosstab_table (
1115   struct crosstabs_proc *, struct crosstabulation *,
1116   size_t crs_leaves[CRS_N_CELLS]);
1117 static struct pivot_table *create_chisq_table (struct crosstabulation *);
1118 static struct pivot_table *create_sym_table (struct crosstabulation *);
1119 static struct pivot_table *create_risk_table (
1120   struct crosstabulation *, struct pivot_dimension **risk_statistics);
1121 static struct pivot_table *create_direct_table (struct crosstabulation *);
1122 static void display_crosstabulation (struct crosstabs_proc *,
1123                                      struct crosstabulation *,
1124                                      struct pivot_table *,
1125                                      size_t crs_leaves[CRS_N_CELLS]);
1126 static void display_chisq (struct crosstabulation *, struct pivot_table *);
1127 static void display_symmetric (struct crosstabs_proc *,
1128                                struct crosstabulation *, struct pivot_table *);
1129 static void display_risk (struct crosstabulation *, struct pivot_table *,
1130                           struct pivot_dimension *risk_statistics);
1131 static void display_directional (struct crosstabs_proc *,
1132                                  struct crosstabulation *,
1133                                  struct pivot_table *);
1134 static void delete_missing (struct crosstabulation *);
1135 static void build_matrix (struct crosstabulation *);
1136
1137 /* Output pivot table XT in the context of PROC. */
1138 static void
1139 output_crosstabulation (struct crosstabs_proc *proc, struct crosstabulation *xt,
1140                         struct lexer *lexer)
1141 {
1142   for (size_t i = 0; i < xt->n_vars; i++)
1143     enum_var_values (xt, i, proc->descending);
1144
1145   if (xt->vars[COL_VAR].n_values == 0)
1146     {
1147       struct string vars;
1148
1149       ds_init_cstr (&vars, var_to_string (xt->vars[0].var));
1150       for (size_t i = 1; i < xt->n_vars; i++)
1151         ds_put_format (&vars, " Ã— %s", var_to_string (xt->vars[i].var));
1152
1153       /* TRANSLATORS: The %s here describes a crosstabulation.  It takes the
1154          form "var1 * var2 * var3 * ...".  */
1155       lex_ofs_msg (lexer, SW, xt->start_ofs, xt->end_ofs,
1156                    _("Crosstabulation %s contained no non-missing cases."),
1157                    ds_cstr (&vars));
1158
1159       ds_destroy (&vars);
1160       for (size_t i = 0; i < xt->n_vars; i++)
1161         free_var_values (xt, i);
1162       return;
1163     }
1164
1165   size_t crs_leaves[CRS_N_CELLS];
1166   struct pivot_table *table = (proc->cells
1167                                ? create_crosstab_table (proc, xt, crs_leaves)
1168                                : NULL);
1169   struct pivot_table *chisq = (proc->statistics & CRS_ST_CHISQ
1170                                ? create_chisq_table (xt)
1171                                : NULL);
1172   struct pivot_table *sym
1173     = (proc->statistics & (CRS_ST_PHI | CRS_ST_CC | CRS_ST_BTAU | CRS_ST_CTAU
1174                            | CRS_ST_GAMMA | CRS_ST_CORR | CRS_ST_KAPPA)
1175        ? create_sym_table (xt)
1176        : NULL);
1177   struct pivot_dimension *risk_statistics = NULL;
1178   struct pivot_table *risk = (proc->statistics & CRS_ST_RISK
1179                               ? create_risk_table (xt, &risk_statistics)
1180                               : NULL);
1181   struct pivot_table *direct
1182     = (proc->statistics & (CRS_ST_LAMBDA | CRS_ST_UC | CRS_ST_D | CRS_ST_ETA)
1183        ? create_direct_table (xt)
1184        : NULL);
1185
1186   size_t row0 = 0;
1187   size_t row1 = 0;
1188   while (find_crosstab (xt, &row0, &row1))
1189     {
1190       struct crosstabulation x;
1191
1192       make_crosstabulation_subset (xt, row0, row1, &x);
1193
1194       size_t n_rows = x.vars[ROW_VAR].n_values;
1195       size_t n_cols = x.vars[COL_VAR].n_values;
1196       if (size_overflow_p (xtimes (xtimes (n_rows, n_cols), sizeof (double))))
1197         xalloc_die ();
1198       x.row_tot = xmalloc (n_rows * sizeof *x.row_tot);
1199       x.col_tot = xmalloc (n_cols * sizeof *x.col_tot);
1200       x.mat = xmalloc (n_rows * n_cols * sizeof *x.mat);
1201
1202       build_matrix (&x);
1203
1204       /* Find the first variable that differs from the last subtable. */
1205       if (table)
1206         display_crosstabulation (proc, &x, table, crs_leaves);
1207
1208       if (proc->exclude == 0)
1209         delete_missing (&x);
1210
1211       if (chisq)
1212         display_chisq (&x, chisq);
1213
1214       if (sym)
1215         display_symmetric (proc, &x, sym);
1216       if (risk)
1217         display_risk (&x, risk, risk_statistics);
1218       if (direct)
1219         display_directional (proc, &x, direct);
1220
1221       free (x.mat);
1222       free (x.row_tot);
1223       free (x.col_tot);
1224       free (x.const_indexes);
1225     }
1226
1227   if (table)
1228     pivot_table_submit (table);
1229
1230   if (chisq)
1231     pivot_table_submit (chisq);
1232
1233   if (sym)
1234     pivot_table_submit (sym);
1235
1236   if (risk)
1237     {
1238       if (!pivot_table_is_empty (risk))
1239         pivot_table_submit (risk);
1240       else
1241         pivot_table_unref (risk);
1242     }
1243
1244   if (direct)
1245     pivot_table_submit (direct);
1246
1247   for (size_t i = 0; i < xt->n_vars; i++)
1248     free_var_values (xt, i);
1249 }
1250
1251 static void
1252 build_matrix (struct crosstabulation *x)
1253 {
1254   const int col_var_width = var_get_width (x->vars[COL_VAR].var);
1255   const int row_var_width = var_get_width (x->vars[ROW_VAR].var);
1256   size_t n_rows = x->vars[ROW_VAR].n_values;
1257   size_t n_cols = x->vars[COL_VAR].n_values;
1258
1259   double *mp = x->mat;
1260   size_t col = 0;
1261   size_t row = 0;
1262   for (struct freq **p = x->entries; p < &x->entries[x->n_entries]; p++)
1263     {
1264       const struct freq *te = *p;
1265
1266       while (!value_equal (&x->vars[ROW_VAR].values[row],
1267                            &te->values[ROW_VAR], row_var_width))
1268         {
1269           for (; col < n_cols; col++)
1270             *mp++ = 0.0;
1271           col = 0;
1272           row++;
1273         }
1274
1275       while (!value_equal (&x->vars[COL_VAR].values[col],
1276                            &te->values[COL_VAR], col_var_width))
1277         {
1278           *mp++ = 0.0;
1279           col++;
1280         }
1281
1282       *mp++ = te->count;
1283       if (++col >= n_cols)
1284         {
1285           col = 0;
1286           row++;
1287         }
1288     }
1289   while (mp < &x->mat[n_cols * n_rows])
1290     *mp++ = 0.0;
1291   assert (mp == &x->mat[n_cols * n_rows]);
1292
1293   /* Column totals, row totals, ns_rows. */
1294   mp = x->mat;
1295   for (col = 0; col < n_cols; col++)
1296     x->col_tot[col] = 0.0;
1297   for (row = 0; row < n_rows; row++)
1298     x->row_tot[row] = 0.0;
1299   x->ns_rows = 0;
1300   for (row = 0; row < n_rows; row++)
1301     {
1302       bool row_is_empty = true;
1303       for (col = 0; col < n_cols; col++)
1304         {
1305           if (*mp != 0.0)
1306             {
1307               row_is_empty = false;
1308               x->col_tot[col] += *mp;
1309               x->row_tot[row] += *mp;
1310             }
1311           mp++;
1312         }
1313       if (!row_is_empty)
1314         x->ns_rows++;
1315     }
1316   assert (mp == &x->mat[n_cols * n_rows]);
1317
1318   /* ns_cols. */
1319   x->ns_cols = 0;
1320   for (col = 0; col < n_cols; col++)
1321     for (row = 0; row < n_rows; row++)
1322       if (x->mat[col + row * n_cols] != 0.0)
1323         {
1324           x->ns_cols++;
1325           break;
1326         }
1327
1328   /* Grand total. */
1329   x->total = 0.0;
1330   for (col = 0; col < n_cols; col++)
1331     x->total += x->col_tot[col];
1332 }
1333
1334 static void
1335 add_var_dimension (struct pivot_table *table, const struct xtab_var *var,
1336                    enum pivot_axis_type axis_type, bool total)
1337 {
1338   struct pivot_dimension *d = pivot_dimension_create__ (
1339     table, axis_type, pivot_value_new_variable (var->var));
1340
1341   struct pivot_footnote *missing_footnote = pivot_table_create_footnote (
1342     table, pivot_value_new_text (N_("Missing value")));
1343
1344   struct pivot_category *group = pivot_category_create_group__ (
1345     d->root, pivot_value_new_variable (var->var));
1346   for (size_t j = 0; j < var->n_values; j++)
1347     {
1348       struct pivot_value *value = pivot_value_new_var_value (
1349         var->var, &var->values[j]);
1350       if (var_is_value_missing (var->var, &var->values[j]))
1351         pivot_value_add_footnote (value, missing_footnote);
1352       pivot_category_create_leaf (group, value);
1353     }
1354
1355   if (total)
1356     pivot_category_create_leaf (d->root, pivot_value_new_text (N_("Total")));
1357 }
1358
1359 static struct pivot_table *
1360 create_crosstab_table (struct crosstabs_proc *proc, struct crosstabulation *xt,
1361                        size_t crs_leaves[CRS_N_CELLS])
1362 {
1363   /* Title. */
1364   struct string title = DS_EMPTY_INITIALIZER;
1365   for (size_t i = 0; i < xt->n_vars; i++)
1366     {
1367       if (i)
1368         ds_put_cstr (&title, " Ã— ");
1369       ds_put_cstr (&title, var_to_string (xt->vars[i].var));
1370     }
1371   for (size_t i = 0; i < xt->n_consts; i++)
1372     {
1373       const struct variable *var = xt->const_vars[i].var;
1374       const union value *value = &xt->entries[0]->values[2 + i];
1375       char *s;
1376
1377       ds_put_format (&title, ", %s=", var_to_string (var));
1378
1379       /* Insert the formatted value of VAR without any leading spaces. */
1380       s = data_out (value, var_get_encoding (var), var_get_print_format (var),
1381                     settings_get_fmt_settings ());
1382       ds_put_cstr (&title, s + strspn (s, " "));
1383       free (s);
1384     }
1385   struct pivot_table *table = pivot_table_create__ (
1386     pivot_value_new_user_text_nocopy (ds_steal_cstr (&title)),
1387     "Crosstabulation");
1388   pivot_table_set_weight_format (table, &proc->weight_format);
1389
1390   struct pivot_dimension *statistics = pivot_dimension_create (
1391     table, PIVOT_AXIS_ROW, N_("Statistics"));
1392
1393   struct statistic
1394     {
1395       const char *label;
1396       const char *rc;
1397     };
1398   static const struct statistic stats[CRS_N_CELLS] =
1399     {
1400 #define C(KEYWORD, STRING, RC) { STRING, RC },
1401       CRS_CELLS
1402 #undef C
1403     };
1404   for (size_t i = 0; i < CRS_N_CELLS; i++)
1405     if (proc->cells & (1u << i) && stats[i].label)
1406         crs_leaves[i] = pivot_category_create_leaf_rc (
1407           statistics->root, pivot_value_new_text (stats[i].label),
1408           stats[i].rc);
1409
1410   for (size_t i = 0; i < xt->n_vars; i++)
1411     add_var_dimension (table, &xt->vars[i],
1412                        i == COL_VAR ? PIVOT_AXIS_COLUMN : PIVOT_AXIS_ROW,
1413                        true);
1414
1415   return table;
1416 }
1417
1418 static struct pivot_table *
1419 create_chisq_table (struct crosstabulation *xt)
1420 {
1421   struct pivot_table *chisq = pivot_table_create (N_("Chi-Square Tests"));
1422   pivot_table_set_weight_format (chisq, &xt->weight_format);
1423
1424   pivot_dimension_create (
1425     chisq, PIVOT_AXIS_ROW, N_("Statistics"),
1426     N_("Pearson Chi-Square"),
1427     N_("Likelihood Ratio"),
1428     N_("Fisher's Exact Test"),
1429     N_("Continuity Correction"),
1430     N_("Linear-by-Linear Association"),
1431     N_("N of Valid Cases"), PIVOT_RC_COUNT);
1432
1433   pivot_dimension_create (
1434     chisq, PIVOT_AXIS_COLUMN, N_("Statistics"),
1435     N_("Value"), PIVOT_RC_OTHER,
1436     N_("df"), PIVOT_RC_COUNT,
1437     N_("Asymptotic Sig. (2-tailed)"), PIVOT_RC_SIGNIFICANCE,
1438     N_("Exact Sig. (2-tailed)"), PIVOT_RC_SIGNIFICANCE,
1439     N_("Exact Sig. (1-tailed)"), PIVOT_RC_SIGNIFICANCE);
1440
1441   for (size_t i = 2; i < xt->n_vars; i++)
1442     add_var_dimension (chisq, &xt->vars[i], PIVOT_AXIS_ROW, false);
1443
1444   return chisq;
1445 }
1446
1447 /* Symmetric measures. */
1448 static struct pivot_table *
1449 create_sym_table (struct crosstabulation *xt)
1450 {
1451   struct pivot_table *sym = pivot_table_create (N_("Symmetric Measures"));
1452   pivot_table_set_weight_format (sym, &xt->weight_format);
1453
1454   pivot_dimension_create (
1455     sym, PIVOT_AXIS_COLUMN, N_("Values"),
1456     N_("Value"), PIVOT_RC_OTHER,
1457     N_("Asymp. Std. Error"), PIVOT_RC_OTHER,
1458     N_("Approx. T"), PIVOT_RC_OTHER,
1459     N_("Approx. Sig."), PIVOT_RC_SIGNIFICANCE);
1460
1461   struct pivot_dimension *statistics = pivot_dimension_create (
1462     sym, PIVOT_AXIS_ROW, N_("Statistics"));
1463   pivot_category_create_group (
1464     statistics->root, N_("Nominal by Nominal"),
1465     N_("Phi"), N_("Cramer's V"), N_("Contingency Coefficient"));
1466   pivot_category_create_group (
1467     statistics->root, N_("Ordinal by Ordinal"),
1468     N_("Kendall's tau-b"), N_("Kendall's tau-c"),
1469     N_("Gamma"), N_("Spearman Correlation"));
1470   pivot_category_create_group (
1471     statistics->root, N_("Interval by Interval"),
1472     N_("Pearson's R"));
1473   pivot_category_create_group (
1474     statistics->root, N_("Measure of Agreement"),
1475     N_("Kappa"));
1476   pivot_category_create_leaves (statistics->root, N_("N of Valid Cases"),
1477                                 PIVOT_RC_COUNT);
1478
1479   for (size_t i = 2; i < xt->n_vars; i++)
1480     add_var_dimension (sym, &xt->vars[i], PIVOT_AXIS_ROW, false);
1481
1482   return sym;
1483 }
1484
1485 /* Risk estimate. */
1486 static struct pivot_table *
1487 create_risk_table (struct crosstabulation *xt,
1488                    struct pivot_dimension **risk_statistics)
1489 {
1490   struct pivot_table *risk = pivot_table_create (N_("Risk Estimate"));
1491   pivot_table_set_weight_format (risk, &xt->weight_format);
1492
1493   struct pivot_dimension *values = pivot_dimension_create (
1494     risk, PIVOT_AXIS_COLUMN, N_("Values"),
1495     N_("Value"), PIVOT_RC_OTHER);
1496   pivot_category_create_group (
1497   /* xgettext:no-c-format */
1498     values->root, N_("95% Confidence Interval"),
1499     N_("Lower"), PIVOT_RC_OTHER,
1500     N_("Upper"), PIVOT_RC_OTHER);
1501
1502   *risk_statistics = pivot_dimension_create (
1503     risk, PIVOT_AXIS_ROW, N_("Statistics"));
1504
1505   for (size_t i = 2; i < xt->n_vars; i++)
1506     add_var_dimension (risk, &xt->vars[i], PIVOT_AXIS_ROW, false);
1507
1508   return risk;
1509 }
1510
1511 static void
1512 create_direct_stat (struct pivot_category *parent,
1513                     const struct crosstabulation *xt,
1514                     const char *name, bool symmetric)
1515 {
1516   struct pivot_category *group = pivot_category_create_group (
1517     parent, name);
1518   if (symmetric)
1519     pivot_category_create_leaf (group, pivot_value_new_text (N_("Symmetric")));
1520
1521   char *row_label = xasprintf (_("%s Dependent"),
1522                                var_to_string (xt->vars[ROW_VAR].var));
1523   pivot_category_create_leaf (group, pivot_value_new_user_text_nocopy (
1524                                 row_label));
1525
1526   char *col_label = xasprintf (_("%s Dependent"),
1527                                var_to_string (xt->vars[COL_VAR].var));
1528   pivot_category_create_leaf (group, pivot_value_new_user_text_nocopy (
1529                                 col_label));
1530 }
1531
1532 /* Directional measures. */
1533 static struct pivot_table *
1534 create_direct_table (struct crosstabulation *xt)
1535 {
1536   struct pivot_table *direct = pivot_table_create (N_("Directional Measures"));
1537   pivot_table_set_weight_format (direct, &xt->weight_format);
1538
1539   pivot_dimension_create (
1540     direct, PIVOT_AXIS_COLUMN, N_("Values"),
1541     N_("Value"), PIVOT_RC_OTHER,
1542     N_("Asymp. Std. Error"), PIVOT_RC_OTHER,
1543     N_("Approx. T"), PIVOT_RC_OTHER,
1544     N_("Approx. Sig."), PIVOT_RC_SIGNIFICANCE);
1545
1546   struct pivot_dimension *statistics = pivot_dimension_create (
1547     direct, PIVOT_AXIS_ROW, N_("Statistics"));
1548   struct pivot_category *nn = pivot_category_create_group (
1549     statistics->root, N_("Nominal by Nominal"));
1550   create_direct_stat (nn, xt, N_("Lambda"), true);
1551   create_direct_stat (nn, xt, N_("Goodman and Kruskal tau"), false);
1552   create_direct_stat (nn, xt, N_("Uncertainty Coefficient"), true);
1553   struct pivot_category *oo = pivot_category_create_group (
1554     statistics->root, N_("Ordinal by Ordinal"));
1555   create_direct_stat (oo, xt, N_("Somers' d"), true);
1556   struct pivot_category *ni = pivot_category_create_group (
1557     statistics->root, N_("Nominal by Interval"));
1558   create_direct_stat (ni, xt, N_("Eta"), false);
1559
1560   for (size_t i = 2; i < xt->n_vars; i++)
1561     add_var_dimension (direct, &xt->vars[i], PIVOT_AXIS_ROW, false);
1562
1563   return direct;
1564 }
1565
1566 /* Delete missing rows and columns for statistical analysis when
1567    /MISSING=REPORT. */
1568 static void
1569 delete_missing (struct crosstabulation *xt)
1570 {
1571   size_t n_rows = xt->vars[ROW_VAR].n_values;
1572   size_t n_cols = xt->vars[COL_VAR].n_values;
1573
1574   for (size_t r = 0; r < n_rows; r++)
1575     if (var_is_num_missing (xt->vars[ROW_VAR].var,
1576                             xt->vars[ROW_VAR].values[r].f) == MV_USER)
1577       {
1578         for (size_t c = 0; c < n_cols; c++)
1579           xt->mat[c + r * n_cols] = 0.;
1580         xt->ns_rows--;
1581       }
1582
1583
1584   for (size_t c = 0; c < n_cols; c++)
1585     if (var_is_num_missing (xt->vars[COL_VAR].var,
1586                             xt->vars[COL_VAR].values[c].f) == MV_USER)
1587       {
1588         for (size_t r = 0; r < n_rows; r++)
1589           xt->mat[c + r * n_cols] = 0.;
1590         xt->ns_cols--;
1591       }
1592 }
1593
1594 static bool
1595 find_crosstab (struct crosstabulation *xt, size_t *row0p, size_t *row1p)
1596 {
1597   size_t row0 = *row1p;
1598   if (row0 >= xt->n_entries)
1599     return false;
1600
1601   size_t row1;
1602   for (row1 = row0 + 1; row1 < xt->n_entries; row1++)
1603     {
1604       struct freq *a = xt->entries[row0];
1605       struct freq *b = xt->entries[row1];
1606       if (compare_table_entry_vars_3way (a, b, xt, 2, xt->n_vars) != 0)
1607         break;
1608     }
1609   *row0p = row0;
1610   *row1p = row1;
1611   return true;
1612 }
1613
1614 /* Compares `union value's A_ and B_ and returns a strcmp()-like
1615    result.  WIDTH_ points to an int which is either 0 for a
1616    numeric value or a string width for a string value. */
1617 static int
1618 compare_value_3way (const void *a_, const void *b_, const void *width_)
1619 {
1620   const union value *a = a_;
1621   const union value *b = b_;
1622   const int *width = width_;
1623
1624   return value_compare_3way (a, b, *width);
1625 }
1626
1627 /* Inverted version of the above */
1628 static int
1629 compare_value_3way_inv (const void *a_, const void *b_, const void *width_)
1630 {
1631   return -compare_value_3way (a_, b_, width_);
1632 }
1633
1634
1635 /* Given an array of ENTRY_CNT table_entry structures starting at
1636    ENTRIES, creates a sorted list of the values that the variable
1637    with index VAR_IDX takes on.  Stores the array of the values in
1638    XT->values and the number of values in XT->n_values. */
1639 static void
1640 enum_var_values (const struct crosstabulation *xt, int var_idx,
1641                  bool descending)
1642 {
1643   struct xtab_var *xv = &xt->vars[var_idx];
1644   const struct var_range *range = get_var_range (xt->proc, xv->var);
1645
1646   if (range)
1647     {
1648       xv->values = xnmalloc (range->count, sizeof *xv->values);
1649       xv->n_values = range->count;
1650       for (size_t i = 0; i < range->count; i++)
1651         xv->values[i].f = range->min + i;
1652     }
1653   else
1654     {
1655       int width = var_get_width (xv->var);
1656       struct hmapx set = HMAPX_INITIALIZER (set);
1657
1658       for (size_t i = 0; i < xt->n_entries; i++)
1659         {
1660           const struct freq *te = xt->entries[i];
1661           const union value *value = &te->values[var_idx];
1662           size_t hash = value_hash (value, width, 0);
1663
1664           const union value *iter;
1665           struct hmapx_node *node;
1666           HMAPX_FOR_EACH_WITH_HASH (iter, node, hash, &set)
1667             if (value_equal (iter, value, width))
1668               goto next_entry;
1669
1670           hmapx_insert (&set, (union value *) value, hash);
1671
1672         next_entry: ;
1673         }
1674
1675       xv->n_values = hmapx_count (&set);
1676       xv->values = xnmalloc (xv->n_values, sizeof *xv->values);
1677       size_t i = 0;
1678       const union value *iter;
1679       struct hmapx_node *node;
1680       HMAPX_FOR_EACH (iter, node, &set)
1681         xv->values[i++] = *iter;
1682       hmapx_destroy (&set);
1683
1684       sort (xv->values, xv->n_values, sizeof *xv->values,
1685             descending ? compare_value_3way_inv : compare_value_3way,
1686             &width);
1687     }
1688 }
1689
1690 static void
1691 free_var_values (const struct crosstabulation *xt, int var_idx)
1692 {
1693   struct xtab_var *xv = &xt->vars[var_idx];
1694   free (xv->values);
1695   xv->values = NULL;
1696   xv->n_values = 0;
1697 }
1698
1699 /* Displays the crosstabulation table. */
1700 static void
1701 display_crosstabulation (struct crosstabs_proc *proc,
1702                          struct crosstabulation *xt, struct pivot_table *table,
1703                          size_t crs_leaves[CRS_N_CELLS])
1704 {
1705   size_t n_rows = xt->vars[ROW_VAR].n_values;
1706   size_t n_cols = xt->vars[COL_VAR].n_values;
1707
1708   size_t *indexes = xnmalloc (table->n_dimensions, sizeof *indexes);
1709   assert (xt->n_vars == 2);
1710   for (size_t i = 0; i < xt->n_consts; i++)
1711     indexes[i + 3] = xt->const_indexes[i];
1712
1713   /* Put in the actual cells. */
1714   double *mp = xt->mat;
1715   for (size_t r = 0; r < n_rows; r++)
1716     {
1717       if (!xt->row_tot[r] && proc->mode != INTEGER)
1718         continue;
1719
1720       indexes[ROW_VAR + 1] = r;
1721       for (size_t c = 0; c < n_cols; c++)
1722         {
1723           if (!xt->col_tot[c] && proc->mode != INTEGER)
1724             continue;
1725
1726           indexes[COL_VAR + 1] = c;
1727
1728           double expected_value = xt->row_tot[r] * xt->col_tot[c] / xt->total;
1729           double residual = *mp - expected_value;
1730           double sresidual = residual / sqrt (expected_value);
1731           double asresidual
1732             = residual / sqrt (expected_value
1733                                * (1. - xt->row_tot[r] / xt->total)
1734                                * (1. - xt->col_tot[c] / xt->total));
1735           double entries[CRS_N_CELLS] = {
1736             [CRS_CL_COUNT] = *mp,
1737             [CRS_CL_ROW] = *mp / xt->row_tot[r] * 100.,
1738             [CRS_CL_COLUMN] = *mp / xt->col_tot[c] * 100.,
1739             [CRS_CL_TOTAL] = *mp / xt->total * 100.,
1740             [CRS_CL_EXPECTED] = expected_value,
1741             [CRS_CL_RESIDUAL] = residual,
1742             [CRS_CL_SRESIDUAL] = sresidual,
1743             [CRS_CL_ASRESIDUAL] = asresidual,
1744           };
1745           for (size_t i = 0; i < proc->n_cells; i++)
1746             {
1747               int cell = proc->a_cells[i];
1748               indexes[0] = crs_leaves[cell];
1749               pivot_table_put (table, indexes, table->n_dimensions,
1750                                pivot_value_new_number (entries[cell]));
1751             }
1752
1753           mp++;
1754         }
1755     }
1756
1757   /* Row totals. */
1758   for (size_t r = 0; r < n_rows; r++)
1759     {
1760       if (!xt->row_tot[r] && proc->mode != INTEGER)
1761         continue;
1762
1763       double expected_value = xt->row_tot[r] / xt->total;
1764       double entries[CRS_N_CELLS] = {
1765         [CRS_CL_COUNT] = xt->row_tot[r],
1766         [CRS_CL_ROW] = 100.0,
1767         [CRS_CL_COLUMN] = expected_value * 100.,
1768         [CRS_CL_TOTAL] = expected_value * 100.,
1769         [CRS_CL_EXPECTED] = expected_value,
1770         [CRS_CL_RESIDUAL] = SYSMIS,
1771         [CRS_CL_SRESIDUAL] = SYSMIS,
1772         [CRS_CL_ASRESIDUAL] = SYSMIS,
1773       };
1774       for (size_t i = 0; i < proc->n_cells; i++)
1775         {
1776           int cell = proc->a_cells[i];
1777           double entry = entries[cell];
1778           if (entry != SYSMIS)
1779             {
1780               indexes[ROW_VAR + 1] = r;
1781               indexes[COL_VAR + 1] = n_cols;
1782               indexes[0] = crs_leaves[cell];
1783               pivot_table_put (table, indexes, table->n_dimensions,
1784                                pivot_value_new_number (entry));
1785             }
1786         }
1787     }
1788
1789   for (size_t c = 0; c <= n_cols; c++)
1790     {
1791       if (c < n_cols && !xt->col_tot[c] && proc->mode != INTEGER)
1792         continue;
1793
1794       double ct = c < n_cols ? xt->col_tot[c] : xt->total;
1795       double expected_value = ct / xt->total;
1796       double entries[CRS_N_CELLS] = {
1797         [CRS_CL_COUNT] = ct,
1798         [CRS_CL_ROW] = expected_value * 100.0,
1799         [CRS_CL_COLUMN] = 100.0,
1800         [CRS_CL_TOTAL] = expected_value * 100.,
1801         [CRS_CL_EXPECTED] = expected_value,
1802         [CRS_CL_RESIDUAL] = SYSMIS,
1803         [CRS_CL_SRESIDUAL] = SYSMIS,
1804         [CRS_CL_ASRESIDUAL] = SYSMIS,
1805       };
1806       for (size_t i = 0; i < proc->n_cells; i++)
1807         {
1808           size_t cell = proc->a_cells[i];
1809           double entry = entries[cell];
1810           if (entry != SYSMIS)
1811             {
1812               indexes[ROW_VAR + 1] = n_rows;
1813               indexes[COL_VAR + 1] = c;
1814               indexes[0] = crs_leaves[cell];
1815               pivot_table_put (table, indexes, table->n_dimensions,
1816                                pivot_value_new_number (entry));
1817             }
1818         }
1819     }
1820
1821   free (indexes);
1822 }
1823
1824 static void calc_r (struct crosstabulation *,
1825                     double *XT, double *Y, double *, double *, double *);
1826 static void calc_chisq (struct crosstabulation *,
1827                         double[N_CHISQ], int[N_CHISQ], double *, double *);
1828
1829 /* Display chi-square statistics. */
1830 static void
1831 display_chisq (struct crosstabulation *xt, struct pivot_table *chisq)
1832 {
1833   double chisq_v[N_CHISQ];
1834   double fisher1, fisher2;
1835   int df[N_CHISQ];
1836   calc_chisq (xt, chisq_v, df, &fisher1, &fisher2);
1837
1838   size_t *indexes = xnmalloc (chisq->n_dimensions, sizeof *indexes);
1839   assert (xt->n_vars == 2);
1840   for (size_t i = 0; i < xt->n_consts; i++)
1841     indexes[i + 2] = xt->const_indexes[i];
1842   for (size_t i = 0; i < N_CHISQ; i++)
1843     {
1844       indexes[0] = i;
1845
1846       double entries[5] = { SYSMIS, SYSMIS, SYSMIS, SYSMIS, SYSMIS };
1847       if (i == 2)
1848         {
1849           entries[3] = fisher2;
1850           entries[4] = fisher1;
1851         }
1852       else if (chisq_v[i] != SYSMIS)
1853         {
1854           entries[0] = chisq_v[i];
1855           entries[1] = df[i];
1856           entries[2] = gsl_cdf_chisq_Q (chisq_v[i], df[i]);
1857         }
1858
1859       for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1860         if (entries[j] != SYSMIS)
1861           {
1862             indexes[1] = j;
1863             pivot_table_put (chisq, indexes, chisq->n_dimensions,
1864                              pivot_value_new_number (entries[j]));
1865         }
1866     }
1867
1868   indexes[0] = 5;
1869   indexes[1] = 0;
1870   pivot_table_put (chisq, indexes, chisq->n_dimensions,
1871                    pivot_value_new_number (xt->total));
1872
1873   free (indexes);
1874 }
1875
1876 static bool calc_symmetric (struct crosstabs_proc *, struct crosstabulation *,
1877                             double[N_SYMMETRIC], double[N_SYMMETRIC],
1878                             double[N_SYMMETRIC],
1879                             double[3], double[3], double[3]);
1880
1881 /* Display symmetric measures. */
1882 static void
1883 display_symmetric (struct crosstabs_proc *proc, struct crosstabulation *xt,
1884                    struct pivot_table *sym)
1885 {
1886   double sym_v[N_SYMMETRIC], sym_ase[N_SYMMETRIC], sym_t[N_SYMMETRIC];
1887   double somers_d_v[3], somers_d_ase[3], somers_d_t[3];
1888
1889   if (!calc_symmetric (proc, xt, sym_v, sym_ase, sym_t,
1890                        somers_d_v, somers_d_ase, somers_d_t))
1891     return;
1892
1893   size_t *indexes = xnmalloc (sym->n_dimensions, sizeof *indexes);
1894   assert (xt->n_vars == 2);
1895   for (size_t i = 0; i < xt->n_consts; i++)
1896     indexes[i + 2] = xt->const_indexes[i];
1897
1898   for (size_t i = 0; i < N_SYMMETRIC; i++)
1899     {
1900       if (sym_v[i] == SYSMIS)
1901         continue;
1902
1903       indexes[1] = i;
1904
1905       double entries[] = { sym_v[i], sym_ase[i], sym_t[i] };
1906       for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1907         if (entries[j] != SYSMIS)
1908           {
1909             indexes[0] = j;
1910             pivot_table_put (sym, indexes, sym->n_dimensions,
1911                              pivot_value_new_number (entries[j]));
1912           }
1913     }
1914
1915   indexes[1] = N_SYMMETRIC;
1916   indexes[0] = 0;
1917   struct pivot_value *total = pivot_value_new_number (xt->total);
1918   pivot_value_set_rc (sym, total, PIVOT_RC_COUNT);
1919   pivot_table_put (sym, indexes, sym->n_dimensions, total);
1920
1921   free (indexes);
1922 }
1923
1924 static bool calc_risk (struct crosstabulation *,
1925                        double[], double[], double[], union value *,
1926                        double *);
1927
1928 /* Display risk estimate. */
1929 static void
1930 display_risk (struct crosstabulation *xt, struct pivot_table *risk,
1931               struct pivot_dimension *risk_statistics)
1932 {
1933   double risk_v[3], lower[3], upper[3], n_valid;
1934   union value c[2];
1935   if (!calc_risk (xt, risk_v, upper, lower, c, &n_valid))
1936     return;
1937   assert (risk_statistics);
1938
1939   size_t *indexes = xnmalloc (risk->n_dimensions, sizeof *indexes);
1940   assert (xt->n_vars == 2);
1941   for (size_t i = 0; i < xt->n_consts; i++)
1942     indexes[i + 2] = xt->const_indexes[i];
1943
1944   for (size_t i = 0; i < 3; i++)
1945     {
1946       const struct variable *cv = xt->vars[COL_VAR].var;
1947       const struct variable *rv = xt->vars[ROW_VAR].var;
1948
1949       if (risk_v[i] == SYSMIS)
1950         continue;
1951
1952       struct string label = DS_EMPTY_INITIALIZER;
1953       switch (i)
1954         {
1955         case 0:
1956           ds_put_format (&label, _("Odds Ratio for %s"), var_to_string (rv));
1957           ds_put_cstr (&label, " (");
1958           var_append_value_name (rv, &c[0], &label);
1959           ds_put_cstr (&label, " / ");
1960           var_append_value_name (rv, &c[1], &label);
1961           ds_put_cstr (&label, ")");
1962           break;
1963         case 1:
1964         case 2:
1965           ds_put_format (&label, _("For cohort %s = "), var_to_string (cv));
1966           var_append_value_name (cv, &xt->vars[ROW_VAR].values[i - 1], &label);
1967           break;
1968         }
1969
1970       indexes[1] = pivot_category_create_leaf (
1971         risk_statistics->root,
1972         pivot_value_new_user_text_nocopy (ds_steal_cstr (&label)));
1973
1974       double entries[] = { risk_v[i], lower[i], upper[i] };
1975       for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1976         {
1977           indexes[0] = j;
1978           pivot_table_put (risk, indexes, risk->n_dimensions,
1979                            pivot_value_new_number (entries[j]));
1980         }
1981     }
1982   indexes[1] = pivot_category_create_leaf (
1983     risk_statistics->root,
1984     pivot_value_new_text (N_("N of Valid Cases")));
1985   indexes[0] = 0;
1986   pivot_table_put (risk, indexes, risk->n_dimensions,
1987                    pivot_value_new_number (n_valid));
1988   free (indexes);
1989 }
1990
1991 static void calc_directional (struct crosstabs_proc *, struct crosstabulation *,
1992                               double[N_DIRECTIONAL], double[N_DIRECTIONAL],
1993                               double[N_DIRECTIONAL], double[N_DIRECTIONAL]);
1994
1995 /* Display directional measures. */
1996 static void
1997 display_directional (struct crosstabs_proc *proc,
1998                      struct crosstabulation *xt, struct pivot_table *direct)
1999 {
2000   double direct_v[N_DIRECTIONAL];
2001   double direct_ase[N_DIRECTIONAL];
2002   double direct_t[N_DIRECTIONAL];
2003   double sig[N_DIRECTIONAL];
2004   calc_directional (proc, xt, direct_v, direct_ase, direct_t, sig);
2005
2006   size_t *indexes = xnmalloc (direct->n_dimensions, sizeof *indexes);
2007   assert (xt->n_vars == 2);
2008   for (size_t i = 0; i < xt->n_consts; i++)
2009     indexes[i + 2] = xt->const_indexes[i];
2010
2011   for (size_t i = 0; i < N_DIRECTIONAL; i++)
2012     {
2013       if (direct_v[i] == SYSMIS)
2014         continue;
2015
2016       indexes[1] = i;
2017
2018       double entries[] = {
2019         direct_v[i], direct_ase[i], direct_t[i], sig[i],
2020       };
2021       for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
2022         if (entries[j] != SYSMIS)
2023           {
2024             indexes[0] = j;
2025             pivot_table_put (direct, indexes, direct->n_dimensions,
2026                              pivot_value_new_number (entries[j]));
2027           }
2028     }
2029
2030   free (indexes);
2031 }
2032 \f
2033 /* Statistical calculations. */
2034
2035 /* Returns the value of the logarithm of gamma (factorial) function for an integer
2036    argument XT. */
2037 static double
2038 log_gamma_int (double xt)
2039 {
2040   double r = 0;
2041   for (int i = 2; i < xt; i++)
2042     r += log(i);
2043   return r;
2044 }
2045
2046 /* Calculate P_r as specified in _SPSS Statistical Algorithms_,
2047    Appendix 5. */
2048 static inline double
2049 Pr (int a, int b, int c, int d)
2050 {
2051   return exp (log_gamma_int (a + b + 1.) -  log_gamma_int (a + 1.)
2052             + log_gamma_int (c + d + 1.) - log_gamma_int (b + 1.)
2053             + log_gamma_int (a + c + 1.) - log_gamma_int (c + 1.)
2054             + log_gamma_int (b + d + 1.) - log_gamma_int (d + 1.)
2055             - log_gamma_int (a + b + c + d + 1.));
2056 }
2057
2058 /* Swap the contents of A and B. */
2059 static inline void
2060 swap (int *a, int *b)
2061 {
2062   int t = *a;
2063   *a = *b;
2064   *b = t;
2065 }
2066
2067 /* Calculate significance for Fisher's exact test as specified in
2068    _SPSS Statistical Algorithms_, Appendix 5. */
2069 static void
2070 calc_fisher (int a, int b, int c, int d, double *fisher1, double *fisher2)
2071 {
2072   if (MIN (c, d) < MIN (a, b))
2073     swap (&a, &c), swap (&b, &d);
2074   if (MIN (b, d) < MIN (a, c))
2075     swap (&a, &b), swap (&c, &d);
2076   if (b * c < a * d)
2077     {
2078       if (b < c)
2079         swap (&a, &b), swap (&c, &d);
2080       else
2081         swap (&a, &c), swap (&b, &d);
2082     }
2083
2084   double pn1 = Pr (a, b, c, d);
2085   *fisher1 = pn1;
2086   for (int xt = 1; xt <= a; xt++)
2087     *fisher1 += Pr (a - xt, b + xt, c + xt, d - xt);
2088
2089   *fisher2 = *fisher1;
2090   for (int xt = 1; xt <= b; xt++)
2091     {
2092       double p = Pr (a + xt, b - xt, c - xt, d + xt);
2093       if (p < pn1)
2094         *fisher2 += p;
2095     }
2096 }
2097
2098 /* Calculates chi-squares into CHISQ.  MAT is a matrix with N_COLS
2099    columns with values COLS and N_ROWS rows with values ROWS.  Values
2100    in the matrix sum to xt->total. */
2101 static void
2102 calc_chisq (struct crosstabulation *xt,
2103             double chisq[N_CHISQ], int df[N_CHISQ],
2104             double *fisher1, double *fisher2)
2105 {
2106   chisq[0] = chisq[1] = 0.;
2107   chisq[2] = chisq[3] = chisq[4] = SYSMIS;
2108   *fisher1 = *fisher2 = SYSMIS;
2109
2110   df[0] = df[1] = (xt->ns_cols - 1) * (xt->ns_rows - 1);
2111
2112   if (xt->ns_rows <= 1 || xt->ns_cols <= 1)
2113     {
2114       chisq[0] = chisq[1] = SYSMIS;
2115       return;
2116     }
2117
2118   size_t n_cols = xt->vars[COL_VAR].n_values;
2119   FOR_EACH_POPULATED_ROW (r, xt)
2120     FOR_EACH_POPULATED_COLUMN (c, xt)
2121       {
2122         const double expected = xt->row_tot[r] * xt->col_tot[c] / xt->total;
2123         const double freq = xt->mat[n_cols * r + c];
2124         const double residual = freq - expected;
2125
2126         chisq[0] += residual * residual / expected;
2127         if (freq)
2128           chisq[1] += freq * log (expected / freq);
2129       }
2130
2131   if (chisq[0] == 0.)
2132     chisq[0] = SYSMIS;
2133
2134   if (chisq[1] != 0.)
2135     chisq[1] *= -2.;
2136   else
2137     chisq[1] = SYSMIS;
2138
2139   /* Calculate Yates and Fisher exact test. */
2140   if (xt->ns_cols == 2 && xt->ns_rows == 2)
2141     {
2142       int nz_cols[2];
2143
2144       size_t j = 0;
2145       FOR_EACH_POPULATED_COLUMN (c, xt)
2146         {
2147           nz_cols[j++] = c;
2148           if (j == 2)
2149             break;
2150         }
2151       assert (j == 2);
2152
2153       double f11 = xt->mat[nz_cols[0]];
2154       double f12 = xt->mat[nz_cols[1]];
2155       double f21 = xt->mat[nz_cols[0] + n_cols];
2156       double f22 = xt->mat[nz_cols[1] + n_cols];
2157
2158       /* Yates. */
2159       const double xt_ = fabs (f11 * f22 - f12 * f21) - 0.5 * xt->total;
2160
2161       if (xt_ > 0.)
2162         chisq[3] = (xt->total * pow2 (xt_)
2163                     / (f11 + f12) / (f21 + f22)
2164                     / (f11 + f21) / (f12 + f22));
2165       else
2166         chisq[3] = 0.;
2167
2168       df[3] = 1.;
2169
2170       /* Fisher. */
2171       calc_fisher (f11 + .5, f12 + .5, f21 + .5, f22 + .5, fisher1, fisher2);
2172     }
2173
2174   /* Calculate Mantel-Haenszel. */
2175   if (var_is_numeric (xt->vars[ROW_VAR].var)
2176       && var_is_numeric (xt->vars[COL_VAR].var))
2177     {
2178       double r, ase_0, ase_1;
2179       calc_r (xt, (double *) xt->vars[ROW_VAR].values,
2180               (double *) xt->vars[COL_VAR].values,
2181               &r, &ase_0, &ase_1);
2182
2183       chisq[4] = (xt->total - 1.) * r * r;
2184       df[4] = 1;
2185     }
2186 }
2187
2188 /* Calculate the value of Pearson's r.  r is stored into R, its T value into
2189    T, and standard error into ERROR.  The row and column values must be
2190    passed in XT and Y. */
2191 static void
2192 calc_r (struct crosstabulation *xt,
2193         double *XT, double *Y, double *r, double *t, double *error)
2194 {
2195   size_t n_rows = xt->vars[ROW_VAR].n_values;
2196   size_t n_cols = xt->vars[COL_VAR].n_values;
2197
2198   double sum_XYf = 0;
2199   for (size_t i = 0; i < n_rows; i++)
2200     for (size_t j = 0; j < n_cols; j++)
2201       {
2202         double fij = xt->mat[j + i * n_cols];
2203         double product = XT[i] * Y[j];
2204         double temp = fij * product;
2205         sum_XYf += temp;
2206       }
2207
2208   double sum_Xr = 0;
2209   double sum_X2r = 0;
2210   for (size_t i = 0; i < n_rows; i++)
2211     {
2212       sum_Xr += XT[i] * xt->row_tot[i];
2213       sum_X2r += pow2 (XT[i]) * xt->row_tot[i];
2214     }
2215   double Xbar = sum_Xr / xt->total;
2216
2217   double sum_Yc = 0;
2218   double sum_Y2c = 0;
2219   for (size_t i = 0; i < n_cols; i++)
2220     {
2221       sum_Yc += Y[i] * xt->col_tot[i];
2222       sum_Y2c += Y[i] * Y[i] * xt->col_tot[i];
2223     }
2224   double Ybar = sum_Yc / xt->total;
2225
2226   double S = sum_XYf - sum_Xr * sum_Yc / xt->total;
2227   double SX = sum_X2r - pow2 (sum_Xr) / xt->total;
2228   double SY = sum_Y2c - pow2 (sum_Yc) / xt->total;
2229   double T = sqrt (SX * SY);
2230   *r = S / T;
2231   *t = *r / sqrt (1 - pow2 (*r)) * sqrt (xt->total - 2);
2232
2233   double s = 0;
2234   double c = 0;
2235   for (size_t i = 0; i < n_rows; i++)
2236     for (size_t j = 0; j < n_cols; j++)
2237       {
2238         double Xresid = XT[i] - Xbar;
2239         double Yresid = Y[j] - Ybar;
2240         double temp = (T * Xresid * Yresid
2241                        - ((S / (2. * T))
2242                           * (Xresid * Xresid * SY + Yresid * Yresid * SX)));
2243         double y = xt->mat[j + i * n_cols] * temp * temp - c;
2244         double t = s + y;
2245         c = (t - s) - y;
2246         s = t;
2247       }
2248   *error = sqrt (s) / (T * T);
2249 }
2250
2251 /* Calculate symmetric statistics and their asymptotic standard
2252    errors.  Returns false if none could be calculated. */
2253 static bool
2254 calc_symmetric (struct crosstabs_proc *proc, struct crosstabulation *xt,
2255                 double v[N_SYMMETRIC], double ase[N_SYMMETRIC],
2256                 double t[N_SYMMETRIC],
2257                 double somers_d_v[3], double somers_d_ase[3],
2258                 double somers_d_t[3])
2259 {
2260   size_t n_rows = xt->vars[ROW_VAR].n_values;
2261   size_t n_cols = xt->vars[COL_VAR].n_values;
2262
2263   size_t q = MIN (xt->ns_rows, xt->ns_cols);
2264   if (q <= 1)
2265     return false;
2266
2267   for (size_t i = 0; i < N_SYMMETRIC; i++)
2268     v[i] = ase[i] = t[i] = SYSMIS;
2269
2270   /* Phi, Cramer's V, contingency coefficient. */
2271   if (proc->statistics & (CRS_ST_PHI | CRS_ST_CC))
2272     {
2273       double Xp = 0.;   /* Pearson chi-square. */
2274
2275       FOR_EACH_POPULATED_ROW (r, xt)
2276         FOR_EACH_POPULATED_COLUMN (c, xt)
2277           {
2278             double expected = xt->row_tot[r] * xt->col_tot[c] / xt->total;
2279             double freq = xt->mat[n_cols * r + c];
2280             double residual = freq - expected;
2281
2282             Xp += residual * residual / expected;
2283           }
2284
2285       if (proc->statistics & CRS_ST_PHI)
2286         {
2287           v[0] = sqrt (Xp / xt->total);
2288           v[1] = sqrt (Xp / (xt->total * (q - 1)));
2289         }
2290       if (proc->statistics & CRS_ST_CC)
2291         v[2] = sqrt (Xp / (Xp + xt->total));
2292     }
2293
2294   if (proc->statistics & (CRS_ST_BTAU | CRS_ST_CTAU
2295                           | CRS_ST_GAMMA | CRS_ST_D))
2296     {
2297       double Dr = pow2 (xt->total);
2298       for (size_t r = 0; r < n_rows; r++)
2299         Dr -= pow2 (xt->row_tot[r]);
2300
2301       double Dc = pow2 (xt->total);
2302       for (size_t c = 0; c < n_cols; c++)
2303         Dc -= pow2 (xt->col_tot[c]);
2304
2305       double *cum = xnmalloc (n_cols * n_rows, sizeof *cum);
2306       for (size_t c = 0; c < n_cols; c++)
2307         {
2308           double ct = 0.;
2309
2310           for (size_t r = 0; r < n_rows; r++)
2311             cum[c + r * n_cols] = ct += xt->mat[c + r * n_cols];
2312         }
2313
2314       /* P and Q. */
2315       double P = 0;
2316       double Q = 0;
2317       for (size_t i = 0; i < n_rows; i++)
2318         {
2319           double Cij = 0;
2320           for (size_t j = 1; j < n_cols; j++)
2321             Cij += xt->col_tot[j] - cum[j + i * n_cols];
2322
2323           double Dij = 0;
2324           if (i > 0)
2325             for (size_t j = 1; j < n_cols; j++)
2326               Dij += cum[j + (i - 1) * n_cols];
2327
2328           for (size_t j = 0;;)
2329             {
2330               double fij = xt->mat[j + i * n_cols];
2331               P += fij * Cij;
2332               Q += fij * Dij;
2333
2334               if (++j >= n_cols)
2335                 break;
2336
2337               Cij -= xt->col_tot[j] - cum[j + i * n_cols];
2338               Dij += xt->col_tot[j - 1] - cum[j - 1 + i * n_cols];
2339
2340               if (i > 0)
2341                 {
2342                   Cij += cum[j - 1 + (i - 1) * n_cols];
2343                   Dij -= cum[j + (i - 1) * n_cols];
2344                 }
2345             }
2346         }
2347
2348       if (proc->statistics & CRS_ST_BTAU)
2349         v[3] = (P - Q) / sqrt (Dr * Dc);
2350       if (proc->statistics & CRS_ST_CTAU)
2351         v[4] = (q * (P - Q)) / (pow2 (xt->total) * (q - 1));
2352       if (proc->statistics & CRS_ST_GAMMA)
2353         v[5] = (P - Q) / (P + Q);
2354
2355       /* ASE for tau-b, tau-c, gamma.  Calculations could be
2356          eliminated here, at expense of memory.  */
2357       double btau_cum = 0;
2358       double ctau_cum = 0;
2359       double gamma_cum = 0;
2360       double d_yx_cum = 0;
2361       double d_xy_cum = 0;
2362       for (size_t i = 0; i < n_rows; i++)
2363         {
2364           double Cij = 0;
2365           for (size_t j = 1; j < n_cols; j++)
2366             Cij += xt->col_tot[j] - cum[j + i * n_cols];
2367
2368           double Dij = 0;
2369           if (i > 0)
2370             for (size_t j = 1; j < n_cols; j++)
2371               Dij += cum[j + (i - 1) * n_cols];
2372
2373           for (size_t j = 0;;)
2374             {
2375               double fij = xt->mat[j + i * n_cols];
2376
2377               if (proc->statistics & CRS_ST_BTAU)
2378                 btau_cum += fij * pow2 (2. * sqrt (Dr * Dc) * (Cij - Dij)
2379                                         + v[3] * (xt->row_tot[i] * Dc
2380                                                   + xt->col_tot[j] * Dr));
2381               ctau_cum += fij * pow2 (Cij - Dij);
2382
2383               if (proc->statistics & CRS_ST_GAMMA)
2384                 gamma_cum += fij * pow2 (Q * Cij - P * Dij);
2385
2386               if (proc->statistics & CRS_ST_D)
2387                 {
2388                   d_yx_cum += fij * pow2 (Dr * (Cij - Dij)
2389                                           - (P - Q) * (xt->total - xt->row_tot[i]));
2390                   d_xy_cum += fij * pow2 (Dc * (Dij - Cij)
2391                                           - (Q - P) * (xt->total - xt->col_tot[j]));
2392                 }
2393
2394               if (++j >= n_cols)
2395                 break;
2396
2397               Cij -= xt->col_tot[j] - cum[j + i * n_cols];
2398               Dij += xt->col_tot[j - 1] - cum[j - 1 + i * n_cols];
2399
2400               if (i > 0)
2401                 {
2402                   Cij += cum[j - 1 + (i - 1) * n_cols];
2403                   Dij -= cum[j + (i - 1) * n_cols];
2404                 }
2405             }
2406         }
2407
2408       if (proc->statistics & CRS_ST_BTAU)
2409         {
2410           double btau_var = ((btau_cum
2411                               - (xt->total * pow2 (xt->total * (P - Q) / sqrt (Dr * Dc) * (Dr + Dc))))
2412                              / pow2 (Dr * Dc));
2413           ase[3] = sqrt (btau_var);
2414           t[3] = v[3] / (2 * sqrt ((ctau_cum - (P - Q) * (P - Q) / xt->total)
2415                                    / (Dr * Dc)));
2416         }
2417       if (proc->statistics & CRS_ST_CTAU)
2418         {
2419           ase[4] = ((2 * q / ((q - 1) * pow2 (xt->total)))
2420                     * sqrt (ctau_cum - (P - Q) * (P - Q) / xt->total));
2421           t[4] = v[4] / ase[4];
2422         }
2423       if (proc->statistics & CRS_ST_GAMMA)
2424         {
2425           ase[5] = ((4. / ((P + Q) * (P + Q))) * sqrt (gamma_cum));
2426           t[5] = v[5] / (2. / (P + Q)
2427                          * sqrt (ctau_cum - (P - Q) * (P - Q) / xt->total));
2428         }
2429       if (proc->statistics & CRS_ST_D)
2430         {
2431           somers_d_v[0] = (P - Q) / (.5 * (Dc + Dr));
2432           somers_d_ase[0] = SYSMIS;
2433           somers_d_t[0] = (somers_d_v[0]
2434                            / (4 / (Dc + Dr)
2435                               * sqrt (ctau_cum - pow2 (P - Q) / xt->total)));
2436           somers_d_v[1] = (P - Q) / Dc;
2437           somers_d_ase[1] = 2. / pow2 (Dc) * sqrt (d_xy_cum);
2438           somers_d_t[1] = (somers_d_v[1]
2439                            / (2. / Dc
2440                               * sqrt (ctau_cum - pow2 (P - Q) / xt->total)));
2441           somers_d_v[2] = (P - Q) / Dr;
2442           somers_d_ase[2] = 2. / pow2 (Dr) * sqrt (d_yx_cum);
2443           somers_d_t[2] = (somers_d_v[2]
2444                            / (2. / Dr
2445                               * sqrt (ctau_cum - pow2 (P - Q) / xt->total)));
2446         }
2447
2448       free (cum);
2449     }
2450
2451   /* Spearman correlation, Pearson's r. */
2452   if (proc->statistics & CRS_ST_CORR)
2453     {
2454       double *R = xmalloc (sizeof *R * n_rows);
2455       double c = 0;
2456       double s = 0;
2457       for (size_t i = 0; i < n_rows; i++)
2458         {
2459           R[i] = s + (xt->row_tot[i] + 1.) / 2.;
2460           double y = xt->row_tot[i] - c;
2461           double t = s + y;
2462           c = (t - s) - y;
2463           s = t;
2464         }
2465
2466       double *C = xmalloc (sizeof *C * n_cols);
2467       c = s = 0;
2468       for (size_t j = 0; j < n_cols; j++)
2469         {
2470           C[j] = s + (xt->col_tot[j] + 1.) / 2;
2471           double y = xt->col_tot[j] - c;
2472           double t = s + y;
2473           c = (t - s) - y;
2474           s = t;
2475         }
2476
2477       calc_r (xt, R, C, &v[6], &t[6], &ase[6]);
2478
2479       free (R);
2480       free (C);
2481
2482       calc_r (xt, (double *) xt->vars[ROW_VAR].values,
2483               (double *) xt->vars[COL_VAR].values,
2484               &v[7], &t[7], &ase[7]);
2485     }
2486
2487   /* Cohen's kappa. */
2488   if (proc->statistics & CRS_ST_KAPPA && xt->ns_rows == xt->ns_cols)
2489     {
2490       double sum_fii = 0;
2491       double sum_rici = 0;
2492       double sum_fiiri_ci = 0;
2493       double sum_riciri_ci = 0;
2494       for (size_t i = 0, j = 0; i < xt->ns_rows; i++, j++)
2495         {
2496           while (xt->col_tot[j] == 0.)
2497             j++;
2498
2499           double prod = xt->row_tot[i] * xt->col_tot[j];
2500           double sum = xt->row_tot[i] + xt->col_tot[j];
2501
2502           sum_fii += xt->mat[j + i * n_cols];
2503           sum_rici += prod;
2504           sum_fiiri_ci += xt->mat[j + i * n_cols] * sum;
2505           sum_riciri_ci += prod * sum;
2506         }
2507
2508       double sum_fijri_ci2 = 0;
2509       for (size_t i = 0; i < xt->ns_rows; i++)
2510         for (size_t j = 0; j < xt->ns_cols; j++)
2511           {
2512             double sum = xt->row_tot[i] + xt->col_tot[j];
2513             sum_fijri_ci2 += xt->mat[j + i * n_cols] * sum * sum;
2514           }
2515
2516       v[8] = (xt->total * sum_fii - sum_rici) / (pow2 (xt->total) - sum_rici);
2517
2518       double ase_under_h0 = sqrt ((pow2 (xt->total) * sum_rici
2519                                    + sum_rici * sum_rici
2520                                    - xt->total * sum_riciri_ci)
2521                                   / (xt->total * (pow2 (xt->total) - sum_rici) * (pow2 (xt->total) - sum_rici)));
2522
2523       ase[8] = sqrt (xt->total * (((sum_fii * (xt->total - sum_fii))
2524                                 / pow2 (pow2 (xt->total) - sum_rici))
2525                                + ((2. * (xt->total - sum_fii)
2526                                    * (2. * sum_fii * sum_rici
2527                                       - xt->total * sum_fiiri_ci))
2528                                   / pow3 (pow2 (xt->total) - sum_rici))
2529                                + (pow2 (xt->total - sum_fii)
2530                                   * (xt->total * sum_fijri_ci2 - 4.
2531                                      * sum_rici * sum_rici)
2532                                   / pow4 (pow2 (xt->total) - sum_rici))));
2533
2534       t[8] = v[8] / ase_under_h0;
2535     }
2536
2537   return true;
2538 }
2539
2540 /* Calculate risk estimate. */
2541 static bool
2542 calc_risk (struct crosstabulation *xt,
2543            double *value, double *upper, double *lower, union value *c,
2544            double *n_valid)
2545 {
2546   size_t n_cols = xt->vars[COL_VAR].n_values;
2547
2548   for (size_t i = 0; i < 3; i++)
2549     value[i] = upper[i] = lower[i] = SYSMIS;
2550
2551   if (xt->ns_rows != 2 || xt->ns_cols != 2)
2552     return false;
2553
2554   /* Find populated columns. */
2555   size_t nz_cols[2];
2556   size_t n = 0;
2557   FOR_EACH_POPULATED_COLUMN (c, xt)
2558     nz_cols[n++] = c;
2559   assert (n == 2);
2560
2561   /* Find populated rows. */
2562   size_t nz_rows[2];
2563   n = 0;
2564   FOR_EACH_POPULATED_ROW (r, xt)
2565     nz_rows[n++] = r;
2566   assert (n == 2);
2567
2568   double f11 = xt->mat[nz_cols[0] + n_cols * nz_rows[0]];
2569   double f12 = xt->mat[nz_cols[1] + n_cols * nz_rows[0]];
2570   double f21 = xt->mat[nz_cols[0] + n_cols * nz_rows[1]];
2571   double f22 = xt->mat[nz_cols[1] + n_cols * nz_rows[1]];
2572   *n_valid = f11 + f12 + f21 + f22;
2573
2574   c[0] = xt->vars[COL_VAR].values[nz_cols[0]];
2575   c[1] = xt->vars[COL_VAR].values[nz_cols[1]];
2576
2577   value[0] = (f11 * f22) / (f12 * f21);
2578   double v = sqrt (1. / f11 + 1. / f12 + 1. / f21 + 1. / f22);
2579   lower[0] = value[0] * exp (-1.960 * v);
2580   upper[0] = value[0] * exp (1.960 * v);
2581
2582   value[1] = (f11 * (f21 + f22)) / (f21 * (f11 + f12));
2583   v = sqrt ((f12 / (f11 * (f11 + f12)))
2584             + (f22 / (f21 * (f21 + f22))));
2585   lower[1] = value[1] * exp (-1.960 * v);
2586   upper[1] = value[1] * exp (1.960 * v);
2587
2588   value[2] = (f12 * (f21 + f22)) / (f22 * (f11 + f12));
2589   v = sqrt ((f11 / (f12 * (f11 + f12)))
2590             + (f21 / (f22 * (f21 + f22))));
2591   lower[2] = value[2] * exp (-1.960 * v);
2592   upper[2] = value[2] * exp (1.960 * v);
2593
2594   return true;
2595 }
2596
2597 /* Calculate directional measures. */
2598 static void
2599 calc_directional (struct crosstabs_proc *proc, struct crosstabulation *xt,
2600                   double v[N_DIRECTIONAL], double ase[N_DIRECTIONAL],
2601                   double t[N_DIRECTIONAL], double sig[N_DIRECTIONAL])
2602 {
2603   size_t n_rows = xt->vars[ROW_VAR].n_values;
2604   size_t n_cols = xt->vars[COL_VAR].n_values;
2605   for (size_t i = 0; i < N_DIRECTIONAL; i++)
2606     v[i] = ase[i] = t[i] = sig[i] = SYSMIS;
2607
2608   /* Lambda. */
2609   if (proc->statistics & CRS_ST_LAMBDA)
2610     {
2611       /* Find maximum for each row and their sum. */
2612       double *fim = xnmalloc (n_rows, sizeof *fim);
2613       size_t *fim_index = xnmalloc (n_rows, sizeof *fim_index);
2614       double sum_fim = 0.0;
2615       for (size_t i = 0; i < n_rows; i++)
2616         {
2617           double max = xt->mat[i * n_cols];
2618           size_t index = 0;
2619
2620           for (size_t j = 1; j < n_cols; j++)
2621             if (xt->mat[j + i * n_cols] > max)
2622               {
2623                 max = xt->mat[j + i * n_cols];
2624                 index = j;
2625               }
2626
2627           fim[i] = max;
2628           sum_fim += max;
2629           fim_index[i] = index;
2630         }
2631
2632       /* Find maximum for each column. */
2633       double *fmj = xnmalloc (n_cols, sizeof *fmj);
2634       size_t *fmj_index = xnmalloc (n_cols, sizeof *fmj_index);
2635       double sum_fmj = 0.0;
2636       for (size_t j = 0; j < n_cols; j++)
2637         {
2638           double max = xt->mat[j];
2639           size_t index = 0;
2640
2641           for (size_t i = 1; i < n_rows; i++)
2642             if (xt->mat[j + i * n_cols] > max)
2643               {
2644                 max = xt->mat[j + i * n_cols];
2645                 index = i;
2646               }
2647
2648           fmj[j] = max;
2649           sum_fmj += max;
2650           fmj_index[j] = index;
2651         }
2652
2653       /* Find maximum row total. */
2654       double rm = xt->row_tot[0];
2655       size_t rm_index = 0;
2656       for (size_t i = 1; i < n_rows; i++)
2657         if (xt->row_tot[i] > rm)
2658           {
2659             rm = xt->row_tot[i];
2660             rm_index = i;
2661           }
2662
2663       /* Find maximum column total. */
2664       double cm = xt->col_tot[0];
2665       size_t cm_index = 0;
2666       for (size_t j = 1; j < n_cols; j++)
2667         if (xt->col_tot[j] > cm)
2668           {
2669             cm = xt->col_tot[j];
2670             cm_index = j;
2671           }
2672
2673       v[0] = (sum_fim + sum_fmj - cm - rm) / (2. * xt->total - rm - cm);
2674       v[1] = (sum_fmj - rm) / (xt->total - rm);
2675       v[2] = (sum_fim - cm) / (xt->total - cm);
2676
2677       /* ASE1 for Y given XT. */
2678       {
2679         double accum = 0.0;
2680         for (size_t i = 0; i < n_rows; i++)
2681           if (cm_index == fim_index[i])
2682             accum += fim[i];
2683         ase[2] = sqrt ((xt->total - sum_fim) * (sum_fim + cm - 2. * accum)
2684                        / pow3 (xt->total - cm));
2685       }
2686
2687       /* ASE0 for Y given XT. */
2688       {
2689         double accum = 0.0;
2690         for (size_t i = 0; i < n_rows; i++)
2691           if (cm_index != fim_index[i])
2692             accum += (xt->mat[i * n_cols + fim_index[i]]
2693                       + xt->mat[i * n_cols + cm_index]);
2694         t[2] = v[2] / (sqrt (accum - pow2 (sum_fim - cm) / xt->total) / (xt->total - cm));
2695       }
2696
2697       /* ASE1 for XT given Y. */
2698       {
2699         double accum = 0.0;
2700         for (size_t j = 0; j < n_cols; j++)
2701           if (rm_index == fmj_index[j])
2702             accum += fmj[j];
2703         ase[1] = sqrt ((xt->total - sum_fmj) * (sum_fmj + rm - 2. * accum)
2704                        / pow3 (xt->total - rm));
2705       }
2706
2707       /* ASE0 for XT given Y. */
2708       {
2709         double accum = 0.0;
2710         for (size_t j = 0; j < n_cols; j++)
2711           if (rm_index != fmj_index[j])
2712             accum += (xt->mat[j + n_cols * fmj_index[j]]
2713                       + xt->mat[j + n_cols * rm_index]);
2714         t[1] = v[1] / (sqrt (accum - pow2 (sum_fmj - rm) / xt->total) / (xt->total - rm));
2715       }
2716
2717       /* Symmetric ASE0 and ASE1. */
2718       {
2719         double accum0 = 0.0;
2720         double accum1 = 0.0;
2721         for (size_t i = 0; i < n_rows; i++)
2722           for (size_t j = 0; j < n_cols; j++)
2723             {
2724               int temp0 = (fmj_index[j] == i) + (fim_index[i] == j);
2725               int temp1 = (i == rm_index) + (j == cm_index);
2726               accum0 += xt->mat[j + i * n_cols] * pow2 (temp0 - temp1);
2727               accum1 += (xt->mat[j + i * n_cols]
2728                          * pow2 (temp0 + (v[0] - 1.) * temp1));
2729             }
2730         ase[0] = sqrt (accum1 - 4. * xt->total * v[0] * v[0]) / (2. * xt->total - rm - cm);
2731         t[0] = v[0] / (sqrt (accum0 - pow2 (sum_fim + sum_fmj - cm - rm) / xt->total)
2732                        / (2. * xt->total - rm - cm));
2733       }
2734
2735       for (size_t i = 0; i < 3; i++)
2736         sig[i] = 2 * gsl_cdf_ugaussian_Q (t[i]);
2737
2738       free (fim);
2739       free (fim_index);
2740       free (fmj);
2741       free (fmj_index);
2742
2743       /* Tau. */
2744       double sum_fij2_ri = 0.0;
2745       double sum_fij2_ci = 0.0;
2746       FOR_EACH_POPULATED_ROW (i, xt)
2747         FOR_EACH_POPULATED_COLUMN (j, xt)
2748         {
2749           double temp = pow2 (xt->mat[j + i * n_cols]);
2750           sum_fij2_ri += temp / xt->row_tot[i];
2751           sum_fij2_ci += temp / xt->col_tot[j];
2752         }
2753
2754       double sum_ri2 = 0.0;
2755       for (size_t i = 0; i < n_rows; i++)
2756         sum_ri2 += pow2 (xt->row_tot[i]);
2757
2758       double sum_cj2 = 0.0;
2759       for (size_t j = 0; j < n_cols; j++)
2760         sum_cj2 += pow2 (xt->col_tot[j]);
2761
2762       v[3] = (xt->total * sum_fij2_ci - sum_ri2) / (pow2 (xt->total) - sum_ri2);
2763       v[4] = (xt->total * sum_fij2_ri - sum_cj2) / (pow2 (xt->total) - sum_cj2);
2764     }
2765
2766   if (proc->statistics & CRS_ST_UC)
2767     {
2768       double UX = 0.0;
2769       FOR_EACH_POPULATED_ROW (i, xt)
2770         UX -= xt->row_tot[i] / xt->total * log (xt->row_tot[i] / xt->total);
2771
2772       double UY = 0.0;
2773       FOR_EACH_POPULATED_COLUMN (j, xt)
2774         UY -= xt->col_tot[j] / xt->total * log (xt->col_tot[j] / xt->total);
2775
2776       double UXY = 0.0;
2777       double P = 0.0;
2778       for (size_t i = 0; i < n_rows; i++)
2779         for (size_t j = 0; j < n_cols; j++)
2780           {
2781             double entry = xt->mat[j + i * n_cols];
2782
2783             if (entry <= 0.)
2784               continue;
2785
2786             P += entry * pow2 (log (xt->col_tot[j] * xt->row_tot[i] / (xt->total * entry)));
2787             UXY -= entry / xt->total * log (entry / xt->total);
2788           }
2789
2790       double ase1_yx = 0.0;
2791       double ase1_xy = 0.0;
2792       double ase1_sym = 0.0;
2793       for (size_t i = 0; i < n_rows; i++)
2794         for (size_t j = 0; j < n_cols; j++)
2795           {
2796             double entry = xt->mat[j + i * n_cols];
2797
2798             if (entry <= 0.)
2799               continue;
2800
2801             ase1_yx += entry * pow2 (UY * log (entry / xt->row_tot[i])
2802                                     + (UX - UXY) * log (xt->col_tot[j] / xt->total));
2803             ase1_xy += entry * pow2 (UX * log (entry / xt->col_tot[j])
2804                                     + (UY - UXY) * log (xt->row_tot[i] / xt->total));
2805             ase1_sym += entry * pow2 ((UXY
2806                                       * log (xt->row_tot[i] * xt->col_tot[j] / pow2 (xt->total)))
2807                                      - (UX + UY) * log (entry / xt->total));
2808           }
2809
2810       v[5] = 2. * ((UX + UY - UXY) / (UX + UY));
2811       ase[5] = (2. / (xt->total * pow2 (UX + UY))) * sqrt (ase1_sym);
2812       t[5] = SYSMIS;
2813
2814       v[6] = (UX + UY - UXY) / UX;
2815       ase[6] = sqrt (ase1_xy) / (xt->total * UX * UX);
2816       t[6] = v[6] / (sqrt (P - xt->total * pow2 (UX + UY - UXY)) / (xt->total * UX));
2817
2818       v[7] = (UX + UY - UXY) / UY;
2819       ase[7] = sqrt (ase1_yx) / (xt->total * UY * UY);
2820       t[7] = v[7] / (sqrt (P - xt->total * pow2 (UX + UY - UXY)) / (xt->total * UY));
2821     }
2822
2823   /* Somers' D. */
2824   if (proc->statistics & CRS_ST_D)
2825     {
2826       double v_dummy[N_SYMMETRIC];
2827       double ase_dummy[N_SYMMETRIC];
2828       double t_dummy[N_SYMMETRIC];
2829       double somers_d_v[3];
2830       double somers_d_ase[3];
2831       double somers_d_t[3];
2832
2833       if (calc_symmetric (proc, xt, v_dummy, ase_dummy, t_dummy,
2834                           somers_d_v, somers_d_ase, somers_d_t))
2835         {
2836           for (size_t i = 0; i < 3; i++)
2837             {
2838               v[8 + i] = somers_d_v[i];
2839               ase[8 + i] = somers_d_ase[i];
2840               t[8 + i] = somers_d_t[i];
2841               sig[8 + i] = 2 * gsl_cdf_ugaussian_Q (fabs (somers_d_t[i]));
2842             }
2843         }
2844     }
2845
2846   /* Eta. */
2847   if (proc->statistics & CRS_ST_ETA)
2848     {
2849       /* X dependent. */
2850       double sum_Xr = 0.0;
2851       double sum_X2r = 0.0;
2852       for (size_t i = 0; i < n_rows; i++)
2853         {
2854           sum_Xr += xt->vars[ROW_VAR].values[i].f * xt->row_tot[i];
2855           sum_X2r += pow2 (xt->vars[ROW_VAR].values[i].f) * xt->row_tot[i];
2856         }
2857       double SX = sum_X2r - pow2 (sum_Xr) / xt->total;
2858
2859       double SXW = 0.0;
2860       FOR_EACH_POPULATED_COLUMN (j, xt)
2861         {
2862           double cum = 0.0;
2863
2864           for (size_t i = 0; i < n_rows; i++)
2865             {
2866               SXW += (pow2 (xt->vars[ROW_VAR].values[i].f)
2867                       * xt->mat[j + i * n_cols]);
2868               cum += (xt->vars[ROW_VAR].values[i].f
2869                       * xt->mat[j + i * n_cols]);
2870             }
2871
2872           SXW -= cum * cum / xt->col_tot[j];
2873         }
2874       v[11] = sqrt (1. - SXW / SX);
2875
2876       /* Y dependent. */
2877       double sum_Yc = 0.0;
2878       double sum_Y2c = 0.0;
2879       for (size_t i = 0; i < n_cols; i++)
2880         {
2881           sum_Yc += xt->vars[COL_VAR].values[i].f * xt->col_tot[i];
2882           sum_Y2c += pow2 (xt->vars[COL_VAR].values[i].f) * xt->col_tot[i];
2883         }
2884       double SY = sum_Y2c - pow2 (sum_Yc) / xt->total;
2885
2886       double SYW = 0.0;
2887       FOR_EACH_POPULATED_ROW (i, xt)
2888         {
2889           double cum = 0.0;
2890           for (size_t j = 0; j < n_cols; j++)
2891             {
2892               SYW += (pow2 (xt->vars[COL_VAR].values[j].f)
2893                       * xt->mat[j + i * n_cols]);
2894               cum += (xt->vars[COL_VAR].values[j].f
2895                       * xt->mat[j + i * n_cols]);
2896             }
2897
2898           SYW -= cum * cum / xt->row_tot[i];
2899         }
2900       v[12] = sqrt (1. - SYW / SY);
2901     }
2902 }