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