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