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/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/string-array.h"
39 #include "math/mode.h"
40 #include "math/moments.h"
41 #include "math/percentiles.h"
42 #include "math/sort.h"
43 #include "output/pivot-table.h"
45 #include "gl/minmax.h"
46 #include "gl/xalloc.h"
49 #define _(msgid) gettext (msgid)
50 #define N_(msgid) (msgid)
54 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
55 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
56 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
57 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
61 - unweighted summaries (U*)
62 - lower confidence limits (*.LCL)
63 - upper confidence limits (*.UCL)
64 - standard error (*.SE)
67 /* All variables. */ \
68 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
69 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
70 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
71 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
72 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
85 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
86 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
87 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
88 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
89 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
90 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
92 /* Scale variables, totals, and subtotals. */ \
93 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
94 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
95 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
98 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
99 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
100 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
101 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
102 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
103 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
104 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
105 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
106 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
107 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
108 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
109 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
110 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
111 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
112 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
113 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
114 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
115 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
117 /* Multiple response sets. */ \
118 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
119 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
120 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
121 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
134 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
135 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
141 enum ctables_summary_function
143 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
149 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
150 N_CTSF_FUNCTIONS = SUMMARIES
154 enum ctables_domain_type
156 /* Within a section, where stacked variables divide one section from
158 CTDT_TABLE, /* All layers of a whole section. */
159 CTDT_LAYER, /* One layer within a section. */
160 CTDT_LAYERROW, /* Row in one layer within a section. */
161 CTDT_LAYERCOL, /* Column in one layer within a section. */
163 /* Within a subtable, where a subtable pairs an innermost row variable with
164 an innermost column variable within a single layer. */
165 CTDT_SUBTABLE, /* Whole subtable. */
166 CTDT_ROW, /* Row within a subtable. */
167 CTDT_COL, /* Column within a subtable. */
171 struct ctables_domain
173 struct hmap_node node;
175 const struct ctables_cell *example;
177 double d_valid; /* Dictionary weight. */
179 double e_valid; /* Effective weight */
183 enum ctables_summary_variant
192 /* In struct ctables_section's 'cells' hmap. Indexed by all the values in
193 all the axes (except the scalar variable, if any). */
194 struct hmap_node node;
196 /* The domains that contain this cell. */
197 bool contributes_to_domains;
198 struct ctables_domain *domains[N_CTDTS];
201 enum ctables_summary_variant sv;
203 struct ctables_cell_axis
205 struct ctables_cell_value
207 const struct ctables_category *category;
215 union ctables_summary *summaries;
220 const struct dictionary *dict;
221 struct pivot_table_look *look;
223 /* If this is NULL, zeros are displayed using the normal print format.
224 Otherwise, this string is displayed. */
227 /* If this is NULL, missing values are displayed using the normal print
228 format. Otherwise, this string is displayed. */
231 /* Indexed by variable dictionary index. */
232 enum ctables_vlabel *vlabels;
234 struct hmap postcomputes; /* Contains "struct ctables_postcompute"s. */
236 bool mrsets_count_duplicates; /* MRSETS. */
237 bool smissing_listwise; /* SMISSING. */
238 struct variable *e_weight; /* WEIGHT. */
239 int hide_threshold; /* HIDESMALLCOUNTS. */
241 struct ctables_table **tables;
245 static struct ctables_postcompute *ctables_find_postcompute (struct ctables *,
248 struct ctables_postcompute
250 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
251 char *name; /* Name, without leading &. */
253 struct msg_location *location; /* Location of definition. */
254 struct ctables_pcexpr *expr;
256 struct ctables_summary_spec_set *specs;
257 bool hide_source_cats;
260 struct ctables_pcexpr
270 enum ctables_postcompute_op
273 CTPO_CONSTANT, /* 5 */
274 CTPO_CAT_NUMBER, /* [5] */
275 CTPO_CAT_STRING, /* ["STRING"] */
276 CTPO_CAT_RANGE, /* [LO THRU 5] */
277 CTPO_CAT_MISSING, /* MISSING */
278 CTPO_CAT_OTHERNM, /* OTHERNM */
279 CTPO_CAT_SUBTOTAL, /* SUBTOTAL */
280 CTPO_CAT_TOTAL, /* TOTAL */
294 /* CTPO_CAT_NUMBER. */
297 /* CTPO_CAT_STRING. */
300 /* CTPO_CAT_RANGE. */
303 /* CTPO_CAT_SUBTOTAL. */
304 size_t subtotal_index;
306 /* Two elements: CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW.
307 One element: CTPO_NEG. */
308 struct ctables_pcexpr *subs[2];
311 /* Source location. */
313 struct msg_location *location;
316 static void ctables_pcexpr_destroy (struct ctables_pcexpr *);
317 static struct ctables_pcexpr *ctables_pcexpr_allocate_binary (
318 enum ctables_postcompute_op, struct ctables_pcexpr *sub0,
319 struct ctables_pcexpr *sub1);
321 struct ctables_summary_spec_set
323 struct ctables_summary_spec *specs;
327 struct variable *var;
330 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
331 const struct ctables_summary_spec_set *);
332 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
334 /* A nested sequence of variables, e.g. a > b > c. */
337 struct variable **vars;
340 size_t *domains[N_CTDTS];
341 size_t n_domains[N_CTDTS];
343 struct ctables_summary_spec_set specs[N_CSVS];
346 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
349 struct ctables_nest *nests;
355 struct hmap_node node;
360 struct ctables_section_value
362 struct hmap_node node;
366 struct ctables_section
368 struct ctables_table *table;
369 struct ctables_nest *nests[PIVOT_N_AXES];
370 struct hmap *occurrences[PIVOT_N_AXES];
371 struct hmap cells; /* Contains "struct ctable_cell"s. */
372 struct hmap domains[N_CTDTS]; /* Contains "struct ctable_domain"s. */
377 struct ctables *ctables;
378 struct ctables_axis *axes[PIVOT_N_AXES];
379 struct ctables_stack stacks[PIVOT_N_AXES];
380 struct ctables_section *sections;
382 enum pivot_axis_type summary_axis;
383 struct ctables_summary_spec_set summary_specs;
385 const struct variable *clabels_example;
386 struct hmap clabels_values_map;
387 struct ctables_value **clabels_values;
388 size_t n_clabels_values;
390 enum pivot_axis_type slabels_axis;
391 bool slabels_visible;
393 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
395 Most commonly, label_axis[a] == a, and in particular we always have
396 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
398 If ROWLABELS or COLLABELS is specified, then one of
399 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
400 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
402 enum pivot_axis_type label_axis[PIVOT_N_AXES];
403 enum pivot_axis_type clabels_from_axis;
405 /* Indexed by variable dictionary index. */
406 struct ctables_categories **categories;
415 struct ctables_chisq *chisq;
416 struct ctables_pairwise *pairwise;
424 struct variable *var;
425 const struct mrset *mrset;
429 static const struct fmt_spec *
430 ctables_var_get_print_format (const struct ctables_var *var)
432 return (var->is_mrset
433 ? var_get_print_format (var->mrset->vars[0])
434 : var_get_print_format (var->var));
438 ctables_var_name (const struct ctables_var *var)
440 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
443 struct ctables_categories
446 struct ctables_category *cats;
451 struct ctables_category
453 enum ctables_category_type
455 /* Explicit category lists. */
463 /* Totals and subtotals. */
468 /* Implicit category lists. */
475 struct ctables_category *subtotal;
479 double number; /* CCT_NUMBER. */
480 char *string; /* CCT_STRING. */
481 double range[2]; /* CCT_RANGE. */
482 char *total_label; /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
483 const struct ctables_postcompute *pc; /* CCT_POSTCOMPUTE. */
485 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
488 bool include_missing;
492 enum ctables_summary_function sort_function;
493 struct variable *sort_var;
500 ctables_category_uninit (struct ctables_category *cat)
511 case CCT_POSTCOMPUTE:
521 free (cat->total_label);
532 ctables_category_equal (const struct ctables_category *a,
533 const struct ctables_category *b)
535 if (a->type != b->type)
541 return a->number == b->number;
544 return strcmp (a->string, b->string);
547 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
553 case CCT_POSTCOMPUTE:
554 return a->pc == b->pc;
559 return !strcmp (a->total_label, b->total_label);
564 return (a->include_missing == b->include_missing
565 && a->sort_ascending == b->sort_ascending
566 && a->sort_function == b->sort_function
567 && a->sort_var == b->sort_var
568 && a->percentile == b->percentile);
575 ctables_categories_unref (struct ctables_categories *c)
580 assert (c->n_refs > 0);
584 for (size_t i = 0; i < c->n_cats; i++)
585 ctables_category_uninit (&c->cats[i]);
591 ctables_categories_equal (const struct ctables_categories *a,
592 const struct ctables_categories *b)
594 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
597 for (size_t i = 0; i < a->n_cats; i++)
598 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
604 /* Chi-square test (SIGTEST). */
612 /* Pairwise comparison test (COMPARETEST). */
613 struct ctables_pairwise
615 enum { PROP, MEAN } type;
618 bool meansvariance_allcats;
620 enum { BONFERRONI = 1, BH } adjust;
644 struct ctables_var var;
646 struct ctables_summary_spec_set specs[N_CSVS];
650 struct ctables_axis *subs[2];
653 struct msg_location *loc;
656 static void ctables_axis_destroy (struct ctables_axis *);
665 enum ctables_function_availability
667 CTFA_ALL, /* Any variables. */
668 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
669 CTFA_MRSETS, /* Only multiple-response sets */
672 struct ctables_summary_spec
674 enum ctables_summary_function function;
675 double percentile; /* CTSF_PTILE only. */
677 struct fmt_spec format; /* XXX extra CTABLES formats */
682 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
683 const struct ctables_summary_spec *src)
686 dst->label = xstrdup (src->label);
690 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
697 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
698 const struct ctables_summary_spec_set *src)
700 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
701 for (size_t i = 0; i < src->n; i++)
702 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
704 *dst = (struct ctables_summary_spec_set) {
713 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
715 for (size_t i = 0; i < set->n; i++)
716 ctables_summary_spec_uninit (&set->specs[i]);
721 parse_col_width (struct lexer *lexer, const char *name, double *width)
723 lex_match (lexer, T_EQUALS);
724 if (lex_match_id (lexer, "DEFAULT"))
726 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
728 *width = lex_number (lexer);
738 parse_bool (struct lexer *lexer, bool *b)
740 if (lex_match_id (lexer, "NO"))
742 else if (lex_match_id (lexer, "YES"))
746 lex_error_expecting (lexer, "YES", "NO");
752 static enum ctables_function_availability
753 ctables_function_availability (enum ctables_summary_function f)
755 static enum ctables_function_availability availability[] = {
756 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
761 return availability[f];
765 parse_ctables_summary_function (struct lexer *lexer,
766 enum ctables_summary_function *f)
770 enum ctables_summary_function function;
771 struct substring name;
773 static struct pair names[] = {
774 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
775 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
778 /* The .COUNT suffix may be omitted. */
779 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
780 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
781 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
782 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
783 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
784 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
785 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
789 if (!lex_force_id (lexer))
792 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
793 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
795 *f = names[i].function;
800 lex_error (lexer, _("Expecting summary function name."));
805 ctables_axis_destroy (struct ctables_axis *axis)
813 for (size_t i = 0; i < N_CSVS; i++)
814 ctables_summary_spec_set_uninit (&axis->specs[i]);
819 ctables_axis_destroy (axis->subs[0]);
820 ctables_axis_destroy (axis->subs[1]);
823 msg_location_destroy (axis->loc);
827 static struct ctables_axis *
828 ctables_axis_new_nonterminal (enum ctables_axis_op op,
829 struct ctables_axis *sub0,
830 struct ctables_axis *sub1,
831 struct lexer *lexer, int start_ofs)
833 struct ctables_axis *axis = xmalloc (sizeof *axis);
834 *axis = (struct ctables_axis) {
836 .subs = { sub0, sub1 },
837 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
842 struct ctables_axis_parse_ctx
845 struct dictionary *dict;
847 struct ctables_table *t;
850 static struct fmt_spec
851 ctables_summary_default_format (enum ctables_summary_function function,
852 const struct ctables_var *var)
854 static const enum ctables_format default_formats[] = {
855 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
859 switch (default_formats[function])
862 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
865 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
868 return *ctables_var_get_print_format (var);
876 ctables_summary_default_label (enum ctables_summary_function function,
879 static const char *default_labels[] = {
880 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
885 return (function == CTSF_PTILE
886 ? xasprintf (_("Percentile %.2f"), percentile)
887 : xstrdup (gettext (default_labels[function])));
891 ctables_summary_function_name (enum ctables_summary_function function)
893 static const char *names[] = {
894 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
898 return names[function];
902 add_summary_spec (struct ctables_axis *axis,
903 enum ctables_summary_function function, double percentile,
904 const char *label, const struct fmt_spec *format,
905 const struct msg_location *loc, enum ctables_summary_variant sv)
907 if (axis->op == CTAO_VAR)
909 const char *function_name = ctables_summary_function_name (function);
910 const char *var_name = ctables_var_name (&axis->var);
911 switch (ctables_function_availability (function))
914 if (!axis->var.is_mrset)
916 msg_at (SE, loc, _("Summary function %s applies only to multiple "
917 "response sets."), function_name);
918 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
928 _("Summary function %s applies only to scale variables."),
930 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
940 struct ctables_summary_spec_set *set = &axis->specs[sv];
941 if (set->n >= set->allocated)
942 set->specs = x2nrealloc (set->specs, &set->allocated,
945 struct ctables_summary_spec *dst = &set->specs[set->n++];
946 *dst = (struct ctables_summary_spec) {
947 .function = function,
948 .percentile = percentile,
949 .label = xstrdup (label),
950 .format = (format ? *format
951 : ctables_summary_default_format (function, &axis->var)),
957 for (size_t i = 0; i < 2; i++)
958 if (!add_summary_spec (axis->subs[i], function, percentile, label,
965 static struct ctables_axis *ctables_axis_parse_stack (
966 struct ctables_axis_parse_ctx *);
969 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
970 struct ctables_var *var)
972 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
974 *var = (struct ctables_var) {
976 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
980 lex_error (lexer, _("'%s' does not name a multiple-response set "
981 "in the active file dictionary."),
982 lex_tokcstr (lexer));
990 *var = (struct ctables_var) {
992 .var = parse_variable (lexer, dict),
994 return var->var != NULL;
998 static struct ctables_axis *
999 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
1001 if (lex_match (ctx->lexer, T_LPAREN))
1003 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
1004 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
1006 ctables_axis_destroy (sub);
1012 if (!lex_force_id (ctx->lexer))
1015 int start_ofs = lex_ofs (ctx->lexer);
1016 struct ctables_var var;
1017 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
1020 struct ctables_axis *axis = xmalloc (sizeof *axis);
1021 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
1023 /* XXX should figure out default measures by reading data */
1024 axis->scale = (var.is_mrset ? false
1025 : lex_match_phrase (ctx->lexer, "[S]") ? true
1026 : lex_match_phrase (ctx->lexer, "[C]") ? false
1027 : var_get_measure (var.var) == MEASURE_SCALE);
1028 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
1029 lex_ofs (ctx->lexer) - 1);
1034 has_digit (const char *s)
1036 return s[strcspn (s, "0123456789")] != '\0';
1039 static struct ctables_axis *
1040 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
1042 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
1043 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
1046 enum ctables_summary_variant sv = CSV_CELL;
1049 int start_ofs = lex_ofs (ctx->lexer);
1051 /* Parse function. */
1052 enum ctables_summary_function function;
1053 if (!parse_ctables_summary_function (ctx->lexer, &function))
1056 /* Parse percentile. */
1057 double percentile = 0;
1058 if (function == CTSF_PTILE)
1060 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1062 percentile = lex_number (ctx->lexer);
1063 lex_get (ctx->lexer);
1068 if (lex_is_string (ctx->lexer))
1070 label = ss_xstrdup (lex_tokss (ctx->lexer));
1071 lex_get (ctx->lexer);
1074 label = ctables_summary_default_label (function, percentile);
1077 struct fmt_spec format;
1078 const struct fmt_spec *formatp;
1079 if (lex_token (ctx->lexer) == T_ID
1080 && has_digit (lex_tokcstr (ctx->lexer)))
1082 if (!parse_format_specifier (ctx->lexer, &format)
1083 || !fmt_check_output (&format)
1084 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1094 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1095 lex_ofs (ctx->lexer) - 1);
1096 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1098 msg_location_destroy (loc);
1100 lex_match (ctx->lexer, T_COMMA);
1101 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1103 if (!lex_force_match (ctx->lexer, T_LBRACK))
1107 else if (lex_match (ctx->lexer, T_RBRACK))
1109 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1116 ctables_axis_destroy (sub);
1120 static const struct ctables_axis *
1121 find_scale (const struct ctables_axis *axis)
1125 else if (axis->op == CTAO_VAR)
1129 assert (!axis->var.is_mrset);
1137 for (size_t i = 0; i < 2; i++)
1139 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1147 static const struct ctables_axis *
1148 find_categorical_summary_spec (const struct ctables_axis *axis)
1152 else if (axis->op == CTAO_VAR)
1153 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1156 for (size_t i = 0; i < 2; i++)
1158 const struct ctables_axis *sum
1159 = find_categorical_summary_spec (axis->subs[i]);
1167 static struct ctables_axis *
1168 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1170 int start_ofs = lex_ofs (ctx->lexer);
1171 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1175 while (lex_match (ctx->lexer, T_GT))
1177 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1181 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1182 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1184 const struct ctables_axis *outer_scale = find_scale (lhs);
1185 const struct ctables_axis *inner_scale = find_scale (rhs);
1186 if (outer_scale && inner_scale)
1188 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1189 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1190 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1191 ctables_axis_destroy (nest);
1195 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1198 msg_at (SE, nest->loc,
1199 _("Summaries may only be requested for categorical variables "
1200 "at the innermost nesting level."));
1201 msg_at (SN, outer_sum->loc,
1202 _("This outer categorical variable has a summary."));
1203 ctables_axis_destroy (nest);
1213 static struct ctables_axis *
1214 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1216 int start_ofs = lex_ofs (ctx->lexer);
1217 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1221 while (lex_match (ctx->lexer, T_PLUS))
1223 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1227 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1228 ctx->lexer, start_ofs);
1235 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1236 struct ctables *ct, struct ctables_table *t,
1237 enum pivot_axis_type a)
1239 if (lex_token (lexer) == T_BY
1240 || lex_token (lexer) == T_SLASH
1241 || lex_token (lexer) == T_ENDCMD)
1244 struct ctables_axis_parse_ctx ctx = {
1250 t->axes[a] = ctables_axis_parse_stack (&ctx);
1251 return t->axes[a] != NULL;
1255 ctables_chisq_destroy (struct ctables_chisq *chisq)
1261 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1267 ctables_table_destroy (struct ctables_table *t)
1272 for (size_t i = 0; i < t->n_categories; i++)
1273 ctables_categories_unref (t->categories[i]);
1274 free (t->categories);
1276 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1277 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1278 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1282 ctables_chisq_destroy (t->chisq);
1283 ctables_pairwise_destroy (t->pairwise);
1288 ctables_destroy (struct ctables *ct)
1293 pivot_table_look_unref (ct->look);
1297 for (size_t i = 0; i < ct->n_tables; i++)
1298 ctables_table_destroy (ct->tables[i]);
1303 static struct ctables_category
1304 cct_range (double low, double high)
1306 return (struct ctables_category) {
1308 .range = { low, high }
1313 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1314 struct ctables *ct, struct ctables_table *t)
1316 if (!lex_match_id (lexer, "VARIABLES"))
1318 lex_match (lexer, T_EQUALS);
1320 struct variable **vars;
1322 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1325 struct ctables_categories *c = xmalloc (sizeof *c);
1326 *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
1327 for (size_t i = 0; i < n_vars; i++)
1329 struct ctables_categories **cp
1330 = &t->categories[var_get_dict_index (vars[i])];
1331 ctables_categories_unref (*cp);
1336 size_t allocated_cats = 0;
1337 if (lex_match (lexer, T_LBRACK))
1341 if (c->n_cats >= allocated_cats)
1342 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1344 struct ctables_category *cat = &c->cats[c->n_cats];
1345 if (lex_match_id (lexer, "OTHERNM"))
1346 cat->type = CCT_OTHERNM;
1347 else if (lex_match_id (lexer, "MISSING"))
1348 cat->type = CCT_MISSING;
1349 else if (lex_match_id (lexer, "SUBTOTAL"))
1350 *cat = (struct ctables_category)
1351 { .type = CCT_SUBTOTAL, .total_label = NULL };
1352 else if (lex_match_id (lexer, "HSUBTOTAL"))
1353 *cat = (struct ctables_category)
1354 { .type = CCT_HSUBTOTAL, .total_label = NULL };
1355 else if (lex_match_id (lexer, "LO"))
1357 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1359 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1362 else if (lex_is_number (lexer))
1364 double number = lex_number (lexer);
1366 if (lex_match_id (lexer, "THRU"))
1368 if (lex_match_id (lexer, "HI"))
1369 *cat = cct_range (number, DBL_MAX);
1372 if (!lex_force_num (lexer))
1374 *cat = cct_range (number, lex_number (lexer));
1379 *cat = (struct ctables_category) {
1384 else if (lex_is_string (lexer))
1386 *cat = (struct ctables_category) {
1388 .string = ss_xstrdup (lex_tokss (lexer)),
1392 else if (lex_match (lexer, T_AND))
1394 if (!lex_force_id (lexer))
1396 struct ctables_postcompute *pc = ctables_find_postcompute (
1397 ct, lex_tokcstr (lexer));
1400 struct msg_location *loc = lex_get_location (lexer, -1, 0);
1401 msg_at (SE, loc, _("Unknown postcompute &%s."),
1402 lex_tokcstr (lexer));
1403 msg_location_destroy (loc);
1408 *cat = (struct ctables_category) {
1409 .type = CCT_POSTCOMPUTE,
1415 lex_error (lexer, NULL);
1419 if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1421 if (lex_match (lexer, T_EQUALS))
1423 if (!lex_force_string (lexer))
1426 cat->total_label = ss_xstrdup (lex_tokss (lexer));
1430 cat->total_label = xstrdup (_("Subtotal"));
1434 lex_match (lexer, T_COMMA);
1436 while (!lex_match (lexer, T_RBRACK));
1439 struct ctables_category cat = {
1441 .include_missing = false,
1442 .sort_ascending = true,
1444 bool show_totals = false;
1445 char *total_label = NULL;
1446 bool totals_before = false;
1447 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1449 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1451 lex_match (lexer, T_EQUALS);
1452 if (lex_match_id (lexer, "A"))
1453 cat.sort_ascending = true;
1454 else if (lex_match_id (lexer, "D"))
1455 cat.sort_ascending = false;
1458 lex_error_expecting (lexer, "A", "D");
1462 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1464 lex_match (lexer, T_EQUALS);
1465 if (lex_match_id (lexer, "VALUE"))
1466 cat.type = CCT_VALUE;
1467 else if (lex_match_id (lexer, "LABEL"))
1468 cat.type = CCT_LABEL;
1471 cat.type = CCT_FUNCTION;
1472 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1475 if (lex_match (lexer, T_LPAREN))
1477 cat.sort_var = parse_variable (lexer, dict);
1481 if (cat.sort_function == CTSF_PTILE)
1483 lex_match (lexer, T_COMMA);
1484 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1486 cat.percentile = lex_number (lexer);
1490 if (!lex_force_match (lexer, T_RPAREN))
1493 else if (ctables_function_availability (cat.sort_function)
1496 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1501 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1503 lex_match (lexer, T_EQUALS);
1504 if (lex_match_id (lexer, "INCLUDE"))
1505 cat.include_missing = true;
1506 else if (lex_match_id (lexer, "EXCLUDE"))
1507 cat.include_missing = false;
1510 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1514 else if (lex_match_id (lexer, "TOTAL"))
1516 lex_match (lexer, T_EQUALS);
1517 if (!parse_bool (lexer, &show_totals))
1520 else if (lex_match_id (lexer, "LABEL"))
1522 lex_match (lexer, T_EQUALS);
1523 if (!lex_force_string (lexer))
1526 total_label = ss_xstrdup (lex_tokss (lexer));
1529 else if (lex_match_id (lexer, "POSITION"))
1531 lex_match (lexer, T_EQUALS);
1532 if (lex_match_id (lexer, "BEFORE"))
1533 totals_before = true;
1534 else if (lex_match_id (lexer, "AFTER"))
1535 totals_before = false;
1538 lex_error_expecting (lexer, "BEFORE", "AFTER");
1542 else if (lex_match_id (lexer, "EMPTY"))
1544 lex_match (lexer, T_EQUALS);
1545 if (lex_match_id (lexer, "INCLUDE"))
1546 c->show_empty = true;
1547 else if (lex_match_id (lexer, "EXCLUDE"))
1548 c->show_empty = false;
1551 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1558 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1559 "TOTAL", "LABEL", "POSITION", "EMPTY");
1561 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1568 if (c->n_cats >= allocated_cats)
1569 c->cats = x2nrealloc (c->cats, &allocated_cats,
1571 c->cats[c->n_cats++] = cat;
1576 if (c->n_cats >= allocated_cats)
1577 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1579 struct ctables_category *totals;
1582 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1583 totals = &c->cats[0];
1586 totals = &c->cats[c->n_cats];
1589 *totals = (struct ctables_category) {
1591 .total_label = total_label ? total_label : xstrdup (_("Total")),
1595 struct ctables_category *subtotal = NULL;
1596 for (size_t i = totals_before ? 0 : c->n_cats;
1597 totals_before ? i < c->n_cats : i-- > 0;
1598 totals_before ? i++ : 0)
1600 struct ctables_category *cat = &c->cats[i];
1608 cat->subtotal = subtotal;
1611 case CCT_POSTCOMPUTE:
1631 ctables_nest_uninit (struct ctables_nest *nest)
1638 ctables_stack_uninit (struct ctables_stack *stack)
1642 for (size_t i = 0; i < stack->n; i++)
1643 ctables_nest_uninit (&stack->nests[i]);
1644 free (stack->nests);
1648 static struct ctables_stack
1649 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1656 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1657 for (size_t i = 0; i < s0.n; i++)
1658 for (size_t j = 0; j < s1.n; j++)
1660 const struct ctables_nest *a = &s0.nests[i];
1661 const struct ctables_nest *b = &s1.nests[j];
1663 size_t allocate = a->n + b->n;
1664 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1665 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1667 for (size_t k = 0; k < a->n; k++)
1668 vars[n++] = a->vars[k];
1669 for (size_t k = 0; k < b->n; k++)
1670 vars[n++] = b->vars[k];
1671 assert (n == allocate);
1673 const struct ctables_nest *summary_src;
1674 if (!a->specs[CSV_CELL].var)
1676 else if (!b->specs[CSV_CELL].var)
1681 struct ctables_nest *new = &stack.nests[stack.n++];
1682 *new = (struct ctables_nest) {
1684 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1685 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1689 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1690 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1692 ctables_stack_uninit (&s0);
1693 ctables_stack_uninit (&s1);
1697 static struct ctables_stack
1698 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1700 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1701 for (size_t i = 0; i < s0.n; i++)
1702 stack.nests[stack.n++] = s0.nests[i];
1703 for (size_t i = 0; i < s1.n; i++)
1704 stack.nests[stack.n++] = s1.nests[i];
1705 assert (stack.n == s0.n + s1.n);
1711 static struct ctables_stack
1712 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1715 return (struct ctables_stack) { .n = 0 };
1720 assert (!a->var.is_mrset);
1722 struct variable **vars = xmalloc (sizeof *vars);
1725 struct ctables_nest *nest = xmalloc (sizeof *nest);
1726 *nest = (struct ctables_nest) {
1729 .scale_idx = a->scale ? 0 : SIZE_MAX,
1731 if (a->specs[CSV_CELL].n || a->scale)
1732 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1734 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1735 nest->specs[sv].var = a->var.var;
1737 return (struct ctables_stack) { .nests = nest, .n = 1 };
1740 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1741 enumerate_fts (axis_type, a->subs[1]));
1744 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1745 enumerate_fts (axis_type, a->subs[1]));
1751 union ctables_summary
1753 /* COUNT, VALIDN, TOTALN. */
1760 /* MINIMUM, MAXIMUM, RANGE. */
1767 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1768 struct moments1 *moments;
1770 /* MEDIAN, MODE, PTILE. */
1773 struct casewriter *writer;
1778 /* XXX multiple response */
1782 ctables_summary_init (union ctables_summary *s,
1783 const struct ctables_summary_spec *ss)
1785 switch (ss->function)
1789 case CTSF_ROWPCT_COUNT:
1790 case CTSF_COLPCT_COUNT:
1791 case CTSF_TABLEPCT_COUNT:
1792 case CTSF_SUBTABLEPCT_COUNT:
1793 case CTSF_LAYERPCT_COUNT:
1794 case CTSF_LAYERROWPCT_COUNT:
1795 case CTSF_LAYERCOLPCT_COUNT:
1796 case CTSF_ROWPCT_VALIDN:
1797 case CTSF_COLPCT_VALIDN:
1798 case CTSF_TABLEPCT_VALIDN:
1799 case CTSF_SUBTABLEPCT_VALIDN:
1800 case CTSF_LAYERPCT_VALIDN:
1801 case CTSF_LAYERROWPCT_VALIDN:
1802 case CTSF_LAYERCOLPCT_VALIDN:
1803 case CTSF_ROWPCT_TOTALN:
1804 case CTSF_COLPCT_TOTALN:
1805 case CTSF_TABLEPCT_TOTALN:
1806 case CTSF_SUBTABLEPCT_TOTALN:
1807 case CTSF_LAYERPCT_TOTALN:
1808 case CTSF_LAYERROWPCT_TOTALN:
1809 case CTSF_LAYERCOLPCT_TOTALN:
1815 s->missing = s->valid = 0;
1821 s->min = s->max = SYSMIS;
1829 case CTSF_ROWPCT_SUM:
1830 case CTSF_COLPCT_SUM:
1831 case CTSF_TABLEPCT_SUM:
1832 case CTSF_SUBTABLEPCT_SUM:
1833 case CTSF_LAYERPCT_SUM:
1834 case CTSF_LAYERROWPCT_SUM:
1835 case CTSF_LAYERCOLPCT_SUM:
1836 s->moments = moments1_create (MOMENT_VARIANCE);
1843 struct caseproto *proto = caseproto_create ();
1844 proto = caseproto_add_width (proto, 0);
1845 proto = caseproto_add_width (proto, 0);
1847 struct subcase ordering;
1848 subcase_init (&ordering, 0, 0, SC_ASCEND);
1849 s->writer = sort_create_writer (&ordering, proto);
1850 subcase_uninit (&ordering);
1851 caseproto_unref (proto);
1858 case CTSF_RESPONSES:
1859 case CTSF_ROWPCT_RESPONSES:
1860 case CTSF_COLPCT_RESPONSES:
1861 case CTSF_TABLEPCT_RESPONSES:
1862 case CTSF_SUBTABLEPCT_RESPONSES:
1863 case CTSF_LAYERPCT_RESPONSES:
1864 case CTSF_LAYERROWPCT_RESPONSES:
1865 case CTSF_LAYERCOLPCT_RESPONSES:
1866 case CTSF_ROWPCT_RESPONSES_COUNT:
1867 case CTSF_COLPCT_RESPONSES_COUNT:
1868 case CTSF_TABLEPCT_RESPONSES_COUNT:
1869 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1870 case CTSF_LAYERPCT_RESPONSES_COUNT:
1871 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1872 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1873 case CTSF_ROWPCT_COUNT_RESPONSES:
1874 case CTSF_COLPCT_COUNT_RESPONSES:
1875 case CTSF_TABLEPCT_COUNT_RESPONSES:
1876 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1877 case CTSF_LAYERPCT_COUNT_RESPONSES:
1878 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1879 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1885 ctables_summary_uninit (union ctables_summary *s,
1886 const struct ctables_summary_spec *ss)
1888 switch (ss->function)
1892 case CTSF_ROWPCT_COUNT:
1893 case CTSF_COLPCT_COUNT:
1894 case CTSF_TABLEPCT_COUNT:
1895 case CTSF_SUBTABLEPCT_COUNT:
1896 case CTSF_LAYERPCT_COUNT:
1897 case CTSF_LAYERROWPCT_COUNT:
1898 case CTSF_LAYERCOLPCT_COUNT:
1899 case CTSF_ROWPCT_VALIDN:
1900 case CTSF_COLPCT_VALIDN:
1901 case CTSF_TABLEPCT_VALIDN:
1902 case CTSF_SUBTABLEPCT_VALIDN:
1903 case CTSF_LAYERPCT_VALIDN:
1904 case CTSF_LAYERROWPCT_VALIDN:
1905 case CTSF_LAYERCOLPCT_VALIDN:
1906 case CTSF_ROWPCT_TOTALN:
1907 case CTSF_COLPCT_TOTALN:
1908 case CTSF_TABLEPCT_TOTALN:
1909 case CTSF_SUBTABLEPCT_TOTALN:
1910 case CTSF_LAYERPCT_TOTALN:
1911 case CTSF_LAYERROWPCT_TOTALN:
1912 case CTSF_LAYERCOLPCT_TOTALN:
1930 case CTSF_ROWPCT_SUM:
1931 case CTSF_COLPCT_SUM:
1932 case CTSF_TABLEPCT_SUM:
1933 case CTSF_SUBTABLEPCT_SUM:
1934 case CTSF_LAYERPCT_SUM:
1935 case CTSF_LAYERROWPCT_SUM:
1936 case CTSF_LAYERCOLPCT_SUM:
1937 moments1_destroy (s->moments);
1943 casewriter_destroy (s->writer);
1946 case CTSF_RESPONSES:
1947 case CTSF_ROWPCT_RESPONSES:
1948 case CTSF_COLPCT_RESPONSES:
1949 case CTSF_TABLEPCT_RESPONSES:
1950 case CTSF_SUBTABLEPCT_RESPONSES:
1951 case CTSF_LAYERPCT_RESPONSES:
1952 case CTSF_LAYERROWPCT_RESPONSES:
1953 case CTSF_LAYERCOLPCT_RESPONSES:
1954 case CTSF_ROWPCT_RESPONSES_COUNT:
1955 case CTSF_COLPCT_RESPONSES_COUNT:
1956 case CTSF_TABLEPCT_RESPONSES_COUNT:
1957 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1958 case CTSF_LAYERPCT_RESPONSES_COUNT:
1959 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1960 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1961 case CTSF_ROWPCT_COUNT_RESPONSES:
1962 case CTSF_COLPCT_COUNT_RESPONSES:
1963 case CTSF_TABLEPCT_COUNT_RESPONSES:
1964 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1965 case CTSF_LAYERPCT_COUNT_RESPONSES:
1966 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1967 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1973 ctables_summary_add (union ctables_summary *s,
1974 const struct ctables_summary_spec *ss,
1975 const struct variable *var, const union value *value,
1976 double d_weight, double e_weight)
1978 switch (ss->function)
1983 if (var_is_value_missing (var, value))
1984 s->missing += d_weight;
1986 s->valid += d_weight;
1990 case CTSF_ROWPCT_COUNT:
1991 case CTSF_COLPCT_COUNT:
1992 case CTSF_TABLEPCT_COUNT:
1993 case CTSF_SUBTABLEPCT_COUNT:
1994 case CTSF_LAYERPCT_COUNT:
1995 case CTSF_LAYERROWPCT_COUNT:
1996 case CTSF_LAYERCOLPCT_COUNT:
1997 case CTSF_ROWPCT_VALIDN:
1998 case CTSF_COLPCT_VALIDN:
1999 case CTSF_TABLEPCT_VALIDN:
2000 case CTSF_SUBTABLEPCT_VALIDN:
2001 case CTSF_LAYERPCT_VALIDN:
2002 case CTSF_LAYERROWPCT_VALIDN:
2003 case CTSF_LAYERCOLPCT_VALIDN:
2004 case CTSF_ROWPCT_TOTALN:
2005 case CTSF_COLPCT_TOTALN:
2006 case CTSF_TABLEPCT_TOTALN:
2007 case CTSF_SUBTABLEPCT_TOTALN:
2008 case CTSF_LAYERPCT_TOTALN:
2009 case CTSF_LAYERROWPCT_TOTALN:
2010 case CTSF_LAYERCOLPCT_TOTALN:
2014 if (var_is_value_missing (var, value))
2015 s->missing += e_weight;
2017 s->valid += e_weight;
2023 if (!var_is_value_missing (var, value))
2025 assert (!var_is_alpha (var)); /* XXX? */
2026 if (s->min == SYSMIS || value->f < s->min)
2028 if (s->max == SYSMIS || value->f > s->max)
2038 case CTSF_ROWPCT_SUM:
2039 case CTSF_COLPCT_SUM:
2040 case CTSF_TABLEPCT_SUM:
2041 case CTSF_SUBTABLEPCT_SUM:
2042 case CTSF_LAYERPCT_SUM:
2043 case CTSF_LAYERROWPCT_SUM:
2044 case CTSF_LAYERCOLPCT_SUM:
2045 if (!var_is_value_missing (var, value))
2046 moments1_add (s->moments, value->f, e_weight);
2052 if (var_is_value_missing (var, value))
2054 s->ovalid += e_weight;
2056 struct ccase *c = case_create (casewriter_get_proto (s->writer));
2057 *case_num_rw_idx (c, 0) = value->f;
2058 *case_num_rw_idx (c, 1) = e_weight;
2059 casewriter_write (s->writer, c);
2063 case CTSF_RESPONSES:
2064 case CTSF_ROWPCT_RESPONSES:
2065 case CTSF_COLPCT_RESPONSES:
2066 case CTSF_TABLEPCT_RESPONSES:
2067 case CTSF_SUBTABLEPCT_RESPONSES:
2068 case CTSF_LAYERPCT_RESPONSES:
2069 case CTSF_LAYERROWPCT_RESPONSES:
2070 case CTSF_LAYERCOLPCT_RESPONSES:
2071 case CTSF_ROWPCT_RESPONSES_COUNT:
2072 case CTSF_COLPCT_RESPONSES_COUNT:
2073 case CTSF_TABLEPCT_RESPONSES_COUNT:
2074 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2075 case CTSF_LAYERPCT_RESPONSES_COUNT:
2076 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2077 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2078 case CTSF_ROWPCT_COUNT_RESPONSES:
2079 case CTSF_COLPCT_COUNT_RESPONSES:
2080 case CTSF_TABLEPCT_COUNT_RESPONSES:
2081 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2082 case CTSF_LAYERPCT_COUNT_RESPONSES:
2083 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2084 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2089 static enum ctables_domain_type
2090 ctables_function_domain (enum ctables_summary_function function)
2112 case CTSF_RESPONSES:
2115 case CTSF_COLPCT_COUNT:
2116 case CTSF_COLPCT_COUNT_RESPONSES:
2117 case CTSF_COLPCT_RESPONSES:
2118 case CTSF_COLPCT_RESPONSES_COUNT:
2119 case CTSF_COLPCT_SUM:
2120 case CTSF_COLPCT_TOTALN:
2121 case CTSF_COLPCT_VALIDN:
2124 case CTSF_LAYERCOLPCT_COUNT:
2125 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2126 case CTSF_LAYERCOLPCT_RESPONSES:
2127 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2128 case CTSF_LAYERCOLPCT_SUM:
2129 case CTSF_LAYERCOLPCT_TOTALN:
2130 case CTSF_LAYERCOLPCT_VALIDN:
2131 return CTDT_LAYERCOL;
2133 case CTSF_LAYERPCT_COUNT:
2134 case CTSF_LAYERPCT_COUNT_RESPONSES:
2135 case CTSF_LAYERPCT_RESPONSES:
2136 case CTSF_LAYERPCT_RESPONSES_COUNT:
2137 case CTSF_LAYERPCT_SUM:
2138 case CTSF_LAYERPCT_TOTALN:
2139 case CTSF_LAYERPCT_VALIDN:
2142 case CTSF_LAYERROWPCT_COUNT:
2143 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2144 case CTSF_LAYERROWPCT_RESPONSES:
2145 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2146 case CTSF_LAYERROWPCT_SUM:
2147 case CTSF_LAYERROWPCT_TOTALN:
2148 case CTSF_LAYERROWPCT_VALIDN:
2149 return CTDT_LAYERROW;
2151 case CTSF_ROWPCT_COUNT:
2152 case CTSF_ROWPCT_COUNT_RESPONSES:
2153 case CTSF_ROWPCT_RESPONSES:
2154 case CTSF_ROWPCT_RESPONSES_COUNT:
2155 case CTSF_ROWPCT_SUM:
2156 case CTSF_ROWPCT_TOTALN:
2157 case CTSF_ROWPCT_VALIDN:
2160 case CTSF_SUBTABLEPCT_COUNT:
2161 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2162 case CTSF_SUBTABLEPCT_RESPONSES:
2163 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2164 case CTSF_SUBTABLEPCT_SUM:
2165 case CTSF_SUBTABLEPCT_TOTALN:
2166 case CTSF_SUBTABLEPCT_VALIDN:
2167 return CTDT_SUBTABLE;
2169 case CTSF_TABLEPCT_COUNT:
2170 case CTSF_TABLEPCT_COUNT_RESPONSES:
2171 case CTSF_TABLEPCT_RESPONSES:
2172 case CTSF_TABLEPCT_RESPONSES_COUNT:
2173 case CTSF_TABLEPCT_SUM:
2174 case CTSF_TABLEPCT_TOTALN:
2175 case CTSF_TABLEPCT_VALIDN:
2183 ctables_summary_value (const struct ctables_cell *cell,
2184 union ctables_summary *s,
2185 const struct ctables_summary_spec *ss)
2187 switch (ss->function)
2193 case CTSF_ROWPCT_COUNT:
2194 case CTSF_COLPCT_COUNT:
2195 case CTSF_TABLEPCT_COUNT:
2196 case CTSF_SUBTABLEPCT_COUNT:
2197 case CTSF_LAYERPCT_COUNT:
2198 case CTSF_LAYERROWPCT_COUNT:
2199 case CTSF_LAYERCOLPCT_COUNT:
2201 enum ctables_domain_type d = ctables_function_domain (ss->function);
2202 return (cell->domains[d]->e_valid
2203 ? s->valid / cell->domains[d]->e_valid * 100
2207 case CTSF_ROWPCT_VALIDN:
2208 case CTSF_COLPCT_VALIDN:
2209 case CTSF_TABLEPCT_VALIDN:
2210 case CTSF_SUBTABLEPCT_VALIDN:
2211 case CTSF_LAYERPCT_VALIDN:
2212 case CTSF_LAYERROWPCT_VALIDN:
2213 case CTSF_LAYERCOLPCT_VALIDN:
2214 case CTSF_ROWPCT_TOTALN:
2215 case CTSF_COLPCT_TOTALN:
2216 case CTSF_TABLEPCT_TOTALN:
2217 case CTSF_SUBTABLEPCT_TOTALN:
2218 case CTSF_LAYERPCT_TOTALN:
2219 case CTSF_LAYERROWPCT_TOTALN:
2220 case CTSF_LAYERCOLPCT_TOTALN:
2228 return s->valid + s->missing;
2241 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2246 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2252 double weight, variance;
2253 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2254 return calc_semean (variance, weight);
2260 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2261 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2266 double weight, mean;
2267 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2268 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2274 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2278 case CTSF_ROWPCT_SUM:
2279 case CTSF_COLPCT_SUM:
2280 case CTSF_TABLEPCT_SUM:
2281 case CTSF_SUBTABLEPCT_SUM:
2282 case CTSF_LAYERPCT_SUM:
2283 case CTSF_LAYERROWPCT_SUM:
2284 case CTSF_LAYERCOLPCT_SUM:
2291 struct casereader *reader = casewriter_make_reader (s->writer);
2294 struct percentile *ptile = percentile_create (
2295 ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2296 struct order_stats *os = &ptile->parent;
2297 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2298 s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2299 statistic_destroy (&ptile->parent.parent);
2306 struct casereader *reader = casewriter_make_reader (s->writer);
2309 struct mode *mode = mode_create ();
2310 struct order_stats *os = &mode->parent;
2311 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2312 s->ovalue = mode->mode;
2313 statistic_destroy (&mode->parent.parent);
2317 case CTSF_RESPONSES:
2318 case CTSF_ROWPCT_RESPONSES:
2319 case CTSF_COLPCT_RESPONSES:
2320 case CTSF_TABLEPCT_RESPONSES:
2321 case CTSF_SUBTABLEPCT_RESPONSES:
2322 case CTSF_LAYERPCT_RESPONSES:
2323 case CTSF_LAYERROWPCT_RESPONSES:
2324 case CTSF_LAYERCOLPCT_RESPONSES:
2325 case CTSF_ROWPCT_RESPONSES_COUNT:
2326 case CTSF_COLPCT_RESPONSES_COUNT:
2327 case CTSF_TABLEPCT_RESPONSES_COUNT:
2328 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2329 case CTSF_LAYERPCT_RESPONSES_COUNT:
2330 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2331 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2332 case CTSF_ROWPCT_COUNT_RESPONSES:
2333 case CTSF_COLPCT_COUNT_RESPONSES:
2334 case CTSF_TABLEPCT_COUNT_RESPONSES:
2335 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2336 case CTSF_LAYERPCT_COUNT_RESPONSES:
2337 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2338 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2345 struct ctables_cell_sort_aux
2347 const struct ctables_nest *nest;
2348 enum pivot_axis_type a;
2352 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2354 const struct ctables_cell_sort_aux *aux = aux_;
2355 struct ctables_cell *const *ap = a_;
2356 struct ctables_cell *const *bp = b_;
2357 const struct ctables_cell *a = *ap;
2358 const struct ctables_cell *b = *bp;
2360 const struct ctables_nest *nest = aux->nest;
2361 for (size_t i = 0; i < nest->n; i++)
2362 if (i != nest->scale_idx)
2364 const struct variable *var = nest->vars[i];
2365 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2366 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2367 if (a_cv->category != b_cv->category)
2368 return a_cv->category > b_cv->category ? 1 : -1;
2370 const union value *a_val = &a_cv->value;
2371 const union value *b_val = &b_cv->value;
2372 switch (a_cv->category->type)
2379 case CCT_POSTCOMPUTE:
2380 /* Must be equal. */
2387 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2395 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2397 return a_cv->category->sort_ascending ? cmp : -cmp;
2403 const char *a_label = var_lookup_value_label (var, a_val);
2404 const char *b_label = var_lookup_value_label (var, b_val);
2406 ? (b_label ? strcmp (a_label, b_label) : 1)
2407 : (b_label ? -1 : value_compare_3way (
2408 a_val, b_val, var_get_width (var))));
2410 return a_cv->category->sort_ascending ? cmp : -cmp;
2424 For each ctables_table:
2425 For each combination of row vars:
2426 For each combination of column vars:
2427 For each combination of layer vars:
2429 Make a table of row values:
2430 Sort entries by row values
2431 Assign a 0-based index to each actual value
2432 Construct a dimension
2433 Make a table of column values
2434 Make a table of layer values
2436 Fill the table entry using the indexes from before.
2439 static struct ctables_domain *
2440 ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
2441 enum ctables_domain_type domain)
2444 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2446 const struct ctables_nest *nest = s->nests[a];
2447 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2449 size_t v_idx = nest->domains[domain][i];
2450 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2451 var_get_width (nest->vars[v_idx]), hash);
2455 struct ctables_domain *d;
2456 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &s->domains[domain])
2458 const struct ctables_cell *df = d->example;
2459 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2461 const struct ctables_nest *nest = s->nests[a];
2462 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2464 size_t v_idx = nest->domains[domain][i];
2465 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2466 &cell->axes[a].cvs[v_idx].value,
2467 var_get_width (nest->vars[v_idx])))
2476 d = xmalloc (sizeof *d);
2477 *d = (struct ctables_domain) { .example = cell };
2478 hmap_insert (&s->domains[domain], &d->node, hash);
2482 static const struct ctables_category *
2483 ctables_categories_match (const struct ctables_categories *c,
2484 const union value *v, const struct variable *var)
2486 const struct ctables_category *othernm = NULL;
2487 for (size_t i = c->n_cats; i-- > 0; )
2489 const struct ctables_category *cat = &c->cats[i];
2493 if (cat->number == v->f)
2501 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2502 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2507 if (var_is_value_missing (var, v))
2511 case CCT_POSTCOMPUTE:
2527 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2532 return var_is_value_missing (var, v) ? NULL : othernm;
2535 static const struct ctables_category *
2536 ctables_categories_total (const struct ctables_categories *c)
2538 const struct ctables_category *first = &c->cats[0];
2539 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2540 return (first->type == CCT_TOTAL ? first
2541 : last->type == CCT_TOTAL ? last
2545 static struct ctables_cell *
2546 ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
2547 const struct ctables_category *cats[PIVOT_N_AXES][10])
2549 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2552 enum ctables_summary_variant sv = CSV_CELL;
2553 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2555 const struct ctables_nest *nest = s->nests[a];
2556 for (size_t i = 0; i < nest->n; i++)
2557 if (i != nest->scale_idx)
2559 hash = hash_pointer (cats[a][i], hash);
2560 if (cats[a][i]->type != CCT_TOTAL
2561 && cats[a][i]->type != CCT_SUBTOTAL
2562 && cats[a][i]->type != CCT_HSUBTOTAL)
2563 hash = value_hash (case_data (c, nest->vars[i]),
2564 var_get_width (nest->vars[i]), hash);
2570 struct ctables_cell *cell;
2571 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &s->cells)
2573 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2575 const struct ctables_nest *nest = s->nests[a];
2576 for (size_t i = 0; i < nest->n; i++)
2577 if (i != nest->scale_idx
2578 && (cats[a][i] != cell->axes[a].cvs[i].category
2579 || (cats[a][i]->type != CCT_TOTAL
2580 && cats[a][i]->type != CCT_SUBTOTAL
2581 && cats[a][i]->type != CCT_HSUBTOTAL
2582 && !value_equal (case_data (c, nest->vars[i]),
2583 &cell->axes[a].cvs[i].value,
2584 var_get_width (nest->vars[i])))))
2593 cell = xmalloc (sizeof *cell);
2596 cell->contributes_to_domains = true;
2597 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2599 const struct ctables_nest *nest = s->nests[a];
2600 cell->axes[a].cvs = (nest->n
2601 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2603 for (size_t i = 0; i < nest->n; i++)
2605 const struct ctables_category *cat = cats[a][i];
2607 if (i != nest->scale_idx)
2609 const struct ctables_category *subtotal = cat->subtotal;
2610 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2613 if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2614 cell->contributes_to_domains = false;
2617 cell->axes[a].cvs[i].category = cat;
2618 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2619 var_get_width (nest->vars[i]));
2623 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2624 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2625 for (size_t i = 0; i < specs->n; i++)
2626 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2627 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2628 cell->domains[dt] = ctables_domain_insert (s, cell, dt);
2629 hmap_insert (&s->cells, &cell->node, hash);
2634 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
2635 const struct ctables_category *cats[PIVOT_N_AXES][10],
2636 double d_weight, double e_weight)
2638 struct ctables_cell *cell = ctables_cell_insert__ (s, c, cats);
2639 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2641 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2642 for (size_t i = 0; i < specs->n; i++)
2643 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2644 case_data (c, specs->var), d_weight, e_weight);
2645 if (cell->contributes_to_domains)
2647 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2649 cell->domains[dt]->d_valid += d_weight;
2650 cell->domains[dt]->e_valid += e_weight;
2656 recurse_totals (struct ctables_section *s, const struct ccase *c,
2657 const struct ctables_category *cats[PIVOT_N_AXES][10],
2658 double d_weight, double e_weight,
2659 enum pivot_axis_type start_axis, size_t start_nest)
2661 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2663 const struct ctables_nest *nest = s->nests[a];
2664 for (size_t i = start_nest; i < nest->n; i++)
2666 if (i == nest->scale_idx)
2669 const struct variable *var = nest->vars[i];
2671 const struct ctables_category *total = ctables_categories_total (
2672 s->table->categories[var_get_dict_index (var)]);
2675 const struct ctables_category *save = cats[a][i];
2677 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2678 recurse_totals (s, c, cats, d_weight, e_weight, a, i + 1);
2687 recurse_subtotals (struct ctables_section *s, const struct ccase *c,
2688 const struct ctables_category *cats[PIVOT_N_AXES][10],
2689 double d_weight, double e_weight,
2690 enum pivot_axis_type start_axis, size_t start_nest)
2692 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2694 const struct ctables_nest *nest = s->nests[a];
2695 for (size_t i = start_nest; i < nest->n; i++)
2697 if (i == nest->scale_idx)
2700 const struct ctables_category *save = cats[a][i];
2703 cats[a][i] = save->subtotal;
2704 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2705 recurse_subtotals (s, c, cats, d_weight, e_weight, a, i + 1);
2714 ctables_add_occurrence (const struct variable *var,
2715 const union value *value,
2716 struct hmap *occurrences)
2718 int width = var_get_width (var);
2719 unsigned int hash = value_hash (value, width, 0);
2721 struct ctables_section_value *sv;
2722 HMAP_FOR_EACH_WITH_HASH (sv, struct ctables_section_value, node, hash,
2724 if (value_equal (value, &sv->value, width))
2727 sv = xmalloc (sizeof *sv);
2728 value_clone (&sv->value, value, width);
2729 hmap_insert (occurrences, &sv->node, hash);
2733 ctables_cell_insert (struct ctables_section *s,
2734 const struct ccase *c,
2735 double d_weight, double e_weight)
2737 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
2738 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2740 const struct ctables_nest *nest = s->nests[a];
2741 for (size_t i = 0; i < nest->n; i++)
2743 if (i == nest->scale_idx)
2746 const struct variable *var = nest->vars[i];
2747 const union value *value = case_data (c, var);
2749 if (var_is_numeric (var) && value->f == SYSMIS)
2752 cats[a][i] = ctables_categories_match (
2753 s->table->categories[var_get_dict_index (var)], value, var);
2759 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2761 const struct ctables_nest *nest = s->nests[a];
2762 for (size_t i = 0; i < nest->n; i++)
2763 if (i != nest->scale_idx)
2765 const struct variable *var = nest->vars[i];
2766 const union value *value = case_data (c, var);
2767 ctables_add_occurrence (var, value, &s->occurrences[a][i]);
2771 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2773 recurse_totals (s, c, cats, d_weight, e_weight, 0, 0);
2774 recurse_subtotals (s, c, cats, d_weight, e_weight, 0, 0);
2779 const struct ctables_summary_spec_set *set;
2784 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2786 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2787 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2788 if (as->function != bs->function)
2789 return as->function > bs->function ? 1 : -1;
2790 else if (as->percentile != bs->percentile)
2791 return as->percentile < bs->percentile ? 1 : -1;
2792 return strcmp (as->label, bs->label);
2795 static struct pivot_value *
2796 ctables_category_create_label (const struct ctables_category *cat,
2797 const struct variable *var,
2798 const union value *value)
2800 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2801 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2802 : pivot_value_new_var_value (var, value));
2805 static struct ctables_value *
2806 ctables_value_find__ (struct ctables_table *t, const union value *value,
2807 int width, unsigned int hash)
2809 struct ctables_value *clv;
2810 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2811 hash, &t->clabels_values_map)
2812 if (value_equal (value, &clv->value, width))
2817 static struct ctables_value *
2818 ctables_value_find (struct ctables_table *t,
2819 const union value *value, int width)
2821 return ctables_value_find__ (t, value, width,
2822 value_hash (value, width, 0));
2826 ctables_table_add_section (struct ctables_table *t, enum pivot_axis_type a,
2827 size_t ix[PIVOT_N_AXES])
2829 if (a < PIVOT_N_AXES)
2831 size_t limit = MAX (t->stacks[a].n, 1);
2832 for (ix[a] = 0; ix[a] < limit; ix[a]++)
2833 ctables_table_add_section (t, a + 1, ix);
2837 struct ctables_section *s = &t->sections[t->n_sections++];
2838 *s = (struct ctables_section) {
2840 .cells = HMAP_INITIALIZER (s->cells),
2842 for (a = 0; a < PIVOT_N_AXES; a++)
2845 struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2847 s->occurrences[a] = xnmalloc (nest->n, sizeof *s->occurrences[a]);
2848 for (size_t i = 0; i < nest->n; i++)
2849 hmap_init (&s->occurrences[a][i]);
2851 for (size_t i = 0; i < N_CTDTS; i++)
2852 hmap_init (&s->domains[i]);
2857 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2859 struct pivot_table *pt = pivot_table_create__ (
2861 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2862 : pivot_value_new_text (N_("Custom Tables"))),
2865 pivot_table_set_caption (
2866 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2868 pivot_table_set_caption (
2869 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2871 bool summary_dimension = (t->summary_axis != t->slabels_axis
2872 || (!t->slabels_visible
2873 && t->summary_specs.n > 1));
2874 if (summary_dimension)
2876 struct pivot_dimension *d = pivot_dimension_create (
2877 pt, t->slabels_axis, N_("Statistics"));
2878 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2879 if (!t->slabels_visible)
2880 d->hide_all_labels = true;
2881 for (size_t i = 0; i < specs->n; i++)
2882 pivot_category_create_leaf (
2883 d->root, pivot_value_new_text (specs->specs[i].label));
2886 bool categories_dimension = t->clabels_example != NULL;
2887 if (categories_dimension)
2889 struct pivot_dimension *d = pivot_dimension_create (
2890 pt, t->label_axis[t->clabels_from_axis],
2891 t->clabels_from_axis == PIVOT_AXIS_ROW
2892 ? N_("Row Categories")
2893 : N_("Column Categories"));
2894 const struct variable *var = t->clabels_example;
2895 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2896 for (size_t i = 0; i < t->n_clabels_values; i++)
2898 const struct ctables_value *value = t->clabels_values[i];
2899 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2900 assert (cat != NULL);
2901 pivot_category_create_leaf (d->root, ctables_category_create_label (
2902 cat, t->clabels_example, &value->value));
2906 pivot_table_set_look (pt, ct->look);
2907 struct pivot_dimension *d[PIVOT_N_AXES];
2908 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2910 static const char *names[] = {
2911 [PIVOT_AXIS_ROW] = N_("Rows"),
2912 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2913 [PIVOT_AXIS_LAYER] = N_("Layers"),
2915 d[a] = (t->axes[a] || a == t->summary_axis
2916 ? pivot_dimension_create (pt, a, names[a])
2921 assert (t->axes[a]);
2923 for (size_t i = 0; i < t->stacks[a].n; i++)
2925 struct ctables_nest *nest = &t->stacks[a].nests[i];
2926 struct ctables_section **sections = xnmalloc (t->n_sections,
2928 size_t n_sections = 0;
2930 size_t n_total_cells = 0;
2931 size_t max_depth = 0;
2932 for (size_t j = 0; j < t->n_sections; j++)
2933 if (t->sections[j].nests[a] == nest)
2935 struct ctables_section *s = &t->sections[j];
2936 sections[n_sections++] = s;
2937 n_total_cells += s->cells.count;
2939 size_t depth = s->nests[a]->n;
2940 max_depth = MAX (depth, max_depth);
2943 struct ctables_cell **sorted = xnmalloc (n_total_cells,
2945 size_t n_sorted = 0;
2947 for (size_t j = 0; j < n_sections; j++)
2949 struct ctables_section *s = sections[j];
2951 struct ctables_cell *cell;
2952 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
2954 sorted[n_sorted++] = cell;
2955 assert (n_sorted <= n_total_cells);
2958 struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
2959 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2961 struct ctables_level
2963 enum ctables_level_type
2965 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2966 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2967 CTL_SUMMARY, /* Summary functions. */
2973 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2974 size_t n_levels = 0;
2975 for (size_t k = 0; k < nest->n; k++)
2977 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2978 if (vlabel != CTVL_NONE)
2980 levels[n_levels++] = (struct ctables_level) {
2986 if (nest->scale_idx != k
2987 && (k != nest->n - 1 || t->label_axis[a] == a))
2989 levels[n_levels++] = (struct ctables_level) {
2990 .type = CTL_CATEGORY,
2996 if (!summary_dimension && a == t->slabels_axis)
2998 levels[n_levels++] = (struct ctables_level) {
2999 .type = CTL_SUMMARY,
3000 .var_idx = SIZE_MAX,
3004 /* Pivot categories:
3006 - variable label for nest->vars[0], if vlabel != CTVL_NONE
3007 - category for nest->vars[0], if nest->scale_idx != 0
3008 - variable label for nest->vars[1], if vlabel != CTVL_NONE
3009 - category for nest->vars[1], if nest->scale_idx != 1
3011 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
3012 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
3013 - summary function, if 'a == t->slabels_axis && a ==
3016 Additional dimensions:
3018 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
3020 - If 't->label_axis[b] == a' for some 'b != a', add a category
3025 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
3027 for (size_t j = 0; j < n_sorted; j++)
3029 struct ctables_cell *cell = sorted[j];
3030 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
3032 size_t n_common = 0;
3035 for (; n_common < n_levels; n_common++)
3037 const struct ctables_level *level = &levels[n_common];
3038 if (level->type == CTL_CATEGORY)
3040 size_t var_idx = level->var_idx;
3041 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3042 if (prev->axes[a].cvs[var_idx].category != c)
3044 else if (c->type != CCT_SUBTOTAL
3045 && c->type != CCT_HSUBTOTAL
3046 && c->type != CCT_TOTAL
3047 && !value_equal (&prev->axes[a].cvs[var_idx].value,
3048 &cell->axes[a].cvs[var_idx].value,
3049 var_get_type (nest->vars[var_idx])))
3055 for (size_t k = n_common; k < n_levels; k++)
3057 const struct ctables_level *level = &levels[k];
3058 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3059 if (level->type == CTL_SUMMARY)
3061 assert (k == n_levels - 1);
3063 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3064 for (size_t m = 0; m < specs->n; m++)
3066 int leaf = pivot_category_create_leaf (
3067 parent, pivot_value_new_text (specs->specs[m].label));
3074 const struct variable *var = nest->vars[level->var_idx];
3075 struct pivot_value *label;
3076 if (level->type == CTL_VAR)
3077 label = pivot_value_new_variable (var);
3078 else if (level->type == CTL_CATEGORY)
3080 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3081 label = ctables_category_create_label (cv->category,
3087 if (k == n_levels - 1)
3088 prev_leaf = pivot_category_create_leaf (parent, label);
3090 groups[k] = pivot_category_create_group__ (parent, label);
3094 cell->axes[a].leaf = prev_leaf;
3101 for (size_t i = 0; i < t->n_sections; i++)
3103 struct ctables_section *s = &t->sections[i];
3105 struct ctables_cell *cell;
3106 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3111 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3112 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3113 for (size_t j = 0; j < specs->n; j++)
3116 size_t n_dindexes = 0;
3118 if (summary_dimension)
3119 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3121 if (categories_dimension)
3123 const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3124 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3125 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3126 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3127 assert (ctv != NULL);
3128 dindexes[n_dindexes++] = ctv->leaf;
3131 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3134 int leaf = cell->axes[a].leaf;
3135 if (a == t->summary_axis && !summary_dimension)
3137 dindexes[n_dindexes++] = leaf;
3140 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
3141 struct pivot_value *value = pivot_value_new_number (d);
3142 value->numeric.format = specs->specs[j].format;
3143 pivot_table_put (pt, dindexes, n_dindexes, value);
3148 pivot_table_submit (pt);
3152 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3154 enum pivot_axis_type label_pos = t->label_axis[a];
3158 t->clabels_from_axis = a;
3160 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3161 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3163 const struct ctables_stack *stack = &t->stacks[a];
3167 const struct ctables_nest *n0 = &stack->nests[0];
3169 const struct variable *v0 = n0->vars[n0->n - 1];
3170 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3171 t->clabels_example = v0;
3173 for (size_t i = 0; i < c0->n_cats; i++)
3174 if (c0->cats[i].type == CCT_FUNCTION)
3176 msg (SE, _("%s=%s is not allowed with sorting based "
3177 "on a summary function."),
3178 subcommand_name, pos_name);
3181 if (n0->n - 1 == n0->scale_idx)
3183 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3184 "but %s is a scale variable."),
3185 subcommand_name, pos_name, var_get_name (v0));
3189 for (size_t i = 1; i < stack->n; i++)
3191 const struct ctables_nest *ni = &stack->nests[i];
3193 const struct variable *vi = ni->vars[ni->n - 1];
3194 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3196 if (ni->n - 1 == ni->scale_idx)
3198 msg (SE, _("%s=%s requires the variables to be moved to be "
3199 "categorical, but %s is a scale variable."),
3200 subcommand_name, pos_name, var_get_name (vi));
3203 if (var_get_width (v0) != var_get_width (vi))
3205 msg (SE, _("%s=%s requires the variables to be "
3206 "moved to have the same width, but %s has "
3207 "width %d and %s has width %d."),
3208 subcommand_name, pos_name,
3209 var_get_name (v0), var_get_width (v0),
3210 var_get_name (vi), var_get_width (vi));
3213 if (!val_labs_equal (var_get_value_labels (v0),
3214 var_get_value_labels (vi)))
3216 msg (SE, _("%s=%s requires the variables to be "
3217 "moved to have the same value labels, but %s "
3218 "and %s have different value labels."),
3219 subcommand_name, pos_name,
3220 var_get_name (v0), var_get_name (vi));
3223 if (!ctables_categories_equal (c0, ci))
3225 msg (SE, _("%s=%s requires the variables to be "
3226 "moved to have the same category "
3227 "specifications, but %s and %s have different "
3228 "category specifications."),
3229 subcommand_name, pos_name,
3230 var_get_name (v0), var_get_name (vi));
3239 ctables_prepare_table (struct ctables_table *t)
3241 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3244 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3246 for (size_t j = 0; j < t->stacks[a].n; j++)
3248 struct ctables_nest *nest = &t->stacks[a].nests[j];
3249 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3251 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3252 nest->n_domains[dt] = 0;
3254 for (size_t k = 0; k < nest->n; k++)
3256 if (k == nest->scale_idx)
3265 if (a != PIVOT_AXIS_LAYER)
3272 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3273 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3274 : a == PIVOT_AXIS_ROW)
3276 if (k == nest->n - 1
3277 || (nest->scale_idx == nest->n - 1
3278 && k == nest->n - 2))
3284 if (a == PIVOT_AXIS_COLUMN)
3289 if (a == PIVOT_AXIS_ROW)
3294 nest->domains[dt][nest->n_domains[dt]++] = k;
3301 struct ctables_nest *nest = xmalloc (sizeof *nest);
3302 *nest = (struct ctables_nest) { .n = 0 };
3303 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3306 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3307 for (size_t i = 0; i < stack->n; i++)
3309 struct ctables_nest *nest = &stack->nests[i];
3310 if (!nest->specs[CSV_CELL].n)
3312 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3313 specs->specs = xmalloc (sizeof *specs->specs);
3316 enum ctables_summary_function function
3317 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3318 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3320 *specs->specs = (struct ctables_summary_spec) {
3321 .function = function,
3322 .format = ctables_summary_default_format (function, &var),
3323 .label = ctables_summary_default_label (function, 0),
3326 specs->var = nest->vars[0];
3328 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3329 &nest->specs[CSV_CELL]);
3331 else if (!nest->specs[CSV_TOTAL].n)
3332 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3333 &nest->specs[CSV_CELL]);
3336 struct ctables_summary_spec_set *merged = &t->summary_specs;
3337 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3339 for (size_t j = 0; j < stack->n; j++)
3341 const struct ctables_nest *nest = &stack->nests[j];
3343 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3344 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3349 struct merge_item min = items[0];
3350 for (size_t j = 1; j < n_left; j++)
3351 if (merge_item_compare_3way (&items[j], &min) < 0)
3354 if (merged->n >= merged->allocated)
3355 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3356 sizeof *merged->specs);
3357 merged->specs[merged->n++] = min.set->specs[min.ofs];
3359 for (size_t j = 0; j < n_left; )
3361 if (merge_item_compare_3way (&items[j], &min) == 0)
3363 struct merge_item *item = &items[j];
3364 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3365 if (++item->ofs >= item->set->n)
3367 items[j] = items[--n_left];
3376 for (size_t j = 0; j < merged->n; j++)
3377 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3379 for (size_t j = 0; j < stack->n; j++)
3381 const struct ctables_nest *nest = &stack->nests[j];
3382 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3384 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3385 for (size_t k = 0; k < specs->n; k++)
3386 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3387 specs->specs[k].axis_idx);
3393 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3394 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3398 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3399 enum pivot_axis_type a)
3401 struct ctables_stack *stack = &t->stacks[a];
3402 for (size_t i = 0; i < stack->n; i++)
3404 const struct ctables_nest *nest = &stack->nests[i];
3405 const struct variable *var = nest->vars[nest->n - 1];
3406 int width = var_get_width (var);
3407 const union value *value = case_data (c, var);
3409 if (var_is_numeric (var) && value->f == SYSMIS)
3412 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3416 unsigned int hash = value_hash (value, width, 0);
3418 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3421 clv = xmalloc (sizeof *clv);
3422 value_clone (&clv->value, value, width);
3423 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3429 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3431 const struct ctables_value *const *ap = a_;
3432 const struct ctables_value *const *bp = b_;
3433 const struct ctables_value *a = *ap;
3434 const struct ctables_value *b = *bp;
3435 const int *width = width_;
3436 return value_compare_3way (&a->value, &b->value, *width);
3440 ctables_sort_clabels_values (struct ctables_table *t)
3442 int width = var_get_width (t->clabels_example);
3444 size_t n = hmap_count (&t->clabels_values_map);
3445 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3447 struct ctables_value *clv;
3449 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3450 t->clabels_values[i++] = clv;
3451 t->n_clabels_values = n;
3454 sort (t->clabels_values, n, sizeof *t->clabels_values,
3455 compare_clabels_values_3way, &width);
3457 for (size_t i = 0; i < n; i++)
3458 t->clabels_values[i]->leaf = i;
3462 ctables_add_category_occurrences (const struct variable *var,
3463 struct hmap *occurrences,
3464 const struct ctables_categories *cats)
3466 const struct val_labs *val_labs = var_get_value_labels (var);
3468 for (size_t i = 0; i < cats->n_cats; i++)
3470 const struct ctables_category *c = &cats->cats[i];
3474 ctables_add_occurrence (var, &(const union value) { .f = c->number },
3482 assert (var_is_numeric (var));
3483 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3484 vl = val_labs_next (val_labs, vl))
3485 if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
3486 ctables_add_occurrence (var, &vl->value, occurrences);
3490 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3491 vl = val_labs_next (val_labs, vl))
3492 if (var_is_value_missing (var, &vl->value))
3493 ctables_add_occurrence (var, &vl->value, occurrences);
3497 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3498 vl = val_labs_next (val_labs, vl))
3499 ctables_add_occurrence (var, &vl->value, occurrences);
3502 case CCT_POSTCOMPUTE:
3513 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3514 vl = val_labs_next (val_labs, vl))
3515 if (c->include_missing || !var_is_value_missing (var, &vl->value))
3516 ctables_add_occurrence (var, &vl->value, occurrences);
3523 ctables_section_recurse_add_empty_categories (
3524 struct ctables_section *s,
3525 const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
3526 enum pivot_axis_type a, size_t a_idx)
3528 if (a >= PIVOT_N_AXES)
3529 ctables_cell_insert__ (s, c, cats);
3530 else if (!s->nests[a] || a_idx >= s->nests[a]->n)
3531 ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
3534 const struct variable *var = s->nests[a]->vars[a_idx];
3535 int width = var_get_width (var);
3536 const struct hmap *occurrences = &s->occurrences[a][a_idx];
3537 const struct ctables_section_value *sv;
3538 HMAP_FOR_EACH (sv, struct ctables_section_value, node, occurrences)
3540 union value *value = case_data_rw (c, var);
3541 value_destroy (value, width);
3542 value_clone (value, &sv->value, width);
3543 cats[a][a_idx] = ctables_categories_match (
3544 s->table->categories[var_get_dict_index (var)], value, var);
3545 assert (cats[a][a_idx] != NULL);
3546 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3552 ctables_section_add_empty_categories (struct ctables_section *s)
3554 bool show_empty = false;
3555 for (size_t a = 0; a < PIVOT_N_AXES; a++)
3557 for (size_t k = 0; k < s->nests[a]->n; k++)
3558 if (k != s->nests[a]->scale_idx)
3560 const struct variable *var = s->nests[a]->vars[k];
3561 const struct ctables_categories *cats = s->table->categories[
3562 var_get_dict_index (var)];
3563 if (cats->show_empty)
3566 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
3572 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
3573 struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
3574 ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
3579 ctables_execute (struct dataset *ds, struct ctables *ct)
3581 for (size_t i = 0; i < ct->n_tables; i++)
3583 struct ctables_table *t = ct->tables[i];
3584 t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
3585 MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
3586 MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
3587 sizeof *t->sections);
3588 size_t ix[PIVOT_N_AXES];
3589 ctables_table_add_section (t, 0, ix);
3592 struct casereader *input = proc_open (ds);
3593 bool warn_on_invalid = true;
3594 for (struct ccase *c = casereader_read (input); c;
3595 case_unref (c), c = casereader_read (input))
3597 double d_weight = dict_get_case_weight (dataset_dict (ds), c,
3599 double e_weight = (ct->e_weight
3600 ? var_force_valid_weight (ct->e_weight,
3601 case_num (c, ct->e_weight),
3605 for (size_t i = 0; i < ct->n_tables; i++)
3607 struct ctables_table *t = ct->tables[i];
3609 for (size_t j = 0; j < t->n_sections; j++)
3610 ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
3612 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3613 if (t->label_axis[a] != a)
3614 ctables_insert_clabels_values (t, c, a);
3617 casereader_destroy (input);
3619 for (size_t i = 0; i < ct->n_tables; i++)
3621 struct ctables_table *t = ct->tables[i];
3623 if (t->clabels_example)
3624 ctables_sort_clabels_values (t);
3626 for (size_t j = 0; j < t->n_sections; j++)
3627 ctables_section_add_empty_categories (&t->sections[j]);
3629 ctables_table_output (ct, ct->tables[i]);
3631 return proc_commit (ds);
3636 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
3639 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
3645 case CTPO_CAT_STRING:
3655 for (size_t i = 0; i < 2; i++)
3656 ctables_pcexpr_destroy (e->subs[i]);
3660 case CTPO_CAT_NUMBER:
3661 case CTPO_CAT_RANGE:
3662 case CTPO_CAT_MISSING:
3663 case CTPO_CAT_OTHERNM:
3664 case CTPO_CAT_SUBTOTAL:
3665 case CTPO_CAT_TOTAL:
3669 msg_location_destroy (e->location);
3674 static struct ctables_pcexpr *
3675 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
3676 struct ctables_pcexpr *sub0,
3677 struct ctables_pcexpr *sub1)
3679 struct ctables_pcexpr *e = xmalloc (sizeof *e);
3680 *e = (struct ctables_pcexpr) {
3682 .subs = { sub0, sub1 },
3683 .ofs = { sub0->ofs[0], sub1->ofs[1] }
3688 static struct msg_location *
3689 ctables_pcexpr_location (struct lexer *lexer, const struct ctables_pcexpr *e_)
3693 struct ctables_pcexpr *e = CONST_CAST (struct ctables_pcexpr *, e_);
3694 e->location = lex_ofs_location (lexer, e->ofs[0], e->ofs[1]);
3696 return e_->location;
3699 /* How to parse an operator. */
3702 enum token_type token;
3703 enum ctables_postcompute_op op;
3706 static const struct operator *
3707 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
3709 for (const struct operator *op = ops; op < ops + n_ops; op++)
3710 if (lex_token (lexer) == op->token)
3712 if (op->token != T_NEG_NUM)
3721 static struct ctables_pcexpr *
3722 parse_binary_operators__ (struct lexer *lexer,
3723 const struct operator ops[], size_t n_ops,
3724 parse_recursively_func *parse_next_level,
3725 const char *chain_warning,
3726 struct ctables_pcexpr *lhs)
3728 for (int op_count = 0; ; op_count++)
3730 const struct operator *op = match_operator (lexer, ops, n_ops);
3733 if (op_count > 1 && chain_warning)
3734 msg_at (SW, ctables_pcexpr_location (lexer, lhs),
3735 "%s", chain_warning);
3740 struct ctables_pcexpr *rhs = parse_next_level (lexer);
3743 ctables_pcexpr_destroy (lhs);
3747 lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
3751 static struct ctables_pcexpr *
3752 parse_binary_operators (struct lexer *lexer,
3753 const struct operator ops[], size_t n_ops,
3754 parse_recursively_func *parse_next_level,
3755 const char *chain_warning)
3757 struct ctables_pcexpr *lhs = parse_next_level (lexer);
3761 return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
3762 chain_warning, lhs);
3765 static struct ctables_pcexpr *parse_add (struct lexer *);
3767 static struct ctables_pcexpr
3768 ctpo_cat_range (double low, double high)
3770 return (struct ctables_pcexpr) {
3771 .op = CTPO_CAT_RANGE,
3772 .range = { low, high },
3776 static struct ctables_pcexpr *
3777 parse_primary (struct lexer *lexer)
3779 int start_ofs = lex_ofs (lexer);
3780 struct ctables_pcexpr e;
3781 if (lex_is_number (lexer))
3783 e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
3784 .number = lex_number (lexer) };
3787 else if (lex_match_id (lexer, "MISSING"))
3788 e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
3789 else if (lex_match_id (lexer, "OTHERNM"))
3790 e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
3791 else if (lex_match_id (lexer, "TOTAL"))
3792 e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
3793 else if (lex_match_id (lexer, "SUBTOTAL"))
3795 size_t subtotal_index = 0;
3796 if (lex_match (lexer, T_LBRACK))
3798 if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
3800 subtotal_index = lex_integer (lexer);
3802 if (!lex_force_match (lexer, T_RBRACK))
3805 e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
3806 .subtotal_index = subtotal_index };
3808 else if (lex_match (lexer, T_LBRACK))
3810 if (lex_match_id (lexer, "LO"))
3812 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
3814 e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
3817 else if (lex_is_number (lexer))
3819 double number = lex_number (lexer);
3821 if (lex_match_id (lexer, "THRU"))
3823 if (lex_match_id (lexer, "HI"))
3824 e = ctpo_cat_range (number, DBL_MAX);
3827 if (!lex_force_num (lexer))
3829 e = ctpo_cat_range (number, lex_number (lexer));
3834 e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
3837 else if (lex_is_string (lexer))
3839 e = (struct ctables_pcexpr) {
3840 .op = CTPO_CAT_STRING,
3841 .string = ss_xstrdup (lex_tokss (lexer)),
3847 lex_error (lexer, NULL);
3851 if (!lex_force_match (lexer, T_RBRACK))
3853 if (e.op == CTPO_CAT_STRING)
3858 else if (lex_match (lexer, T_LPAREN))
3860 struct ctables_pcexpr *ep = parse_add (lexer);
3863 if (!lex_force_match (lexer, T_RPAREN))
3865 ctables_pcexpr_destroy (ep);
3872 lex_error (lexer, NULL);
3876 e.ofs[0] = start_ofs;
3877 e.ofs[1] = lex_ofs (lexer) - 1;
3878 return xmemdup (&e, sizeof e);
3881 static struct ctables_pcexpr *
3882 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
3883 struct lexer *lexer, int start_ofs)
3885 struct ctables_pcexpr *e = xmalloc (sizeof *e);
3886 *e = (struct ctables_pcexpr) {
3889 .ofs = { start_ofs, lex_ofs (lexer) - 1 },
3894 static struct ctables_pcexpr *
3895 parse_exp (struct lexer *lexer)
3897 static const struct operator op = { T_EXP, CTPO_POW };
3899 const char *chain_warning =
3900 _("The exponentiation operator (`**') is left-associative: "
3901 "`a**b**c' equals `(a**b)**c', not `a**(b**c)'. "
3902 "To disable this warning, insert parentheses.");
3904 if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
3905 return parse_binary_operators (lexer, &op, 1,
3906 parse_primary, chain_warning);
3908 /* Special case for situations like "-5**6", which must be parsed as
3911 int start_ofs = lex_ofs (lexer);
3912 struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
3913 *lhs = (struct ctables_pcexpr) {
3914 .op = CTPO_CONSTANT,
3915 .number = -lex_tokval (lexer),
3916 .ofs = { start_ofs, lex_ofs (lexer) },
3920 struct ctables_pcexpr *node = parse_binary_operators__ (
3921 lexer, &op, 1, parse_primary, chain_warning, lhs);
3925 return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
3928 /* Parses the unary minus level. */
3929 static struct ctables_pcexpr *
3930 parse_neg (struct lexer *lexer)
3932 int start_ofs = lex_ofs (lexer);
3933 if (!lex_match (lexer, T_DASH))
3934 return parse_exp (lexer);
3936 struct ctables_pcexpr *inner = parse_neg (lexer);
3940 return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
3943 /* Parses the multiplication and division level. */
3944 static struct ctables_pcexpr *
3945 parse_mul (struct lexer *lexer)
3947 static const struct operator ops[] =
3949 { T_ASTERISK, CTPO_MUL },
3950 { T_SLASH, CTPO_DIV },
3953 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
3957 /* Parses the addition and subtraction level. */
3958 static struct ctables_pcexpr *
3959 parse_add (struct lexer *lexer)
3961 static const struct operator ops[] =
3963 { T_PLUS, CTPO_ADD },
3964 { T_DASH, CTPO_SUB },
3965 { T_NEG_NUM, CTPO_ADD },
3968 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
3972 static struct ctables_postcompute *
3973 ctables_find_postcompute (struct ctables *ct, const char *name)
3975 struct ctables_postcompute *pc;
3976 HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
3977 utf8_hash_case_string (name, 0), &ct->postcomputes)
3978 if (!utf8_strcasecmp (pc->name, name))
3984 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
3986 int start_ofs = lex_ofs (lexer) - 1;
3988 if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
3991 char *name = ss_xstrdup (lex_tokss (lexer));
3994 if (!lex_force_match (lexer, T_EQUALS)
3995 || !lex_force_match_id (lexer, "EXPR")
3996 || !lex_force_match (lexer, T_LPAREN))
4002 struct ctables_pcexpr *expr = parse_add (lexer);
4003 if (!expr || !lex_force_match (lexer, T_RPAREN))
4009 struct msg_location *location = lex_ofs_location (lexer, start_ofs,
4010 lex_ofs (lexer) - 1);
4012 struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
4015 msg_at (SW, location, _("New definition of &%s will override the "
4016 "previous definition."),
4018 msg_at (SN, pc->location, _("This is the previous definition."));
4020 ctables_pcexpr_destroy (pc->expr);
4021 msg_location_destroy (pc->location);
4026 pc = xmalloc (sizeof *pc);
4027 *pc = (struct ctables_postcompute) { .name = name };
4028 hmap_insert (&ct->postcomputes, &pc->hmap_node,
4029 utf8_hash_case_string (pc->name, 0));
4032 pc->location = location;
4037 ctables_parse_pproperties_format (struct lexer *lexer,
4038 struct ctables_summary_spec_set *sss)
4040 *sss = (struct ctables_summary_spec_set) { .n = 0 };
4042 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4043 && !(lex_token (lexer) == T_ID
4044 && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4045 || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4046 lex_tokss (lexer)))))
4048 /* Parse function. */
4049 enum ctables_summary_function function;
4050 if (!parse_ctables_summary_function (lexer, &function))
4053 /* Parse percentile. */
4054 double percentile = 0;
4055 if (function == CTSF_PTILE)
4057 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4059 percentile = lex_number (lexer);
4064 struct fmt_spec format;
4065 if (!parse_format_specifier (lexer, &format)
4066 || !fmt_check_output (&format)
4067 || !fmt_check_type_compat (&format, VAL_NUMERIC))
4070 if (sss->n >= sss->allocated)
4071 sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4072 sizeof *sss->specs);
4073 sss->specs[sss->n++] = (struct ctables_summary_spec) {
4074 .function = function,
4075 .percentile = percentile,
4082 ctables_summary_spec_set_uninit (sss);
4087 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4089 struct ctables_postcompute **pcs = NULL;
4091 size_t allocated_pcs = 0;
4093 while (lex_match (lexer, T_AND))
4095 if (!lex_force_id (lexer))
4097 struct ctables_postcompute *pc
4098 = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4101 msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4106 if (n_pcs >= allocated_pcs)
4107 pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4111 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4113 if (lex_match_id (lexer, "LABEL"))
4115 lex_match (lexer, T_EQUALS);
4116 if (!lex_force_string (lexer))
4119 for (size_t i = 0; i < n_pcs; i++)
4121 free (pcs[i]->label);
4122 pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4127 else if (lex_match_id (lexer, "FORMAT"))
4129 lex_match (lexer, T_EQUALS);
4131 struct ctables_summary_spec_set sss;
4132 if (!ctables_parse_pproperties_format (lexer, &sss))
4135 for (size_t i = 0; i < n_pcs; i++)
4138 ctables_summary_spec_set_uninit (pcs[i]->specs);
4140 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4141 ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4143 ctables_summary_spec_set_uninit (&sss);
4145 else if (lex_match_id (lexer, "HIDESOURCECATS"))
4147 lex_match (lexer, T_EQUALS);
4148 bool hide_source_cats;
4149 if (!parse_bool (lexer, &hide_source_cats))
4151 for (size_t i = 0; i < n_pcs; i++)
4152 pcs[i]->hide_source_cats = hide_source_cats;
4156 lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4169 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4171 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4172 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4173 enum settings_value_show tvars = settings_get_show_variables ();
4174 for (size_t i = 0; i < n_vars; i++)
4175 vlabels[i] = (enum ctables_vlabel) tvars;
4177 struct ctables *ct = xmalloc (sizeof *ct);
4178 *ct = (struct ctables) {
4179 .dict = dataset_dict (ds),
4180 .look = pivot_table_look_unshare (pivot_table_look_ref (
4181 pivot_table_look_get_default ())),
4183 .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
4184 .hide_threshold = 5,
4186 ct->look->omit_empty = false;
4188 if (!lex_force_match (lexer, T_SLASH))
4191 while (!lex_match_id (lexer, "TABLE"))
4193 if (lex_match_id (lexer, "FORMAT"))
4195 double widths[2] = { SYSMIS, SYSMIS };
4196 double units_per_inch = 72.0;
4198 while (lex_token (lexer) != T_SLASH)
4200 if (lex_match_id (lexer, "MINCOLWIDTH"))
4202 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4205 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4207 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4210 else if (lex_match_id (lexer, "UNITS"))
4212 lex_match (lexer, T_EQUALS);
4213 if (lex_match_id (lexer, "POINTS"))
4214 units_per_inch = 72.0;
4215 else if (lex_match_id (lexer, "INCHES"))
4216 units_per_inch = 1.0;
4217 else if (lex_match_id (lexer, "CM"))
4218 units_per_inch = 2.54;
4221 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4225 else if (lex_match_id (lexer, "EMPTY"))
4230 lex_match (lexer, T_EQUALS);
4231 if (lex_match_id (lexer, "ZERO"))
4233 /* Nothing to do. */
4235 else if (lex_match_id (lexer, "BLANK"))
4236 ct->zero = xstrdup ("");
4237 else if (lex_force_string (lexer))
4239 ct->zero = ss_xstrdup (lex_tokss (lexer));
4245 else if (lex_match_id (lexer, "MISSING"))
4247 lex_match (lexer, T_EQUALS);
4248 if (!lex_force_string (lexer))
4252 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4253 ? ss_xstrdup (lex_tokss (lexer))
4259 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4260 "UNITS", "EMPTY", "MISSING");
4265 if (widths[0] != SYSMIS && widths[1] != SYSMIS
4266 && widths[0] > widths[1])
4268 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4272 for (size_t i = 0; i < 2; i++)
4273 if (widths[i] != SYSMIS)
4275 int *wr = ct->look->width_ranges[TABLE_HORZ];
4276 wr[i] = widths[i] / units_per_inch * 96.0;
4281 else if (lex_match_id (lexer, "VLABELS"))
4283 if (!lex_force_match_id (lexer, "VARIABLES"))
4285 lex_match (lexer, T_EQUALS);
4287 struct variable **vars;
4289 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4293 if (!lex_force_match_id (lexer, "DISPLAY"))
4298 lex_match (lexer, T_EQUALS);
4300 enum ctables_vlabel vlabel;
4301 if (lex_match_id (lexer, "DEFAULT"))
4302 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4303 else if (lex_match_id (lexer, "NAME"))
4305 else if (lex_match_id (lexer, "LABEL"))
4306 vlabel = CTVL_LABEL;
4307 else if (lex_match_id (lexer, "BOTH"))
4309 else if (lex_match_id (lexer, "NONE"))
4313 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4319 for (size_t i = 0; i < n_vars; i++)
4320 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4323 else if (lex_match_id (lexer, "MRSETS"))
4325 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4327 lex_match (lexer, T_EQUALS);
4328 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4331 else if (lex_match_id (lexer, "SMISSING"))
4333 if (lex_match_id (lexer, "VARIABLE"))
4334 ct->smissing_listwise = false;
4335 else if (lex_match_id (lexer, "LISTWISE"))
4336 ct->smissing_listwise = true;
4339 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4343 else if (lex_match_id (lexer, "PCOMPUTE"))
4345 if (!ctables_parse_pcompute (lexer, ct))
4348 else if (lex_match_id (lexer, "PPROPERTIES"))
4350 if (!ctables_parse_pproperties (lexer, ct))
4353 else if (lex_match_id (lexer, "WEIGHT"))
4355 if (!lex_force_match_id (lexer, "VARIABLE"))
4357 lex_match (lexer, T_EQUALS);
4358 ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4362 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
4364 if (!lex_force_match_id (lexer, "COUNT"))
4366 lex_match (lexer, T_EQUALS);
4367 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
4369 ct->hide_threshold = lex_integer (lexer);
4374 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4375 "SMISSING", "PCOMPUTE", "PPROPERTIES",
4376 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4380 if (!lex_force_match (lexer, T_SLASH))
4384 size_t allocated_tables = 0;
4387 if (ct->n_tables >= allocated_tables)
4388 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4389 sizeof *ct->tables);
4391 struct ctables_category *cat = xmalloc (sizeof *cat);
4392 *cat = (struct ctables_category) {
4394 .include_missing = false,
4395 .sort_ascending = true,
4398 struct ctables_categories *c = xmalloc (sizeof *c);
4399 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4400 *c = (struct ctables_categories) {
4407 struct ctables_categories **categories = xnmalloc (n_vars,
4408 sizeof *categories);
4409 for (size_t i = 0; i < n_vars; i++)
4412 struct ctables_table *t = xmalloc (sizeof *t);
4413 *t = (struct ctables_table) {
4415 .slabels_axis = PIVOT_AXIS_COLUMN,
4416 .slabels_visible = true,
4417 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
4419 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
4420 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
4421 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
4423 .clabels_from_axis = PIVOT_AXIS_LAYER,
4424 .categories = categories,
4425 .n_categories = n_vars,
4428 ct->tables[ct->n_tables++] = t;
4430 lex_match (lexer, T_EQUALS);
4431 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
4433 if (lex_match (lexer, T_BY))
4435 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4436 ct, t, PIVOT_AXIS_COLUMN))
4439 if (lex_match (lexer, T_BY))
4441 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4442 ct, t, PIVOT_AXIS_LAYER))
4447 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
4448 && !t->axes[PIVOT_AXIS_LAYER])
4450 lex_error (lexer, _("At least one variable must be specified."));
4454 const struct ctables_axis *scales[PIVOT_N_AXES];
4455 size_t n_scales = 0;
4456 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4458 scales[a] = find_scale (t->axes[a]);
4464 msg (SE, _("Scale variables may appear only on one axis."));
4465 if (scales[PIVOT_AXIS_ROW])
4466 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
4467 _("This scale variable appears on the rows axis."));
4468 if (scales[PIVOT_AXIS_COLUMN])
4469 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
4470 _("This scale variable appears on the columns axis."));
4471 if (scales[PIVOT_AXIS_LAYER])
4472 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
4473 _("This scale variable appears on the layer axis."));
4477 const struct ctables_axis *summaries[PIVOT_N_AXES];
4478 size_t n_summaries = 0;
4479 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4481 summaries[a] = (scales[a]
4483 : find_categorical_summary_spec (t->axes[a]));
4487 if (n_summaries > 1)
4489 msg (SE, _("Summaries may appear only on one axis."));
4490 if (summaries[PIVOT_AXIS_ROW])
4491 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
4492 _("This variable on the rows axis has a summary."));
4493 if (summaries[PIVOT_AXIS_COLUMN])
4494 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
4495 _("This variable on the columns axis has a summary."));
4496 if (summaries[PIVOT_AXIS_LAYER])
4497 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
4498 _("This variable on the layers axis has a summary."));
4501 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4502 if (n_summaries ? summaries[a] : t->axes[a])
4504 t->summary_axis = a;
4508 if (lex_token (lexer) == T_ENDCMD)
4510 if (!ctables_prepare_table (t))
4514 if (!lex_force_match (lexer, T_SLASH))
4517 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
4519 if (lex_match_id (lexer, "SLABELS"))
4521 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4523 if (lex_match_id (lexer, "POSITION"))
4525 lex_match (lexer, T_EQUALS);
4526 if (lex_match_id (lexer, "COLUMN"))
4527 t->slabels_axis = PIVOT_AXIS_COLUMN;
4528 else if (lex_match_id (lexer, "ROW"))
4529 t->slabels_axis = PIVOT_AXIS_ROW;
4530 else if (lex_match_id (lexer, "LAYER"))
4531 t->slabels_axis = PIVOT_AXIS_LAYER;
4534 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
4538 else if (lex_match_id (lexer, "VISIBLE"))
4540 lex_match (lexer, T_EQUALS);
4541 if (!parse_bool (lexer, &t->slabels_visible))
4546 lex_error_expecting (lexer, "POSITION", "VISIBLE");
4551 else if (lex_match_id (lexer, "CLABELS"))
4553 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4555 if (lex_match_id (lexer, "AUTO"))
4557 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
4558 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
4560 else if (lex_match_id (lexer, "ROWLABELS"))
4562 lex_match (lexer, T_EQUALS);
4563 if (lex_match_id (lexer, "OPPOSITE"))
4564 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
4565 else if (lex_match_id (lexer, "LAYER"))
4566 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
4569 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4573 else if (lex_match_id (lexer, "COLLABELS"))
4575 lex_match (lexer, T_EQUALS);
4576 if (lex_match_id (lexer, "OPPOSITE"))
4577 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
4578 else if (lex_match_id (lexer, "LAYER"))
4579 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
4582 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4588 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
4594 else if (lex_match_id (lexer, "CRITERIA"))
4596 if (!lex_force_match_id (lexer, "CILEVEL"))
4598 lex_match (lexer, T_EQUALS);
4600 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
4602 t->cilevel = lex_number (lexer);
4605 else if (lex_match_id (lexer, "CATEGORIES"))
4607 if (!ctables_table_parse_categories (lexer, dataset_dict (ds),
4611 else if (lex_match_id (lexer, "TITLES"))
4616 if (lex_match_id (lexer, "CAPTION"))
4617 textp = &t->caption;
4618 else if (lex_match_id (lexer, "CORNER"))
4620 else if (lex_match_id (lexer, "TITLE"))
4624 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
4627 lex_match (lexer, T_EQUALS);
4629 struct string s = DS_EMPTY_INITIALIZER;
4630 while (lex_is_string (lexer))
4632 if (!ds_is_empty (&s))
4633 ds_put_byte (&s, ' ');
4634 ds_put_substring (&s, lex_tokss (lexer));
4638 *textp = ds_steal_cstr (&s);
4640 while (lex_token (lexer) != T_SLASH
4641 && lex_token (lexer) != T_ENDCMD);
4643 else if (lex_match_id (lexer, "SIGTEST"))
4647 t->chisq = xmalloc (sizeof *t->chisq);
4648 *t->chisq = (struct ctables_chisq) {
4650 .include_mrsets = true,
4651 .all_visible = true,
4657 if (lex_match_id (lexer, "TYPE"))
4659 lex_match (lexer, T_EQUALS);
4660 if (!lex_force_match_id (lexer, "CHISQUARE"))
4663 else if (lex_match_id (lexer, "ALPHA"))
4665 lex_match (lexer, T_EQUALS);
4666 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
4668 t->chisq->alpha = lex_number (lexer);
4671 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
4673 lex_match (lexer, T_EQUALS);
4674 if (parse_bool (lexer, &t->chisq->include_mrsets))
4677 else if (lex_match_id (lexer, "CATEGORIES"))
4679 lex_match (lexer, T_EQUALS);
4680 if (lex_match_id (lexer, "ALLVISIBLE"))
4681 t->chisq->all_visible = true;
4682 else if (lex_match_id (lexer, "SUBTOTALS"))
4683 t->chisq->all_visible = false;
4686 lex_error_expecting (lexer,
4687 "ALLVISIBLE", "SUBTOTALS");
4693 lex_error_expecting (lexer, "TYPE", "ALPHA",
4694 "INCLUDEMRSETS", "CATEGORIES");
4698 while (lex_token (lexer) != T_SLASH
4699 && lex_token (lexer) != T_ENDCMD);
4701 else if (lex_match_id (lexer, "COMPARETEST"))
4705 t->pairwise = xmalloc (sizeof *t->pairwise);
4706 *t->pairwise = (struct ctables_pairwise) {
4708 .alpha = { .05, .05 },
4709 .adjust = BONFERRONI,
4710 .include_mrsets = true,
4711 .meansvariance_allcats = true,
4712 .all_visible = true,
4721 if (lex_match_id (lexer, "TYPE"))
4723 lex_match (lexer, T_EQUALS);
4724 if (lex_match_id (lexer, "PROP"))
4725 t->pairwise->type = PROP;
4726 else if (lex_match_id (lexer, "MEAN"))
4727 t->pairwise->type = MEAN;
4730 lex_error_expecting (lexer, "PROP", "MEAN");
4734 else if (lex_match_id (lexer, "ALPHA"))
4736 lex_match (lexer, T_EQUALS);
4738 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
4740 double a0 = lex_number (lexer);
4743 lex_match (lexer, T_COMMA);
4744 if (lex_is_number (lexer))
4746 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
4748 double a1 = lex_number (lexer);
4751 t->pairwise->alpha[0] = MIN (a0, a1);
4752 t->pairwise->alpha[1] = MAX (a0, a1);
4755 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
4757 else if (lex_match_id (lexer, "ADJUST"))
4759 lex_match (lexer, T_EQUALS);
4760 if (lex_match_id (lexer, "BONFERRONI"))
4761 t->pairwise->adjust = BONFERRONI;
4762 else if (lex_match_id (lexer, "BH"))
4763 t->pairwise->adjust = BH;
4764 else if (lex_match_id (lexer, "NONE"))
4765 t->pairwise->adjust = 0;
4768 lex_error_expecting (lexer, "BONFERRONI", "BH",
4773 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
4775 lex_match (lexer, T_EQUALS);
4776 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
4779 else if (lex_match_id (lexer, "MEANSVARIANCE"))
4781 lex_match (lexer, T_EQUALS);
4782 if (lex_match_id (lexer, "ALLCATS"))
4783 t->pairwise->meansvariance_allcats = true;
4784 else if (lex_match_id (lexer, "TESTEDCATS"))
4785 t->pairwise->meansvariance_allcats = false;
4788 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
4792 else if (lex_match_id (lexer, "CATEGORIES"))
4794 lex_match (lexer, T_EQUALS);
4795 if (lex_match_id (lexer, "ALLVISIBLE"))
4796 t->pairwise->all_visible = true;
4797 else if (lex_match_id (lexer, "SUBTOTALS"))
4798 t->pairwise->all_visible = false;
4801 lex_error_expecting (lexer, "ALLVISIBLE",
4806 else if (lex_match_id (lexer, "MERGE"))
4808 lex_match (lexer, T_EQUALS);
4809 if (!parse_bool (lexer, &t->pairwise->merge))
4812 else if (lex_match_id (lexer, "STYLE"))
4814 lex_match (lexer, T_EQUALS);
4815 if (lex_match_id (lexer, "APA"))
4816 t->pairwise->apa_style = true;
4817 else if (lex_match_id (lexer, "SIMPLE"))
4818 t->pairwise->apa_style = false;
4821 lex_error_expecting (lexer, "APA", "SIMPLE");
4825 else if (lex_match_id (lexer, "SHOWSIG"))
4827 lex_match (lexer, T_EQUALS);
4828 if (!parse_bool (lexer, &t->pairwise->show_sig))
4833 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
4834 "INCLUDEMRSETS", "MEANSVARIANCE",
4835 "CATEGORIES", "MERGE", "STYLE",
4840 while (lex_token (lexer) != T_SLASH
4841 && lex_token (lexer) != T_ENDCMD);
4845 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
4846 "CRITERIA", "CATEGORIES", "TITLES",
4847 "SIGTEST", "COMPARETEST");
4851 if (!lex_match (lexer, T_SLASH))
4855 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
4856 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
4858 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
4862 if (!ctables_prepare_table (t))
4865 while (lex_token (lexer) != T_ENDCMD);
4867 bool ok = ctables_execute (ds, ct);
4868 ctables_destroy (ct);
4869 return ok ? CMD_SUCCESS : CMD_FAILURE;
4872 ctables_destroy (ct);