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