1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Free Software Foundation, Inc.
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.
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.
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/>. */
19 - How to calculate significance of some symmetric and directional measures?
20 - How to calculate ASE for symmetric Somers ' d?
21 - How to calculate ASE for Goodman and Kruskal's tau?
22 - How to calculate approx. T of symmetric uncertainty coefficient?
30 #include <gsl/gsl_cdf.h>
34 #include "data/case.h"
35 #include "data/casegrouper.h"
36 #include "data/casereader.h"
37 #include "data/data-out.h"
38 #include "data/dataset.h"
39 #include "data/dictionary.h"
40 #include "data/format.h"
41 #include "data/value-labels.h"
42 #include "data/variable.h"
43 #include "language/command.h"
44 #include "language/stats/freq.h"
45 #include "language/dictionary/split-file.h"
46 #include "language/lexer/lexer.h"
47 #include "language/lexer/variable-parser.h"
48 #include "libpspp/array.h"
49 #include "libpspp/assertion.h"
50 #include "libpspp/compiler.h"
51 #include "libpspp/hash-functions.h"
52 #include "libpspp/hmap.h"
53 #include "libpspp/hmapx.h"
54 #include "libpspp/message.h"
55 #include "libpspp/misc.h"
56 #include "libpspp/pool.h"
57 #include "libpspp/str.h"
58 #include "output/tab.h"
59 #include "output/chart-item.h"
60 #include "output/charts/barchart.h"
62 #include "gl/minmax.h"
63 #include "gl/xalloc.h"
67 #define _(msgid) gettext (msgid)
68 #define N_(msgid) msgid
76 missing=miss:!table/include/report;
77 count=roundwhat:asis/case/!cell,
78 roundhow:!round/truncate;
79 +write[wr_]=none,cells,all;
80 +format=val:!avalue/dvalue,
82 tabl:!tables/notables,
86 +cells[cl_]=count,expected,row,column,total,residual,sresidual,
88 +statistics[st_]=chisq,phi,cc,lambda,uc,none,btau,ctau,risk,gamma,d,
94 /* Number of chi-square statistics. */
97 /* Number of symmetric statistics. */
100 /* Number of directional statistics. */
101 #define N_DIRECTIONAL 13
104 /* Indexes into the 'vars' member of struct pivot_table and
105 struct crosstab member. */
108 ROW_VAR = 0, /* Row variable. */
109 COL_VAR = 1 /* Column variable. */
110 /* Higher indexes cause multiple tables to be output. */
113 /* A crosstabulation of 2 or more variables. */
116 struct crosstabs_proc *proc;
117 struct fmt_spec weight_format; /* Format for weight variable. */
118 double missing; /* Weight of missing cases. */
120 /* Variables (2 or more). */
122 const struct variable **vars;
124 /* Constants (0 or more). */
126 const struct variable **const_vars;
127 union value *const_values;
131 struct freq **entries;
134 /* Column values, number of columns. */
138 /* Row values, number of rows. */
142 /* Number of statistically interesting columns/rows
143 (columns/rows with data in them). */
144 int ns_cols, ns_rows;
146 /* Matrix contents. */
147 double *mat; /* Matrix proper. */
148 double *row_tot; /* Row totals. */
149 double *col_tot; /* Column totals. */
150 double total; /* Grand total. */
153 /* Integer mode variable info. */
156 struct hmap_node hmap_node; /* In struct crosstabs_proc var_ranges map. */
157 const struct variable *var; /* The variable. */
158 int min; /* Minimum value. */
159 int max; /* Maximum value + 1. */
160 int count; /* max - min. */
163 struct crosstabs_proc
165 const struct dictionary *dict;
166 enum { INTEGER, GENERAL } mode;
167 enum mv_class exclude;
171 struct fmt_spec weight_format;
173 /* Variables specifies on VARIABLES. */
174 const struct variable **variables;
176 struct hmap var_ranges;
179 struct pivot_table *pivots;
183 int n_cells; /* Number of cells requested. */
184 unsigned int cells; /* Bit k is 1 if cell k is requested. */
185 int a_cells[CRS_CL_count]; /* 0...n_cells-1 are the requested cells. */
187 /* Rounding of cells. */
188 bool round_case_weights; /* Round case weights? */
189 bool round_cells; /* If !round_case_weights, round cells? */
190 bool round_down; /* Round down? (otherwise to nearest) */
193 unsigned int statistics; /* Bit k is 1 if statistic k is requested. */
195 bool descending; /* True if descending sort order is requested. */
198 const struct var_range *get_var_range (const struct crosstabs_proc *,
199 const struct variable *);
201 static bool should_tabulate_case (const struct pivot_table *,
202 const struct ccase *, enum mv_class exclude);
203 static void tabulate_general_case (struct pivot_table *, const struct ccase *,
205 static void tabulate_integer_case (struct pivot_table *, const struct ccase *,
207 static void postcalc (struct crosstabs_proc *);
208 static void submit (struct pivot_table *, struct tab_table *);
211 round_weight (const struct crosstabs_proc *proc, double weight)
213 return proc->round_down ? floor (weight) : floor (weight + 0.5);
216 /* Parses and executes the CROSSTABS procedure. */
218 cmd_crosstabs (struct lexer *lexer, struct dataset *ds)
220 struct var_range *range, *next_range;
221 struct crosstabs_proc proc;
222 struct casegrouper *grouper;
223 struct casereader *input, *group;
224 struct cmd_crosstabs cmd;
225 struct pivot_table *pt;
230 proc.dict = dataset_dict (ds);
231 proc.bad_warn = true;
232 proc.variables = NULL;
233 proc.n_variables = 0;
234 hmap_init (&proc.var_ranges);
237 proc.descending = false;
238 proc.weight_format = *dict_get_weight_format (dataset_dict (ds));
240 if (!parse_crosstabs (lexer, ds, &cmd, &proc))
242 result = CMD_FAILURE;
246 proc.mode = proc.n_variables ? INTEGER : GENERAL;
247 proc.barchart = cmd.sbc_barchart > 0;
249 proc.descending = cmd.val == CRS_DVALUE;
251 proc.round_case_weights = cmd.sbc_count && cmd.roundwhat == CRS_CASE;
252 proc.round_cells = cmd.sbc_count && cmd.roundwhat == CRS_CELL;
253 proc.round_down = cmd.roundhow == CRS_TRUNCATE;
257 proc.cells = 1u << CRS_CL_COUNT;
258 else if (cmd.a_cells[CRS_CL_ALL])
259 proc.cells = UINT_MAX;
263 for (i = 0; i < CRS_CL_count; i++)
265 proc.cells |= 1u << i;
267 proc.cells = ((1u << CRS_CL_COUNT)
269 | (1u << CRS_CL_COLUMN)
270 | (1u << CRS_CL_TOTAL));
272 proc.cells &= ((1u << CRS_CL_count) - 1);
273 proc.cells &= ~((1u << CRS_CL_NONE) | (1u << CRS_CL_ALL));
275 for (i = 0; i < CRS_CL_count; i++)
276 if (proc.cells & (1u << i))
277 proc.a_cells[proc.n_cells++] = i;
280 if (cmd.a_statistics[CRS_ST_ALL])
281 proc.statistics = UINT_MAX;
282 else if (cmd.sbc_statistics)
287 for (i = 0; i < CRS_ST_count; i++)
288 if (cmd.a_statistics[i])
289 proc.statistics |= 1u << i;
290 if (proc.statistics == 0)
291 proc.statistics |= 1u << CRS_ST_CHISQ;
297 proc.exclude = (cmd.miss == CRS_TABLE ? MV_ANY
298 : cmd.miss == CRS_INCLUDE ? MV_SYSTEM
300 if (proc.mode == GENERAL && proc.exclude == MV_NEVER)
302 msg (SE, _("Missing mode %s not allowed in general mode. "
303 "Assuming %s."), "REPORT", "MISSING=TABLE");
304 proc.exclude = MV_ANY;
308 proc.pivot = cmd.pivot == CRS_PIVOT;
310 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
312 grouper = casegrouper_create_splits (input, dataset_dict (ds));
313 while (casegrouper_get_next_group (grouper, &group))
317 /* Output SPLIT FILE variables. */
318 c = casereader_peek (group, 0);
321 output_split_file_values (ds, c);
325 /* Initialize hash tables. */
326 for (pt = &proc.pivots[0]; pt < &proc.pivots[proc.n_pivots]; pt++)
327 hmap_init (&pt->data);
330 for (; (c = casereader_read (group)) != NULL; case_unref (c))
331 for (pt = &proc.pivots[0]; pt < &proc.pivots[proc.n_pivots]; pt++)
333 double weight = dict_get_case_weight (dataset_dict (ds), c,
335 if (cmd.roundwhat == CRS_CASE)
337 weight = round_weight (&proc, weight);
341 if (should_tabulate_case (pt, c, proc.exclude))
343 if (proc.mode == GENERAL)
344 tabulate_general_case (pt, c, weight);
346 tabulate_integer_case (pt, c, weight);
349 pt->missing += weight;
351 casereader_destroy (group);
356 ok = casegrouper_destroy (grouper);
357 ok = proc_commit (ds) && ok;
359 result = ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
362 free (proc.variables);
363 HMAP_FOR_EACH_SAFE (range, next_range, struct var_range, hmap_node,
366 hmap_delete (&proc.var_ranges, &range->hmap_node);
369 for (pt = &proc.pivots[0]; pt < &proc.pivots[proc.n_pivots]; pt++)
372 free (pt->const_vars);
373 /* We must not call value_destroy on const_values because
374 it is a wild pointer; it never pointed to anything owned
377 The rest of the data was allocated and destroyed at a
378 lower level already. */
385 /* Parses the TABLES subcommand. */
387 crs_custom_tables (struct lexer *lexer, struct dataset *ds,
388 struct cmd_crosstabs *cmd UNUSED, void *proc_)
390 struct crosstabs_proc *proc = proc_;
391 struct const_var_set *var_set;
393 const struct variable ***by = NULL;
395 size_t *by_nvar = NULL;
400 /* Ensure that this is a TABLES subcommand. */
401 if (!lex_match_id (lexer, "TABLES")
402 && (lex_token (lexer) != T_ID ||
403 dict_lookup_var (dataset_dict (ds), lex_tokcstr (lexer)) == NULL)
404 && lex_token (lexer) != T_ALL)
406 lex_match (lexer, T_EQUALS);
408 if (proc->variables != NULL)
409 var_set = const_var_set_create_from_array (proc->variables,
412 var_set = const_var_set_create_from_dict (dataset_dict (ds));
413 assert (var_set != NULL);
417 by = xnrealloc (by, n_by + 1, sizeof *by);
418 by_nvar = xnrealloc (by_nvar, n_by + 1, sizeof *by_nvar);
419 if (!parse_const_var_set_vars (lexer, var_set, &by[n_by], &by_nvar[n_by],
420 PV_NO_DUPLICATE | PV_NO_SCRATCH))
422 if (xalloc_oversized (nx, by_nvar[n_by]))
424 msg (SE, _("Too many cross-tabulation variables or dimensions."));
430 if (!lex_match (lexer, T_BY))
439 by_iter = xcalloc (n_by, sizeof *by_iter);
440 proc->pivots = xnrealloc (proc->pivots,
441 proc->n_pivots + nx, sizeof *proc->pivots);
442 for (i = 0; i < nx; i++)
444 struct pivot_table *pt = &proc->pivots[proc->n_pivots++];
448 pt->weight_format = proc->weight_format;
451 pt->vars = xmalloc (n_by * sizeof *pt->vars);
453 pt->const_vars = NULL;
454 pt->const_values = NULL;
456 for (j = 0; j < n_by; j++)
457 pt->vars[j] = by[j][by_iter[j]];
459 for (j = n_by - 1; j >= 0; j--)
461 if (++by_iter[j] < by_nvar[j])
470 /* All return paths lead here. */
471 for (i = 0; i < n_by; i++)
476 const_var_set_destroy (var_set);
481 /* Parses the VARIABLES subcommand. */
483 crs_custom_variables (struct lexer *lexer, struct dataset *ds,
484 struct cmd_crosstabs *cmd UNUSED, void *proc_)
486 struct crosstabs_proc *proc = proc_;
489 msg (SE, _("%s must be specified before %s."), "VARIABLES", "TABLES");
493 lex_match (lexer, T_EQUALS);
497 size_t orig_nv = proc->n_variables;
502 if (!parse_variables_const (lexer, dataset_dict (ds),
503 &proc->variables, &proc->n_variables,
504 (PV_APPEND | PV_NUMERIC
505 | PV_NO_DUPLICATE | PV_NO_SCRATCH)))
508 if (!lex_force_match (lexer, T_LPAREN))
511 if (!lex_force_int (lexer))
513 min = lex_integer (lexer);
516 lex_match (lexer, T_COMMA);
518 if (!lex_force_int (lexer))
520 max = lex_integer (lexer);
523 msg (SE, _("Maximum value (%ld) less than minimum value (%ld)."),
529 if (!lex_force_match (lexer, T_RPAREN))
532 for (i = orig_nv; i < proc->n_variables; i++)
534 const struct variable *var = proc->variables[i];
535 struct var_range *vr = xmalloc (sizeof *vr);
540 vr->count = max - min + 1;
541 hmap_insert (&proc->var_ranges, &vr->hmap_node,
542 hash_pointer (var, 0));
545 if (lex_token (lexer) == T_SLASH)
552 free (proc->variables);
553 proc->variables = NULL;
554 proc->n_variables = 0;
558 /* Data file processing. */
560 const struct var_range *
561 get_var_range (const struct crosstabs_proc *proc, const struct variable *var)
563 if (!hmap_is_empty (&proc->var_ranges))
565 const struct var_range *range;
567 HMAP_FOR_EACH_IN_BUCKET (range, struct var_range, hmap_node,
568 hash_pointer (var, 0), &proc->var_ranges)
569 if (range->var == var)
577 should_tabulate_case (const struct pivot_table *pt, const struct ccase *c,
578 enum mv_class exclude)
581 for (j = 0; j < pt->n_vars; j++)
583 const struct variable *var = pt->vars[j];
584 const struct var_range *range = get_var_range (pt->proc, var);
586 if (var_is_value_missing (var, case_data (c, var), exclude))
591 double num = case_num (c, var);
592 if (num < range->min || num >= range->max + 1.)
600 tabulate_integer_case (struct pivot_table *pt, const struct ccase *c,
608 for (j = 0; j < pt->n_vars; j++)
610 /* Throw away fractional parts of values. */
611 hash = hash_int (case_num (c, pt->vars[j]), hash);
614 HMAP_FOR_EACH_WITH_HASH (te, struct freq, node, hash, &pt->data)
616 for (j = 0; j < pt->n_vars; j++)
617 if ((int) case_num (c, pt->vars[j]) != (int) te->values[j].f)
620 /* Found an existing entry. */
627 /* No existing entry. Create a new one. */
628 te = xmalloc (table_entry_size (pt->n_vars));
630 for (j = 0; j < pt->n_vars; j++)
631 te->values[j].f = (int) case_num (c, pt->vars[j]);
632 hmap_insert (&pt->data, &te->node, hash);
636 tabulate_general_case (struct pivot_table *pt, const struct ccase *c,
644 for (j = 0; j < pt->n_vars; j++)
646 const struct variable *var = pt->vars[j];
647 hash = value_hash (case_data (c, var), var_get_width (var), hash);
650 HMAP_FOR_EACH_WITH_HASH (te, struct freq, node, hash, &pt->data)
652 for (j = 0; j < pt->n_vars; j++)
654 const struct variable *var = pt->vars[j];
655 if (!value_equal (case_data (c, var), &te->values[j],
656 var_get_width (var)))
660 /* Found an existing entry. */
667 /* No existing entry. Create a new one. */
668 te = xmalloc (table_entry_size (pt->n_vars));
670 for (j = 0; j < pt->n_vars; j++)
672 const struct variable *var = pt->vars[j];
673 value_clone (&te->values[j], case_data (c, var), var_get_width (var));
675 hmap_insert (&pt->data, &te->node, hash);
678 /* Post-data reading calculations. */
680 static int compare_table_entry_vars_3way (const struct freq *a,
681 const struct freq *b,
682 const struct pivot_table *pt,
684 static int compare_table_entry_3way (const void *ap_, const void *bp_,
686 static int compare_table_entry_3way_inv (const void *ap_, const void *bp_,
689 static void enum_var_values (const struct pivot_table *, int var_idx,
690 union value **valuesp, int *n_values, bool descending);
691 static void output_pivot_table (struct crosstabs_proc *,
692 struct pivot_table *);
693 static void make_pivot_table_subset (struct pivot_table *pt,
694 size_t row0, size_t row1,
695 struct pivot_table *subset);
696 static void make_summary_table (struct crosstabs_proc *);
697 static bool find_crosstab (struct pivot_table *, size_t *row0p, size_t *row1p);
700 postcalc (struct crosstabs_proc *proc)
703 /* Round hash table entries, if requested
705 If this causes any of the cell counts to fall to zero, delete those
707 if (proc->round_cells)
708 for (struct pivot_table *pt = proc->pivots;
709 pt < &proc->pivots[proc->n_pivots]; pt++)
711 struct freq *e, *next;
712 HMAP_FOR_EACH_SAFE (e, next, struct freq, node, &pt->data)
714 e->count = round_weight (proc, e->count);
717 hmap_delete (&pt->data, &e->node);
723 /* Convert hash tables into sorted arrays of entries. */
724 for (struct pivot_table *pt = proc->pivots;
725 pt < &proc->pivots[proc->n_pivots]; pt++)
729 pt->n_entries = hmap_count (&pt->data);
730 pt->entries = xnmalloc (pt->n_entries, sizeof *pt->entries);
732 HMAP_FOR_EACH (e, struct freq, node, &pt->data)
733 pt->entries[i++] = e;
734 hmap_destroy (&pt->data);
736 sort (pt->entries, pt->n_entries, sizeof *pt->entries,
737 proc->descending ? compare_table_entry_3way_inv : compare_table_entry_3way,
742 make_summary_table (proc);
744 /* Output each pivot table. */
745 for (struct pivot_table *pt = proc->pivots;
746 pt < &proc->pivots[proc->n_pivots]; pt++)
748 if (proc->pivot || pt->n_vars == 2)
749 output_pivot_table (proc, pt);
752 size_t row0 = 0, row1 = 0;
753 while (find_crosstab (pt, &row0, &row1))
755 struct pivot_table subset;
756 make_pivot_table_subset (pt, row0, row1, &subset);
757 output_pivot_table (proc, &subset);
762 (barchart_create (pt->vars, pt->n_vars, _("Count"), false, pt->entries, pt->n_entries));
765 /* Free output and prepare for next split file. */
766 for (struct pivot_table *pt = proc->pivots;
767 pt < &proc->pivots[proc->n_pivots]; pt++)
771 /* Free the members that were allocated in this function(and the values
772 owned by the entries.
774 The other pointer members are either both allocated and destroyed at a
775 lower level (in output_pivot_table), or both allocated and destroyed
776 at a higher level (in crs_custom_tables and free_proc,
778 for (size_t i = 0; i < pt->n_vars; i++)
780 int width = var_get_width (pt->vars[i]);
781 if (value_needs_init (width))
785 for (j = 0; j < pt->n_entries; j++)
786 value_destroy (&pt->entries[j]->values[i], width);
790 for (size_t i = 0; i < pt->n_entries; i++)
791 free (pt->entries[i]);
797 make_pivot_table_subset (struct pivot_table *pt, size_t row0, size_t row1,
798 struct pivot_table *subset)
803 assert (pt->n_consts == 0);
804 subset->missing = pt->missing;
806 subset->vars = pt->vars;
807 subset->n_consts = pt->n_vars - 2;
808 subset->const_vars = pt->vars + 2;
809 subset->const_values = &pt->entries[row0]->values[2];
811 subset->entries = &pt->entries[row0];
812 subset->n_entries = row1 - row0;
816 compare_table_entry_var_3way (const struct freq *a,
817 const struct freq *b,
818 const struct pivot_table *pt,
821 return value_compare_3way (&a->values[idx], &b->values[idx],
822 var_get_width (pt->vars[idx]));
826 compare_table_entry_vars_3way (const struct freq *a,
827 const struct freq *b,
828 const struct pivot_table *pt,
833 for (i = idx1 - 1; i >= idx0; i--)
835 int cmp = compare_table_entry_var_3way (a, b, pt, i);
842 /* Compare the struct freq at *AP to the one at *BP and
843 return a strcmp()-type result. */
845 compare_table_entry_3way (const void *ap_, const void *bp_, const void *pt_)
847 const struct freq *const *ap = ap_;
848 const struct freq *const *bp = bp_;
849 const struct freq *a = *ap;
850 const struct freq *b = *bp;
851 const struct pivot_table *pt = pt_;
854 cmp = compare_table_entry_vars_3way (a, b, pt, 2, pt->n_vars);
858 cmp = compare_table_entry_var_3way (a, b, pt, ROW_VAR);
862 return compare_table_entry_var_3way (a, b, pt, COL_VAR);
865 /* Inverted version of compare_table_entry_3way */
867 compare_table_entry_3way_inv (const void *ap_, const void *bp_, const void *pt_)
869 return -compare_table_entry_3way (ap_, bp_, pt_);
873 find_first_difference (const struct pivot_table *pt, size_t row)
876 return pt->n_vars - 1;
879 const struct freq *a = pt->entries[row];
880 const struct freq *b = pt->entries[row - 1];
883 for (col = pt->n_vars - 1; col >= 0; col--)
884 if (compare_table_entry_var_3way (a, b, pt, col))
890 /* Output a table summarizing the cases processed. */
892 make_summary_table (struct crosstabs_proc *proc)
894 struct tab_table *summary;
895 struct pivot_table *pt;
899 summary = tab_create (7, 3 + proc->n_pivots);
900 tab_set_format (summary, RC_WEIGHT, &proc->weight_format);
901 tab_title (summary, _("Summary."));
902 tab_headers (summary, 1, 0, 3, 0);
903 tab_joint_text (summary, 1, 0, 6, 0, TAB_CENTER, _("Cases"));
904 tab_joint_text (summary, 1, 1, 2, 1, TAB_CENTER, _("Valid"));
905 tab_joint_text (summary, 3, 1, 4, 1, TAB_CENTER, _("Missing"));
906 tab_joint_text (summary, 5, 1, 6, 1, TAB_CENTER, _("Total"));
907 tab_hline (summary, TAL_1, 1, 6, 1);
908 tab_hline (summary, TAL_1, 1, 6, 2);
909 tab_vline (summary, TAL_1, 3, 1, 1);
910 tab_vline (summary, TAL_1, 5, 1, 1);
911 for (i = 0; i < 3; i++)
913 tab_text (summary, 1 + i * 2, 2, TAB_RIGHT, _("N"));
914 tab_text (summary, 2 + i * 2, 2, TAB_RIGHT, _("Percent"));
916 tab_offset (summary, 0, 3);
918 ds_init_empty (&name);
919 for (pt = &proc->pivots[0]; pt < &proc->pivots[proc->n_pivots]; pt++)
925 tab_hline (summary, TAL_1, 0, 6, 0);
928 for (i = 0; i < pt->n_vars; i++)
931 ds_put_cstr (&name, " * ");
932 ds_put_cstr (&name, var_to_string (pt->vars[i]));
934 tab_text (summary, 0, 0, TAB_LEFT, ds_cstr (&name));
937 for (i = 0; i < pt->n_entries; i++)
938 valid += pt->entries[i]->count;
943 for (i = 0; i < 3; i++)
945 tab_double (summary, i * 2 + 1, 0, TAB_RIGHT, n[i], NULL, RC_WEIGHT);
946 tab_text_format (summary, i * 2 + 2, 0, TAB_RIGHT, "%.1f%%",
950 tab_next_row (summary);
954 submit (NULL, summary);
959 static struct tab_table *create_crosstab_table (struct crosstabs_proc *,
960 struct pivot_table *);
961 static struct tab_table *create_chisq_table (struct crosstabs_proc *proc, struct pivot_table *);
962 static struct tab_table *create_sym_table (struct crosstabs_proc *proc, struct pivot_table *);
963 static struct tab_table *create_risk_table (struct crosstabs_proc *proc, struct pivot_table *);
964 static struct tab_table *create_direct_table (struct crosstabs_proc *proc, struct pivot_table *);
965 static void display_dimensions (struct crosstabs_proc *, struct pivot_table *,
966 struct tab_table *, int first_difference);
967 static void display_crosstabulation (struct crosstabs_proc *,
968 struct pivot_table *,
970 static void display_chisq (struct pivot_table *, struct tab_table *,
971 bool *showed_fisher);
972 static void display_symmetric (struct crosstabs_proc *, struct pivot_table *,
974 static void display_risk (struct pivot_table *, struct tab_table *);
975 static void display_directional (struct crosstabs_proc *, struct pivot_table *,
977 static void table_value_missing (struct crosstabs_proc *proc,
978 struct tab_table *table, int c, int r,
979 unsigned char opt, const union value *v,
980 const struct variable *var);
981 static void delete_missing (struct pivot_table *);
982 static void build_matrix (struct pivot_table *);
984 /* Output pivot table PT in the context of PROC. */
986 output_pivot_table (struct crosstabs_proc *proc, struct pivot_table *pt)
988 struct tab_table *table = NULL; /* Crosstabulation table. */
989 struct tab_table *chisq = NULL; /* Chi-square table. */
990 bool showed_fisher = false;
991 struct tab_table *sym = NULL; /* Symmetric measures table. */
992 struct tab_table *risk = NULL; /* Risk estimate table. */
993 struct tab_table *direct = NULL; /* Directional measures table. */
996 enum_var_values (pt, COL_VAR, &pt->cols, &pt->n_cols, proc->descending);
1003 ds_init_cstr (&vars, var_to_string (pt->vars[0]));
1004 for (i = 1; i < pt->n_vars; i++)
1005 ds_put_format (&vars, " * %s", var_to_string (pt->vars[i]));
1007 /* TRANSLATORS: The %s here describes a crosstabulation. It takes the
1008 form "var1 * var2 * var3 * ...". */
1009 msg (SW, _("Crosstabulation %s contained no non-missing cases."),
1018 table = create_crosstab_table (proc, pt);
1019 if (proc->statistics & (1u << CRS_ST_CHISQ))
1020 chisq = create_chisq_table (proc, pt);
1021 if (proc->statistics & ((1u << CRS_ST_PHI) | (1u << CRS_ST_CC)
1022 | (1u << CRS_ST_BTAU) | (1u << CRS_ST_CTAU)
1023 | (1u << CRS_ST_GAMMA) | (1u << CRS_ST_CORR)
1024 | (1u << CRS_ST_KAPPA)))
1025 sym = create_sym_table (proc, pt);
1026 if (proc->statistics & (1u << CRS_ST_RISK))
1027 risk = create_risk_table (proc, pt);
1028 if (proc->statistics & ((1u << CRS_ST_LAMBDA) | (1u << CRS_ST_UC)
1029 | (1u << CRS_ST_D) | (1u << CRS_ST_ETA)))
1030 direct = create_direct_table (proc, pt);
1033 while (find_crosstab (pt, &row0, &row1))
1035 struct pivot_table x;
1036 int first_difference;
1038 make_pivot_table_subset (pt, row0, row1, &x);
1040 /* Find all the row variable values. */
1041 enum_var_values (&x, ROW_VAR, &x.rows, &x.n_rows, proc->descending);
1043 if (size_overflow_p (xtimes (xtimes (x.n_rows, x.n_cols),
1046 x.row_tot = xmalloc (x.n_rows * sizeof *x.row_tot);
1047 x.col_tot = xmalloc (x.n_cols * sizeof *x.col_tot);
1048 x.mat = xmalloc (x.n_rows * x.n_cols * sizeof *x.mat);
1050 /* Allocate table space for the matrix. */
1052 && tab_row (table) + (x.n_rows + 1) * proc->n_cells > tab_nr (table))
1053 tab_realloc (table, -1,
1054 MAX (tab_nr (table) + (x.n_rows + 1) * proc->n_cells,
1055 tab_nr (table) * pt->n_entries / x.n_entries));
1059 /* Find the first variable that differs from the last subtable. */
1060 first_difference = find_first_difference (pt, row0);
1063 display_dimensions (proc, &x, table, first_difference);
1064 display_crosstabulation (proc, &x, table);
1067 if (proc->exclude == MV_NEVER)
1068 delete_missing (&x);
1072 display_dimensions (proc, &x, chisq, first_difference);
1073 display_chisq (&x, chisq, &showed_fisher);
1077 display_dimensions (proc, &x, sym, first_difference);
1078 display_symmetric (proc, &x, sym);
1082 display_dimensions (proc, &x, risk, first_difference);
1083 display_risk (&x, risk);
1087 display_dimensions (proc, &x, direct, first_difference);
1088 display_directional (proc, &x, direct);
1091 /* Free the parts of x that are not owned by pt. In
1092 particular we must not free x.cols, which is the same as
1093 pt->cols, which is freed at the end of this function. */
1101 submit (NULL, table);
1106 tab_resize (chisq, 4 + (pt->n_vars - 2), -1);
1112 submit (pt, direct);
1118 build_matrix (struct pivot_table *x)
1120 const int col_var_width = var_get_width (x->vars[COL_VAR]);
1121 const int row_var_width = var_get_width (x->vars[ROW_VAR]);
1128 for (p = x->entries; p < &x->entries[x->n_entries]; p++)
1130 const struct freq *te = *p;
1132 while (!value_equal (&x->rows[row], &te->values[ROW_VAR], row_var_width))
1134 for (; col < x->n_cols; col++)
1140 while (!value_equal (&x->cols[col], &te->values[COL_VAR], col_var_width))
1147 if (++col >= x->n_cols)
1153 while (mp < &x->mat[x->n_cols * x->n_rows])
1155 assert (mp == &x->mat[x->n_cols * x->n_rows]);
1157 /* Column totals, row totals, ns_rows. */
1159 for (col = 0; col < x->n_cols; col++)
1160 x->col_tot[col] = 0.0;
1161 for (row = 0; row < x->n_rows; row++)
1162 x->row_tot[row] = 0.0;
1164 for (row = 0; row < x->n_rows; row++)
1166 bool row_is_empty = true;
1167 for (col = 0; col < x->n_cols; col++)
1171 row_is_empty = false;
1172 x->col_tot[col] += *mp;
1173 x->row_tot[row] += *mp;
1180 assert (mp == &x->mat[x->n_cols * x->n_rows]);
1184 for (col = 0; col < x->n_cols; col++)
1185 for (row = 0; row < x->n_rows; row++)
1186 if (x->mat[col + row * x->n_cols] != 0.0)
1194 for (col = 0; col < x->n_cols; col++)
1195 x->total += x->col_tot[col];
1198 static struct tab_table *
1199 create_crosstab_table (struct crosstabs_proc *proc, struct pivot_table *pt)
1206 static const struct tuple names[] =
1208 {CRS_CL_COUNT, N_("count")},
1209 {CRS_CL_ROW, N_("row %")},
1210 {CRS_CL_COLUMN, N_("column %")},
1211 {CRS_CL_TOTAL, N_("total %")},
1212 {CRS_CL_EXPECTED, N_("expected")},
1213 {CRS_CL_RESIDUAL, N_("residual")},
1214 {CRS_CL_SRESIDUAL, N_("std. resid.")},
1215 {CRS_CL_ASRESIDUAL, N_("adj. resid.")},
1217 const int n_names = sizeof names / sizeof *names;
1218 const struct tuple *t;
1220 struct tab_table *table;
1221 struct string title;
1222 struct pivot_table x;
1226 make_pivot_table_subset (pt, 0, 0, &x);
1228 table = tab_create (x.n_consts + 1 + x.n_cols + 1,
1229 (x.n_entries / x.n_cols) * 3 / 2 * proc->n_cells + 10);
1230 tab_headers (table, x.n_consts + 1, 0, 2, 0);
1231 tab_set_format (table, RC_WEIGHT, &proc->weight_format);
1233 /* First header line. */
1234 tab_joint_text (table, x.n_consts + 1, 0,
1235 (x.n_consts + 1) + (x.n_cols - 1), 0,
1236 TAB_CENTER | TAT_TITLE, var_to_string (x.vars[COL_VAR]));
1238 tab_hline (table, TAL_1, x.n_consts + 1,
1239 x.n_consts + 2 + x.n_cols - 2, 1);
1241 /* Second header line. */
1242 for (i = 2; i < x.n_consts + 2; i++)
1243 tab_joint_text (table, x.n_consts + 2 - i - 1, 0,
1244 x.n_consts + 2 - i - 1, 1,
1245 TAB_RIGHT | TAT_TITLE, var_to_string (x.vars[i]));
1246 tab_text (table, x.n_consts + 2 - 2, 1, TAB_RIGHT | TAT_TITLE,
1247 var_to_string (x.vars[ROW_VAR]));
1248 for (i = 0; i < x.n_cols; i++)
1249 table_value_missing (proc, table, x.n_consts + 2 + i - 1, 1, TAB_RIGHT,
1250 &x.cols[i], x.vars[COL_VAR]);
1251 tab_text (table, x.n_consts + 2 + x.n_cols - 1, 1, TAB_CENTER, _("Total"));
1253 tab_hline (table, TAL_1, 0, x.n_consts + 2 + x.n_cols - 1, 2);
1254 tab_vline (table, TAL_1, x.n_consts + 2 + x.n_cols - 1, 0, 1);
1257 ds_init_empty (&title);
1258 for (i = 0; i < x.n_consts + 2; i++)
1261 ds_put_cstr (&title, " * ");
1262 ds_put_cstr (&title, var_to_string (x.vars[i]));
1264 for (i = 0; i < pt->n_consts; i++)
1266 const struct variable *var = pt->const_vars[i];
1269 ds_put_format (&title, ", %s=", var_to_string (var));
1271 /* Insert the formatted value of VAR without any leading spaces. */
1272 s = data_out (&pt->const_values[i], var_get_encoding (var),
1273 var_get_print_format (var));
1274 ds_put_cstr (&title, s + strspn (s, " "));
1278 ds_put_cstr (&title, " [");
1280 for (t = names; t < &names[n_names]; t++)
1281 if (proc->cells & (1u << t->value))
1284 ds_put_cstr (&title, ", ");
1285 ds_put_cstr (&title, gettext (t->name));
1287 ds_put_cstr (&title, "].");
1289 tab_title (table, "%s", ds_cstr (&title));
1290 ds_destroy (&title);
1292 tab_offset (table, 0, 2);
1296 static struct tab_table *
1297 create_chisq_table (struct crosstabs_proc *proc, struct pivot_table *pt)
1299 struct tab_table *chisq;
1301 chisq = tab_create (6 + (pt->n_vars - 2),
1302 pt->n_entries / pt->n_cols * 3 / 2 * N_CHISQ + 10);
1303 tab_headers (chisq, 1 + (pt->n_vars - 2), 0, 1, 0);
1304 tab_set_format (chisq, RC_WEIGHT, &proc->weight_format);
1306 tab_title (chisq, _("Chi-square tests."));
1308 tab_offset (chisq, pt->n_vars - 2, 0);
1309 tab_text (chisq, 0, 0, TAB_LEFT | TAT_TITLE, _("Statistic"));
1310 tab_text (chisq, 1, 0, TAB_RIGHT | TAT_TITLE, _("Value"));
1311 tab_text (chisq, 2, 0, TAB_RIGHT | TAT_TITLE, _("df"));
1312 tab_text (chisq, 3, 0, TAB_RIGHT | TAT_TITLE,
1313 _("Asymp. Sig. (2-tailed)"));
1314 tab_text_format (chisq, 4, 0, TAB_RIGHT | TAT_TITLE,
1315 _("Exact Sig. (%d-tailed)"), 2);
1316 tab_text_format (chisq, 5, 0, TAB_RIGHT | TAT_TITLE,
1317 _("Exact Sig. (%d-tailed)"), 1);
1318 tab_offset (chisq, 0, 1);
1323 /* Symmetric measures. */
1324 static struct tab_table *
1325 create_sym_table (struct crosstabs_proc *proc, struct pivot_table *pt)
1327 struct tab_table *sym;
1329 sym = tab_create (6 + (pt->n_vars - 2),
1330 pt->n_entries / pt->n_cols * 7 + 10);
1332 tab_set_format (sym, RC_WEIGHT, &proc->weight_format);
1334 tab_headers (sym, 2 + (pt->n_vars - 2), 0, 1, 0);
1335 tab_title (sym, _("Symmetric measures."));
1337 tab_offset (sym, pt->n_vars - 2, 0);
1338 tab_text (sym, 0, 0, TAB_LEFT | TAT_TITLE, _("Category"));
1339 tab_text (sym, 1, 0, TAB_LEFT | TAT_TITLE, _("Statistic"));
1340 tab_text (sym, 2, 0, TAB_RIGHT | TAT_TITLE, _("Value"));
1341 tab_text (sym, 3, 0, TAB_RIGHT | TAT_TITLE, _("Asymp. Std. Error"));
1342 tab_text (sym, 4, 0, TAB_RIGHT | TAT_TITLE, _("Approx. T"));
1343 tab_text (sym, 5, 0, TAB_RIGHT | TAT_TITLE, _("Approx. Sig."));
1344 tab_offset (sym, 0, 1);
1349 /* Risk estimate. */
1350 static struct tab_table *
1351 create_risk_table (struct crosstabs_proc *proc, struct pivot_table *pt)
1353 struct tab_table *risk;
1355 risk = tab_create (4 + (pt->n_vars - 2), pt->n_entries / pt->n_cols * 4 + 10);
1356 tab_headers (risk, 1 + pt->n_vars - 2, 0, 2, 0);
1357 tab_title (risk, _("Risk estimate."));
1358 tab_set_format (risk, RC_WEIGHT, &proc->weight_format);
1360 tab_offset (risk, pt->n_vars - 2, 0);
1361 tab_joint_text_format (risk, 2, 0, 3, 0, TAB_CENTER | TAT_TITLE,
1362 _("95%% Confidence Interval"));
1363 tab_text (risk, 0, 1, TAB_LEFT | TAT_TITLE, _("Statistic"));
1364 tab_text (risk, 1, 1, TAB_RIGHT | TAT_TITLE, _("Value"));
1365 tab_text (risk, 2, 1, TAB_RIGHT | TAT_TITLE, _("Lower"));
1366 tab_text (risk, 3, 1, TAB_RIGHT | TAT_TITLE, _("Upper"));
1367 tab_hline (risk, TAL_1, 2, 3, 1);
1368 tab_vline (risk, TAL_1, 2, 0, 1);
1369 tab_offset (risk, 0, 2);
1374 /* Directional measures. */
1375 static struct tab_table *
1376 create_direct_table (struct crosstabs_proc *proc, struct pivot_table *pt)
1378 struct tab_table *direct;
1380 direct = tab_create (7 + (pt->n_vars - 2),
1381 pt->n_entries / pt->n_cols * 7 + 10);
1382 tab_headers (direct, 3 + (pt->n_vars - 2), 0, 1, 0);
1383 tab_title (direct, _("Directional measures."));
1384 tab_set_format (direct, RC_WEIGHT, &proc->weight_format);
1386 tab_offset (direct, pt->n_vars - 2, 0);
1387 tab_text (direct, 0, 0, TAB_LEFT | TAT_TITLE, _("Category"));
1388 tab_text (direct, 1, 0, TAB_LEFT | TAT_TITLE, _("Statistic"));
1389 tab_text (direct, 2, 0, TAB_LEFT | TAT_TITLE, _("Type"));
1390 tab_text (direct, 3, 0, TAB_RIGHT | TAT_TITLE, _("Value"));
1391 tab_text (direct, 4, 0, TAB_RIGHT | TAT_TITLE, _("Asymp. Std. Error"));
1392 tab_text (direct, 5, 0, TAB_RIGHT | TAT_TITLE, _("Approx. T"));
1393 tab_text (direct, 6, 0, TAB_RIGHT | TAT_TITLE, _("Approx. Sig."));
1394 tab_offset (direct, 0, 1);
1400 /* Delete missing rows and columns for statistical analysis when
1403 delete_missing (struct pivot_table *pt)
1407 for (r = 0; r < pt->n_rows; r++)
1408 if (var_is_num_missing (pt->vars[ROW_VAR], pt->rows[r].f, MV_USER))
1410 for (c = 0; c < pt->n_cols; c++)
1411 pt->mat[c + r * pt->n_cols] = 0.;
1416 for (c = 0; c < pt->n_cols; c++)
1417 if (var_is_num_missing (pt->vars[COL_VAR], pt->cols[c].f, MV_USER))
1419 for (r = 0; r < pt->n_rows; r++)
1420 pt->mat[c + r * pt->n_cols] = 0.;
1425 /* Prepare table T for submission, and submit it. */
1427 submit (struct pivot_table *pt, struct tab_table *t)
1434 tab_resize (t, -1, 0);
1435 if (tab_nr (t) == tab_t (t))
1437 table_unref (&t->table);
1440 tab_offset (t, 0, 0);
1442 for (i = 2; i < pt->n_vars; i++)
1443 tab_text (t, pt->n_vars - i - 1, 0, TAB_RIGHT | TAT_TITLE,
1444 var_to_string (pt->vars[i]));
1445 tab_box (t, TAL_2, TAL_2, -1, -1, 0, 0, tab_nc (t) - 1, tab_nr (t) - 1);
1446 tab_box (t, -1, -1, -1, TAL_1, tab_l (t), tab_t (t) - 1, tab_nc (t) - 1,
1448 tab_vline (t, TAL_2, tab_l (t), 0, tab_nr (t) - 1);
1454 find_crosstab (struct pivot_table *pt, size_t *row0p, size_t *row1p)
1456 size_t row0 = *row1p;
1459 if (row0 >= pt->n_entries)
1462 for (row1 = row0 + 1; row1 < pt->n_entries; row1++)
1464 struct freq *a = pt->entries[row0];
1465 struct freq *b = pt->entries[row1];
1466 if (compare_table_entry_vars_3way (a, b, pt, 2, pt->n_vars) != 0)
1474 /* Compares `union value's A_ and B_ and returns a strcmp()-like
1475 result. WIDTH_ points to an int which is either 0 for a
1476 numeric value or a string width for a string value. */
1478 compare_value_3way (const void *a_, const void *b_, const void *width_)
1480 const union value *a = a_;
1481 const union value *b = b_;
1482 const int *width = width_;
1484 return value_compare_3way (a, b, *width);
1487 /* Inverted version of the above */
1489 compare_value_3way_inv (const void *a_, const void *b_, const void *width_)
1491 return -compare_value_3way (a_, b_, width_);
1495 /* Given an array of ENTRY_CNT table_entry structures starting at
1496 ENTRIES, creates a sorted list of the values that the variable
1497 with index VAR_IDX takes on. The values are returned as a
1498 malloc()'d array stored in *VALUES, with the number of values
1499 stored in *VALUE_CNT.
1501 The caller must eventually free *VALUES, but each pointer in *VALUES points
1502 to existing data not owned by *VALUES itself. */
1504 enum_var_values (const struct pivot_table *pt, int var_idx,
1505 union value **valuesp, int *n_values, bool descending)
1507 const struct variable *var = pt->vars[var_idx];
1508 const struct var_range *range = get_var_range (pt->proc, var);
1509 union value *values;
1514 values = *valuesp = xnmalloc (range->count, sizeof *values);
1515 *n_values = range->count;
1516 for (i = 0; i < range->count; i++)
1517 values[i].f = range->min + i;
1521 int width = var_get_width (var);
1522 struct hmapx_node *node;
1523 const union value *iter;
1527 for (i = 0; i < pt->n_entries; i++)
1529 const struct freq *te = pt->entries[i];
1530 const union value *value = &te->values[var_idx];
1531 size_t hash = value_hash (value, width, 0);
1533 HMAPX_FOR_EACH_WITH_HASH (iter, node, hash, &set)
1534 if (value_equal (iter, value, width))
1537 hmapx_insert (&set, (union value *) value, hash);
1542 *n_values = hmapx_count (&set);
1543 values = *valuesp = xnmalloc (*n_values, sizeof *values);
1545 HMAPX_FOR_EACH (iter, node, &set)
1546 values[i++] = *iter;
1547 hmapx_destroy (&set);
1549 sort (values, *n_values, sizeof *values,
1550 descending ? compare_value_3way_inv : compare_value_3way,
1555 /* Sets cell (C,R) in TABLE, with options OPT, to have a value taken
1556 from V, displayed with print format spec from variable VAR. When
1557 in REPORT missing-value mode, missing values have an M appended. */
1559 table_value_missing (struct crosstabs_proc *proc,
1560 struct tab_table *table, int c, int r, unsigned char opt,
1561 const union value *v, const struct variable *var)
1563 const char *label = var_lookup_value_label (var, v);
1565 tab_text (table, c, r, TAB_LEFT, label);
1568 const struct fmt_spec *print = var_get_print_format (var);
1569 if (proc->exclude == MV_NEVER && var_is_value_missing (var, v, MV_USER))
1571 char *s = data_out (v, dict_get_encoding (proc->dict), print);
1572 tab_text_format (table, c, r, opt, "%sM", s + strspn (s, " "));
1576 tab_value (table, c, r, opt, v, var, print);
1580 /* Draws a line across TABLE at the current row to indicate the most
1581 major dimension variable with index FIRST_DIFFERENCE out of N_VARS
1582 that changed, and puts the values that changed into the table. TB
1583 and PT must be the corresponding table_entry and crosstab,
1586 display_dimensions (struct crosstabs_proc *proc, struct pivot_table *pt,
1587 struct tab_table *table, int first_difference)
1589 tab_hline (table, TAL_1, pt->n_consts + pt->n_vars - first_difference - 1, tab_nc (table) - 1, 0);
1591 for (; first_difference >= 2; first_difference--)
1592 table_value_missing (proc, table, pt->n_consts + pt->n_vars - first_difference - 1, 0,
1593 TAB_RIGHT, &pt->entries[0]->values[first_difference],
1594 pt->vars[first_difference]);
1597 /* Put VALUE into cell (C,R) of TABLE, suffixed with character
1598 SUFFIX if nonzero. If MARK_MISSING is true the entry is
1599 additionally suffixed with a letter `M'. */
1601 format_cell_entry (struct tab_table *table, int c, int r, double value,
1602 char suffix, bool mark_missing, const struct dictionary *dict)
1610 s = data_out (&v, dict_get_encoding (dict), settings_get_format ());
1614 suffixes[suffix_len++] = suffix;
1616 suffixes[suffix_len++] = 'M';
1617 suffixes[suffix_len] = '\0';
1619 tab_text_format (table, c, r, TAB_RIGHT, "%s%s",
1620 s + strspn (s, " "), suffixes);
1625 /* Displays the crosstabulation table. */
1627 display_crosstabulation (struct crosstabs_proc *proc, struct pivot_table *pt,
1628 struct tab_table *table)
1634 for (r = 0; r < pt->n_rows; r++)
1635 table_value_missing (proc, table, pt->n_consts + pt->n_vars - 2,
1636 r * proc->n_cells, TAB_RIGHT, &pt->rows[r],
1639 tab_text (table, pt->n_vars - 2, pt->n_rows * proc->n_cells,
1640 TAB_LEFT, _("Total"));
1642 /* Put in the actual cells. */
1644 tab_offset (table, pt->n_consts + pt->n_vars - 1, -1);
1645 for (r = 0; r < pt->n_rows; r++)
1647 if (proc->n_cells > 1)
1648 tab_hline (table, TAL_1, -1, pt->n_cols, 0);
1649 for (c = 0; c < pt->n_cols; c++)
1651 bool mark_missing = false;
1652 double expected_value = pt->row_tot[r] * pt->col_tot[c] / pt->total;
1653 if (proc->exclude == MV_NEVER
1654 && (var_is_num_missing (pt->vars[COL_VAR], pt->cols[c].f, MV_USER)
1655 || var_is_num_missing (pt->vars[ROW_VAR], pt->rows[r].f,
1657 mark_missing = true;
1658 for (i = 0; i < proc->n_cells; i++)
1663 switch (proc->a_cells[i])
1669 v = *mp / pt->row_tot[r] * 100.;
1673 v = *mp / pt->col_tot[c] * 100.;
1677 v = *mp / pt->total * 100.;
1680 case CRS_CL_EXPECTED:
1683 case CRS_CL_RESIDUAL:
1684 v = *mp - expected_value;
1686 case CRS_CL_SRESIDUAL:
1687 v = (*mp - expected_value) / sqrt (expected_value);
1689 case CRS_CL_ASRESIDUAL:
1690 v = ((*mp - expected_value)
1691 / sqrt (expected_value
1692 * (1. - pt->row_tot[r] / pt->total)
1693 * (1. - pt->col_tot[c] / pt->total)));
1698 format_cell_entry (table, c, i, v, suffix, mark_missing, proc->dict);
1704 tab_offset (table, -1, tab_row (table) + proc->n_cells);
1708 tab_offset (table, -1, tab_row (table) - proc->n_cells * pt->n_rows);
1709 for (r = 0; r < pt->n_rows; r++)
1711 bool mark_missing = false;
1713 if (proc->exclude == MV_NEVER
1714 && var_is_num_missing (pt->vars[ROW_VAR], pt->rows[r].f, MV_USER))
1715 mark_missing = true;
1717 for (i = 0; i < proc->n_cells; i++)
1722 switch (proc->a_cells[i])
1732 v = pt->row_tot[r] / pt->total * 100.;
1736 v = pt->row_tot[r] / pt->total * 100.;
1739 case CRS_CL_EXPECTED:
1740 case CRS_CL_RESIDUAL:
1741 case CRS_CL_SRESIDUAL:
1742 case CRS_CL_ASRESIDUAL:
1749 format_cell_entry (table, pt->n_cols, 0, v, suffix, mark_missing, proc->dict);
1750 tab_next_row (table);
1754 /* Column totals, grand total. */
1756 if (proc->n_cells > 1)
1757 tab_hline (table, TAL_1, -1, pt->n_cols, 0);
1758 for (c = 0; c <= pt->n_cols; c++)
1760 double ct = c < pt->n_cols ? pt->col_tot[c] : pt->total;
1761 bool mark_missing = false;
1764 if (proc->exclude == MV_NEVER && c < pt->n_cols
1765 && var_is_num_missing (pt->vars[COL_VAR], pt->cols[c].f, MV_USER))
1766 mark_missing = true;
1768 for (i = 0; i < proc->n_cells; i++)
1773 switch (proc->a_cells[i])
1779 v = ct / pt->total * 100.;
1787 v = ct / pt->total * 100.;
1790 case CRS_CL_EXPECTED:
1791 case CRS_CL_RESIDUAL:
1792 case CRS_CL_SRESIDUAL:
1793 case CRS_CL_ASRESIDUAL:
1799 format_cell_entry (table, c, i, v, suffix, mark_missing, proc->dict);
1804 tab_offset (table, -1, tab_row (table) + last_row);
1805 tab_offset (table, 0, -1);
1808 static void calc_r (struct pivot_table *,
1809 double *PT, double *Y, double *, double *, double *);
1810 static void calc_chisq (struct pivot_table *,
1811 double[N_CHISQ], int[N_CHISQ], double *, double *);
1813 /* Display chi-square statistics. */
1815 display_chisq (struct pivot_table *pt, struct tab_table *chisq,
1816 bool *showed_fisher)
1818 static const char *chisq_stats[N_CHISQ] =
1820 N_("Pearson Chi-Square"),
1821 N_("Likelihood Ratio"),
1822 N_("Fisher's Exact Test"),
1823 N_("Continuity Correction"),
1824 N_("Linear-by-Linear Association"),
1826 double chisq_v[N_CHISQ];
1827 double fisher1, fisher2;
1832 calc_chisq (pt, chisq_v, df, &fisher1, &fisher2);
1834 tab_offset (chisq, pt->n_consts + pt->n_vars - 2, -1);
1836 for (i = 0; i < N_CHISQ; i++)
1838 if ((i != 2 && chisq_v[i] == SYSMIS)
1839 || (i == 2 && fisher1 == SYSMIS))
1842 tab_text (chisq, 0, 0, TAB_LEFT, gettext (chisq_stats[i]));
1845 tab_double (chisq, 1, 0, TAB_RIGHT, chisq_v[i], NULL, RC_OTHER);
1846 tab_double (chisq, 2, 0, TAB_RIGHT, df[i], NULL, RC_WEIGHT);
1847 tab_double (chisq, 3, 0, TAB_RIGHT,
1848 gsl_cdf_chisq_Q (chisq_v[i], df[i]), NULL, RC_PVALUE);
1852 *showed_fisher = true;
1853 tab_double (chisq, 4, 0, TAB_RIGHT, fisher2, NULL, RC_PVALUE);
1854 tab_double (chisq, 5, 0, TAB_RIGHT, fisher1, NULL, RC_PVALUE);
1856 tab_next_row (chisq);
1859 tab_text (chisq, 0, 0, TAB_LEFT, _("N of Valid Cases"));
1860 tab_double (chisq, 1, 0, TAB_RIGHT, pt->total, NULL, RC_WEIGHT);
1861 tab_next_row (chisq);
1863 tab_offset (chisq, 0, -1);
1866 static int calc_symmetric (struct crosstabs_proc *, struct pivot_table *,
1867 double[N_SYMMETRIC], double[N_SYMMETRIC],
1868 double[N_SYMMETRIC],
1869 double[3], double[3], double[3]);
1871 /* Display symmetric measures. */
1873 display_symmetric (struct crosstabs_proc *proc, struct pivot_table *pt,
1874 struct tab_table *sym)
1876 static const char *categories[] =
1878 N_("Nominal by Nominal"),
1879 N_("Ordinal by Ordinal"),
1880 N_("Interval by Interval"),
1881 N_("Measure of Agreement"),
1884 static const char *stats[N_SYMMETRIC] =
1888 N_("Contingency Coefficient"),
1889 N_("Kendall's tau-b"),
1890 N_("Kendall's tau-c"),
1892 N_("Spearman Correlation"),
1897 static const int stats_categories[N_SYMMETRIC] =
1899 0, 0, 0, 1, 1, 1, 1, 2, 3,
1903 double sym_v[N_SYMMETRIC], sym_ase[N_SYMMETRIC], sym_t[N_SYMMETRIC];
1904 double somers_d_v[3], somers_d_ase[3], somers_d_t[3];
1907 if (!calc_symmetric (proc, pt, sym_v, sym_ase, sym_t,
1908 somers_d_v, somers_d_ase, somers_d_t))
1911 tab_offset (sym, pt->n_consts + pt->n_vars - 2, -1);
1913 for (i = 0; i < N_SYMMETRIC; i++)
1915 if (sym_v[i] == SYSMIS)
1918 if (stats_categories[i] != last_cat)
1920 last_cat = stats_categories[i];
1921 tab_text (sym, 0, 0, TAB_LEFT, gettext (categories[last_cat]));
1924 tab_text (sym, 1, 0, TAB_LEFT, gettext (stats[i]));
1925 tab_double (sym, 2, 0, TAB_RIGHT, sym_v[i], NULL, RC_OTHER);
1926 if (sym_ase[i] != SYSMIS)
1927 tab_double (sym, 3, 0, TAB_RIGHT, sym_ase[i], NULL, RC_OTHER);
1928 if (sym_t[i] != SYSMIS)
1929 tab_double (sym, 4, 0, TAB_RIGHT, sym_t[i], NULL, RC_OTHER);
1930 /*tab_double (sym, 5, 0, TAB_RIGHT, normal_sig (sym_v[i]), NULL, RC_PVALUE);*/
1934 tab_text (sym, 0, 0, TAB_LEFT, _("N of Valid Cases"));
1935 tab_double (sym, 2, 0, TAB_RIGHT, pt->total, NULL, RC_WEIGHT);
1938 tab_offset (sym, 0, -1);
1941 static int calc_risk (struct pivot_table *,
1942 double[], double[], double[], union value *);
1944 /* Display risk estimate. */
1946 display_risk (struct pivot_table *pt, struct tab_table *risk)
1949 double risk_v[3], lower[3], upper[3];
1953 if (!calc_risk (pt, risk_v, upper, lower, c))
1956 tab_offset (risk, pt->n_consts + pt->n_vars - 2, -1);
1958 for (i = 0; i < 3; i++)
1960 const struct variable *cv = pt->vars[COL_VAR];
1961 const struct variable *rv = pt->vars[ROW_VAR];
1962 int cvw = var_get_width (cv);
1963 int rvw = var_get_width (rv);
1965 if (risk_v[i] == SYSMIS)
1971 if (var_is_numeric (cv))
1972 sprintf (buf, _("Odds Ratio for %s (%g / %g)"),
1973 var_to_string (cv), c[0].f, c[1].f);
1975 sprintf (buf, _("Odds Ratio for %s (%.*s / %.*s)"),
1977 cvw, value_str (&c[0], cvw),
1978 cvw, value_str (&c[1], cvw));
1982 if (var_is_numeric (rv))
1983 sprintf (buf, _("For cohort %s = %.*g"),
1984 var_to_string (rv), DBL_DIG + 1, pt->rows[i - 1].f);
1986 sprintf (buf, _("For cohort %s = %.*s"),
1988 rvw, value_str (&pt->rows[i - 1], rvw));
1992 tab_text (risk, 0, 0, TAB_LEFT, buf);
1993 tab_double (risk, 1, 0, TAB_RIGHT, risk_v[i], NULL, RC_OTHER);
1994 tab_double (risk, 2, 0, TAB_RIGHT, lower[i], NULL, RC_OTHER);
1995 tab_double (risk, 3, 0, TAB_RIGHT, upper[i], NULL, RC_OTHER);
1996 tab_next_row (risk);
1999 tab_text (risk, 0, 0, TAB_LEFT, _("N of Valid Cases"));
2000 tab_double (risk, 1, 0, TAB_RIGHT, pt->total, NULL, RC_WEIGHT);
2001 tab_next_row (risk);
2003 tab_offset (risk, 0, -1);
2006 static int calc_directional (struct crosstabs_proc *, struct pivot_table *,
2007 double[N_DIRECTIONAL], double[N_DIRECTIONAL],
2008 double[N_DIRECTIONAL], double[N_DIRECTIONAL]);
2010 /* Display directional measures. */
2012 display_directional (struct crosstabs_proc *proc, struct pivot_table *pt,
2013 struct tab_table *direct)
2015 static const char *categories[] =
2017 N_("Nominal by Nominal"),
2018 N_("Ordinal by Ordinal"),
2019 N_("Nominal by Interval"),
2022 static const char *stats[] =
2025 N_("Goodman and Kruskal tau"),
2026 N_("Uncertainty Coefficient"),
2031 static const char *types[] =
2038 static const int stats_categories[N_DIRECTIONAL] =
2040 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2,
2043 static const int stats_stats[N_DIRECTIONAL] =
2045 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4,
2048 static const int stats_types[N_DIRECTIONAL] =
2050 0, 1, 2, 1, 2, 0, 1, 2, 0, 1, 2, 1, 2,
2053 static const int *stats_lookup[] =
2060 static const char **stats_names[] =
2072 double direct_v[N_DIRECTIONAL];
2073 double direct_ase[N_DIRECTIONAL];
2074 double direct_t[N_DIRECTIONAL];
2075 double sig[N_DIRECTIONAL];
2079 if (!calc_directional (proc, pt, direct_v, direct_ase, direct_t, sig))
2082 tab_offset (direct, pt->n_consts + pt->n_vars - 2, -1);
2084 for (i = 0; i < N_DIRECTIONAL; i++)
2086 if (direct_v[i] == SYSMIS)
2092 for (j = 0; j < 3; j++)
2093 if (last[j] != stats_lookup[j][i])
2096 tab_hline (direct, TAL_1, j, 6, 0);
2101 int k = last[j] = stats_lookup[j][i];
2106 string = var_to_string (pt->vars[0]);
2108 string = var_to_string (pt->vars[1]);
2110 tab_text_format (direct, j, 0, TAB_LEFT,
2111 gettext (stats_names[j][k]), string);
2116 tab_double (direct, 3, 0, TAB_RIGHT, direct_v[i], NULL, RC_OTHER);
2117 if (direct_ase[i] != SYSMIS)
2118 tab_double (direct, 4, 0, TAB_RIGHT, direct_ase[i], NULL, RC_OTHER);
2119 if (direct_t[i] != SYSMIS)
2120 tab_double (direct, 5, 0, TAB_RIGHT, direct_t[i], NULL, RC_OTHER);
2121 tab_double (direct, 6, 0, TAB_RIGHT, sig[i], NULL, RC_PVALUE);
2122 tab_next_row (direct);
2125 tab_offset (direct, 0, -1);
2128 /* Statistical calculations. */
2130 /* Returns the value of the logarithm of gamma (factorial) function for an integer
2133 log_gamma_int (double pt)
2138 for (i = 2; i < pt; i++)
2144 /* Calculate P_r as specified in _SPSS Statistical Algorithms_,
2146 static inline double
2147 Pr (int a, int b, int c, int d)
2149 return exp (log_gamma_int (a + b + 1.) - log_gamma_int (a + 1.)
2150 + log_gamma_int (c + d + 1.) - log_gamma_int (b + 1.)
2151 + log_gamma_int (a + c + 1.) - log_gamma_int (c + 1.)
2152 + log_gamma_int (b + d + 1.) - log_gamma_int (d + 1.)
2153 - log_gamma_int (a + b + c + d + 1.));
2156 /* Swap the contents of A and B. */
2158 swap (int *a, int *b)
2165 /* Calculate significance for Fisher's exact test as specified in
2166 _SPSS Statistical Algorithms_, Appendix 5. */
2168 calc_fisher (int a, int b, int c, int d, double *fisher1, double *fisher2)
2173 if (MIN (c, d) < MIN (a, b))
2174 swap (&a, &c), swap (&b, &d);
2175 if (MIN (b, d) < MIN (a, c))
2176 swap (&a, &b), swap (&c, &d);
2180 swap (&a, &b), swap (&c, &d);
2182 swap (&a, &c), swap (&b, &d);
2185 pn1 = Pr (a, b, c, d);
2187 for (pt = 1; pt <= a; pt++)
2189 *fisher1 += Pr (a - pt, b + pt, c + pt, d - pt);
2192 *fisher2 = *fisher1;
2194 for (pt = 1; pt <= b; pt++)
2196 double p = Pr (a + pt, b - pt, c - pt, d + pt);
2202 /* Calculates chi-squares into CHISQ. MAT is a matrix with N_COLS
2203 columns with values COLS and N_ROWS rows with values ROWS. Values
2204 in the matrix sum to pt->total. */
2206 calc_chisq (struct pivot_table *pt,
2207 double chisq[N_CHISQ], int df[N_CHISQ],
2208 double *fisher1, double *fisher2)
2212 chisq[0] = chisq[1] = 0.;
2213 chisq[2] = chisq[3] = chisq[4] = SYSMIS;
2214 *fisher1 = *fisher2 = SYSMIS;
2216 df[0] = df[1] = (pt->ns_cols - 1) * (pt->ns_rows - 1);
2218 if (pt->ns_rows <= 1 || pt->ns_cols <= 1)
2220 chisq[0] = chisq[1] = SYSMIS;
2224 for (r = 0; r < pt->n_rows; r++)
2225 for (c = 0; c < pt->n_cols; c++)
2227 const double expected = pt->row_tot[r] * pt->col_tot[c] / pt->total;
2228 const double freq = pt->mat[pt->n_cols * r + c];
2229 const double residual = freq - expected;
2231 chisq[0] += residual * residual / expected;
2233 chisq[1] += freq * log (expected / freq);
2244 /* Calculate Yates and Fisher exact test. */
2245 if (pt->ns_cols == 2 && pt->ns_rows == 2)
2247 double f11, f12, f21, f22;
2253 for (i = j = 0; i < pt->n_cols; i++)
2254 if (pt->col_tot[i] != 0.)
2263 f11 = pt->mat[nz_cols[0]];
2264 f12 = pt->mat[nz_cols[1]];
2265 f21 = pt->mat[nz_cols[0] + pt->n_cols];
2266 f22 = pt->mat[nz_cols[1] + pt->n_cols];
2271 const double pt_ = fabs (f11 * f22 - f12 * f21) - 0.5 * pt->total;
2274 chisq[3] = (pt->total * pow2 (pt_)
2275 / (f11 + f12) / (f21 + f22)
2276 / (f11 + f21) / (f12 + f22));
2284 calc_fisher (f11 + .5, f12 + .5, f21 + .5, f22 + .5, fisher1, fisher2);
2287 /* Calculate Mantel-Haenszel. */
2288 if (var_is_numeric (pt->vars[ROW_VAR]) && var_is_numeric (pt->vars[COL_VAR]))
2290 double r, ase_0, ase_1;
2291 calc_r (pt, (double *) pt->rows, (double *) pt->cols, &r, &ase_0, &ase_1);
2293 chisq[4] = (pt->total - 1.) * r * r;
2298 /* Calculate the value of Pearson's r. r is stored into R, its T value into
2299 T, and standard error into ERROR. The row and column values must be
2300 passed in PT and Y. */
2302 calc_r (struct pivot_table *pt,
2303 double *PT, double *Y, double *r, double *t, double *error)
2305 double SX, SY, S, T;
2307 double sum_XYf, sum_X2Y2f;
2308 double sum_Xr, sum_X2r;
2309 double sum_Yc, sum_Y2c;
2312 for (sum_X2Y2f = sum_XYf = 0., i = 0; i < pt->n_rows; i++)
2313 for (j = 0; j < pt->n_cols; j++)
2315 double fij = pt->mat[j + i * pt->n_cols];
2316 double product = PT[i] * Y[j];
2317 double temp = fij * product;
2319 sum_X2Y2f += temp * product;
2322 for (sum_Xr = sum_X2r = 0., i = 0; i < pt->n_rows; i++)
2324 sum_Xr += PT[i] * pt->row_tot[i];
2325 sum_X2r += pow2 (PT[i]) * pt->row_tot[i];
2327 Xbar = sum_Xr / pt->total;
2329 for (sum_Yc = sum_Y2c = 0., i = 0; i < pt->n_cols; i++)
2331 sum_Yc += Y[i] * pt->col_tot[i];
2332 sum_Y2c += Y[i] * Y[i] * pt->col_tot[i];
2334 Ybar = sum_Yc / pt->total;
2336 S = sum_XYf - sum_Xr * sum_Yc / pt->total;
2337 SX = sum_X2r - pow2 (sum_Xr) / pt->total;
2338 SY = sum_Y2c - pow2 (sum_Yc) / pt->total;
2341 *t = *r / sqrt (1 - pow2 (*r)) * sqrt (pt->total - 2);
2346 for (s = c = 0., i = 0; i < pt->n_rows; i++)
2347 for (j = 0; j < pt->n_cols; j++)
2349 double Xresid, Yresid;
2352 Xresid = PT[i] - Xbar;
2353 Yresid = Y[j] - Ybar;
2354 temp = (T * Xresid * Yresid
2356 * (Xresid * Xresid * SY + Yresid * Yresid * SX)));
2357 y = pt->mat[j + i * pt->n_cols] * temp * temp - c;
2362 *error = sqrt (s) / (T * T);
2366 /* Calculate symmetric statistics and their asymptotic standard
2367 errors. Returns 0 if none could be calculated. */
2369 calc_symmetric (struct crosstabs_proc *proc, struct pivot_table *pt,
2370 double v[N_SYMMETRIC], double ase[N_SYMMETRIC],
2371 double t[N_SYMMETRIC],
2372 double somers_d_v[3], double somers_d_ase[3],
2373 double somers_d_t[3])
2377 q = MIN (pt->ns_rows, pt->ns_cols);
2381 for (i = 0; i < N_SYMMETRIC; i++)
2382 v[i] = ase[i] = t[i] = SYSMIS;
2384 /* Phi, Cramer's V, contingency coefficient. */
2385 if (proc->statistics & ((1u << CRS_ST_PHI) | (1u << CRS_ST_CC)))
2387 double Xp = 0.; /* Pearson chi-square. */
2390 for (r = 0; r < pt->n_rows; r++)
2391 for (c = 0; c < pt->n_cols; c++)
2393 const double expected = pt->row_tot[r] * pt->col_tot[c] / pt->total;
2394 const double freq = pt->mat[pt->n_cols * r + c];
2395 const double residual = freq - expected;
2397 Xp += residual * residual / expected;
2400 if (proc->statistics & (1u << CRS_ST_PHI))
2402 v[0] = sqrt (Xp / pt->total);
2403 v[1] = sqrt (Xp / (pt->total * (q - 1)));
2405 if (proc->statistics & (1u << CRS_ST_CC))
2406 v[2] = sqrt (Xp / (Xp + pt->total));
2409 if (proc->statistics & ((1u << CRS_ST_BTAU) | (1u << CRS_ST_CTAU)
2410 | (1u << CRS_ST_GAMMA) | (1u << CRS_ST_D)))
2415 double btau_cum, ctau_cum, gamma_cum, d_yx_cum, d_xy_cum;
2419 Dr = Dc = pow2 (pt->total);
2420 for (r = 0; r < pt->n_rows; r++)
2421 Dr -= pow2 (pt->row_tot[r]);
2422 for (c = 0; c < pt->n_cols; c++)
2423 Dc -= pow2 (pt->col_tot[c]);
2425 cum = xnmalloc (pt->n_cols * pt->n_rows, sizeof *cum);
2426 for (c = 0; c < pt->n_cols; c++)
2430 for (r = 0; r < pt->n_rows; r++)
2431 cum[c + r * pt->n_cols] = ct += pt->mat[c + r * pt->n_cols];
2440 for (i = 0; i < pt->n_rows; i++)
2444 for (j = 1; j < pt->n_cols; j++)
2445 Cij += pt->col_tot[j] - cum[j + i * pt->n_cols];
2448 for (j = 1; j < pt->n_cols; j++)
2449 Dij += cum[j + (i - 1) * pt->n_cols];
2453 double fij = pt->mat[j + i * pt->n_cols];
2457 if (++j == pt->n_cols)
2459 assert (j < pt->n_cols);
2461 Cij -= pt->col_tot[j] - cum[j + i * pt->n_cols];
2462 Dij += pt->col_tot[j - 1] - cum[j - 1 + i * pt->n_cols];
2466 Cij += cum[j - 1 + (i - 1) * pt->n_cols];
2467 Dij -= cum[j + (i - 1) * pt->n_cols];
2473 if (proc->statistics & (1u << CRS_ST_BTAU))
2474 v[3] = (P - Q) / sqrt (Dr * Dc);
2475 if (proc->statistics & (1u << CRS_ST_CTAU))
2476 v[4] = (q * (P - Q)) / (pow2 (pt->total) * (q - 1));
2477 if (proc->statistics & (1u << CRS_ST_GAMMA))
2478 v[5] = (P - Q) / (P + Q);
2480 /* ASE for tau-b, tau-c, gamma. Calculations could be
2481 eliminated here, at expense of memory. */
2486 btau_cum = ctau_cum = gamma_cum = d_yx_cum = d_xy_cum = 0.;
2487 for (i = 0; i < pt->n_rows; i++)
2491 for (j = 1; j < pt->n_cols; j++)
2492 Cij += pt->col_tot[j] - cum[j + i * pt->n_cols];
2495 for (j = 1; j < pt->n_cols; j++)
2496 Dij += cum[j + (i - 1) * pt->n_cols];
2500 double fij = pt->mat[j + i * pt->n_cols];
2502 if (proc->statistics & (1u << CRS_ST_BTAU))
2504 const double temp = (2. * sqrt (Dr * Dc) * (Cij - Dij)
2505 + v[3] * (pt->row_tot[i] * Dc
2506 + pt->col_tot[j] * Dr));
2507 btau_cum += fij * temp * temp;
2511 const double temp = Cij - Dij;
2512 ctau_cum += fij * temp * temp;
2515 if (proc->statistics & (1u << CRS_ST_GAMMA))
2517 const double temp = Q * Cij - P * Dij;
2518 gamma_cum += fij * temp * temp;
2521 if (proc->statistics & (1u << CRS_ST_D))
2523 d_yx_cum += fij * pow2 (Dr * (Cij - Dij)
2524 - (P - Q) * (pt->total - pt->row_tot[i]));
2525 d_xy_cum += fij * pow2 (Dc * (Dij - Cij)
2526 - (Q - P) * (pt->total - pt->col_tot[j]));
2529 if (++j == pt->n_cols)
2531 assert (j < pt->n_cols);
2533 Cij -= pt->col_tot[j] - cum[j + i * pt->n_cols];
2534 Dij += pt->col_tot[j - 1] - cum[j - 1 + i * pt->n_cols];
2538 Cij += cum[j - 1 + (i - 1) * pt->n_cols];
2539 Dij -= cum[j + (i - 1) * pt->n_cols];
2545 btau_var = ((btau_cum
2546 - (pt->total * pow2 (pt->total * (P - Q) / sqrt (Dr * Dc) * (Dr + Dc))))
2548 if (proc->statistics & (1u << CRS_ST_BTAU))
2550 ase[3] = sqrt (btau_var);
2551 t[3] = v[3] / (2 * sqrt ((ctau_cum - (P - Q) * (P - Q) / pt->total)
2554 if (proc->statistics & (1u << CRS_ST_CTAU))
2556 ase[4] = ((2 * q / ((q - 1) * pow2 (pt->total)))
2557 * sqrt (ctau_cum - (P - Q) * (P - Q) / pt->total));
2558 t[4] = v[4] / ase[4];
2560 if (proc->statistics & (1u << CRS_ST_GAMMA))
2562 ase[5] = ((4. / ((P + Q) * (P + Q))) * sqrt (gamma_cum));
2563 t[5] = v[5] / (2. / (P + Q)
2564 * sqrt (ctau_cum - (P - Q) * (P - Q) / pt->total));
2566 if (proc->statistics & (1u << CRS_ST_D))
2568 somers_d_v[0] = (P - Q) / (.5 * (Dc + Dr));
2569 somers_d_ase[0] = SYSMIS;
2570 somers_d_t[0] = (somers_d_v[0]
2572 * sqrt (ctau_cum - pow2 (P - Q) / pt->total)));
2573 somers_d_v[1] = (P - Q) / Dc;
2574 somers_d_ase[1] = 2. / pow2 (Dc) * sqrt (d_xy_cum);
2575 somers_d_t[1] = (somers_d_v[1]
2577 * sqrt (ctau_cum - pow2 (P - Q) / pt->total)));
2578 somers_d_v[2] = (P - Q) / Dr;
2579 somers_d_ase[2] = 2. / pow2 (Dr) * sqrt (d_yx_cum);
2580 somers_d_t[2] = (somers_d_v[2]
2582 * sqrt (ctau_cum - pow2 (P - Q) / pt->total)));
2588 /* Spearman correlation, Pearson's r. */
2589 if (proc->statistics & (1u << CRS_ST_CORR))
2591 double *R = xmalloc (sizeof *R * pt->n_rows);
2592 double *C = xmalloc (sizeof *C * pt->n_cols);
2595 double y, t, c = 0., s = 0.;
2600 R[i] = s + (pt->row_tot[i] + 1.) / 2.;
2601 y = pt->row_tot[i] - c;
2605 if (++i == pt->n_rows)
2607 assert (i < pt->n_rows);
2612 double y, t, c = 0., s = 0.;
2617 C[j] = s + (pt->col_tot[j] + 1.) / 2;
2618 y = pt->col_tot[j] - c;
2622 if (++j == pt->n_cols)
2624 assert (j < pt->n_cols);
2628 calc_r (pt, R, C, &v[6], &t[6], &ase[6]);
2633 calc_r (pt, (double *) pt->rows, (double *) pt->cols, &v[7], &t[7], &ase[7]);
2636 /* Cohen's kappa. */
2637 if (proc->statistics & (1u << CRS_ST_KAPPA) && pt->ns_rows == pt->ns_cols)
2639 double ase_under_h0;
2640 double sum_fii, sum_rici, sum_fiiri_ci, sum_fijri_ci2, sum_riciri_ci;
2643 for (sum_fii = sum_rici = sum_fiiri_ci = sum_riciri_ci = 0., i = j = 0;
2644 i < pt->ns_rows; i++, j++)
2648 while (pt->col_tot[j] == 0.)
2651 prod = pt->row_tot[i] * pt->col_tot[j];
2652 sum = pt->row_tot[i] + pt->col_tot[j];
2654 sum_fii += pt->mat[j + i * pt->n_cols];
2656 sum_fiiri_ci += pt->mat[j + i * pt->n_cols] * sum;
2657 sum_riciri_ci += prod * sum;
2659 for (sum_fijri_ci2 = 0., i = 0; i < pt->ns_rows; i++)
2660 for (j = 0; j < pt->ns_cols; j++)
2662 double sum = pt->row_tot[i] + pt->col_tot[j];
2663 sum_fijri_ci2 += pt->mat[j + i * pt->n_cols] * sum * sum;
2666 v[8] = (pt->total * sum_fii - sum_rici) / (pow2 (pt->total) - sum_rici);
2668 ase_under_h0 = sqrt ((pow2 (pt->total) * sum_rici
2669 + sum_rici * sum_rici
2670 - pt->total * sum_riciri_ci)
2671 / (pt->total * (pow2 (pt->total) - sum_rici) * (pow2 (pt->total) - sum_rici)));
2673 ase[8] = sqrt (pt->total * (((sum_fii * (pt->total - sum_fii))
2674 / pow2 (pow2 (pt->total) - sum_rici))
2675 + ((2. * (pt->total - sum_fii)
2676 * (2. * sum_fii * sum_rici
2677 - pt->total * sum_fiiri_ci))
2678 / pow3 (pow2 (pt->total) - sum_rici))
2679 + (pow2 (pt->total - sum_fii)
2680 * (pt->total * sum_fijri_ci2 - 4.
2681 * sum_rici * sum_rici)
2682 / pow4 (pow2 (pt->total) - sum_rici))));
2684 t[8] = v[8] / ase_under_h0;
2690 /* Calculate risk estimate. */
2692 calc_risk (struct pivot_table *pt,
2693 double *value, double *upper, double *lower, union value *c)
2695 double f11, f12, f21, f22;
2701 for (i = 0; i < 3; i++)
2702 value[i] = upper[i] = lower[i] = SYSMIS;
2705 if (pt->ns_rows != 2 || pt->ns_cols != 2)
2712 for (i = j = 0; i < pt->n_cols; i++)
2713 if (pt->col_tot[i] != 0.)
2722 f11 = pt->mat[nz_cols[0]];
2723 f12 = pt->mat[nz_cols[1]];
2724 f21 = pt->mat[nz_cols[0] + pt->n_cols];
2725 f22 = pt->mat[nz_cols[1] + pt->n_cols];
2727 c[0] = pt->cols[nz_cols[0]];
2728 c[1] = pt->cols[nz_cols[1]];
2731 value[0] = (f11 * f22) / (f12 * f21);
2732 v = sqrt (1. / f11 + 1. / f12 + 1. / f21 + 1. / f22);
2733 lower[0] = value[0] * exp (-1.960 * v);
2734 upper[0] = value[0] * exp (1.960 * v);
2736 value[1] = (f11 * (f21 + f22)) / (f21 * (f11 + f12));
2737 v = sqrt ((f12 / (f11 * (f11 + f12)))
2738 + (f22 / (f21 * (f21 + f22))));
2739 lower[1] = value[1] * exp (-1.960 * v);
2740 upper[1] = value[1] * exp (1.960 * v);
2742 value[2] = (f12 * (f21 + f22)) / (f22 * (f11 + f12));
2743 v = sqrt ((f11 / (f12 * (f11 + f12)))
2744 + (f21 / (f22 * (f21 + f22))));
2745 lower[2] = value[2] * exp (-1.960 * v);
2746 upper[2] = value[2] * exp (1.960 * v);
2751 /* Calculate directional measures. */
2753 calc_directional (struct crosstabs_proc *proc, struct pivot_table *pt,
2754 double v[N_DIRECTIONAL], double ase[N_DIRECTIONAL],
2755 double t[N_DIRECTIONAL], double sig[N_DIRECTIONAL])
2760 for (i = 0; i < N_DIRECTIONAL; i++)
2761 v[i] = ase[i] = t[i] = sig[i] = SYSMIS;
2765 if (proc->statistics & (1u << CRS_ST_LAMBDA))
2767 double *fim = xnmalloc (pt->n_rows, sizeof *fim);
2768 int *fim_index = xnmalloc (pt->n_rows, sizeof *fim_index);
2769 double *fmj = xnmalloc (pt->n_cols, sizeof *fmj);
2770 int *fmj_index = xnmalloc (pt->n_cols, sizeof *fmj_index);
2771 double sum_fim, sum_fmj;
2773 int rm_index, cm_index;
2776 /* Find maximum for each row and their sum. */
2777 for (sum_fim = 0., i = 0; i < pt->n_rows; i++)
2779 double max = pt->mat[i * pt->n_cols];
2782 for (j = 1; j < pt->n_cols; j++)
2783 if (pt->mat[j + i * pt->n_cols] > max)
2785 max = pt->mat[j + i * pt->n_cols];
2789 sum_fim += fim[i] = max;
2790 fim_index[i] = index;
2793 /* Find maximum for each column. */
2794 for (sum_fmj = 0., j = 0; j < pt->n_cols; j++)
2796 double max = pt->mat[j];
2799 for (i = 1; i < pt->n_rows; i++)
2800 if (pt->mat[j + i * pt->n_cols] > max)
2802 max = pt->mat[j + i * pt->n_cols];
2806 sum_fmj += fmj[j] = max;
2807 fmj_index[j] = index;
2810 /* Find maximum row total. */
2811 rm = pt->row_tot[0];
2813 for (i = 1; i < pt->n_rows; i++)
2814 if (pt->row_tot[i] > rm)
2816 rm = pt->row_tot[i];
2820 /* Find maximum column total. */
2821 cm = pt->col_tot[0];
2823 for (j = 1; j < pt->n_cols; j++)
2824 if (pt->col_tot[j] > cm)
2826 cm = pt->col_tot[j];
2830 v[0] = (sum_fim + sum_fmj - cm - rm) / (2. * pt->total - rm - cm);
2831 v[1] = (sum_fmj - rm) / (pt->total - rm);
2832 v[2] = (sum_fim - cm) / (pt->total - cm);
2834 /* ASE1 for Y given PT. */
2839 for (i = 0; i < pt->n_rows; i++)
2840 if (cm_index == fim_index[i])
2842 ase[2] = sqrt ((pt->total - sum_fim) * (sum_fim + cm - 2. * accum)
2843 / pow3 (pt->total - cm));
2846 /* ASE0 for Y given PT. */
2850 for (accum = 0., i = 0; i < pt->n_rows; i++)
2851 if (cm_index != fim_index[i])
2852 accum += (pt->mat[i * pt->n_cols + fim_index[i]]
2853 + pt->mat[i * pt->n_cols + cm_index]);
2854 t[2] = v[2] / (sqrt (accum - pow2 (sum_fim - cm) / pt->total) / (pt->total - cm));
2857 /* ASE1 for PT given Y. */
2862 for (j = 0; j < pt->n_cols; j++)
2863 if (rm_index == fmj_index[j])
2865 ase[1] = sqrt ((pt->total - sum_fmj) * (sum_fmj + rm - 2. * accum)
2866 / pow3 (pt->total - rm));
2869 /* ASE0 for PT given Y. */
2873 for (accum = 0., j = 0; j < pt->n_cols; j++)
2874 if (rm_index != fmj_index[j])
2875 accum += (pt->mat[j + pt->n_cols * fmj_index[j]]
2876 + pt->mat[j + pt->n_cols * rm_index]);
2877 t[1] = v[1] / (sqrt (accum - pow2 (sum_fmj - rm) / pt->total) / (pt->total - rm));
2880 /* Symmetric ASE0 and ASE1. */
2885 for (accum0 = accum1 = 0., i = 0; i < pt->n_rows; i++)
2886 for (j = 0; j < pt->n_cols; j++)
2888 int temp0 = (fmj_index[j] == i) + (fim_index[i] == j);
2889 int temp1 = (i == rm_index) + (j == cm_index);
2890 accum0 += pt->mat[j + i * pt->n_cols] * pow2 (temp0 - temp1);
2891 accum1 += (pt->mat[j + i * pt->n_cols]
2892 * pow2 (temp0 + (v[0] - 1.) * temp1));
2894 ase[0] = sqrt (accum1 - 4. * pt->total * v[0] * v[0]) / (2. * pt->total - rm - cm);
2895 t[0] = v[0] / (sqrt (accum0 - pow2 (sum_fim + sum_fmj - cm - rm) / pt->total)
2896 / (2. * pt->total - rm - cm));
2899 for (i = 0; i < 3; i++)
2900 sig[i] = 2 * gsl_cdf_ugaussian_Q (t[i]);
2909 double sum_fij2_ri, sum_fij2_ci;
2910 double sum_ri2, sum_cj2;
2912 for (sum_fij2_ri = sum_fij2_ci = 0., i = 0; i < pt->n_rows; i++)
2913 for (j = 0; j < pt->n_cols; j++)
2915 double temp = pow2 (pt->mat[j + i * pt->n_cols]);
2916 sum_fij2_ri += temp / pt->row_tot[i];
2917 sum_fij2_ci += temp / pt->col_tot[j];
2920 for (sum_ri2 = 0., i = 0; i < pt->n_rows; i++)
2921 sum_ri2 += pow2 (pt->row_tot[i]);
2923 for (sum_cj2 = 0., j = 0; j < pt->n_cols; j++)
2924 sum_cj2 += pow2 (pt->col_tot[j]);
2926 v[3] = (pt->total * sum_fij2_ci - sum_ri2) / (pow2 (pt->total) - sum_ri2);
2927 v[4] = (pt->total * sum_fij2_ri - sum_cj2) / (pow2 (pt->total) - sum_cj2);
2931 if (proc->statistics & (1u << CRS_ST_UC))
2933 double UX, UY, UXY, P;
2934 double ase1_yx, ase1_xy, ase1_sym;
2937 for (UX = 0., i = 0; i < pt->n_rows; i++)
2938 if (pt->row_tot[i] > 0.)
2939 UX -= pt->row_tot[i] / pt->total * log (pt->row_tot[i] / pt->total);
2941 for (UY = 0., j = 0; j < pt->n_cols; j++)
2942 if (pt->col_tot[j] > 0.)
2943 UY -= pt->col_tot[j] / pt->total * log (pt->col_tot[j] / pt->total);
2945 for (UXY = P = 0., i = 0; i < pt->n_rows; i++)
2946 for (j = 0; j < pt->n_cols; j++)
2948 double entry = pt->mat[j + i * pt->n_cols];
2953 P += entry * pow2 (log (pt->col_tot[j] * pt->row_tot[i] / (pt->total * entry)));
2954 UXY -= entry / pt->total * log (entry / pt->total);
2957 for (ase1_yx = ase1_xy = ase1_sym = 0., i = 0; i < pt->n_rows; i++)
2958 for (j = 0; j < pt->n_cols; j++)
2960 double entry = pt->mat[j + i * pt->n_cols];
2965 ase1_yx += entry * pow2 (UY * log (entry / pt->row_tot[i])
2966 + (UX - UXY) * log (pt->col_tot[j] / pt->total));
2967 ase1_xy += entry * pow2 (UX * log (entry / pt->col_tot[j])
2968 + (UY - UXY) * log (pt->row_tot[i] / pt->total));
2969 ase1_sym += entry * pow2 ((UXY
2970 * log (pt->row_tot[i] * pt->col_tot[j] / pow2 (pt->total)))
2971 - (UX + UY) * log (entry / pt->total));
2974 v[5] = 2. * ((UX + UY - UXY) / (UX + UY));
2975 ase[5] = (2. / (pt->total * pow2 (UX + UY))) * sqrt (ase1_sym);
2978 v[6] = (UX + UY - UXY) / UX;
2979 ase[6] = sqrt (ase1_xy) / (pt->total * UX * UX);
2980 t[6] = v[6] / (sqrt (P - pt->total * pow2 (UX + UY - UXY)) / (pt->total * UX));
2982 v[7] = (UX + UY - UXY) / UY;
2983 ase[7] = sqrt (ase1_yx) / (pt->total * UY * UY);
2984 t[7] = v[7] / (sqrt (P - pt->total * pow2 (UX + UY - UXY)) / (pt->total * UY));
2988 if (proc->statistics & (1u << CRS_ST_D))
2990 double v_dummy[N_SYMMETRIC];
2991 double ase_dummy[N_SYMMETRIC];
2992 double t_dummy[N_SYMMETRIC];
2993 double somers_d_v[3];
2994 double somers_d_ase[3];
2995 double somers_d_t[3];
2997 if (calc_symmetric (proc, pt, v_dummy, ase_dummy, t_dummy,
2998 somers_d_v, somers_d_ase, somers_d_t))
3001 for (i = 0; i < 3; i++)
3003 v[8 + i] = somers_d_v[i];
3004 ase[8 + i] = somers_d_ase[i];
3005 t[8 + i] = somers_d_t[i];
3006 sig[8 + i] = 2 * gsl_cdf_ugaussian_Q (fabs (somers_d_t[i]));
3012 if (proc->statistics & (1u << CRS_ST_ETA))
3015 double sum_Xr, sum_X2r;
3019 for (sum_Xr = sum_X2r = 0., i = 0; i < pt->n_rows; i++)
3021 sum_Xr += pt->rows[i].f * pt->row_tot[i];
3022 sum_X2r += pow2 (pt->rows[i].f) * pt->row_tot[i];
3024 SX = sum_X2r - pow2 (sum_Xr) / pt->total;
3026 for (SXW = 0., j = 0; j < pt->n_cols; j++)
3030 for (cum = 0., i = 0; i < pt->n_rows; i++)
3032 SXW += pow2 (pt->rows[i].f) * pt->mat[j + i * pt->n_cols];
3033 cum += pt->rows[i].f * pt->mat[j + i * pt->n_cols];
3036 SXW -= cum * cum / pt->col_tot[j];
3038 v[11] = sqrt (1. - SXW / SX);
3042 double sum_Yc, sum_Y2c;
3046 for (sum_Yc = sum_Y2c = 0., i = 0; i < pt->n_cols; i++)
3048 sum_Yc += pt->cols[i].f * pt->col_tot[i];
3049 sum_Y2c += pow2 (pt->cols[i].f) * pt->col_tot[i];
3051 SY = sum_Y2c - sum_Yc * sum_Yc / pt->total;
3053 for (SYW = 0., i = 0; i < pt->n_rows; i++)
3057 for (cum = 0., j = 0; j < pt->n_cols; j++)
3059 SYW += pow2 (pt->cols[j].f) * pt->mat[j + i * pt->n_cols];
3060 cum += pt->cols[j].f * pt->mat[j + i * pt->n_cols];
3063 SYW -= cum * cum / pt->row_tot[i];
3065 v[12] = sqrt (1. - SYW / SY);