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