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