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