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