1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2021 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/>. */
21 #include "data/casereader.h"
22 #include "data/casewriter.h"
23 #include "data/dataset.h"
24 #include "data/dictionary.h"
25 #include "data/mrset.h"
26 #include "data/subcase.h"
27 #include "data/value-labels.h"
28 #include "language/command.h"
29 #include "language/lexer/format-parser.h"
30 #include "language/lexer/lexer.h"
31 #include "language/lexer/variable-parser.h"
32 #include "libpspp/array.h"
33 #include "libpspp/assertion.h"
34 #include "libpspp/hash-functions.h"
35 #include "libpspp/hmap.h"
36 #include "libpspp/message.h"
37 #include "libpspp/string-array.h"
38 #include "math/moments.h"
39 #include "math/percentiles.h"
40 #include "math/sort.h"
41 #include "output/pivot-table.h"
43 #include "gl/minmax.h"
44 #include "gl/xalloc.h"
47 #define _(msgid) gettext (msgid)
48 #define N_(msgid) (msgid)
52 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
53 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
54 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
55 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
59 - unweighted summaries (U*)
60 - lower confidence limits (*.LCL)
61 - upper confidence limits (*.UCL)
62 - standard error (*.SE)
65 /* All variables. */ \
66 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
67 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
68 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
69 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
70 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
71 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
72 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
85 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
86 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
87 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
88 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
90 /* Scale variables, totals, and subtotals. */ \
91 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
92 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
93 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
94 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
95 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
98 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
99 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
100 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
101 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
102 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
103 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
104 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
105 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
106 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
107 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
108 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
109 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
110 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
111 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
112 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
113 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
115 /* Multiple response sets. */ \
116 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
117 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
118 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
119 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
120 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
121 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
134 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
135 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
139 enum ctables_summary_function
141 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
147 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
148 N_CTSF_FUNCTIONS = SUMMARIES
152 enum ctables_domain_type
154 /* Within a section, where stacked variables divide one section from
156 CTDT_TABLE, /* All layers of a whole section. */
157 CTDT_LAYER, /* One layer within a section. */
158 CTDT_LAYERROW, /* Row in one layer within a section. */
159 CTDT_LAYERCOL, /* Column in one layer within a section. */
161 /* Within a subtable, where a subtable pairs an innermost row variable with
162 an innermost column variable within a single layer. */
163 CTDT_SUBTABLE, /* Whole subtable. */
164 CTDT_ROW, /* Row within a subtable. */
165 CTDT_COL, /* Column within a subtable. */
169 struct ctables_domain
171 struct hmap_node node;
173 const struct ctables_cell *example;
179 enum ctables_summary_variant
188 /* In struct ctables's 'cells' hmap. Indexed by all the values in all the
189 axes (except the scalar variable, if any). */
190 struct hmap_node node;
192 /* The domains that contain this cell. */
193 bool contributes_to_domains;
194 struct ctables_domain *domains[N_CTDTS];
197 enum ctables_summary_variant sv;
202 struct ctables_cell_value
204 const struct ctables_category *category;
212 union ctables_summary *summaries;
217 struct pivot_table_look *look;
219 /* If this is NULL, zeros are displayed using the normal print format.
220 Otherwise, this string is displayed. */
223 /* If this is NULL, missing values are displayed using the normal print
224 format. Otherwise, this string is displayed. */
227 /* Indexed by variable dictionary index. */
228 enum ctables_vlabel *vlabels;
230 bool mrsets_count_duplicates; /* MRSETS. */
231 bool smissing_listwise; /* SMISSING. */
232 struct variable *base_weight; /* WEIGHT. */
233 int hide_threshold; /* HIDESMALLCOUNTS. */
235 struct ctables_table **tables;
239 struct ctables_postcompute
241 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
242 const char *name; /* Name, without leading &. */
244 struct ctables_postcompute_expr *expr;
247 bool hide_source_cats;
250 struct ctables_postcompute_expr
252 enum ctables_postcompute_op
260 /* XXX SUBTOTAL and HSUBTOTAL */
273 /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
278 XXX what about string ranges? */
281 /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
282 struct ctables_postcompute_expr *subs[2];
286 struct ctables_summary_spec_set
288 struct ctables_summary_spec *specs;
292 struct variable *var;
295 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
296 const struct ctables_summary_spec_set *);
297 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
299 /* A nested sequence of variables, e.g. a > b > c. */
302 struct variable **vars;
305 size_t *domains[N_CTDTS];
306 size_t n_domains[N_CTDTS];
308 struct ctables_summary_spec_set specs[N_CSVS];
311 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
314 struct ctables_nest *nests;
320 struct hmap_node node;
327 struct ctables_axis *axes[PIVOT_N_AXES];
328 struct ctables_stack stacks[PIVOT_N_AXES];
329 enum pivot_axis_type summary_axis;
330 struct ctables_summary_spec_set summary_specs;
332 struct hmap domains[N_CTDTS];
334 const struct variable *clabels_example;
335 struct hmap clabels_values_map;
336 struct ctables_value **clabels_values;
337 size_t n_clabels_values;
339 enum pivot_axis_type slabels_axis;
340 bool slabels_visible;
342 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
344 Most commonly, label_axis[a] == a, and in particular we always have
345 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
347 If ROWLABELS or COLLABELS is specified, then one of
348 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
349 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
351 enum pivot_axis_type label_axis[PIVOT_N_AXES];
352 enum pivot_axis_type clabels_from_axis;
354 /* Indexed by variable dictionary index. */
355 struct ctables_categories **categories;
364 struct ctables_chisq *chisq;
365 struct ctables_pairwise *pairwise;
373 struct variable *var;
374 const struct mrset *mrset;
378 static const struct fmt_spec *
379 ctables_var_get_print_format (const struct ctables_var *var)
381 return (var->is_mrset
382 ? var_get_print_format (var->mrset->vars[0])
383 : var_get_print_format (var->var));
387 ctables_var_name (const struct ctables_var *var)
389 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
392 struct ctables_categories
395 struct ctables_category *cats;
400 struct ctables_category
402 enum ctables_category_type
420 struct ctables_category *subtotal;
424 double number; /* CCT_NUMBER. */
425 char *string; /* CCT_STRING. */
426 double range[2]; /* CCT_RANGE. */
427 char *total_label; /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
429 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
432 bool include_missing;
436 enum ctables_summary_function sort_function;
437 struct variable *sort_var;
444 ctables_category_uninit (struct ctables_category *cat)
464 free (cat->total_label);
475 ctables_category_equal (const struct ctables_category *a,
476 const struct ctables_category *b)
478 if (a->type != b->type)
484 return a->number == b->number;
487 return strcmp (a->string, b->string);
490 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
499 return !strcmp (a->total_label, b->total_label);
504 return (a->include_missing == b->include_missing
505 && a->sort_ascending == b->sort_ascending
506 && a->sort_function == b->sort_function
507 && a->sort_var == b->sort_var
508 && a->percentile == b->percentile);
515 ctables_categories_unref (struct ctables_categories *c)
520 assert (c->n_refs > 0);
524 for (size_t i = 0; i < c->n_cats; i++)
525 ctables_category_uninit (&c->cats[i]);
531 ctables_categories_equal (const struct ctables_categories *a,
532 const struct ctables_categories *b)
534 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
537 for (size_t i = 0; i < a->n_cats; i++)
538 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
544 /* Chi-square test (SIGTEST). */
552 /* Pairwise comparison test (COMPARETEST). */
553 struct ctables_pairwise
555 enum { PROP, MEAN } type;
558 bool meansvariance_allcats;
560 enum { BONFERRONI = 1, BH } adjust;
584 struct ctables_var var;
586 struct ctables_summary_spec_set specs[N_CSVS];
590 struct ctables_axis *subs[2];
593 struct msg_location *loc;
596 static void ctables_axis_destroy (struct ctables_axis *);
605 enum ctables_function_availability
607 CTFA_ALL, /* Any variables. */
608 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
609 CTFA_MRSETS, /* Only multiple-response sets */
612 struct ctables_summary_spec
614 enum ctables_summary_function function;
615 double percentile; /* CTSF_PTILE only. */
617 struct fmt_spec format; /* XXX extra CTABLES formats */
622 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
623 const struct ctables_summary_spec *src)
626 dst->label = xstrdup (src->label);
630 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
637 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
638 const struct ctables_summary_spec_set *src)
640 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
641 for (size_t i = 0; i < src->n; i++)
642 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
644 *dst = (struct ctables_summary_spec_set) {
653 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
655 for (size_t i = 0; i < set->n; i++)
656 ctables_summary_spec_uninit (&set->specs[i]);
661 parse_col_width (struct lexer *lexer, const char *name, double *width)
663 lex_match (lexer, T_EQUALS);
664 if (lex_match_id (lexer, "DEFAULT"))
666 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
668 *width = lex_number (lexer);
678 parse_bool (struct lexer *lexer, bool *b)
680 if (lex_match_id (lexer, "NO"))
682 else if (lex_match_id (lexer, "YES"))
686 lex_error_expecting (lexer, "YES", "NO");
692 static enum ctables_function_availability
693 ctables_function_availability (enum ctables_summary_function f)
695 static enum ctables_function_availability availability[] = {
696 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
701 return availability[f];
705 parse_ctables_summary_function (struct lexer *lexer,
706 enum ctables_summary_function *f)
710 enum ctables_summary_function function;
711 struct substring name;
713 static struct pair names[] = {
714 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
715 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
718 /* The .COUNT suffix may be omitted. */
719 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
720 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
721 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
722 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
723 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
724 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
725 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
729 if (!lex_force_id (lexer))
732 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
733 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
735 *f = names[i].function;
740 lex_error (lexer, _("Expecting summary function name."));
745 ctables_axis_destroy (struct ctables_axis *axis)
753 for (size_t i = 0; i < N_CSVS; i++)
754 ctables_summary_spec_set_uninit (&axis->specs[i]);
759 ctables_axis_destroy (axis->subs[0]);
760 ctables_axis_destroy (axis->subs[1]);
763 msg_location_destroy (axis->loc);
767 static struct ctables_axis *
768 ctables_axis_new_nonterminal (enum ctables_axis_op op,
769 struct ctables_axis *sub0,
770 struct ctables_axis *sub1,
771 struct lexer *lexer, int start_ofs)
773 struct ctables_axis *axis = xmalloc (sizeof *axis);
774 *axis = (struct ctables_axis) {
776 .subs = { sub0, sub1 },
777 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
782 struct ctables_axis_parse_ctx
785 struct dictionary *dict;
787 struct ctables_table *t;
790 static struct fmt_spec
791 ctables_summary_default_format (enum ctables_summary_function function,
792 const struct ctables_var *var)
794 static const enum ctables_format default_formats[] = {
795 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
799 switch (default_formats[function])
802 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
805 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
808 return *ctables_var_get_print_format (var);
816 ctables_summary_default_label (enum ctables_summary_function function,
819 static const char *default_labels[] = {
820 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
825 return (function == CTSF_PTILE
826 ? xasprintf (_("Percentile %.2f"), percentile)
827 : xstrdup (gettext (default_labels[function])));
831 ctables_summary_function_name (enum ctables_summary_function function)
833 static const char *names[] = {
834 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
838 return names[function];
842 add_summary_spec (struct ctables_axis *axis,
843 enum ctables_summary_function function, double percentile,
844 const char *label, const struct fmt_spec *format,
845 const struct msg_location *loc, enum ctables_summary_variant sv)
847 if (axis->op == CTAO_VAR)
849 const char *function_name = ctables_summary_function_name (function);
850 const char *var_name = ctables_var_name (&axis->var);
851 switch (ctables_function_availability (function))
854 if (!axis->var.is_mrset)
856 msg_at (SE, loc, _("Summary function %s applies only to multiple "
857 "response sets."), function_name);
858 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
868 _("Summary function %s applies only to scale variables."),
870 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
880 struct ctables_summary_spec_set *set = &axis->specs[sv];
881 if (set->n >= set->allocated)
882 set->specs = x2nrealloc (set->specs, &set->allocated,
885 struct ctables_summary_spec *dst = &set->specs[set->n++];
886 *dst = (struct ctables_summary_spec) {
887 .function = function,
888 .percentile = percentile,
889 .label = xstrdup (label),
890 .format = (format ? *format
891 : ctables_summary_default_format (function, &axis->var)),
897 for (size_t i = 0; i < 2; i++)
898 if (!add_summary_spec (axis->subs[i], function, percentile, label,
905 static struct ctables_axis *ctables_axis_parse_stack (
906 struct ctables_axis_parse_ctx *);
909 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
910 struct ctables_var *var)
912 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
914 *var = (struct ctables_var) {
916 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
920 lex_error (lexer, _("'%s' does not name a multiple-response set "
921 "in the active file dictionary."),
922 lex_tokcstr (lexer));
930 *var = (struct ctables_var) {
932 .var = parse_variable (lexer, dict),
934 return var->var != NULL;
938 static struct ctables_axis *
939 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
941 if (lex_match (ctx->lexer, T_LPAREN))
943 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
944 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
946 ctables_axis_destroy (sub);
952 if (!lex_force_id (ctx->lexer))
955 int start_ofs = lex_ofs (ctx->lexer);
956 struct ctables_var var;
957 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
960 struct ctables_axis *axis = xmalloc (sizeof *axis);
961 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
963 /* XXX should figure out default measures by reading data */
964 axis->scale = (var.is_mrset ? false
965 : lex_match_phrase (ctx->lexer, "[S]") ? true
966 : lex_match_phrase (ctx->lexer, "[C]") ? false
967 : var_get_measure (var.var) == MEASURE_SCALE);
968 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
969 lex_ofs (ctx->lexer) - 1);
974 has_digit (const char *s)
976 return s[strcspn (s, "0123456789")] != '\0';
979 static struct ctables_axis *
980 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
982 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
983 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
986 enum ctables_summary_variant sv = CSV_CELL;
989 int start_ofs = lex_ofs (ctx->lexer);
991 /* Parse function. */
992 enum ctables_summary_function function;
993 if (!parse_ctables_summary_function (ctx->lexer, &function))
996 /* Parse percentile. */
997 double percentile = 0;
998 if (function == CTSF_PTILE)
1000 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1002 percentile = lex_number (ctx->lexer);
1003 lex_get (ctx->lexer);
1008 if (lex_is_string (ctx->lexer))
1010 label = ss_xstrdup (lex_tokss (ctx->lexer));
1011 lex_get (ctx->lexer);
1014 label = ctables_summary_default_label (function, percentile);
1017 struct fmt_spec format;
1018 const struct fmt_spec *formatp;
1019 if (lex_token (ctx->lexer) == T_ID
1020 && has_digit (lex_tokcstr (ctx->lexer)))
1022 if (!parse_format_specifier (ctx->lexer, &format)
1023 || !fmt_check_output (&format)
1024 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1034 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1035 lex_ofs (ctx->lexer) - 1);
1036 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1038 msg_location_destroy (loc);
1040 lex_match (ctx->lexer, T_COMMA);
1041 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1043 if (!lex_force_match (ctx->lexer, T_LBRACK))
1047 else if (lex_match (ctx->lexer, T_RBRACK))
1049 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1056 ctables_axis_destroy (sub);
1060 static const struct ctables_axis *
1061 find_scale (const struct ctables_axis *axis)
1065 else if (axis->op == CTAO_VAR)
1069 assert (!axis->var.is_mrset);
1077 for (size_t i = 0; i < 2; i++)
1079 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1087 static const struct ctables_axis *
1088 find_categorical_summary_spec (const struct ctables_axis *axis)
1092 else if (axis->op == CTAO_VAR)
1093 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1096 for (size_t i = 0; i < 2; i++)
1098 const struct ctables_axis *sum
1099 = find_categorical_summary_spec (axis->subs[i]);
1107 static struct ctables_axis *
1108 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1110 int start_ofs = lex_ofs (ctx->lexer);
1111 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1115 while (lex_match (ctx->lexer, T_GT))
1117 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1121 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1122 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1124 const struct ctables_axis *outer_scale = find_scale (lhs);
1125 const struct ctables_axis *inner_scale = find_scale (rhs);
1126 if (outer_scale && inner_scale)
1128 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1129 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1130 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1131 ctables_axis_destroy (nest);
1135 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1138 msg_at (SE, nest->loc,
1139 _("Summaries may only be requested for categorical variables "
1140 "at the innermost nesting level."));
1141 msg_at (SN, outer_sum->loc,
1142 _("This outer categorical variable has a summary."));
1143 ctables_axis_destroy (nest);
1153 static struct ctables_axis *
1154 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1156 int start_ofs = lex_ofs (ctx->lexer);
1157 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1161 while (lex_match (ctx->lexer, T_PLUS))
1163 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1167 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1168 ctx->lexer, start_ofs);
1175 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1176 struct ctables *ct, struct ctables_table *t,
1177 enum pivot_axis_type a)
1179 if (lex_token (lexer) == T_BY
1180 || lex_token (lexer) == T_SLASH
1181 || lex_token (lexer) == T_ENDCMD)
1184 struct ctables_axis_parse_ctx ctx = {
1190 t->axes[a] = ctables_axis_parse_stack (&ctx);
1191 return t->axes[a] != NULL;
1195 ctables_chisq_destroy (struct ctables_chisq *chisq)
1201 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1207 ctables_table_destroy (struct ctables_table *t)
1212 for (size_t i = 0; i < t->n_categories; i++)
1213 ctables_categories_unref (t->categories[i]);
1214 free (t->categories);
1216 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1217 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1218 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1222 ctables_chisq_destroy (t->chisq);
1223 ctables_pairwise_destroy (t->pairwise);
1228 ctables_destroy (struct ctables *ct)
1233 pivot_table_look_unref (ct->look);
1237 for (size_t i = 0; i < ct->n_tables; i++)
1238 ctables_table_destroy (ct->tables[i]);
1243 static struct ctables_category
1244 cct_range (double low, double high)
1246 return (struct ctables_category) {
1248 .range = { low, high }
1253 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1254 struct ctables_table *t)
1256 if (!lex_match_id (lexer, "VARIABLES"))
1258 lex_match (lexer, T_EQUALS);
1260 struct variable **vars;
1262 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1265 struct ctables_categories *c = xmalloc (sizeof *c);
1266 *c = (struct ctables_categories) { .n_refs = n_vars };
1267 for (size_t i = 0; i < n_vars; i++)
1269 struct ctables_categories **cp
1270 = &t->categories[var_get_dict_index (vars[i])];
1271 ctables_categories_unref (*cp);
1276 size_t allocated_cats = 0;
1277 if (lex_match (lexer, T_LBRACK))
1281 if (c->n_cats >= allocated_cats)
1282 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1284 struct ctables_category *cat = &c->cats[c->n_cats];
1285 if (lex_match_id (lexer, "OTHERNM"))
1286 cat->type = CCT_OTHERNM;
1287 else if (lex_match_id (lexer, "MISSING"))
1288 cat->type = CCT_MISSING;
1289 else if (lex_match_id (lexer, "SUBTOTAL"))
1290 *cat = (struct ctables_category)
1291 { .type = CCT_SUBTOTAL, .total_label = NULL };
1292 else if (lex_match_id (lexer, "HSUBTOTAL"))
1293 *cat = (struct ctables_category)
1294 { .type = CCT_HSUBTOTAL, .total_label = NULL };
1295 else if (lex_match_id (lexer, "LO"))
1297 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1299 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1302 else if (lex_is_number (lexer))
1304 double number = lex_number (lexer);
1306 if (lex_match_id (lexer, "THRU"))
1308 cat->type = CCT_RANGE;
1309 cat->range[0] = number;
1310 if (lex_match_id (lexer, "HI"))
1311 *cat = cct_range (number, DBL_MAX);
1314 if (!lex_force_num (lexer))
1316 *cat = cct_range (number, lex_number (lexer));
1321 *cat = (struct ctables_category) {
1326 else if (lex_is_string (lexer))
1328 *cat = (struct ctables_category) {
1330 .string = ss_xstrdup (lex_tokss (lexer)),
1336 lex_error (lexer, NULL);
1340 if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1342 if (lex_match (lexer, T_EQUALS))
1344 if (!lex_force_string (lexer))
1347 cat->total_label = ss_xstrdup (lex_tokss (lexer));
1351 cat->total_label = xstrdup (_("Subtotal"));
1355 lex_match (lexer, T_COMMA);
1357 while (!lex_match (lexer, T_RBRACK));
1360 struct ctables_category cat = {
1362 .include_missing = false,
1363 .sort_ascending = true,
1365 bool show_totals = false;
1366 char *total_label = NULL;
1367 bool totals_before = false;
1368 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1370 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1372 lex_match (lexer, T_EQUALS);
1373 if (lex_match_id (lexer, "A"))
1374 cat.sort_ascending = true;
1375 else if (lex_match_id (lexer, "D"))
1376 cat.sort_ascending = false;
1379 lex_error_expecting (lexer, "A", "D");
1383 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1385 lex_match (lexer, T_EQUALS);
1386 if (lex_match_id (lexer, "VALUE"))
1387 cat.type = CCT_VALUE;
1388 else if (lex_match_id (lexer, "LABEL"))
1389 cat.type = CCT_LABEL;
1392 cat.type = CCT_FUNCTION;
1393 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1396 if (lex_match (lexer, T_LPAREN))
1398 cat.sort_var = parse_variable (lexer, dict);
1402 if (cat.sort_function == CTSF_PTILE)
1404 lex_match (lexer, T_COMMA);
1405 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1407 cat.percentile = lex_number (lexer);
1411 if (!lex_force_match (lexer, T_RPAREN))
1414 else if (ctables_function_availability (cat.sort_function)
1417 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1422 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1424 lex_match (lexer, T_EQUALS);
1425 if (lex_match_id (lexer, "INCLUDE"))
1426 cat.include_missing = true;
1427 else if (lex_match_id (lexer, "EXCLUDE"))
1428 cat.include_missing = false;
1431 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1435 else if (lex_match_id (lexer, "TOTAL"))
1437 lex_match (lexer, T_EQUALS);
1438 if (!parse_bool (lexer, &show_totals))
1441 else if (lex_match_id (lexer, "LABEL"))
1443 lex_match (lexer, T_EQUALS);
1444 if (!lex_force_string (lexer))
1447 total_label = ss_xstrdup (lex_tokss (lexer));
1450 else if (lex_match_id (lexer, "POSITION"))
1452 lex_match (lexer, T_EQUALS);
1453 if (lex_match_id (lexer, "BEFORE"))
1454 totals_before = true;
1455 else if (lex_match_id (lexer, "AFTER"))
1456 totals_before = false;
1459 lex_error_expecting (lexer, "BEFORE", "AFTER");
1463 else if (lex_match_id (lexer, "EMPTY"))
1465 lex_match (lexer, T_EQUALS);
1466 if (lex_match_id (lexer, "INCLUDE"))
1467 c->show_empty = true;
1468 else if (lex_match_id (lexer, "EXCLUDE"))
1469 c->show_empty = false;
1472 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1479 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1480 "TOTAL", "LABEL", "POSITION", "EMPTY");
1482 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1489 if (c->n_cats >= allocated_cats)
1490 c->cats = x2nrealloc (c->cats, &allocated_cats,
1492 c->cats[c->n_cats++] = cat;
1497 if (c->n_cats >= allocated_cats)
1498 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1500 struct ctables_category *totals;
1503 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1504 totals = &c->cats[0];
1507 totals = &c->cats[c->n_cats];
1510 *totals = (struct ctables_category) {
1512 .total_label = total_label ? total_label : xstrdup (_("Total")),
1516 struct ctables_category *subtotal = NULL;
1517 for (size_t i = totals_before ? 0 : c->n_cats;
1518 totals_before ? i < c->n_cats : i-- > 0;
1519 totals_before ? i++ : 0)
1521 struct ctables_category *cat = &c->cats[i];
1529 cat->subtotal = subtotal;
1549 ctables_nest_uninit (struct ctables_nest *nest)
1556 ctables_stack_uninit (struct ctables_stack *stack)
1560 for (size_t i = 0; i < stack->n; i++)
1561 ctables_nest_uninit (&stack->nests[i]);
1562 free (stack->nests);
1566 static struct ctables_stack
1567 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1574 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1575 for (size_t i = 0; i < s0.n; i++)
1576 for (size_t j = 0; j < s1.n; j++)
1578 const struct ctables_nest *a = &s0.nests[i];
1579 const struct ctables_nest *b = &s1.nests[j];
1581 size_t allocate = a->n + b->n;
1582 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1583 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1585 for (size_t k = 0; k < a->n; k++)
1586 vars[n++] = a->vars[k];
1587 for (size_t k = 0; k < b->n; k++)
1588 vars[n++] = b->vars[k];
1589 assert (n == allocate);
1591 const struct ctables_nest *summary_src;
1592 if (!a->specs[CSV_CELL].var)
1594 else if (!b->specs[CSV_CELL].var)
1599 struct ctables_nest *new = &stack.nests[stack.n++];
1600 *new = (struct ctables_nest) {
1602 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1603 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1607 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1608 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1610 ctables_stack_uninit (&s0);
1611 ctables_stack_uninit (&s1);
1615 static struct ctables_stack
1616 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1618 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1619 for (size_t i = 0; i < s0.n; i++)
1620 stack.nests[stack.n++] = s0.nests[i];
1621 for (size_t i = 0; i < s1.n; i++)
1622 stack.nests[stack.n++] = s1.nests[i];
1623 assert (stack.n == s0.n + s1.n);
1629 static struct ctables_stack
1630 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1633 return (struct ctables_stack) { .n = 0 };
1638 assert (!a->var.is_mrset);
1640 struct variable **vars = xmalloc (sizeof *vars);
1643 struct ctables_nest *nest = xmalloc (sizeof *nest);
1644 *nest = (struct ctables_nest) {
1647 .scale_idx = a->scale ? 0 : SIZE_MAX,
1649 if (a->specs[CSV_CELL].n || a->scale)
1650 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1652 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1653 nest->specs[sv].var = a->var.var;
1655 return (struct ctables_stack) { .nests = nest, .n = 1 };
1658 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1659 enumerate_fts (axis_type, a->subs[1]));
1662 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1663 enumerate_fts (axis_type, a->subs[1]));
1669 union ctables_summary
1671 /* COUNT, VALIDN, TOTALN. */
1678 /* MINIMUM, MAXIMUM, RANGE. */
1685 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1686 struct moments1 *moments;
1690 struct casewriter *writer;
1695 /* XXX percentiles, mode, multiple response */
1699 ctables_summary_init (union ctables_summary *s,
1700 const struct ctables_summary_spec *ss)
1702 switch (ss->function)
1706 case CTSF_ROWPCT_COUNT:
1707 case CTSF_COLPCT_COUNT:
1708 case CTSF_TABLEPCT_COUNT:
1709 case CTSF_SUBTABLEPCT_COUNT:
1710 case CTSF_LAYERPCT_COUNT:
1711 case CTSF_LAYERROWPCT_COUNT:
1712 case CTSF_LAYERCOLPCT_COUNT:
1713 case CTSF_ROWPCT_VALIDN:
1714 case CTSF_COLPCT_VALIDN:
1715 case CTSF_TABLEPCT_VALIDN:
1716 case CTSF_SUBTABLEPCT_VALIDN:
1717 case CTSF_LAYERPCT_VALIDN:
1718 case CTSF_LAYERROWPCT_VALIDN:
1719 case CTSF_LAYERCOLPCT_VALIDN:
1720 case CTSF_ROWPCT_TOTALN:
1721 case CTSF_COLPCT_TOTALN:
1722 case CTSF_TABLEPCT_TOTALN:
1723 case CTSF_SUBTABLEPCT_TOTALN:
1724 case CTSF_LAYERPCT_TOTALN:
1725 case CTSF_LAYERROWPCT_TOTALN:
1726 case CTSF_LAYERCOLPCT_TOTALN:
1732 s->missing = s->valid = 0;
1738 s->min = s->max = SYSMIS;
1746 case CTSF_ROWPCT_SUM:
1747 case CTSF_COLPCT_SUM:
1748 case CTSF_TABLEPCT_SUM:
1749 case CTSF_SUBTABLEPCT_SUM:
1750 case CTSF_LAYERPCT_SUM:
1751 case CTSF_LAYERROWPCT_SUM:
1752 case CTSF_LAYERCOLPCT_SUM:
1753 s->moments = moments1_create (MOMENT_VARIANCE);
1758 struct caseproto *proto = caseproto_create ();
1759 proto = caseproto_add_width (proto, 0);
1760 proto = caseproto_add_width (proto, 0);
1762 struct subcase ordering;
1763 subcase_init (&ordering, 0, 0, SC_ASCEND);
1764 s->writer = sort_create_writer (&ordering, proto);
1765 subcase_uninit (&ordering);
1766 caseproto_unref (proto);
1777 case CTSF_RESPONSES:
1778 case CTSF_ROWPCT_RESPONSES:
1779 case CTSF_COLPCT_RESPONSES:
1780 case CTSF_TABLEPCT_RESPONSES:
1781 case CTSF_SUBTABLEPCT_RESPONSES:
1782 case CTSF_LAYERPCT_RESPONSES:
1783 case CTSF_LAYERROWPCT_RESPONSES:
1784 case CTSF_LAYERCOLPCT_RESPONSES:
1785 case CTSF_ROWPCT_RESPONSES_COUNT:
1786 case CTSF_COLPCT_RESPONSES_COUNT:
1787 case CTSF_TABLEPCT_RESPONSES_COUNT:
1788 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1789 case CTSF_LAYERPCT_RESPONSES_COUNT:
1790 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1791 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1792 case CTSF_ROWPCT_COUNT_RESPONSES:
1793 case CTSF_COLPCT_COUNT_RESPONSES:
1794 case CTSF_TABLEPCT_COUNT_RESPONSES:
1795 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1796 case CTSF_LAYERPCT_COUNT_RESPONSES:
1797 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1798 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1804 ctables_summary_uninit (union ctables_summary *s,
1805 const struct ctables_summary_spec *ss)
1807 switch (ss->function)
1811 case CTSF_ROWPCT_COUNT:
1812 case CTSF_COLPCT_COUNT:
1813 case CTSF_TABLEPCT_COUNT:
1814 case CTSF_SUBTABLEPCT_COUNT:
1815 case CTSF_LAYERPCT_COUNT:
1816 case CTSF_LAYERROWPCT_COUNT:
1817 case CTSF_LAYERCOLPCT_COUNT:
1818 case CTSF_ROWPCT_VALIDN:
1819 case CTSF_COLPCT_VALIDN:
1820 case CTSF_TABLEPCT_VALIDN:
1821 case CTSF_SUBTABLEPCT_VALIDN:
1822 case CTSF_LAYERPCT_VALIDN:
1823 case CTSF_LAYERROWPCT_VALIDN:
1824 case CTSF_LAYERCOLPCT_VALIDN:
1825 case CTSF_ROWPCT_TOTALN:
1826 case CTSF_COLPCT_TOTALN:
1827 case CTSF_TABLEPCT_TOTALN:
1828 case CTSF_SUBTABLEPCT_TOTALN:
1829 case CTSF_LAYERPCT_TOTALN:
1830 case CTSF_LAYERROWPCT_TOTALN:
1831 case CTSF_LAYERCOLPCT_TOTALN:
1849 case CTSF_ROWPCT_SUM:
1850 case CTSF_COLPCT_SUM:
1851 case CTSF_TABLEPCT_SUM:
1852 case CTSF_SUBTABLEPCT_SUM:
1853 case CTSF_LAYERPCT_SUM:
1854 case CTSF_LAYERROWPCT_SUM:
1855 case CTSF_LAYERCOLPCT_SUM:
1856 moments1_destroy (s->moments);
1860 casewriter_destroy (s->writer);
1867 case CTSF_RESPONSES:
1868 case CTSF_ROWPCT_RESPONSES:
1869 case CTSF_COLPCT_RESPONSES:
1870 case CTSF_TABLEPCT_RESPONSES:
1871 case CTSF_SUBTABLEPCT_RESPONSES:
1872 case CTSF_LAYERPCT_RESPONSES:
1873 case CTSF_LAYERROWPCT_RESPONSES:
1874 case CTSF_LAYERCOLPCT_RESPONSES:
1875 case CTSF_ROWPCT_RESPONSES_COUNT:
1876 case CTSF_COLPCT_RESPONSES_COUNT:
1877 case CTSF_TABLEPCT_RESPONSES_COUNT:
1878 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1879 case CTSF_LAYERPCT_RESPONSES_COUNT:
1880 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1881 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1882 case CTSF_ROWPCT_COUNT_RESPONSES:
1883 case CTSF_COLPCT_COUNT_RESPONSES:
1884 case CTSF_TABLEPCT_COUNT_RESPONSES:
1885 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1886 case CTSF_LAYERPCT_COUNT_RESPONSES:
1887 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1888 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1894 ctables_summary_add (union ctables_summary *s,
1895 const struct ctables_summary_spec *ss,
1896 const struct variable *var, const union value *value,
1899 switch (ss->function)
1903 case CTSF_ROWPCT_COUNT:
1904 case CTSF_COLPCT_COUNT:
1905 case CTSF_TABLEPCT_COUNT:
1906 case CTSF_SUBTABLEPCT_COUNT:
1907 case CTSF_LAYERPCT_COUNT:
1908 case CTSF_LAYERROWPCT_COUNT:
1909 case CTSF_LAYERCOLPCT_COUNT:
1910 case CTSF_ROWPCT_VALIDN:
1911 case CTSF_COLPCT_VALIDN:
1912 case CTSF_TABLEPCT_VALIDN:
1913 case CTSF_SUBTABLEPCT_VALIDN:
1914 case CTSF_LAYERPCT_VALIDN:
1915 case CTSF_LAYERROWPCT_VALIDN:
1916 case CTSF_LAYERCOLPCT_VALIDN:
1917 case CTSF_ROWPCT_TOTALN:
1918 case CTSF_COLPCT_TOTALN:
1919 case CTSF_TABLEPCT_TOTALN:
1920 case CTSF_SUBTABLEPCT_TOTALN:
1921 case CTSF_LAYERPCT_TOTALN:
1922 case CTSF_LAYERROWPCT_TOTALN:
1923 case CTSF_LAYERCOLPCT_TOTALN:
1929 if (var_is_value_missing (var, value))
1930 s->missing += weight;
1938 if (!var_is_value_missing (var, value))
1940 assert (!var_is_alpha (var)); /* XXX? */
1941 if (s->min == SYSMIS || value->f < s->min)
1943 if (s->max == SYSMIS || value->f > s->max)
1953 case CTSF_ROWPCT_SUM:
1954 case CTSF_COLPCT_SUM:
1955 case CTSF_TABLEPCT_SUM:
1956 case CTSF_SUBTABLEPCT_SUM:
1957 case CTSF_LAYERPCT_SUM:
1958 case CTSF_LAYERROWPCT_SUM:
1959 case CTSF_LAYERCOLPCT_SUM:
1960 if (!var_is_value_missing (var, value))
1961 moments1_add (s->moments, value->f, weight);
1965 if (var_is_value_missing (var, value))
1967 s->mvalid += weight;
1969 struct ccase *c = case_create (casewriter_get_proto (s->writer));
1970 *case_num_rw_idx (c, 0) = value->f;
1971 *case_num_rw_idx (c, 1) = weight;
1972 casewriter_write (s->writer, c);
1980 case CTSF_RESPONSES:
1981 case CTSF_ROWPCT_RESPONSES:
1982 case CTSF_COLPCT_RESPONSES:
1983 case CTSF_TABLEPCT_RESPONSES:
1984 case CTSF_SUBTABLEPCT_RESPONSES:
1985 case CTSF_LAYERPCT_RESPONSES:
1986 case CTSF_LAYERROWPCT_RESPONSES:
1987 case CTSF_LAYERCOLPCT_RESPONSES:
1988 case CTSF_ROWPCT_RESPONSES_COUNT:
1989 case CTSF_COLPCT_RESPONSES_COUNT:
1990 case CTSF_TABLEPCT_RESPONSES_COUNT:
1991 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1992 case CTSF_LAYERPCT_RESPONSES_COUNT:
1993 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1994 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1995 case CTSF_ROWPCT_COUNT_RESPONSES:
1996 case CTSF_COLPCT_COUNT_RESPONSES:
1997 case CTSF_TABLEPCT_COUNT_RESPONSES:
1998 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1999 case CTSF_LAYERPCT_COUNT_RESPONSES:
2000 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2001 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2007 ctables_summary_value (const struct ctables_cell *cell,
2008 union ctables_summary *s,
2009 const struct ctables_summary_spec *ss)
2011 switch (ss->function)
2017 case CTSF_SUBTABLEPCT_COUNT:
2018 return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
2020 case CTSF_ROWPCT_COUNT:
2021 return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
2023 case CTSF_COLPCT_COUNT:
2024 return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
2026 case CTSF_TABLEPCT_COUNT:
2027 return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
2029 case CTSF_LAYERPCT_COUNT:
2030 return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
2032 case CTSF_LAYERROWPCT_COUNT:
2033 return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
2035 case CTSF_LAYERCOLPCT_COUNT:
2036 return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
2038 case CTSF_ROWPCT_VALIDN:
2039 case CTSF_COLPCT_VALIDN:
2040 case CTSF_TABLEPCT_VALIDN:
2041 case CTSF_SUBTABLEPCT_VALIDN:
2042 case CTSF_LAYERPCT_VALIDN:
2043 case CTSF_LAYERROWPCT_VALIDN:
2044 case CTSF_LAYERCOLPCT_VALIDN:
2045 case CTSF_ROWPCT_TOTALN:
2046 case CTSF_COLPCT_TOTALN:
2047 case CTSF_TABLEPCT_TOTALN:
2048 case CTSF_SUBTABLEPCT_TOTALN:
2049 case CTSF_LAYERPCT_TOTALN:
2050 case CTSF_LAYERROWPCT_TOTALN:
2051 case CTSF_LAYERCOLPCT_TOTALN:
2059 return s->valid + s->missing;
2072 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2077 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2083 double weight, variance;
2084 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2085 return calc_semean (variance, weight);
2091 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2092 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2097 double weight, mean;
2098 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2099 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2105 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2109 case CTSF_ROWPCT_SUM:
2110 case CTSF_COLPCT_SUM:
2111 case CTSF_TABLEPCT_SUM:
2112 case CTSF_SUBTABLEPCT_SUM:
2113 case CTSF_LAYERPCT_SUM:
2114 case CTSF_LAYERROWPCT_SUM:
2115 case CTSF_LAYERCOLPCT_SUM:
2121 struct casereader *reader = casewriter_make_reader (s->writer);
2124 struct percentile *median = percentile_create (0.5, s->mvalid);
2125 struct order_stats *os = &median->parent;
2126 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2127 s->median = percentile_calculate (median, PC_HAVERAGE);
2128 statistic_destroy (&median->parent.parent);
2136 case CTSF_RESPONSES:
2137 case CTSF_ROWPCT_RESPONSES:
2138 case CTSF_COLPCT_RESPONSES:
2139 case CTSF_TABLEPCT_RESPONSES:
2140 case CTSF_SUBTABLEPCT_RESPONSES:
2141 case CTSF_LAYERPCT_RESPONSES:
2142 case CTSF_LAYERROWPCT_RESPONSES:
2143 case CTSF_LAYERCOLPCT_RESPONSES:
2144 case CTSF_ROWPCT_RESPONSES_COUNT:
2145 case CTSF_COLPCT_RESPONSES_COUNT:
2146 case CTSF_TABLEPCT_RESPONSES_COUNT:
2147 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2148 case CTSF_LAYERPCT_RESPONSES_COUNT:
2149 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2150 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2151 case CTSF_ROWPCT_COUNT_RESPONSES:
2152 case CTSF_COLPCT_COUNT_RESPONSES:
2153 case CTSF_TABLEPCT_COUNT_RESPONSES:
2154 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2155 case CTSF_LAYERPCT_COUNT_RESPONSES:
2156 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2157 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2164 struct ctables_cell_sort_aux
2166 const struct ctables_table *t;
2167 enum pivot_axis_type a;
2171 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2173 const struct ctables_cell_sort_aux *aux = aux_;
2174 struct ctables_cell *const *ap = a_;
2175 struct ctables_cell *const *bp = b_;
2176 const struct ctables_cell *a = *ap;
2177 const struct ctables_cell *b = *bp;
2179 size_t a_idx = a->axes[aux->a].nest_idx;
2180 size_t b_idx = b->axes[aux->a].nest_idx;
2182 return a_idx < b_idx ? -1 : 1;
2184 const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2185 for (size_t i = 0; i < nest->n; i++)
2186 if (i != nest->scale_idx)
2188 const struct variable *var = nest->vars[i];
2189 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2190 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2191 if (a_cv->category != b_cv->category)
2192 return a_cv->category > b_cv->category ? 1 : -1;
2194 const union value *a_val = &a_cv->value;
2195 const union value *b_val = &b_cv->value;
2196 switch (a_cv->category->type)
2203 /* Must be equal. */
2210 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2218 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2220 return a_cv->category->sort_ascending ? cmp : -cmp;
2226 const char *a_label = var_lookup_value_label (var, a_val);
2227 const char *b_label = var_lookup_value_label (var, b_val);
2229 ? (b_label ? strcmp (a_label, b_label) : 1)
2230 : (b_label ? -1 : value_compare_3way (
2231 a_val, b_val, var_get_width (var))));
2233 return a_cv->category->sort_ascending ? cmp : -cmp;
2247 For each ctables_table:
2248 For each combination of row vars:
2249 For each combination of column vars:
2250 For each combination of layer vars:
2252 Make a table of row values:
2253 Sort entries by row values
2254 Assign a 0-based index to each actual value
2255 Construct a dimension
2256 Make a table of column values
2257 Make a table of layer values
2259 Fill the table entry using the indexes from before.
2262 static struct ctables_domain *
2263 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2264 enum ctables_domain_type domain)
2267 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2269 size_t idx = cell->axes[a].nest_idx;
2270 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2271 hash = hash_int (idx, hash);
2272 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2274 size_t v_idx = nest->domains[domain][i];
2275 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2276 var_get_width (nest->vars[v_idx]), hash);
2280 struct ctables_domain *d;
2281 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2283 const struct ctables_cell *df = d->example;
2284 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2286 size_t idx = cell->axes[a].nest_idx;
2287 if (idx != df->axes[a].nest_idx)
2290 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2291 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2293 size_t v_idx = nest->domains[domain][i];
2294 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2295 &cell->axes[a].cvs[v_idx].value,
2296 var_get_width (nest->vars[v_idx])))
2305 d = xmalloc (sizeof *d);
2306 *d = (struct ctables_domain) { .example = cell };
2307 hmap_insert (&t->domains[domain], &d->node, hash);
2311 static const struct ctables_category *
2312 ctables_categories_match (const struct ctables_categories *c,
2313 const union value *v, const struct variable *var)
2315 const struct ctables_category *othernm = NULL;
2316 for (size_t i = c->n_cats; i-- > 0; )
2318 const struct ctables_category *cat = &c->cats[i];
2322 if (cat->number == v->f)
2330 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2331 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2336 if (var_is_value_missing (var, v))
2353 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2358 return var_is_value_missing (var, v) ? NULL : othernm;
2361 static const struct ctables_category *
2362 ctables_categories_total (const struct ctables_categories *c)
2364 const struct ctables_category *first = &c->cats[0];
2365 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2366 return (first->type == CCT_TOTAL ? first
2367 : last->type == CCT_TOTAL ? last
2371 static struct ctables_cell *
2372 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2373 size_t ix[PIVOT_N_AXES],
2374 const struct ctables_category *cats[PIVOT_N_AXES][10])
2376 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2379 enum ctables_summary_variant sv = CSV_CELL;
2380 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2382 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2383 hash = hash_int (ix[a], hash);
2384 for (size_t i = 0; i < nest->n; i++)
2385 if (i != nest->scale_idx)
2387 hash = hash_pointer (cats[a][i], hash);
2388 if (cats[a][i]->type != CCT_TOTAL
2389 && cats[a][i]->type != CCT_SUBTOTAL
2390 && cats[a][i]->type != CCT_HSUBTOTAL)
2391 hash = value_hash (case_data (c, nest->vars[i]),
2392 var_get_width (nest->vars[i]), hash);
2398 struct ctables_cell *cell;
2399 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2401 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2403 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2404 if (cell->axes[a].nest_idx != ix[a])
2406 for (size_t i = 0; i < nest->n; i++)
2407 if (i != nest->scale_idx
2408 && (cats[a][i] != cell->axes[a].cvs[i].category
2409 || (cats[a][i]->type != CCT_TOTAL
2410 && cats[a][i]->type != CCT_SUBTOTAL
2411 && cats[a][i]->type != CCT_HSUBTOTAL
2412 && !value_equal (case_data (c, nest->vars[i]),
2413 &cell->axes[a].cvs[i].value,
2414 var_get_width (nest->vars[i])))))
2423 cell = xmalloc (sizeof *cell);
2426 cell->contributes_to_domains = true;
2427 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2429 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2430 cell->axes[a].nest_idx = ix[a];
2431 cell->axes[a].cvs = (nest->n
2432 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2434 for (size_t i = 0; i < nest->n; i++)
2436 const struct ctables_category *cat = cats[a][i];
2438 if (i != nest->scale_idx)
2440 const struct ctables_category *subtotal = cat->subtotal;
2441 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2444 if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2445 cell->contributes_to_domains = false;
2448 cell->axes[a].cvs[i].category = cat;
2449 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2450 var_get_width (nest->vars[i]));
2454 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2455 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2456 for (size_t i = 0; i < specs->n; i++)
2457 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2458 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2459 cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2460 hmap_insert (&t->cells, &cell->node, hash);
2465 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2466 size_t ix[PIVOT_N_AXES],
2467 const struct ctables_category *cats[PIVOT_N_AXES][10],
2470 struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2471 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2473 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2474 for (size_t i = 0; i < specs->n; i++)
2475 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2476 case_data (c, specs->var), weight);
2477 if (cell->contributes_to_domains)
2478 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2479 cell->domains[dt]->valid += weight;
2483 recurse_totals (struct ctables_table *t, const struct ccase *c,
2484 size_t ix[PIVOT_N_AXES],
2485 const struct ctables_category *cats[PIVOT_N_AXES][10],
2487 enum pivot_axis_type start_axis, size_t start_nest)
2489 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2491 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2492 for (size_t i = start_nest; i < nest->n; i++)
2494 if (i == nest->scale_idx)
2497 const struct variable *var = nest->vars[i];
2499 const struct ctables_category *total = ctables_categories_total (
2500 t->categories[var_get_dict_index (var)]);
2503 const struct ctables_category *save = cats[a][i];
2505 ctables_cell_add__ (t, c, ix, cats, weight);
2506 recurse_totals (t, c, ix, cats, weight, a, i + 1);
2515 recurse_subtotals (struct ctables_table *t, const struct ccase *c,
2516 size_t ix[PIVOT_N_AXES],
2517 const struct ctables_category *cats[PIVOT_N_AXES][10],
2519 enum pivot_axis_type start_axis, size_t start_nest)
2521 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2523 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2524 for (size_t i = start_nest; i < nest->n; i++)
2526 if (i == nest->scale_idx)
2529 const struct ctables_category *save = cats[a][i];
2532 cats[a][i] = save->subtotal;
2533 ctables_cell_add__ (t, c, ix, cats, weight);
2534 recurse_subtotals (t, c, ix, cats, weight, a, i + 1);
2543 ctables_cell_insert (struct ctables_table *t,
2544 const struct ccase *c,
2545 size_t ir, size_t ic, size_t il,
2548 size_t ix[PIVOT_N_AXES] = {
2549 [PIVOT_AXIS_ROW] = ir,
2550 [PIVOT_AXIS_COLUMN] = ic,
2551 [PIVOT_AXIS_LAYER] = il,
2554 const struct ctables_category *cats[PIVOT_N_AXES][10];
2555 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2557 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2558 for (size_t i = 0; i < nest->n; i++)
2560 if (i == nest->scale_idx)
2563 const struct variable *var = nest->vars[i];
2564 const union value *value = case_data (c, var);
2566 if (var_is_numeric (var) && value->f == SYSMIS)
2569 cats[a][i] = ctables_categories_match (
2570 t->categories[var_get_dict_index (var)], value, var);
2576 ctables_cell_add__ (t, c, ix, cats, weight);
2578 recurse_totals (t, c, ix, cats, weight, 0, 0);
2579 recurse_subtotals (t, c, ix, cats, weight, 0, 0);
2584 const struct ctables_summary_spec_set *set;
2589 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2591 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2592 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2593 if (as->function != bs->function)
2594 return as->function > bs->function ? 1 : -1;
2595 else if (as->percentile != bs->percentile)
2596 return as->percentile < bs->percentile ? 1 : -1;
2597 return strcmp (as->label, bs->label);
2600 static struct pivot_value *
2601 ctables_category_create_label (const struct ctables_category *cat,
2602 const struct variable *var,
2603 const union value *value)
2605 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2606 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2607 : pivot_value_new_var_value (var, value));
2610 static struct ctables_value *
2611 ctables_value_find__ (struct ctables_table *t, const union value *value,
2612 int width, unsigned int hash)
2614 struct ctables_value *clv;
2615 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2616 hash, &t->clabels_values_map)
2617 if (value_equal (value, &clv->value, width))
2622 static struct ctables_value *
2623 ctables_value_find (struct ctables_table *t,
2624 const union value *value, int width)
2626 return ctables_value_find__ (t, value, width,
2627 value_hash (value, width, 0));
2631 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2633 struct pivot_table *pt = pivot_table_create__ (
2635 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2636 : pivot_value_new_text (N_("Custom Tables"))),
2639 pivot_table_set_caption (
2640 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2642 pivot_table_set_caption (
2643 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2645 bool summary_dimension = (t->summary_axis != t->slabels_axis
2646 || (!t->slabels_visible
2647 && t->summary_specs.n > 1));
2648 if (summary_dimension)
2650 struct pivot_dimension *d = pivot_dimension_create (
2651 pt, t->slabels_axis, N_("Statistics"));
2652 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2653 if (!t->slabels_visible)
2654 d->hide_all_labels = true;
2655 for (size_t i = 0; i < specs->n; i++)
2656 pivot_category_create_leaf (
2657 d->root, pivot_value_new_text (specs->specs[i].label));
2660 bool categories_dimension = t->clabels_example != NULL;
2661 if (categories_dimension)
2663 struct pivot_dimension *d = pivot_dimension_create (
2664 pt, t->label_axis[t->clabels_from_axis],
2665 t->clabels_from_axis == PIVOT_AXIS_ROW
2666 ? N_("Row Categories")
2667 : N_("Column Categories"));
2668 const struct variable *var = t->clabels_example;
2669 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2670 for (size_t i = 0; i < t->n_clabels_values; i++)
2672 const struct ctables_value *value = t->clabels_values[i];
2673 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2674 assert (cat != NULL);
2675 pivot_category_create_leaf (d->root, ctables_category_create_label (
2676 cat, t->clabels_example, &value->value));
2680 pivot_table_set_look (pt, ct->look);
2681 struct pivot_dimension *d[PIVOT_N_AXES];
2682 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2684 static const char *names[] = {
2685 [PIVOT_AXIS_ROW] = N_("Rows"),
2686 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2687 [PIVOT_AXIS_LAYER] = N_("Layers"),
2689 d[a] = (t->axes[a] || a == t->summary_axis
2690 ? pivot_dimension_create (pt, a, names[a])
2695 assert (t->axes[a]);
2697 struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2698 size_t n_sorted = 0;
2700 struct ctables_cell *cell;
2701 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2703 sorted[n_sorted++] = cell;
2704 assert (n_sorted <= t->cells.count);
2706 struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2707 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2709 size_t max_depth = 0;
2710 for (size_t j = 0; j < t->stacks[a].n; j++)
2711 if (t->stacks[a].nests[j].n > max_depth)
2712 max_depth = t->stacks[a].nests[j].n;
2714 /* Pivot categories:
2716 - variable label for nest->vars[0], if vlabel != CTVL_NONE
2717 - category for nest->vars[0], if nest->scale_idx != 0
2718 - variable label for nest->vars[1], if vlabel != CTVL_NONE
2719 - category for nest->vars[1], if nest->scale_idx != 1
2721 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2722 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2723 - summary function, if 'a == t->slabels_axis && a ==
2726 Additional dimensions:
2728 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2730 - If 't->label_axis[b] == a' for some 'b != a', add a category
2734 struct ctables_level
2736 enum ctables_level_type
2738 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2739 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2740 CTL_SUMMARY, /* Summary functions. */
2746 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2747 size_t n_levels = 0;
2749 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2751 for (size_t j = 0; j < n_sorted; j++)
2753 struct ctables_cell *cell = sorted[j];
2754 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2755 const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2757 bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2761 for (size_t k = 0; k < nest->n; k++)
2763 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2764 if (vlabel != CTVL_NONE)
2766 levels[n_levels++] = (struct ctables_level) {
2772 if (nest->scale_idx != k
2773 && (k != nest->n - 1 || t->label_axis[a] == a))
2775 levels[n_levels++] = (struct ctables_level) {
2776 .type = CTL_CATEGORY,
2782 if (!summary_dimension && a == t->slabels_axis)
2784 levels[n_levels++] = (struct ctables_level) {
2785 .type = CTL_SUMMARY,
2786 .var_idx = SIZE_MAX,
2791 size_t n_common = 0;
2794 for (; n_common < n_levels; n_common++)
2796 const struct ctables_level *level = &levels[n_common];
2797 if (level->type == CTL_CATEGORY)
2799 size_t var_idx = level->var_idx;
2800 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
2801 if (prev->axes[a].cvs[var_idx].category != c)
2803 else if (c->type != CCT_SUBTOTAL
2804 && c->type != CCT_HSUBTOTAL
2805 && c->type != CCT_TOTAL
2806 && !value_equal (&prev->axes[a].cvs[var_idx].value,
2807 &cell->axes[a].cvs[var_idx].value,
2808 var_get_type (nest->vars[var_idx])))
2814 for (size_t k = n_common; k < n_levels; k++)
2816 const struct ctables_level *level = &levels[k];
2817 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2818 if (level->type == CTL_SUMMARY)
2820 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2821 for (size_t m = 0; m < specs->n; m++)
2823 int leaf = pivot_category_create_leaf (
2824 parent, pivot_value_new_text (specs->specs[m].label));
2831 const struct variable *var = nest->vars[level->var_idx];
2832 struct pivot_value *label;
2833 if (level->type == CTL_VAR)
2834 label = pivot_value_new_variable (var);
2835 else if (level->type == CTL_CATEGORY)
2837 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2838 label = ctables_category_create_label (cv->category,
2844 if (k == n_levels - 1)
2845 prev_leaf = pivot_category_create_leaf (parent, label);
2847 groups[k] = pivot_category_create_group__ (parent, label);
2851 cell->axes[a].leaf = prev_leaf;
2857 struct ctables_cell *cell;
2858 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2863 const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2864 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2865 for (size_t j = 0; j < specs->n; j++)
2868 size_t n_dindexes = 0;
2870 if (summary_dimension)
2871 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2873 if (categories_dimension)
2875 const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2876 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2877 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2878 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2879 assert (ctv != NULL);
2880 dindexes[n_dindexes++] = ctv->leaf;
2883 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2886 int leaf = cell->axes[a].leaf;
2887 if (a == t->summary_axis && !summary_dimension)
2889 dindexes[n_dindexes++] = leaf;
2892 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2893 struct pivot_value *value = pivot_value_new_number (d);
2894 value->numeric.format = specs->specs[j].format;
2895 pivot_table_put (pt, dindexes, n_dindexes, value);
2899 pivot_table_submit (pt);
2903 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2905 enum pivot_axis_type label_pos = t->label_axis[a];
2909 t->clabels_from_axis = a;
2911 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2912 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2914 const struct ctables_stack *stack = &t->stacks[a];
2918 const struct ctables_nest *n0 = &stack->nests[0];
2920 const struct variable *v0 = n0->vars[n0->n - 1];
2921 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2922 t->clabels_example = v0;
2924 for (size_t i = 0; i < c0->n_cats; i++)
2925 if (c0->cats[i].type == CCT_FUNCTION)
2927 msg (SE, _("%s=%s is not allowed with sorting based "
2928 "on a summary function."),
2929 subcommand_name, pos_name);
2932 if (n0->n - 1 == n0->scale_idx)
2934 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2935 "but %s is a scale variable."),
2936 subcommand_name, pos_name, var_get_name (v0));
2940 for (size_t i = 1; i < stack->n; i++)
2942 const struct ctables_nest *ni = &stack->nests[i];
2944 const struct variable *vi = ni->vars[ni->n - 1];
2945 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2947 if (ni->n - 1 == ni->scale_idx)
2949 msg (SE, _("%s=%s requires the variables to be moved to be "
2950 "categorical, but %s is a scale variable."),
2951 subcommand_name, pos_name, var_get_name (vi));
2954 if (var_get_width (v0) != var_get_width (vi))
2956 msg (SE, _("%s=%s requires the variables to be "
2957 "moved to have the same width, but %s has "
2958 "width %d and %s has width %d."),
2959 subcommand_name, pos_name,
2960 var_get_name (v0), var_get_width (v0),
2961 var_get_name (vi), var_get_width (vi));
2964 if (!val_labs_equal (var_get_value_labels (v0),
2965 var_get_value_labels (vi)))
2967 msg (SE, _("%s=%s requires the variables to be "
2968 "moved to have the same value labels, but %s "
2969 "and %s have different value labels."),
2970 subcommand_name, pos_name,
2971 var_get_name (v0), var_get_name (vi));
2974 if (!ctables_categories_equal (c0, ci))
2976 msg (SE, _("%s=%s requires the variables to be "
2977 "moved to have the same category "
2978 "specifications, but %s and %s have different "
2979 "category specifications."),
2980 subcommand_name, pos_name,
2981 var_get_name (v0), var_get_name (vi));
2990 ctables_prepare_table (struct ctables_table *t)
2992 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2995 t->stacks[a] = enumerate_fts (a, t->axes[a]);
2997 for (size_t j = 0; j < t->stacks[a].n; j++)
2999 struct ctables_nest *nest = &t->stacks[a].nests[j];
3000 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3002 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3003 nest->n_domains[dt] = 0;
3005 for (size_t k = 0; k < nest->n; k++)
3007 if (k == nest->scale_idx)
3016 if (a != PIVOT_AXIS_LAYER)
3023 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3024 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3025 : a == PIVOT_AXIS_ROW)
3027 if (k == nest->n - 1
3028 || (nest->scale_idx == nest->n - 1
3029 && k == nest->n - 2))
3035 if (a == PIVOT_AXIS_COLUMN)
3040 if (a == PIVOT_AXIS_ROW)
3045 nest->domains[dt][nest->n_domains[dt]++] = k;
3052 struct ctables_nest *nest = xmalloc (sizeof *nest);
3053 *nest = (struct ctables_nest) { .n = 0 };
3054 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3057 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3058 for (size_t i = 0; i < stack->n; i++)
3060 struct ctables_nest *nest = &stack->nests[i];
3061 if (!nest->specs[CSV_CELL].n)
3063 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3064 specs->specs = xmalloc (sizeof *specs->specs);
3067 enum ctables_summary_function function
3068 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3069 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3071 *specs->specs = (struct ctables_summary_spec) {
3072 .function = function,
3073 .format = ctables_summary_default_format (function, &var),
3074 .label = ctables_summary_default_label (function, 0),
3077 specs->var = nest->vars[0];
3079 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3080 &nest->specs[CSV_CELL]);
3082 else if (!nest->specs[CSV_TOTAL].n)
3083 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3084 &nest->specs[CSV_CELL]);
3087 struct ctables_summary_spec_set *merged = &t->summary_specs;
3088 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3090 for (size_t j = 0; j < stack->n; j++)
3092 const struct ctables_nest *nest = &stack->nests[j];
3094 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3095 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3100 struct merge_item min = items[0];
3101 for (size_t j = 1; j < n_left; j++)
3102 if (merge_item_compare_3way (&items[j], &min) < 0)
3105 if (merged->n >= merged->allocated)
3106 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3107 sizeof *merged->specs);
3108 merged->specs[merged->n++] = min.set->specs[min.ofs];
3110 for (size_t j = 0; j < n_left; )
3112 if (merge_item_compare_3way (&items[j], &min) == 0)
3114 struct merge_item *item = &items[j];
3115 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3116 if (++item->ofs >= item->set->n)
3118 items[j] = items[--n_left];
3127 for (size_t j = 0; j < merged->n; j++)
3128 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3130 for (size_t j = 0; j < stack->n; j++)
3132 const struct ctables_nest *nest = &stack->nests[j];
3133 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3135 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3136 for (size_t k = 0; k < specs->n; k++)
3137 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3138 specs->specs[k].axis_idx);
3144 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3145 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3149 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3150 enum pivot_axis_type a)
3152 struct ctables_stack *stack = &t->stacks[a];
3153 for (size_t i = 0; i < stack->n; i++)
3155 const struct ctables_nest *nest = &stack->nests[i];
3156 const struct variable *var = nest->vars[nest->n - 1];
3157 int width = var_get_width (var);
3158 const union value *value = case_data (c, var);
3160 if (var_is_numeric (var) && value->f == SYSMIS)
3163 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3167 unsigned int hash = value_hash (value, width, 0);
3169 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3172 clv = xmalloc (sizeof *clv);
3173 value_clone (&clv->value, value, width);
3174 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3180 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3182 const struct ctables_value *const *ap = a_;
3183 const struct ctables_value *const *bp = b_;
3184 const struct ctables_value *a = *ap;
3185 const struct ctables_value *b = *bp;
3186 const int *width = width_;
3187 return value_compare_3way (&a->value, &b->value, *width);
3191 ctables_sort_clabels_values (struct ctables_table *t)
3193 int width = var_get_width (t->clabels_example);
3195 size_t n = hmap_count (&t->clabels_values_map);
3196 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3198 struct ctables_value *clv;
3200 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3201 t->clabels_values[i++] = clv;
3202 t->n_clabels_values = n;
3205 sort (t->clabels_values, n, sizeof *t->clabels_values,
3206 compare_clabels_values_3way, &width);
3208 for (size_t i = 0; i < n; i++)
3209 t->clabels_values[i]->leaf = i;
3213 ctables_execute (struct dataset *ds, struct ctables *ct)
3215 struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3218 bool warn_on_invalid = true;
3219 double total_weight = 0;
3220 for (struct ccase *c = casereader_read (input); c;
3221 case_unref (c), c = casereader_read (input))
3223 double weight = dict_get_case_weight (dataset_dict (ds), c,
3225 total_weight += weight;
3227 for (size_t i = 0; i < ct->n_tables; i++)
3229 struct ctables_table *t = ct->tables[i];
3231 for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3232 for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3233 for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3234 ctables_cell_insert (t, c, ir, ic, il, weight);
3236 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3237 if (t->label_axis[a] != a)
3238 ctables_insert_clabels_values (t, c, a);
3241 casereader_destroy (input);
3243 for (size_t i = 0; i < ct->n_tables; i++)
3245 struct ctables_table *t = ct->tables[i];
3247 if (t->clabels_example)
3248 ctables_sort_clabels_values (t);
3250 ctables_table_output (ct, ct->tables[i]);
3252 return proc_commit (ds);
3256 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3258 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3259 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3260 enum settings_value_show tvars = settings_get_show_variables ();
3261 for (size_t i = 0; i < n_vars; i++)
3262 vlabels[i] = (enum ctables_vlabel) tvars;
3264 struct ctables *ct = xmalloc (sizeof *ct);
3265 *ct = (struct ctables) {
3266 .look = pivot_table_look_unshare (pivot_table_look_ref (
3267 pivot_table_look_get_default ())),
3269 .hide_threshold = 5,
3271 ct->look->omit_empty = false;
3273 if (!lex_force_match (lexer, T_SLASH))
3276 while (!lex_match_id (lexer, "TABLE"))
3278 if (lex_match_id (lexer, "FORMAT"))
3280 double widths[2] = { SYSMIS, SYSMIS };
3281 double units_per_inch = 72.0;
3283 while (lex_token (lexer) != T_SLASH)
3285 if (lex_match_id (lexer, "MINCOLWIDTH"))
3287 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3290 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3292 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3295 else if (lex_match_id (lexer, "UNITS"))
3297 lex_match (lexer, T_EQUALS);
3298 if (lex_match_id (lexer, "POINTS"))
3299 units_per_inch = 72.0;
3300 else if (lex_match_id (lexer, "INCHES"))
3301 units_per_inch = 1.0;
3302 else if (lex_match_id (lexer, "CM"))
3303 units_per_inch = 2.54;
3306 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3310 else if (lex_match_id (lexer, "EMPTY"))
3315 lex_match (lexer, T_EQUALS);
3316 if (lex_match_id (lexer, "ZERO"))
3318 /* Nothing to do. */
3320 else if (lex_match_id (lexer, "BLANK"))
3321 ct->zero = xstrdup ("");
3322 else if (lex_force_string (lexer))
3324 ct->zero = ss_xstrdup (lex_tokss (lexer));
3330 else if (lex_match_id (lexer, "MISSING"))
3332 lex_match (lexer, T_EQUALS);
3333 if (!lex_force_string (lexer))
3337 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3338 ? ss_xstrdup (lex_tokss (lexer))
3344 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3345 "UNITS", "EMPTY", "MISSING");
3350 if (widths[0] != SYSMIS && widths[1] != SYSMIS
3351 && widths[0] > widths[1])
3353 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3357 for (size_t i = 0; i < 2; i++)
3358 if (widths[i] != SYSMIS)
3360 int *wr = ct->look->width_ranges[TABLE_HORZ];
3361 wr[i] = widths[i] / units_per_inch * 96.0;
3366 else if (lex_match_id (lexer, "VLABELS"))
3368 if (!lex_force_match_id (lexer, "VARIABLES"))
3370 lex_match (lexer, T_EQUALS);
3372 struct variable **vars;
3374 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3378 if (!lex_force_match_id (lexer, "DISPLAY"))
3383 lex_match (lexer, T_EQUALS);
3385 enum ctables_vlabel vlabel;
3386 if (lex_match_id (lexer, "DEFAULT"))
3387 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3388 else if (lex_match_id (lexer, "NAME"))
3390 else if (lex_match_id (lexer, "LABEL"))
3391 vlabel = CTVL_LABEL;
3392 else if (lex_match_id (lexer, "BOTH"))
3394 else if (lex_match_id (lexer, "NONE"))
3398 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3404 for (size_t i = 0; i < n_vars; i++)
3405 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3408 else if (lex_match_id (lexer, "MRSETS"))
3410 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3412 lex_match (lexer, T_EQUALS);
3413 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3416 else if (lex_match_id (lexer, "SMISSING"))
3418 if (lex_match_id (lexer, "VARIABLE"))
3419 ct->smissing_listwise = false;
3420 else if (lex_match_id (lexer, "LISTWISE"))
3421 ct->smissing_listwise = true;
3424 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3429 else if (lex_match_id (lexer, "WEIGHT"))
3431 if (!lex_force_match_id (lexer, "VARIABLE"))
3433 lex_match (lexer, T_EQUALS);
3434 ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3435 if (!ct->base_weight)
3438 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3440 if (!lex_force_match_id (lexer, "COUNT"))
3442 lex_match (lexer, T_EQUALS);
3443 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3445 ct->hide_threshold = lex_integer (lexer);
3450 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3451 "SMISSING", "PCOMPUTE", "PPROPERTIES",
3452 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3456 if (!lex_force_match (lexer, T_SLASH))
3460 size_t allocated_tables = 0;
3463 if (ct->n_tables >= allocated_tables)
3464 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3465 sizeof *ct->tables);
3467 struct ctables_category *cat = xmalloc (sizeof *cat);
3468 *cat = (struct ctables_category) {
3470 .include_missing = false,
3471 .sort_ascending = true,
3474 struct ctables_categories *c = xmalloc (sizeof *c);
3475 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3476 *c = (struct ctables_categories) {
3482 struct ctables_categories **categories = xnmalloc (n_vars,
3483 sizeof *categories);
3484 for (size_t i = 0; i < n_vars; i++)
3487 struct ctables_table *t = xmalloc (sizeof *t);
3488 *t = (struct ctables_table) {
3489 .cells = HMAP_INITIALIZER (t->cells),
3490 .slabels_axis = PIVOT_AXIS_COLUMN,
3491 .slabels_visible = true,
3492 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3494 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3495 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3496 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3498 .clabels_from_axis = PIVOT_AXIS_LAYER,
3499 .categories = categories,
3500 .n_categories = n_vars,
3503 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3504 hmap_init (&t->domains[dt]);
3505 ct->tables[ct->n_tables++] = t;
3507 lex_match (lexer, T_EQUALS);
3508 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3510 if (lex_match (lexer, T_BY))
3512 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3513 ct, t, PIVOT_AXIS_COLUMN))
3516 if (lex_match (lexer, T_BY))
3518 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3519 ct, t, PIVOT_AXIS_LAYER))
3524 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3525 && !t->axes[PIVOT_AXIS_LAYER])
3527 lex_error (lexer, _("At least one variable must be specified."));
3531 const struct ctables_axis *scales[PIVOT_N_AXES];
3532 size_t n_scales = 0;
3533 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3535 scales[a] = find_scale (t->axes[a]);
3541 msg (SE, _("Scale variables may appear only on one axis."));
3542 if (scales[PIVOT_AXIS_ROW])
3543 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3544 _("This scale variable appears on the rows axis."));
3545 if (scales[PIVOT_AXIS_COLUMN])
3546 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3547 _("This scale variable appears on the columns axis."));
3548 if (scales[PIVOT_AXIS_LAYER])
3549 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3550 _("This scale variable appears on the layer axis."));
3554 const struct ctables_axis *summaries[PIVOT_N_AXES];
3555 size_t n_summaries = 0;
3556 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3558 summaries[a] = (scales[a]
3560 : find_categorical_summary_spec (t->axes[a]));
3564 if (n_summaries > 1)
3566 msg (SE, _("Summaries may appear only on one axis."));
3567 if (summaries[PIVOT_AXIS_ROW])
3568 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3569 _("This variable on the rows axis has a summary."));
3570 if (summaries[PIVOT_AXIS_COLUMN])
3571 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3572 _("This variable on the columns axis has a summary."));
3573 if (summaries[PIVOT_AXIS_LAYER])
3574 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3575 _("This variable on the layers axis has a summary."));
3578 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3579 if (n_summaries ? summaries[a] : t->axes[a])
3581 t->summary_axis = a;
3585 if (lex_token (lexer) == T_ENDCMD)
3587 if (!ctables_prepare_table (t))
3591 if (!lex_force_match (lexer, T_SLASH))
3594 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3596 if (lex_match_id (lexer, "SLABELS"))
3598 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3600 if (lex_match_id (lexer, "POSITION"))
3602 lex_match (lexer, T_EQUALS);
3603 if (lex_match_id (lexer, "COLUMN"))
3604 t->slabels_axis = PIVOT_AXIS_COLUMN;
3605 else if (lex_match_id (lexer, "ROW"))
3606 t->slabels_axis = PIVOT_AXIS_ROW;
3607 else if (lex_match_id (lexer, "LAYER"))
3608 t->slabels_axis = PIVOT_AXIS_LAYER;
3611 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3615 else if (lex_match_id (lexer, "VISIBLE"))
3617 lex_match (lexer, T_EQUALS);
3618 if (!parse_bool (lexer, &t->slabels_visible))
3623 lex_error_expecting (lexer, "POSITION", "VISIBLE");
3628 else if (lex_match_id (lexer, "CLABELS"))
3630 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3632 if (lex_match_id (lexer, "AUTO"))
3634 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3635 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3637 else if (lex_match_id (lexer, "ROWLABELS"))
3639 lex_match (lexer, T_EQUALS);
3640 if (lex_match_id (lexer, "OPPOSITE"))
3641 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3642 else if (lex_match_id (lexer, "LAYER"))
3643 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3646 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3650 else if (lex_match_id (lexer, "COLLABELS"))
3652 lex_match (lexer, T_EQUALS);
3653 if (lex_match_id (lexer, "OPPOSITE"))
3654 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3655 else if (lex_match_id (lexer, "LAYER"))
3656 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3659 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3665 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3671 else if (lex_match_id (lexer, "CRITERIA"))
3673 if (!lex_force_match_id (lexer, "CILEVEL"))
3675 lex_match (lexer, T_EQUALS);
3677 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3679 t->cilevel = lex_number (lexer);
3682 else if (lex_match_id (lexer, "CATEGORIES"))
3684 if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3687 else if (lex_match_id (lexer, "TITLES"))
3692 if (lex_match_id (lexer, "CAPTION"))
3693 textp = &t->caption;
3694 else if (lex_match_id (lexer, "CORNER"))
3696 else if (lex_match_id (lexer, "TITLE"))
3700 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3703 lex_match (lexer, T_EQUALS);
3705 struct string s = DS_EMPTY_INITIALIZER;
3706 while (lex_is_string (lexer))
3708 if (!ds_is_empty (&s))
3709 ds_put_byte (&s, ' ');
3710 ds_put_substring (&s, lex_tokss (lexer));
3714 *textp = ds_steal_cstr (&s);
3716 while (lex_token (lexer) != T_SLASH
3717 && lex_token (lexer) != T_ENDCMD);
3719 else if (lex_match_id (lexer, "SIGTEST"))
3723 t->chisq = xmalloc (sizeof *t->chisq);
3724 *t->chisq = (struct ctables_chisq) {
3726 .include_mrsets = true,
3727 .all_visible = true,
3733 if (lex_match_id (lexer, "TYPE"))
3735 lex_match (lexer, T_EQUALS);
3736 if (!lex_force_match_id (lexer, "CHISQUARE"))
3739 else if (lex_match_id (lexer, "ALPHA"))
3741 lex_match (lexer, T_EQUALS);
3742 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3744 t->chisq->alpha = lex_number (lexer);
3747 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3749 lex_match (lexer, T_EQUALS);
3750 if (parse_bool (lexer, &t->chisq->include_mrsets))
3753 else if (lex_match_id (lexer, "CATEGORIES"))
3755 lex_match (lexer, T_EQUALS);
3756 if (lex_match_id (lexer, "ALLVISIBLE"))
3757 t->chisq->all_visible = true;
3758 else if (lex_match_id (lexer, "SUBTOTALS"))
3759 t->chisq->all_visible = false;
3762 lex_error_expecting (lexer,
3763 "ALLVISIBLE", "SUBTOTALS");
3769 lex_error_expecting (lexer, "TYPE", "ALPHA",
3770 "INCLUDEMRSETS", "CATEGORIES");
3774 while (lex_token (lexer) != T_SLASH
3775 && lex_token (lexer) != T_ENDCMD);
3777 else if (lex_match_id (lexer, "COMPARETEST"))
3781 t->pairwise = xmalloc (sizeof *t->pairwise);
3782 *t->pairwise = (struct ctables_pairwise) {
3784 .alpha = { .05, .05 },
3785 .adjust = BONFERRONI,
3786 .include_mrsets = true,
3787 .meansvariance_allcats = true,
3788 .all_visible = true,
3797 if (lex_match_id (lexer, "TYPE"))
3799 lex_match (lexer, T_EQUALS);
3800 if (lex_match_id (lexer, "PROP"))
3801 t->pairwise->type = PROP;
3802 else if (lex_match_id (lexer, "MEAN"))
3803 t->pairwise->type = MEAN;
3806 lex_error_expecting (lexer, "PROP", "MEAN");
3810 else if (lex_match_id (lexer, "ALPHA"))
3812 lex_match (lexer, T_EQUALS);
3814 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3816 double a0 = lex_number (lexer);
3819 lex_match (lexer, T_COMMA);
3820 if (lex_is_number (lexer))
3822 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3824 double a1 = lex_number (lexer);
3827 t->pairwise->alpha[0] = MIN (a0, a1);
3828 t->pairwise->alpha[1] = MAX (a0, a1);
3831 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3833 else if (lex_match_id (lexer, "ADJUST"))
3835 lex_match (lexer, T_EQUALS);
3836 if (lex_match_id (lexer, "BONFERRONI"))
3837 t->pairwise->adjust = BONFERRONI;
3838 else if (lex_match_id (lexer, "BH"))
3839 t->pairwise->adjust = BH;
3840 else if (lex_match_id (lexer, "NONE"))
3841 t->pairwise->adjust = 0;
3844 lex_error_expecting (lexer, "BONFERRONI", "BH",
3849 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3851 lex_match (lexer, T_EQUALS);
3852 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3855 else if (lex_match_id (lexer, "MEANSVARIANCE"))
3857 lex_match (lexer, T_EQUALS);
3858 if (lex_match_id (lexer, "ALLCATS"))
3859 t->pairwise->meansvariance_allcats = true;
3860 else if (lex_match_id (lexer, "TESTEDCATS"))
3861 t->pairwise->meansvariance_allcats = false;
3864 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3868 else if (lex_match_id (lexer, "CATEGORIES"))
3870 lex_match (lexer, T_EQUALS);
3871 if (lex_match_id (lexer, "ALLVISIBLE"))
3872 t->pairwise->all_visible = true;
3873 else if (lex_match_id (lexer, "SUBTOTALS"))
3874 t->pairwise->all_visible = false;
3877 lex_error_expecting (lexer, "ALLVISIBLE",
3882 else if (lex_match_id (lexer, "MERGE"))
3884 lex_match (lexer, T_EQUALS);
3885 if (!parse_bool (lexer, &t->pairwise->merge))
3888 else if (lex_match_id (lexer, "STYLE"))
3890 lex_match (lexer, T_EQUALS);
3891 if (lex_match_id (lexer, "APA"))
3892 t->pairwise->apa_style = true;
3893 else if (lex_match_id (lexer, "SIMPLE"))
3894 t->pairwise->apa_style = false;
3897 lex_error_expecting (lexer, "APA", "SIMPLE");
3901 else if (lex_match_id (lexer, "SHOWSIG"))
3903 lex_match (lexer, T_EQUALS);
3904 if (!parse_bool (lexer, &t->pairwise->show_sig))
3909 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3910 "INCLUDEMRSETS", "MEANSVARIANCE",
3911 "CATEGORIES", "MERGE", "STYLE",
3916 while (lex_token (lexer) != T_SLASH
3917 && lex_token (lexer) != T_ENDCMD);
3921 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3922 "CRITERIA", "CATEGORIES", "TITLES",
3923 "SIGTEST", "COMPARETEST");
3927 if (!lex_match (lexer, T_SLASH))
3931 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3932 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3934 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3938 if (!ctables_prepare_table (t))
3941 while (lex_token (lexer) != T_ENDCMD);
3943 bool ok = ctables_execute (ds, ct);
3944 ctables_destroy (ct);
3945 return ok ? CMD_SUCCESS : CMD_FAILURE;
3948 ctables_destroy (ct);