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/>. */
22 #include "data/casereader.h"
23 #include "data/casewriter.h"
24 #include "data/dataset.h"
25 #include "data/dictionary.h"
26 #include "data/mrset.h"
27 #include "data/subcase.h"
28 #include "data/value-labels.h"
29 #include "language/command.h"
30 #include "language/lexer/format-parser.h"
31 #include "language/lexer/lexer.h"
32 #include "language/lexer/variable-parser.h"
33 #include "libpspp/array.h"
34 #include "libpspp/assertion.h"
35 #include "libpspp/hash-functions.h"
36 #include "libpspp/hmap.h"
37 #include "libpspp/i18n.h"
38 #include "libpspp/message.h"
39 #include "libpspp/string-array.h"
40 #include "math/mode.h"
41 #include "math/moments.h"
42 #include "math/percentiles.h"
43 #include "math/sort.h"
44 #include "output/pivot-table.h"
46 #include "gl/minmax.h"
47 #include "gl/xalloc.h"
50 #define _(msgid) gettext (msgid)
51 #define N_(msgid) (msgid)
55 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
56 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
57 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
58 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
62 - unweighted summaries (U*)
63 - lower confidence limits (*.LCL)
64 - upper confidence limits (*.UCL)
65 - standard error (*.SE)
68 /* All variables. */ \
69 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
70 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
71 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
72 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
85 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
86 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
87 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
88 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
89 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
90 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
91 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
93 /* Scale variables, totals, and subtotals. */ \
94 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
95 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
98 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
99 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
100 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
101 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
102 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
103 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
104 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
105 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
106 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
107 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
108 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
109 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
110 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
111 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
112 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
113 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
114 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
115 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
116 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
118 /* Multiple response sets. */ \
119 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
120 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
121 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
134 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
135 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
140 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
142 enum ctables_summary_function
144 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
150 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
151 N_CTSF_FUNCTIONS = SUMMARIES
155 enum ctables_domain_type
157 /* Within a section, where stacked variables divide one section from
159 CTDT_TABLE, /* All layers of a whole section. */
160 CTDT_LAYER, /* One layer within a section. */
161 CTDT_LAYERROW, /* Row in one layer within a section. */
162 CTDT_LAYERCOL, /* Column in one layer within a section. */
164 /* Within a subtable, where a subtable pairs an innermost row variable with
165 an innermost column variable within a single layer. */
166 CTDT_SUBTABLE, /* Whole subtable. */
167 CTDT_ROW, /* Row within a subtable. */
168 CTDT_COL, /* Column within a subtable. */
172 struct ctables_domain
174 struct hmap_node node;
176 const struct ctables_cell *example;
178 double d_valid; /* Dictionary weight. */
180 double e_valid; /* Effective weight */
184 enum ctables_summary_variant
193 /* In struct ctables_section's 'cells' hmap. Indexed by all the values in
194 all the axes (except the scalar variable, if any). */
195 struct hmap_node node;
197 /* The domains that contain this cell. */
198 bool contributes_to_domains;
199 struct ctables_domain *domains[N_CTDTS];
203 enum ctables_summary_variant sv;
205 struct ctables_cell_axis
207 struct ctables_cell_value
209 const struct ctables_category *category;
217 union ctables_summary *summaries;
222 const struct dictionary *dict;
223 struct pivot_table_look *look;
225 /* If this is NULL, zeros are displayed using the normal print format.
226 Otherwise, this string is displayed. */
229 /* If this is NULL, missing values are displayed using the normal print
230 format. Otherwise, this string is displayed. */
233 /* Indexed by variable dictionary index. */
234 enum ctables_vlabel *vlabels;
236 struct hmap postcomputes; /* Contains "struct ctables_postcompute"s. */
238 bool mrsets_count_duplicates; /* MRSETS. */
239 bool smissing_listwise; /* SMISSING. */
240 struct variable *e_weight; /* WEIGHT. */
241 int hide_threshold; /* HIDESMALLCOUNTS. */
243 struct ctables_table **tables;
247 static struct ctables_postcompute *ctables_find_postcompute (struct ctables *,
250 struct ctables_postcompute
252 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
253 char *name; /* Name, without leading &. */
255 struct msg_location *location; /* Location of definition. */
256 struct ctables_pcexpr *expr;
258 struct ctables_summary_spec_set *specs;
259 bool hide_source_cats;
262 struct ctables_pcexpr
272 enum ctables_postcompute_op
275 CTPO_CONSTANT, /* 5 */
276 CTPO_CAT_NUMBER, /* [5] */
277 CTPO_CAT_STRING, /* ["STRING"] */
278 CTPO_CAT_RANGE, /* [LO THRU 5] */
279 CTPO_CAT_MISSING, /* MISSING */
280 CTPO_CAT_OTHERNM, /* OTHERNM */
281 CTPO_CAT_SUBTOTAL, /* SUBTOTAL */
282 CTPO_CAT_TOTAL, /* TOTAL */
296 /* CTPO_CAT_NUMBER. */
299 /* CTPO_CAT_STRING. */
302 /* CTPO_CAT_RANGE. */
305 /* CTPO_CAT_SUBTOTAL. */
306 size_t subtotal_index;
308 /* Two elements: CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW.
309 One element: CTPO_NEG. */
310 struct ctables_pcexpr *subs[2];
313 /* Source location. */
314 struct msg_location *location;
317 static void ctables_pcexpr_destroy (struct ctables_pcexpr *);
318 static struct ctables_pcexpr *ctables_pcexpr_allocate_binary (
319 enum ctables_postcompute_op, struct ctables_pcexpr *sub0,
320 struct ctables_pcexpr *sub1);
322 struct ctables_summary_spec_set
324 struct ctables_summary_spec *specs;
328 struct variable *var;
331 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
332 const struct ctables_summary_spec_set *);
333 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
335 /* A nested sequence of variables, e.g. a > b > c. */
338 struct variable **vars;
341 size_t *domains[N_CTDTS];
342 size_t n_domains[N_CTDTS];
344 struct ctables_summary_spec_set specs[N_CSVS];
347 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
350 struct ctables_nest *nests;
356 struct hmap_node node;
361 struct ctables_section_value
363 struct hmap_node node;
367 struct ctables_section
369 struct ctables_table *table;
370 struct ctables_nest *nests[PIVOT_N_AXES];
371 struct hmap *occurrences[PIVOT_N_AXES];
372 struct hmap cells; /* Contains "struct ctable_cell"s. */
373 struct hmap domains[N_CTDTS]; /* Contains "struct ctable_domain"s. */
378 struct ctables *ctables;
379 struct ctables_axis *axes[PIVOT_N_AXES];
380 struct ctables_stack stacks[PIVOT_N_AXES];
381 struct ctables_section *sections;
383 enum pivot_axis_type summary_axis;
384 struct ctables_summary_spec_set summary_specs;
386 const struct variable *clabels_example;
387 struct hmap clabels_values_map;
388 struct ctables_value **clabels_values;
389 size_t n_clabels_values;
391 enum pivot_axis_type slabels_axis;
392 bool slabels_visible;
394 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
396 Most commonly, label_axis[a] == a, and in particular we always have
397 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
399 If ROWLABELS or COLLABELS is specified, then one of
400 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
401 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
403 enum pivot_axis_type label_axis[PIVOT_N_AXES];
404 enum pivot_axis_type clabels_from_axis;
406 /* Indexed by variable dictionary index. */
407 struct ctables_categories **categories;
416 struct ctables_chisq *chisq;
417 struct ctables_pairwise *pairwise;
425 struct variable *var;
426 const struct mrset *mrset;
430 static const struct fmt_spec *
431 ctables_var_get_print_format (const struct ctables_var *var)
433 return (var->is_mrset
434 ? var_get_print_format (var->mrset->vars[0])
435 : var_get_print_format (var->var));
439 ctables_var_name (const struct ctables_var *var)
441 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
444 struct ctables_categories
447 struct ctables_category *cats;
452 struct ctables_category
454 enum ctables_category_type
456 /* Explicit category lists. */
464 /* Totals and subtotals. */
468 /* Implicit category lists. */
475 struct ctables_category *subtotal;
481 double number; /* CCT_NUMBER. */
482 char *string; /* CCT_STRING. */
483 double range[2]; /* CCT_RANGE. */
487 char *total_label; /* CCT_SUBTOTAL, CCT_TOTAL. */
488 bool hide_subcategories; /* CCT_SUBTOTAL. */
491 const struct ctables_postcompute *pc; /* CCT_POSTCOMPUTE. */
493 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
496 bool include_missing;
500 enum ctables_summary_function sort_function;
501 struct variable *sort_var;
506 /* Source location. This is null for CCT_TOTAL, CCT_VALUE, CCT_LABEL,
508 struct msg_location *location;
512 ctables_category_uninit (struct ctables_category *cat)
523 case CCT_POSTCOMPUTE:
532 free (cat->total_label);
543 ctables_category_equal (const struct ctables_category *a,
544 const struct ctables_category *b)
546 if (a->type != b->type)
552 return a->number == b->number;
555 return strcmp (a->string, b->string);
558 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
564 case CCT_POSTCOMPUTE:
565 return a->pc == b->pc;
569 return !strcmp (a->total_label, b->total_label);
574 return (a->include_missing == b->include_missing
575 && a->sort_ascending == b->sort_ascending
576 && a->sort_function == b->sort_function
577 && a->sort_var == b->sort_var
578 && a->percentile == b->percentile);
585 ctables_categories_unref (struct ctables_categories *c)
590 assert (c->n_refs > 0);
594 for (size_t i = 0; i < c->n_cats; i++)
595 ctables_category_uninit (&c->cats[i]);
601 ctables_categories_equal (const struct ctables_categories *a,
602 const struct ctables_categories *b)
604 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
607 for (size_t i = 0; i < a->n_cats; i++)
608 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
614 /* Chi-square test (SIGTEST). */
622 /* Pairwise comparison test (COMPARETEST). */
623 struct ctables_pairwise
625 enum { PROP, MEAN } type;
628 bool meansvariance_allcats;
630 enum { BONFERRONI = 1, BH } adjust;
654 struct ctables_var var;
656 struct ctables_summary_spec_set specs[N_CSVS];
660 struct ctables_axis *subs[2];
663 struct msg_location *loc;
666 static void ctables_axis_destroy (struct ctables_axis *);
675 enum ctables_function_availability
677 CTFA_ALL, /* Any variables. */
678 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
679 CTFA_MRSETS, /* Only multiple-response sets */
682 struct ctables_summary_spec
684 enum ctables_summary_function function;
685 double percentile; /* CTSF_PTILE only. */
687 struct fmt_spec format; /* XXX extra CTABLES formats */
692 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
693 const struct ctables_summary_spec *src)
696 dst->label = xstrdup (src->label);
700 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
707 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
708 const struct ctables_summary_spec_set *src)
710 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
711 for (size_t i = 0; i < src->n; i++)
712 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
714 *dst = (struct ctables_summary_spec_set) {
723 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
725 for (size_t i = 0; i < set->n; i++)
726 ctables_summary_spec_uninit (&set->specs[i]);
731 parse_col_width (struct lexer *lexer, const char *name, double *width)
733 lex_match (lexer, T_EQUALS);
734 if (lex_match_id (lexer, "DEFAULT"))
736 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
738 *width = lex_number (lexer);
748 parse_bool (struct lexer *lexer, bool *b)
750 if (lex_match_id (lexer, "NO"))
752 else if (lex_match_id (lexer, "YES"))
756 lex_error_expecting (lexer, "YES", "NO");
762 static enum ctables_function_availability
763 ctables_function_availability (enum ctables_summary_function f)
765 static enum ctables_function_availability availability[] = {
766 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
771 return availability[f];
775 parse_ctables_summary_function (struct lexer *lexer,
776 enum ctables_summary_function *f)
780 enum ctables_summary_function function;
781 struct substring name;
783 static struct pair names[] = {
784 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
785 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
788 /* The .COUNT suffix may be omitted. */
789 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
790 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
791 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
792 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
793 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
794 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
795 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
799 if (!lex_force_id (lexer))
802 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
803 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
805 *f = names[i].function;
810 lex_error (lexer, _("Expecting summary function name."));
815 ctables_axis_destroy (struct ctables_axis *axis)
823 for (size_t i = 0; i < N_CSVS; i++)
824 ctables_summary_spec_set_uninit (&axis->specs[i]);
829 ctables_axis_destroy (axis->subs[0]);
830 ctables_axis_destroy (axis->subs[1]);
833 msg_location_destroy (axis->loc);
837 static struct ctables_axis *
838 ctables_axis_new_nonterminal (enum ctables_axis_op op,
839 struct ctables_axis *sub0,
840 struct ctables_axis *sub1,
841 struct lexer *lexer, int start_ofs)
843 struct ctables_axis *axis = xmalloc (sizeof *axis);
844 *axis = (struct ctables_axis) {
846 .subs = { sub0, sub1 },
847 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
852 struct ctables_axis_parse_ctx
855 struct dictionary *dict;
857 struct ctables_table *t;
860 static struct fmt_spec
861 ctables_summary_default_format (enum ctables_summary_function function,
862 const struct ctables_var *var)
864 static const enum ctables_format default_formats[] = {
865 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
869 switch (default_formats[function])
872 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
875 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
878 return *ctables_var_get_print_format (var);
886 ctables_summary_default_label (enum ctables_summary_function function,
889 static const char *default_labels[] = {
890 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
895 return (function == CTSF_PTILE
896 ? xasprintf (_("Percentile %.2f"), percentile)
897 : xstrdup (gettext (default_labels[function])));
901 ctables_summary_function_name (enum ctables_summary_function function)
903 static const char *names[] = {
904 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
908 return names[function];
912 add_summary_spec (struct ctables_axis *axis,
913 enum ctables_summary_function function, double percentile,
914 const char *label, const struct fmt_spec *format,
915 const struct msg_location *loc, enum ctables_summary_variant sv)
917 if (axis->op == CTAO_VAR)
919 const char *function_name = ctables_summary_function_name (function);
920 const char *var_name = ctables_var_name (&axis->var);
921 switch (ctables_function_availability (function))
924 if (!axis->var.is_mrset)
926 msg_at (SE, loc, _("Summary function %s applies only to multiple "
927 "response sets."), function_name);
928 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
938 _("Summary function %s applies only to scale variables."),
940 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
950 struct ctables_summary_spec_set *set = &axis->specs[sv];
951 if (set->n >= set->allocated)
952 set->specs = x2nrealloc (set->specs, &set->allocated,
955 struct ctables_summary_spec *dst = &set->specs[set->n++];
956 *dst = (struct ctables_summary_spec) {
957 .function = function,
958 .percentile = percentile,
959 .label = xstrdup (label),
960 .format = (format ? *format
961 : ctables_summary_default_format (function, &axis->var)),
967 for (size_t i = 0; i < 2; i++)
968 if (!add_summary_spec (axis->subs[i], function, percentile, label,
975 static struct ctables_axis *ctables_axis_parse_stack (
976 struct ctables_axis_parse_ctx *);
979 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
980 struct ctables_var *var)
982 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
984 *var = (struct ctables_var) {
986 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
990 lex_error (lexer, _("'%s' does not name a multiple-response set "
991 "in the active file dictionary."),
992 lex_tokcstr (lexer));
1000 *var = (struct ctables_var) {
1002 .var = parse_variable (lexer, dict),
1004 return var->var != NULL;
1008 static struct ctables_axis *
1009 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
1011 if (lex_match (ctx->lexer, T_LPAREN))
1013 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
1014 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
1016 ctables_axis_destroy (sub);
1022 if (!lex_force_id (ctx->lexer))
1025 int start_ofs = lex_ofs (ctx->lexer);
1026 struct ctables_var var;
1027 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
1030 struct ctables_axis *axis = xmalloc (sizeof *axis);
1031 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
1033 /* XXX should figure out default measures by reading data */
1034 axis->scale = (var.is_mrset ? false
1035 : lex_match_phrase (ctx->lexer, "[S]") ? true
1036 : lex_match_phrase (ctx->lexer, "[C]") ? false
1037 : var_get_measure (var.var) == MEASURE_SCALE);
1038 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
1039 lex_ofs (ctx->lexer) - 1);
1044 has_digit (const char *s)
1046 return s[strcspn (s, "0123456789")] != '\0';
1049 static struct ctables_axis *
1050 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
1052 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
1053 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
1056 enum ctables_summary_variant sv = CSV_CELL;
1059 int start_ofs = lex_ofs (ctx->lexer);
1061 /* Parse function. */
1062 enum ctables_summary_function function;
1063 if (!parse_ctables_summary_function (ctx->lexer, &function))
1066 /* Parse percentile. */
1067 double percentile = 0;
1068 if (function == CTSF_PTILE)
1070 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1072 percentile = lex_number (ctx->lexer);
1073 lex_get (ctx->lexer);
1078 if (lex_is_string (ctx->lexer))
1080 label = ss_xstrdup (lex_tokss (ctx->lexer));
1081 lex_get (ctx->lexer);
1084 label = ctables_summary_default_label (function, percentile);
1087 struct fmt_spec format;
1088 const struct fmt_spec *formatp;
1089 if (lex_token (ctx->lexer) == T_ID
1090 && has_digit (lex_tokcstr (ctx->lexer)))
1092 if (!parse_format_specifier (ctx->lexer, &format)
1093 || !fmt_check_output (&format)
1094 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1104 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1105 lex_ofs (ctx->lexer) - 1);
1106 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1108 msg_location_destroy (loc);
1110 lex_match (ctx->lexer, T_COMMA);
1111 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1113 if (!lex_force_match (ctx->lexer, T_LBRACK))
1117 else if (lex_match (ctx->lexer, T_RBRACK))
1119 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1126 ctables_axis_destroy (sub);
1130 static const struct ctables_axis *
1131 find_scale (const struct ctables_axis *axis)
1135 else if (axis->op == CTAO_VAR)
1139 assert (!axis->var.is_mrset);
1147 for (size_t i = 0; i < 2; i++)
1149 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1157 static const struct ctables_axis *
1158 find_categorical_summary_spec (const struct ctables_axis *axis)
1162 else if (axis->op == CTAO_VAR)
1163 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1166 for (size_t i = 0; i < 2; i++)
1168 const struct ctables_axis *sum
1169 = find_categorical_summary_spec (axis->subs[i]);
1177 static struct ctables_axis *
1178 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1180 int start_ofs = lex_ofs (ctx->lexer);
1181 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1185 while (lex_match (ctx->lexer, T_GT))
1187 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1191 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1192 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1194 const struct ctables_axis *outer_scale = find_scale (lhs);
1195 const struct ctables_axis *inner_scale = find_scale (rhs);
1196 if (outer_scale && inner_scale)
1198 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1199 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1200 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1201 ctables_axis_destroy (nest);
1205 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1208 msg_at (SE, nest->loc,
1209 _("Summaries may only be requested for categorical variables "
1210 "at the innermost nesting level."));
1211 msg_at (SN, outer_sum->loc,
1212 _("This outer categorical variable has a summary."));
1213 ctables_axis_destroy (nest);
1223 static struct ctables_axis *
1224 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1226 int start_ofs = lex_ofs (ctx->lexer);
1227 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1231 while (lex_match (ctx->lexer, T_PLUS))
1233 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1237 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1238 ctx->lexer, start_ofs);
1245 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1246 struct ctables *ct, struct ctables_table *t,
1247 enum pivot_axis_type a)
1249 if (lex_token (lexer) == T_BY
1250 || lex_token (lexer) == T_SLASH
1251 || lex_token (lexer) == T_ENDCMD)
1254 struct ctables_axis_parse_ctx ctx = {
1260 t->axes[a] = ctables_axis_parse_stack (&ctx);
1261 return t->axes[a] != NULL;
1265 ctables_chisq_destroy (struct ctables_chisq *chisq)
1271 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1277 ctables_table_destroy (struct ctables_table *t)
1282 for (size_t i = 0; i < t->n_categories; i++)
1283 ctables_categories_unref (t->categories[i]);
1284 free (t->categories);
1286 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1287 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1288 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1292 ctables_chisq_destroy (t->chisq);
1293 ctables_pairwise_destroy (t->pairwise);
1298 ctables_destroy (struct ctables *ct)
1303 pivot_table_look_unref (ct->look);
1307 for (size_t i = 0; i < ct->n_tables; i++)
1308 ctables_table_destroy (ct->tables[i]);
1313 static struct ctables_category
1314 cct_range (double low, double high)
1316 return (struct ctables_category) {
1318 .range = { low, high }
1323 ctables_table_parse_subtotal (struct lexer *lexer, bool hide_subcategories,
1324 struct ctables_category *cat)
1327 if (lex_match (lexer, T_EQUALS))
1329 if (!lex_force_string (lexer))
1332 total_label = ss_xstrdup (lex_tokss (lexer));
1336 total_label = xstrdup (_("Subtotal"));
1338 *cat = (struct ctables_category) {
1339 .type = CCT_SUBTOTAL,
1340 .hide_subcategories = hide_subcategories,
1341 .total_label = total_label
1347 ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
1348 struct ctables_category *cat)
1350 if (lex_match_id (lexer, "OTHERNM"))
1351 *cat = (struct ctables_category) { .type = CCT_OTHERNM };
1352 else if (lex_match_id (lexer, "MISSING"))
1353 *cat = (struct ctables_category) { .type = CCT_MISSING };
1354 else if (lex_match_id (lexer, "SUBTOTAL"))
1355 return ctables_table_parse_subtotal (lexer, false, cat);
1356 else if (lex_match_id (lexer, "HSUBTOTAL"))
1357 return ctables_table_parse_subtotal (lexer, true, cat);
1358 else if (lex_match_id (lexer, "LO"))
1360 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1362 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1365 else if (lex_is_number (lexer))
1367 double number = lex_number (lexer);
1369 if (lex_match_id (lexer, "THRU"))
1371 if (lex_match_id (lexer, "HI"))
1372 *cat = cct_range (number, DBL_MAX);
1375 if (!lex_force_num (lexer))
1377 *cat = cct_range (number, lex_number (lexer));
1382 *cat = (struct ctables_category) {
1387 else if (lex_is_string (lexer))
1389 *cat = (struct ctables_category) {
1391 .string = ss_xstrdup (lex_tokss (lexer)),
1395 else if (lex_match (lexer, T_AND))
1397 if (!lex_force_id (lexer))
1399 struct ctables_postcompute *pc = ctables_find_postcompute (
1400 ct, lex_tokcstr (lexer));
1403 struct msg_location *loc = lex_get_location (lexer, -1, 0);
1404 msg_at (SE, loc, _("Unknown postcompute &%s."),
1405 lex_tokcstr (lexer));
1406 msg_location_destroy (loc);
1411 *cat = (struct ctables_category) { .type = CCT_POSTCOMPUTE, .pc = pc };
1415 lex_error (lexer, NULL);
1422 static struct ctables_category *
1423 ctables_find_category_for_postcompute (const struct ctables_categories *cats,
1424 const struct ctables_pcexpr *e)
1426 struct ctables_category *best = NULL;
1427 size_t n_subtotals = 0;
1428 for (size_t i = 0; i < cats->n_cats; i++)
1430 struct ctables_category *cat = &cats->cats[i];
1433 case CTPO_CAT_NUMBER:
1434 if (cat->type == CCT_NUMBER && cat->number == e->number)
1438 case CTPO_CAT_STRING:
1439 if (cat->type == CCT_STRING && !strcmp (cat->string, e->string))
1443 case CTPO_CAT_RANGE:
1444 if (cat->type == CCT_RANGE
1445 && cat->range[0] == e->range[0]
1446 && cat->range[1] == e->range[1])
1450 case CTPO_CAT_MISSING:
1451 if (cat->type == CCT_MISSING)
1455 case CTPO_CAT_OTHERNM:
1456 if (cat->type == CCT_OTHERNM)
1460 case CTPO_CAT_SUBTOTAL:
1461 if (cat->type == CCT_SUBTOTAL)
1464 if (e->subtotal_index == n_subtotals)
1466 else if (e->subtotal_index == 0)
1471 case CTPO_CAT_TOTAL:
1472 if (cat->type == CCT_TOTAL)
1486 if (e->op == CTPO_CAT_SUBTOTAL && e->subtotal_index == 0 && n_subtotals > 1)
1492 ctables_recursive_check_postcompute (const struct ctables_pcexpr *e,
1493 struct ctables_category *pc_cat,
1494 const struct ctables_categories *cats,
1495 const struct msg_location *cats_location)
1499 case CTPO_CAT_NUMBER:
1500 case CTPO_CAT_STRING:
1501 case CTPO_CAT_RANGE:
1502 case CTPO_CAT_MISSING:
1503 case CTPO_CAT_OTHERNM:
1504 case CTPO_CAT_SUBTOTAL:
1505 case CTPO_CAT_TOTAL:
1507 struct ctables_category *cat = ctables_find_category_for_postcompute (
1511 if (e->op == CTPO_CAT_SUBTOTAL && e->subtotal_index == 0)
1513 size_t n_subtotals = 0;
1514 for (size_t i = 0; i < cats->n_cats; i++)
1515 n_subtotals += cats->cats[i].type == CCT_SUBTOTAL;
1516 if (n_subtotals > 1)
1518 msg_at (SE, cats_location,
1519 ngettext ("These categories include %zu instance "
1520 "of SUBTOTAL or HSUBTOTAL, so references "
1521 "from computed categories must refer to "
1522 "subtotals by position.",
1523 "These categories include %zu instances "
1524 "of SUBTOTAL or HSUBTOTAL, so references "
1525 "from computed categories must refer to "
1526 "subtotals by position.",
1529 msg_at (SN, e->location,
1530 _("This is the reference that lacks a position."));
1535 msg_at (SE, pc_cat->location,
1536 _("Computed category &%s references a category not included "
1537 "in the category list."),
1539 msg_at (SN, e->location, _("This is the missing category."));
1540 msg_at (SN, cats_location,
1541 _("To fix the problem, add the missing category to the "
1542 "list of categories here."));
1545 if (pc_cat->pc->hide_source_cats)
1559 for (size_t i = 0; i < 2; i++)
1560 if (e->subs[i] && !ctables_recursive_check_postcompute (
1561 e->subs[i], pc_cat, cats, cats_location))
1571 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1572 struct ctables *ct, struct ctables_table *t)
1574 if (!lex_match_id (lexer, "VARIABLES"))
1576 lex_match (lexer, T_EQUALS);
1578 struct variable **vars;
1580 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1583 struct ctables_categories *c = xmalloc (sizeof *c);
1584 *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
1585 for (size_t i = 0; i < n_vars; i++)
1587 struct ctables_categories **cp
1588 = &t->categories[var_get_dict_index (vars[i])];
1589 ctables_categories_unref (*cp);
1594 size_t allocated_cats = 0;
1595 if (lex_match (lexer, T_LBRACK))
1597 int cats_start_ofs = lex_ofs (lexer);
1600 if (c->n_cats >= allocated_cats)
1601 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1603 int start_ofs = lex_ofs (lexer);
1604 struct ctables_category *cat = &c->cats[c->n_cats];
1605 if (!ctables_table_parse_explicit_category (lexer, ct, cat))
1607 cat->location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
1610 lex_match (lexer, T_COMMA);
1612 while (!lex_match (lexer, T_RBRACK));
1614 struct msg_location *cats_location
1615 = lex_ofs_location (lexer, cats_start_ofs, lex_ofs (lexer) - 1);
1616 for (size_t i = 0; i < c->n_cats; i++)
1618 struct ctables_category *cat = &c->cats[i];
1619 if (cat->type == CCT_POSTCOMPUTE
1620 && !ctables_recursive_check_postcompute (cat->pc->expr, cat,
1626 struct ctables_category cat = {
1628 .include_missing = false,
1629 .sort_ascending = true,
1631 bool show_totals = false;
1632 char *total_label = NULL;
1633 bool totals_before = false;
1634 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1636 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1638 lex_match (lexer, T_EQUALS);
1639 if (lex_match_id (lexer, "A"))
1640 cat.sort_ascending = true;
1641 else if (lex_match_id (lexer, "D"))
1642 cat.sort_ascending = false;
1645 lex_error_expecting (lexer, "A", "D");
1649 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1651 lex_match (lexer, T_EQUALS);
1652 if (lex_match_id (lexer, "VALUE"))
1653 cat.type = CCT_VALUE;
1654 else if (lex_match_id (lexer, "LABEL"))
1655 cat.type = CCT_LABEL;
1658 cat.type = CCT_FUNCTION;
1659 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1662 if (lex_match (lexer, T_LPAREN))
1664 cat.sort_var = parse_variable (lexer, dict);
1668 if (cat.sort_function == CTSF_PTILE)
1670 lex_match (lexer, T_COMMA);
1671 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1673 cat.percentile = lex_number (lexer);
1677 if (!lex_force_match (lexer, T_RPAREN))
1680 else if (ctables_function_availability (cat.sort_function)
1683 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1688 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1690 lex_match (lexer, T_EQUALS);
1691 if (lex_match_id (lexer, "INCLUDE"))
1692 cat.include_missing = true;
1693 else if (lex_match_id (lexer, "EXCLUDE"))
1694 cat.include_missing = false;
1697 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1701 else if (lex_match_id (lexer, "TOTAL"))
1703 lex_match (lexer, T_EQUALS);
1704 if (!parse_bool (lexer, &show_totals))
1707 else if (lex_match_id (lexer, "LABEL"))
1709 lex_match (lexer, T_EQUALS);
1710 if (!lex_force_string (lexer))
1713 total_label = ss_xstrdup (lex_tokss (lexer));
1716 else if (lex_match_id (lexer, "POSITION"))
1718 lex_match (lexer, T_EQUALS);
1719 if (lex_match_id (lexer, "BEFORE"))
1720 totals_before = true;
1721 else if (lex_match_id (lexer, "AFTER"))
1722 totals_before = false;
1725 lex_error_expecting (lexer, "BEFORE", "AFTER");
1729 else if (lex_match_id (lexer, "EMPTY"))
1731 lex_match (lexer, T_EQUALS);
1732 if (lex_match_id (lexer, "INCLUDE"))
1733 c->show_empty = true;
1734 else if (lex_match_id (lexer, "EXCLUDE"))
1735 c->show_empty = false;
1738 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1745 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1746 "TOTAL", "LABEL", "POSITION", "EMPTY");
1748 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1755 if (c->n_cats >= allocated_cats)
1756 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1757 c->cats[c->n_cats++] = cat;
1762 if (c->n_cats >= allocated_cats)
1763 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1765 struct ctables_category *totals;
1768 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1769 totals = &c->cats[0];
1772 totals = &c->cats[c->n_cats];
1775 *totals = (struct ctables_category) {
1777 .total_label = total_label ? total_label : xstrdup (_("Total")),
1781 struct ctables_category *subtotal = NULL;
1782 for (size_t i = totals_before ? 0 : c->n_cats;
1783 totals_before ? i < c->n_cats : i-- > 0;
1784 totals_before ? i++ : 0)
1786 struct ctables_category *cat = &c->cats[i];
1794 cat->subtotal = subtotal;
1797 case CCT_POSTCOMPUTE:
1816 ctables_nest_uninit (struct ctables_nest *nest)
1823 ctables_stack_uninit (struct ctables_stack *stack)
1827 for (size_t i = 0; i < stack->n; i++)
1828 ctables_nest_uninit (&stack->nests[i]);
1829 free (stack->nests);
1833 static struct ctables_stack
1834 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1841 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1842 for (size_t i = 0; i < s0.n; i++)
1843 for (size_t j = 0; j < s1.n; j++)
1845 const struct ctables_nest *a = &s0.nests[i];
1846 const struct ctables_nest *b = &s1.nests[j];
1848 size_t allocate = a->n + b->n;
1849 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1850 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1852 for (size_t k = 0; k < a->n; k++)
1853 vars[n++] = a->vars[k];
1854 for (size_t k = 0; k < b->n; k++)
1855 vars[n++] = b->vars[k];
1856 assert (n == allocate);
1858 const struct ctables_nest *summary_src;
1859 if (!a->specs[CSV_CELL].var)
1861 else if (!b->specs[CSV_CELL].var)
1866 struct ctables_nest *new = &stack.nests[stack.n++];
1867 *new = (struct ctables_nest) {
1869 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1870 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1874 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1875 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1877 ctables_stack_uninit (&s0);
1878 ctables_stack_uninit (&s1);
1882 static struct ctables_stack
1883 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1885 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1886 for (size_t i = 0; i < s0.n; i++)
1887 stack.nests[stack.n++] = s0.nests[i];
1888 for (size_t i = 0; i < s1.n; i++)
1889 stack.nests[stack.n++] = s1.nests[i];
1890 assert (stack.n == s0.n + s1.n);
1896 static struct ctables_stack
1897 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1900 return (struct ctables_stack) { .n = 0 };
1905 assert (!a->var.is_mrset);
1907 struct variable **vars = xmalloc (sizeof *vars);
1910 struct ctables_nest *nest = xmalloc (sizeof *nest);
1911 *nest = (struct ctables_nest) {
1914 .scale_idx = a->scale ? 0 : SIZE_MAX,
1916 if (a->specs[CSV_CELL].n || a->scale)
1917 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1919 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1920 nest->specs[sv].var = a->var.var;
1922 return (struct ctables_stack) { .nests = nest, .n = 1 };
1925 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1926 enumerate_fts (axis_type, a->subs[1]));
1929 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1930 enumerate_fts (axis_type, a->subs[1]));
1936 union ctables_summary
1938 /* COUNT, VALIDN, TOTALN. */
1945 /* MINIMUM, MAXIMUM, RANGE. */
1952 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1953 struct moments1 *moments;
1955 /* MEDIAN, MODE, PTILE. */
1958 struct casewriter *writer;
1963 /* XXX multiple response */
1967 ctables_summary_init (union ctables_summary *s,
1968 const struct ctables_summary_spec *ss)
1970 switch (ss->function)
1974 case CTSF_ROWPCT_COUNT:
1975 case CTSF_COLPCT_COUNT:
1976 case CTSF_TABLEPCT_COUNT:
1977 case CTSF_SUBTABLEPCT_COUNT:
1978 case CTSF_LAYERPCT_COUNT:
1979 case CTSF_LAYERROWPCT_COUNT:
1980 case CTSF_LAYERCOLPCT_COUNT:
1981 case CTSF_ROWPCT_VALIDN:
1982 case CTSF_COLPCT_VALIDN:
1983 case CTSF_TABLEPCT_VALIDN:
1984 case CTSF_SUBTABLEPCT_VALIDN:
1985 case CTSF_LAYERPCT_VALIDN:
1986 case CTSF_LAYERROWPCT_VALIDN:
1987 case CTSF_LAYERCOLPCT_VALIDN:
1988 case CTSF_ROWPCT_TOTALN:
1989 case CTSF_COLPCT_TOTALN:
1990 case CTSF_TABLEPCT_TOTALN:
1991 case CTSF_SUBTABLEPCT_TOTALN:
1992 case CTSF_LAYERPCT_TOTALN:
1993 case CTSF_LAYERROWPCT_TOTALN:
1994 case CTSF_LAYERCOLPCT_TOTALN:
2000 s->missing = s->valid = 0;
2006 s->min = s->max = SYSMIS;
2014 case CTSF_ROWPCT_SUM:
2015 case CTSF_COLPCT_SUM:
2016 case CTSF_TABLEPCT_SUM:
2017 case CTSF_SUBTABLEPCT_SUM:
2018 case CTSF_LAYERPCT_SUM:
2019 case CTSF_LAYERROWPCT_SUM:
2020 case CTSF_LAYERCOLPCT_SUM:
2021 s->moments = moments1_create (MOMENT_VARIANCE);
2028 struct caseproto *proto = caseproto_create ();
2029 proto = caseproto_add_width (proto, 0);
2030 proto = caseproto_add_width (proto, 0);
2032 struct subcase ordering;
2033 subcase_init (&ordering, 0, 0, SC_ASCEND);
2034 s->writer = sort_create_writer (&ordering, proto);
2035 subcase_uninit (&ordering);
2036 caseproto_unref (proto);
2043 case CTSF_RESPONSES:
2044 case CTSF_ROWPCT_RESPONSES:
2045 case CTSF_COLPCT_RESPONSES:
2046 case CTSF_TABLEPCT_RESPONSES:
2047 case CTSF_SUBTABLEPCT_RESPONSES:
2048 case CTSF_LAYERPCT_RESPONSES:
2049 case CTSF_LAYERROWPCT_RESPONSES:
2050 case CTSF_LAYERCOLPCT_RESPONSES:
2051 case CTSF_ROWPCT_RESPONSES_COUNT:
2052 case CTSF_COLPCT_RESPONSES_COUNT:
2053 case CTSF_TABLEPCT_RESPONSES_COUNT:
2054 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2055 case CTSF_LAYERPCT_RESPONSES_COUNT:
2056 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2057 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2058 case CTSF_ROWPCT_COUNT_RESPONSES:
2059 case CTSF_COLPCT_COUNT_RESPONSES:
2060 case CTSF_TABLEPCT_COUNT_RESPONSES:
2061 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2062 case CTSF_LAYERPCT_COUNT_RESPONSES:
2063 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2064 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2070 ctables_summary_uninit (union ctables_summary *s,
2071 const struct ctables_summary_spec *ss)
2073 switch (ss->function)
2077 case CTSF_ROWPCT_COUNT:
2078 case CTSF_COLPCT_COUNT:
2079 case CTSF_TABLEPCT_COUNT:
2080 case CTSF_SUBTABLEPCT_COUNT:
2081 case CTSF_LAYERPCT_COUNT:
2082 case CTSF_LAYERROWPCT_COUNT:
2083 case CTSF_LAYERCOLPCT_COUNT:
2084 case CTSF_ROWPCT_VALIDN:
2085 case CTSF_COLPCT_VALIDN:
2086 case CTSF_TABLEPCT_VALIDN:
2087 case CTSF_SUBTABLEPCT_VALIDN:
2088 case CTSF_LAYERPCT_VALIDN:
2089 case CTSF_LAYERROWPCT_VALIDN:
2090 case CTSF_LAYERCOLPCT_VALIDN:
2091 case CTSF_ROWPCT_TOTALN:
2092 case CTSF_COLPCT_TOTALN:
2093 case CTSF_TABLEPCT_TOTALN:
2094 case CTSF_SUBTABLEPCT_TOTALN:
2095 case CTSF_LAYERPCT_TOTALN:
2096 case CTSF_LAYERROWPCT_TOTALN:
2097 case CTSF_LAYERCOLPCT_TOTALN:
2115 case CTSF_ROWPCT_SUM:
2116 case CTSF_COLPCT_SUM:
2117 case CTSF_TABLEPCT_SUM:
2118 case CTSF_SUBTABLEPCT_SUM:
2119 case CTSF_LAYERPCT_SUM:
2120 case CTSF_LAYERROWPCT_SUM:
2121 case CTSF_LAYERCOLPCT_SUM:
2122 moments1_destroy (s->moments);
2128 casewriter_destroy (s->writer);
2131 case CTSF_RESPONSES:
2132 case CTSF_ROWPCT_RESPONSES:
2133 case CTSF_COLPCT_RESPONSES:
2134 case CTSF_TABLEPCT_RESPONSES:
2135 case CTSF_SUBTABLEPCT_RESPONSES:
2136 case CTSF_LAYERPCT_RESPONSES:
2137 case CTSF_LAYERROWPCT_RESPONSES:
2138 case CTSF_LAYERCOLPCT_RESPONSES:
2139 case CTSF_ROWPCT_RESPONSES_COUNT:
2140 case CTSF_COLPCT_RESPONSES_COUNT:
2141 case CTSF_TABLEPCT_RESPONSES_COUNT:
2142 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2143 case CTSF_LAYERPCT_RESPONSES_COUNT:
2144 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2145 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2146 case CTSF_ROWPCT_COUNT_RESPONSES:
2147 case CTSF_COLPCT_COUNT_RESPONSES:
2148 case CTSF_TABLEPCT_COUNT_RESPONSES:
2149 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2150 case CTSF_LAYERPCT_COUNT_RESPONSES:
2151 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2152 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2158 ctables_summary_add (union ctables_summary *s,
2159 const struct ctables_summary_spec *ss,
2160 const struct variable *var, const union value *value,
2161 double d_weight, double e_weight)
2163 switch (ss->function)
2168 if (var_is_value_missing (var, value))
2169 s->missing += d_weight;
2171 s->valid += d_weight;
2175 case CTSF_ROWPCT_COUNT:
2176 case CTSF_COLPCT_COUNT:
2177 case CTSF_TABLEPCT_COUNT:
2178 case CTSF_SUBTABLEPCT_COUNT:
2179 case CTSF_LAYERPCT_COUNT:
2180 case CTSF_LAYERROWPCT_COUNT:
2181 case CTSF_LAYERCOLPCT_COUNT:
2182 case CTSF_ROWPCT_VALIDN:
2183 case CTSF_COLPCT_VALIDN:
2184 case CTSF_TABLEPCT_VALIDN:
2185 case CTSF_SUBTABLEPCT_VALIDN:
2186 case CTSF_LAYERPCT_VALIDN:
2187 case CTSF_LAYERROWPCT_VALIDN:
2188 case CTSF_LAYERCOLPCT_VALIDN:
2189 case CTSF_ROWPCT_TOTALN:
2190 case CTSF_COLPCT_TOTALN:
2191 case CTSF_TABLEPCT_TOTALN:
2192 case CTSF_SUBTABLEPCT_TOTALN:
2193 case CTSF_LAYERPCT_TOTALN:
2194 case CTSF_LAYERROWPCT_TOTALN:
2195 case CTSF_LAYERCOLPCT_TOTALN:
2199 if (var_is_value_missing (var, value))
2200 s->missing += e_weight;
2202 s->valid += e_weight;
2208 if (!var_is_value_missing (var, value))
2210 assert (!var_is_alpha (var)); /* XXX? */
2211 if (s->min == SYSMIS || value->f < s->min)
2213 if (s->max == SYSMIS || value->f > s->max)
2223 case CTSF_ROWPCT_SUM:
2224 case CTSF_COLPCT_SUM:
2225 case CTSF_TABLEPCT_SUM:
2226 case CTSF_SUBTABLEPCT_SUM:
2227 case CTSF_LAYERPCT_SUM:
2228 case CTSF_LAYERROWPCT_SUM:
2229 case CTSF_LAYERCOLPCT_SUM:
2230 if (!var_is_value_missing (var, value))
2231 moments1_add (s->moments, value->f, e_weight);
2237 if (var_is_value_missing (var, value))
2239 s->ovalid += e_weight;
2241 struct ccase *c = case_create (casewriter_get_proto (s->writer));
2242 *case_num_rw_idx (c, 0) = value->f;
2243 *case_num_rw_idx (c, 1) = e_weight;
2244 casewriter_write (s->writer, c);
2248 case CTSF_RESPONSES:
2249 case CTSF_ROWPCT_RESPONSES:
2250 case CTSF_COLPCT_RESPONSES:
2251 case CTSF_TABLEPCT_RESPONSES:
2252 case CTSF_SUBTABLEPCT_RESPONSES:
2253 case CTSF_LAYERPCT_RESPONSES:
2254 case CTSF_LAYERROWPCT_RESPONSES:
2255 case CTSF_LAYERCOLPCT_RESPONSES:
2256 case CTSF_ROWPCT_RESPONSES_COUNT:
2257 case CTSF_COLPCT_RESPONSES_COUNT:
2258 case CTSF_TABLEPCT_RESPONSES_COUNT:
2259 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2260 case CTSF_LAYERPCT_RESPONSES_COUNT:
2261 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2262 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2263 case CTSF_ROWPCT_COUNT_RESPONSES:
2264 case CTSF_COLPCT_COUNT_RESPONSES:
2265 case CTSF_TABLEPCT_COUNT_RESPONSES:
2266 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2267 case CTSF_LAYERPCT_COUNT_RESPONSES:
2268 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2269 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2274 static enum ctables_domain_type
2275 ctables_function_domain (enum ctables_summary_function function)
2297 case CTSF_RESPONSES:
2300 case CTSF_COLPCT_COUNT:
2301 case CTSF_COLPCT_COUNT_RESPONSES:
2302 case CTSF_COLPCT_RESPONSES:
2303 case CTSF_COLPCT_RESPONSES_COUNT:
2304 case CTSF_COLPCT_SUM:
2305 case CTSF_COLPCT_TOTALN:
2306 case CTSF_COLPCT_VALIDN:
2309 case CTSF_LAYERCOLPCT_COUNT:
2310 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2311 case CTSF_LAYERCOLPCT_RESPONSES:
2312 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2313 case CTSF_LAYERCOLPCT_SUM:
2314 case CTSF_LAYERCOLPCT_TOTALN:
2315 case CTSF_LAYERCOLPCT_VALIDN:
2316 return CTDT_LAYERCOL;
2318 case CTSF_LAYERPCT_COUNT:
2319 case CTSF_LAYERPCT_COUNT_RESPONSES:
2320 case CTSF_LAYERPCT_RESPONSES:
2321 case CTSF_LAYERPCT_RESPONSES_COUNT:
2322 case CTSF_LAYERPCT_SUM:
2323 case CTSF_LAYERPCT_TOTALN:
2324 case CTSF_LAYERPCT_VALIDN:
2327 case CTSF_LAYERROWPCT_COUNT:
2328 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2329 case CTSF_LAYERROWPCT_RESPONSES:
2330 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2331 case CTSF_LAYERROWPCT_SUM:
2332 case CTSF_LAYERROWPCT_TOTALN:
2333 case CTSF_LAYERROWPCT_VALIDN:
2334 return CTDT_LAYERROW;
2336 case CTSF_ROWPCT_COUNT:
2337 case CTSF_ROWPCT_COUNT_RESPONSES:
2338 case CTSF_ROWPCT_RESPONSES:
2339 case CTSF_ROWPCT_RESPONSES_COUNT:
2340 case CTSF_ROWPCT_SUM:
2341 case CTSF_ROWPCT_TOTALN:
2342 case CTSF_ROWPCT_VALIDN:
2345 case CTSF_SUBTABLEPCT_COUNT:
2346 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2347 case CTSF_SUBTABLEPCT_RESPONSES:
2348 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2349 case CTSF_SUBTABLEPCT_SUM:
2350 case CTSF_SUBTABLEPCT_TOTALN:
2351 case CTSF_SUBTABLEPCT_VALIDN:
2352 return CTDT_SUBTABLE;
2354 case CTSF_TABLEPCT_COUNT:
2355 case CTSF_TABLEPCT_COUNT_RESPONSES:
2356 case CTSF_TABLEPCT_RESPONSES:
2357 case CTSF_TABLEPCT_RESPONSES_COUNT:
2358 case CTSF_TABLEPCT_SUM:
2359 case CTSF_TABLEPCT_TOTALN:
2360 case CTSF_TABLEPCT_VALIDN:
2368 ctables_summary_value (const struct ctables_cell *cell,
2369 union ctables_summary *s,
2370 const struct ctables_summary_spec *ss)
2372 switch (ss->function)
2378 case CTSF_ROWPCT_COUNT:
2379 case CTSF_COLPCT_COUNT:
2380 case CTSF_TABLEPCT_COUNT:
2381 case CTSF_SUBTABLEPCT_COUNT:
2382 case CTSF_LAYERPCT_COUNT:
2383 case CTSF_LAYERROWPCT_COUNT:
2384 case CTSF_LAYERCOLPCT_COUNT:
2386 enum ctables_domain_type d = ctables_function_domain (ss->function);
2387 return (cell->domains[d]->e_valid
2388 ? s->valid / cell->domains[d]->e_valid * 100
2392 case CTSF_ROWPCT_VALIDN:
2393 case CTSF_COLPCT_VALIDN:
2394 case CTSF_TABLEPCT_VALIDN:
2395 case CTSF_SUBTABLEPCT_VALIDN:
2396 case CTSF_LAYERPCT_VALIDN:
2397 case CTSF_LAYERROWPCT_VALIDN:
2398 case CTSF_LAYERCOLPCT_VALIDN:
2399 case CTSF_ROWPCT_TOTALN:
2400 case CTSF_COLPCT_TOTALN:
2401 case CTSF_TABLEPCT_TOTALN:
2402 case CTSF_SUBTABLEPCT_TOTALN:
2403 case CTSF_LAYERPCT_TOTALN:
2404 case CTSF_LAYERROWPCT_TOTALN:
2405 case CTSF_LAYERCOLPCT_TOTALN:
2413 return s->valid + s->missing;
2426 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2431 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2437 double weight, variance;
2438 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2439 return calc_semean (variance, weight);
2445 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2446 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2451 double weight, mean;
2452 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2453 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2459 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2463 case CTSF_ROWPCT_SUM:
2464 case CTSF_COLPCT_SUM:
2465 case CTSF_TABLEPCT_SUM:
2466 case CTSF_SUBTABLEPCT_SUM:
2467 case CTSF_LAYERPCT_SUM:
2468 case CTSF_LAYERROWPCT_SUM:
2469 case CTSF_LAYERCOLPCT_SUM:
2476 struct casereader *reader = casewriter_make_reader (s->writer);
2479 struct percentile *ptile = percentile_create (
2480 ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2481 struct order_stats *os = &ptile->parent;
2482 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2483 s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2484 statistic_destroy (&ptile->parent.parent);
2491 struct casereader *reader = casewriter_make_reader (s->writer);
2494 struct mode *mode = mode_create ();
2495 struct order_stats *os = &mode->parent;
2496 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2497 s->ovalue = mode->mode;
2498 statistic_destroy (&mode->parent.parent);
2502 case CTSF_RESPONSES:
2503 case CTSF_ROWPCT_RESPONSES:
2504 case CTSF_COLPCT_RESPONSES:
2505 case CTSF_TABLEPCT_RESPONSES:
2506 case CTSF_SUBTABLEPCT_RESPONSES:
2507 case CTSF_LAYERPCT_RESPONSES:
2508 case CTSF_LAYERROWPCT_RESPONSES:
2509 case CTSF_LAYERCOLPCT_RESPONSES:
2510 case CTSF_ROWPCT_RESPONSES_COUNT:
2511 case CTSF_COLPCT_RESPONSES_COUNT:
2512 case CTSF_TABLEPCT_RESPONSES_COUNT:
2513 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2514 case CTSF_LAYERPCT_RESPONSES_COUNT:
2515 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2516 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2517 case CTSF_ROWPCT_COUNT_RESPONSES:
2518 case CTSF_COLPCT_COUNT_RESPONSES:
2519 case CTSF_TABLEPCT_COUNT_RESPONSES:
2520 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2521 case CTSF_LAYERPCT_COUNT_RESPONSES:
2522 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2523 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2530 struct ctables_cell_sort_aux
2532 const struct ctables_nest *nest;
2533 enum pivot_axis_type a;
2537 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2539 const struct ctables_cell_sort_aux *aux = aux_;
2540 struct ctables_cell *const *ap = a_;
2541 struct ctables_cell *const *bp = b_;
2542 const struct ctables_cell *a = *ap;
2543 const struct ctables_cell *b = *bp;
2545 const struct ctables_nest *nest = aux->nest;
2546 for (size_t i = 0; i < nest->n; i++)
2547 if (i != nest->scale_idx)
2549 const struct variable *var = nest->vars[i];
2550 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2551 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2552 if (a_cv->category != b_cv->category)
2553 return a_cv->category > b_cv->category ? 1 : -1;
2555 const union value *a_val = &a_cv->value;
2556 const union value *b_val = &b_cv->value;
2557 switch (a_cv->category->type)
2563 case CCT_POSTCOMPUTE:
2564 /* Must be equal. */
2571 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2579 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2581 return a_cv->category->sort_ascending ? cmp : -cmp;
2587 const char *a_label = var_lookup_value_label (var, a_val);
2588 const char *b_label = var_lookup_value_label (var, b_val);
2590 ? (b_label ? strcmp (a_label, b_label) : 1)
2591 : (b_label ? -1 : value_compare_3way (
2592 a_val, b_val, var_get_width (var))));
2594 return a_cv->category->sort_ascending ? cmp : -cmp;
2608 For each ctables_table:
2609 For each combination of row vars:
2610 For each combination of column vars:
2611 For each combination of layer vars:
2613 Make a table of row values:
2614 Sort entries by row values
2615 Assign a 0-based index to each actual value
2616 Construct a dimension
2617 Make a table of column values
2618 Make a table of layer values
2620 Fill the table entry using the indexes from before.
2623 static struct ctables_domain *
2624 ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
2625 enum ctables_domain_type domain)
2628 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2630 const struct ctables_nest *nest = s->nests[a];
2631 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2633 size_t v_idx = nest->domains[domain][i];
2634 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2635 var_get_width (nest->vars[v_idx]), hash);
2639 struct ctables_domain *d;
2640 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &s->domains[domain])
2642 const struct ctables_cell *df = d->example;
2643 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2645 const struct ctables_nest *nest = s->nests[a];
2646 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2648 size_t v_idx = nest->domains[domain][i];
2649 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2650 &cell->axes[a].cvs[v_idx].value,
2651 var_get_width (nest->vars[v_idx])))
2660 d = xmalloc (sizeof *d);
2661 *d = (struct ctables_domain) { .example = cell };
2662 hmap_insert (&s->domains[domain], &d->node, hash);
2666 static const struct ctables_category *
2667 ctables_categories_match (const struct ctables_categories *c,
2668 const union value *v, const struct variable *var)
2670 const struct ctables_category *othernm = NULL;
2671 for (size_t i = c->n_cats; i-- > 0; )
2673 const struct ctables_category *cat = &c->cats[i];
2677 if (cat->number == v->f)
2685 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2686 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2691 if (var_is_value_missing (var, v))
2695 case CCT_POSTCOMPUTE:
2710 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2715 return var_is_value_missing (var, v) ? NULL : othernm;
2718 static const struct ctables_category *
2719 ctables_categories_total (const struct ctables_categories *c)
2721 const struct ctables_category *first = &c->cats[0];
2722 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2723 return (first->type == CCT_TOTAL ? first
2724 : last->type == CCT_TOTAL ? last
2728 static struct ctables_cell *
2729 ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
2730 const struct ctables_category *cats[PIVOT_N_AXES][10])
2733 enum ctables_summary_variant sv = CSV_CELL;
2734 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2736 const struct ctables_nest *nest = s->nests[a];
2737 for (size_t i = 0; i < nest->n; i++)
2738 if (i != nest->scale_idx)
2740 hash = hash_pointer (cats[a][i], hash);
2741 if (cats[a][i]->type != CCT_TOTAL
2742 && cats[a][i]->type != CCT_SUBTOTAL
2743 && cats[a][i]->type != CCT_POSTCOMPUTE)
2744 hash = value_hash (case_data (c, nest->vars[i]),
2745 var_get_width (nest->vars[i]), hash);
2751 struct ctables_cell *cell;
2752 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &s->cells)
2754 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2756 const struct ctables_nest *nest = s->nests[a];
2757 for (size_t i = 0; i < nest->n; i++)
2758 if (i != nest->scale_idx
2759 && (cats[a][i] != cell->axes[a].cvs[i].category
2760 || (cats[a][i]->type != CCT_TOTAL
2761 && cats[a][i]->type != CCT_SUBTOTAL
2762 && cats[a][i]->type != CCT_POSTCOMPUTE
2763 && !value_equal (case_data (c, nest->vars[i]),
2764 &cell->axes[a].cvs[i].value,
2765 var_get_width (nest->vars[i])))))
2774 cell = xmalloc (sizeof *cell);
2777 cell->contributes_to_domains = true;
2778 cell->postcompute = false;
2779 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2781 const struct ctables_nest *nest = s->nests[a];
2782 cell->axes[a].cvs = (nest->n
2783 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2785 for (size_t i = 0; i < nest->n; i++)
2787 const struct ctables_category *cat = cats[a][i];
2788 if (i != nest->scale_idx)
2790 const struct ctables_category *subtotal = cat->subtotal;
2791 if (cat->hide || (subtotal && subtotal->hide_subcategories))
2794 if (cat->type == CCT_TOTAL
2795 || cat->type == CCT_SUBTOTAL
2796 || cat->type == CCT_POSTCOMPUTE)
2797 cell->contributes_to_domains = false;
2798 if (cat->type == CCT_POSTCOMPUTE)
2799 cell->postcompute = true;
2802 cell->axes[a].cvs[i].category = cat;
2803 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2804 var_get_width (nest->vars[i]));
2808 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2809 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2810 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2811 for (size_t i = 0; i < specs->n; i++)
2812 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2813 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2814 cell->domains[dt] = ctables_domain_insert (s, cell, dt);
2815 hmap_insert (&s->cells, &cell->node, hash);
2820 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
2821 const struct ctables_category *cats[PIVOT_N_AXES][10],
2822 double d_weight, double e_weight)
2824 struct ctables_cell *cell = ctables_cell_insert__ (s, c, cats);
2825 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2827 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2828 for (size_t i = 0; i < specs->n; i++)
2829 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2830 case_data (c, specs->var), d_weight, e_weight);
2831 if (cell->contributes_to_domains)
2833 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2835 cell->domains[dt]->d_valid += d_weight;
2836 cell->domains[dt]->e_valid += e_weight;
2842 recurse_totals (struct ctables_section *s, const struct ccase *c,
2843 const struct ctables_category *cats[PIVOT_N_AXES][10],
2844 double d_weight, double e_weight,
2845 enum pivot_axis_type start_axis, size_t start_nest)
2847 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2849 const struct ctables_nest *nest = s->nests[a];
2850 for (size_t i = start_nest; i < nest->n; i++)
2852 if (i == nest->scale_idx)
2855 const struct variable *var = nest->vars[i];
2857 const struct ctables_category *total = ctables_categories_total (
2858 s->table->categories[var_get_dict_index (var)]);
2861 const struct ctables_category *save = cats[a][i];
2863 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2864 recurse_totals (s, c, cats, d_weight, e_weight, a, i + 1);
2873 recurse_subtotals (struct ctables_section *s, const struct ccase *c,
2874 const struct ctables_category *cats[PIVOT_N_AXES][10],
2875 double d_weight, double e_weight,
2876 enum pivot_axis_type start_axis, size_t start_nest)
2878 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2880 const struct ctables_nest *nest = s->nests[a];
2881 for (size_t i = start_nest; i < nest->n; i++)
2883 if (i == nest->scale_idx)
2886 const struct ctables_category *save = cats[a][i];
2889 cats[a][i] = save->subtotal;
2890 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2891 recurse_subtotals (s, c, cats, d_weight, e_weight, a, i + 1);
2900 ctables_add_occurrence (const struct variable *var,
2901 const union value *value,
2902 struct hmap *occurrences)
2904 int width = var_get_width (var);
2905 unsigned int hash = value_hash (value, width, 0);
2907 struct ctables_section_value *sv;
2908 HMAP_FOR_EACH_WITH_HASH (sv, struct ctables_section_value, node, hash,
2910 if (value_equal (value, &sv->value, width))
2913 sv = xmalloc (sizeof *sv);
2914 value_clone (&sv->value, value, width);
2915 hmap_insert (occurrences, &sv->node, hash);
2919 ctables_cell_insert (struct ctables_section *s,
2920 const struct ccase *c,
2921 double d_weight, double e_weight)
2923 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
2924 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2926 const struct ctables_nest *nest = s->nests[a];
2927 for (size_t i = 0; i < nest->n; i++)
2929 if (i == nest->scale_idx)
2932 const struct variable *var = nest->vars[i];
2933 const union value *value = case_data (c, var);
2935 if (var_is_numeric (var) && value->f == SYSMIS)
2938 cats[a][i] = ctables_categories_match (
2939 s->table->categories[var_get_dict_index (var)], value, var);
2945 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2947 const struct ctables_nest *nest = s->nests[a];
2948 for (size_t i = 0; i < nest->n; i++)
2949 if (i != nest->scale_idx)
2951 const struct variable *var = nest->vars[i];
2952 const union value *value = case_data (c, var);
2953 ctables_add_occurrence (var, value, &s->occurrences[a][i]);
2957 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2959 recurse_totals (s, c, cats, d_weight, e_weight, 0, 0);
2960 recurse_subtotals (s, c, cats, d_weight, e_weight, 0, 0);
2965 const struct ctables_summary_spec_set *set;
2970 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2972 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2973 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2974 if (as->function != bs->function)
2975 return as->function > bs->function ? 1 : -1;
2976 else if (as->percentile != bs->percentile)
2977 return as->percentile < bs->percentile ? 1 : -1;
2978 return strcmp (as->label, bs->label);
2981 static struct pivot_value *
2982 ctables_category_create_label (const struct ctables_category *cat,
2983 const struct variable *var,
2984 const union value *value)
2986 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL
2987 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2988 : cat->type == CCT_POSTCOMPUTE && cat->pc->label
2989 ? pivot_value_new_user_text (cat->pc->label, SIZE_MAX)
2990 : pivot_value_new_var_value (var, value));
2993 static struct ctables_value *
2994 ctables_value_find__ (struct ctables_table *t, const union value *value,
2995 int width, unsigned int hash)
2997 struct ctables_value *clv;
2998 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2999 hash, &t->clabels_values_map)
3000 if (value_equal (value, &clv->value, width))
3005 static struct ctables_value *
3006 ctables_value_find (struct ctables_table *t,
3007 const union value *value, int width)
3009 return ctables_value_find__ (t, value, width,
3010 value_hash (value, width, 0));
3014 ctables_table_add_section (struct ctables_table *t, enum pivot_axis_type a,
3015 size_t ix[PIVOT_N_AXES])
3017 if (a < PIVOT_N_AXES)
3019 size_t limit = MAX (t->stacks[a].n, 1);
3020 for (ix[a] = 0; ix[a] < limit; ix[a]++)
3021 ctables_table_add_section (t, a + 1, ix);
3025 struct ctables_section *s = &t->sections[t->n_sections++];
3026 *s = (struct ctables_section) {
3028 .cells = HMAP_INITIALIZER (s->cells),
3030 for (a = 0; a < PIVOT_N_AXES; a++)
3033 struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
3035 s->occurrences[a] = xnmalloc (nest->n, sizeof *s->occurrences[a]);
3036 for (size_t i = 0; i < nest->n; i++)
3037 hmap_init (&s->occurrences[a][i]);
3039 for (size_t i = 0; i < N_CTDTS; i++)
3040 hmap_init (&s->domains[i]);
3045 ctpo_add (double a, double b)
3051 ctpo_sub (double a, double b)
3057 ctpo_mul (double a, double b)
3063 ctpo_div (double a, double b)
3065 return b ? a / b : SYSMIS;
3069 ctpo_pow (double a, double b)
3071 int save_errno = errno;
3073 double result = pow (a, b);
3081 ctpo_neg (double a, double b UNUSED)
3086 struct ctables_pcexpr_evaluate_ctx
3088 const struct ctables_cell *cell;
3089 const struct ctables_section *section;
3090 const struct ctables_categories *cats;
3091 enum pivot_axis_type pc_a;
3095 static double ctables_pcexpr_evaluate (
3096 const struct ctables_pcexpr_evaluate_ctx *, const struct ctables_pcexpr *);
3099 ctables_pcexpr_evaluate_nonterminal (
3100 const struct ctables_pcexpr_evaluate_ctx *ctx,
3101 const struct ctables_pcexpr *e, size_t n_args,
3102 double evaluate (double, double))
3104 double args[2] = { 0, 0 };
3105 for (size_t i = 0; i < n_args; i++)
3107 args[i] = ctables_pcexpr_evaluate (ctx, e->subs[i]);
3108 if (!isfinite (args[i]) || args[i] == SYSMIS)
3111 return evaluate (args[0], args[1]);
3115 ctables_pcexpr_evaluate_category (const struct ctables_pcexpr_evaluate_ctx *ctx,
3116 const struct ctables_category *cat)
3118 const struct ctables_section *s = ctx->section;
3121 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3123 const struct ctables_nest *nest = s->nests[a];
3124 for (size_t i = 0; i < nest->n; i++)
3125 if (a == ctx->pc_a && i == ctx->pc_a_idx)
3127 /* XXX anything other than just a constant.... need a higher level
3128 loop to go through occurrences */
3129 hash = hash_pointer (cat, hash);
3130 hash = hash_double (cat->number, hash);
3132 else if (i != nest->scale_idx)
3134 const struct ctables_cell_value *cv = &ctx->cell->axes[a].cvs[i];
3135 hash = hash_pointer (cv->category, hash);
3136 if (cv->category->type != CCT_TOTAL
3137 && cv->category->type != CCT_SUBTOTAL
3138 && cv->category->type != CCT_POSTCOMPUTE)
3139 hash = value_hash (&cv->value,
3140 var_get_width (nest->vars[i]), hash);
3144 struct ctables_cell *tc;
3145 HMAP_FOR_EACH_WITH_HASH (tc, struct ctables_cell, node, hash, &s->cells)
3147 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3149 const struct ctables_nest *nest = s->nests[a];
3150 for (size_t i = 0; i < nest->n; i++)
3152 const struct ctables_cell_value *p_cv = &ctx->cell->axes[a].cvs[i];
3153 const struct ctables_cell_value *t_cv = &tc->axes[a].cvs[i];
3155 if (i == nest->scale_idx)
3157 /* Nothing to do. */
3159 else if (a == ctx->pc_a && i == ctx->pc_a_idx)
3161 /* XXX anything other than a constant.... */
3162 if (t_cv->category != cat || t_cv->value.f != cat->number)
3165 else if (p_cv->category != t_cv->category
3166 || (p_cv->category->type != CCT_TOTAL
3167 && p_cv->category->type != CCT_SUBTOTAL
3168 && p_cv->category->type != CCT_POSTCOMPUTE
3169 && !value_equal (&p_cv->value,
3171 var_get_width (nest->vars[i]))))
3183 const struct ctables_table *t = s->table;
3184 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3185 const struct ctables_summary_spec_set *specs = &specs_nest->specs[tc->sv];
3186 size_t j = 0 /* XXX */;
3187 return ctables_summary_value (tc, &tc->summaries[j], &specs->specs[j]);
3191 ctables_pcexpr_evaluate (const struct ctables_pcexpr_evaluate_ctx *ctx,
3192 const struct ctables_pcexpr *e)
3199 case CTPO_CAT_NUMBER:
3200 case CTPO_CAT_STRING:
3201 case CTPO_CAT_RANGE:
3202 case CTPO_CAT_MISSING:
3203 case CTPO_CAT_OTHERNM:
3204 case CTPO_CAT_SUBTOTAL:
3205 case CTPO_CAT_TOTAL:
3207 struct ctables_category *cat = ctables_find_category_for_postcompute (
3209 assert (cat != NULL);
3211 return ctables_pcexpr_evaluate_category (ctx, cat);
3215 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_add);
3218 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_sub);
3221 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_mul);
3224 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_div);
3227 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_pow);
3230 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 1, ctpo_neg);
3237 ctables_cell_calculate_postcompute (const struct ctables_section *s,
3238 const struct ctables_cell *cell)
3240 enum pivot_axis_type pc_a;
3242 const struct ctables_postcompute *pc;
3243 for (pc_a = 0; ; pc_a++)
3245 assert (pc_a < PIVOT_N_AXES);
3246 for (pc_a_idx = 0; pc_a_idx < s->nests[pc_a]->n; pc_a_idx++)
3248 const struct ctables_cell_value *cv = &cell->axes[pc_a].cvs[pc_a_idx];
3249 if (cv->category->type == CCT_POSTCOMPUTE)
3251 pc = cv->category->pc;
3258 const struct variable *var = s->nests[pc_a]->vars[pc_a_idx];
3259 const struct ctables_categories *cats = s->table->categories[
3260 var_get_dict_index (var)];
3261 struct ctables_pcexpr_evaluate_ctx ctx = {
3266 .pc_a_idx = pc_a_idx,
3268 return ctables_pcexpr_evaluate (&ctx, pc->expr);
3272 ctables_table_output (struct ctables *ct, struct ctables_table *t)
3274 struct pivot_table *pt = pivot_table_create__ (
3276 ? pivot_value_new_user_text (t->title, SIZE_MAX)
3277 : pivot_value_new_text (N_("Custom Tables"))),
3280 pivot_table_set_caption (
3281 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
3283 pivot_table_set_caption (
3284 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
3286 bool summary_dimension = (t->summary_axis != t->slabels_axis
3287 || (!t->slabels_visible
3288 && t->summary_specs.n > 1));
3289 if (summary_dimension)
3291 struct pivot_dimension *d = pivot_dimension_create (
3292 pt, t->slabels_axis, N_("Statistics"));
3293 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3294 if (!t->slabels_visible)
3295 d->hide_all_labels = true;
3296 for (size_t i = 0; i < specs->n; i++)
3297 pivot_category_create_leaf (
3298 d->root, pivot_value_new_text (specs->specs[i].label));
3301 bool categories_dimension = t->clabels_example != NULL;
3302 if (categories_dimension)
3304 struct pivot_dimension *d = pivot_dimension_create (
3305 pt, t->label_axis[t->clabels_from_axis],
3306 t->clabels_from_axis == PIVOT_AXIS_ROW
3307 ? N_("Row Categories")
3308 : N_("Column Categories"));
3309 const struct variable *var = t->clabels_example;
3310 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
3311 for (size_t i = 0; i < t->n_clabels_values; i++)
3313 const struct ctables_value *value = t->clabels_values[i];
3314 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
3315 assert (cat != NULL);
3316 pivot_category_create_leaf (d->root, ctables_category_create_label (
3317 cat, t->clabels_example, &value->value));
3321 pivot_table_set_look (pt, ct->look);
3322 struct pivot_dimension *d[PIVOT_N_AXES];
3323 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3325 static const char *names[] = {
3326 [PIVOT_AXIS_ROW] = N_("Rows"),
3327 [PIVOT_AXIS_COLUMN] = N_("Columns"),
3328 [PIVOT_AXIS_LAYER] = N_("Layers"),
3330 d[a] = (t->axes[a] || a == t->summary_axis
3331 ? pivot_dimension_create (pt, a, names[a])
3336 assert (t->axes[a]);
3338 for (size_t i = 0; i < t->stacks[a].n; i++)
3340 struct ctables_nest *nest = &t->stacks[a].nests[i];
3341 struct ctables_section **sections = xnmalloc (t->n_sections,
3343 size_t n_sections = 0;
3345 size_t n_total_cells = 0;
3346 size_t max_depth = 0;
3347 for (size_t j = 0; j < t->n_sections; j++)
3348 if (t->sections[j].nests[a] == nest)
3350 struct ctables_section *s = &t->sections[j];
3351 sections[n_sections++] = s;
3352 n_total_cells += s->cells.count;
3354 size_t depth = s->nests[a]->n;
3355 max_depth = MAX (depth, max_depth);
3358 struct ctables_cell **sorted = xnmalloc (n_total_cells,
3360 size_t n_sorted = 0;
3362 for (size_t j = 0; j < n_sections; j++)
3364 struct ctables_section *s = sections[j];
3366 struct ctables_cell *cell;
3367 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3369 sorted[n_sorted++] = cell;
3370 assert (n_sorted <= n_total_cells);
3373 struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
3374 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
3376 struct ctables_level
3378 enum ctables_level_type
3380 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
3381 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
3382 CTL_SUMMARY, /* Summary functions. */
3388 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
3389 size_t n_levels = 0;
3390 for (size_t k = 0; k < nest->n; k++)
3392 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
3393 if (vlabel != CTVL_NONE)
3395 levels[n_levels++] = (struct ctables_level) {
3401 if (nest->scale_idx != k
3402 && (k != nest->n - 1 || t->label_axis[a] == a))
3404 levels[n_levels++] = (struct ctables_level) {
3405 .type = CTL_CATEGORY,
3411 if (!summary_dimension && a == t->slabels_axis)
3413 levels[n_levels++] = (struct ctables_level) {
3414 .type = CTL_SUMMARY,
3415 .var_idx = SIZE_MAX,
3419 /* Pivot categories:
3421 - variable label for nest->vars[0], if vlabel != CTVL_NONE
3422 - category for nest->vars[0], if nest->scale_idx != 0
3423 - variable label for nest->vars[1], if vlabel != CTVL_NONE
3424 - category for nest->vars[1], if nest->scale_idx != 1
3426 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
3427 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
3428 - summary function, if 'a == t->slabels_axis && a ==
3431 Additional dimensions:
3433 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
3435 - If 't->label_axis[b] == a' for some 'b != a', add a category
3440 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
3442 for (size_t j = 0; j < n_sorted; j++)
3444 struct ctables_cell *cell = sorted[j];
3445 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
3447 size_t n_common = 0;
3450 for (; n_common < n_levels; n_common++)
3452 const struct ctables_level *level = &levels[n_common];
3453 if (level->type == CTL_CATEGORY)
3455 size_t var_idx = level->var_idx;
3456 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3457 if (prev->axes[a].cvs[var_idx].category != c)
3459 else if (c->type != CCT_SUBTOTAL
3460 && c->type != CCT_TOTAL
3461 && c->type != CCT_POSTCOMPUTE
3462 && !value_equal (&prev->axes[a].cvs[var_idx].value,
3463 &cell->axes[a].cvs[var_idx].value,
3464 var_get_type (nest->vars[var_idx])))
3470 for (size_t k = n_common; k < n_levels; k++)
3472 const struct ctables_level *level = &levels[k];
3473 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3474 if (level->type == CTL_SUMMARY)
3476 assert (k == n_levels - 1);
3478 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3479 for (size_t m = 0; m < specs->n; m++)
3481 int leaf = pivot_category_create_leaf (
3482 parent, pivot_value_new_text (specs->specs[m].label));
3489 const struct variable *var = nest->vars[level->var_idx];
3490 struct pivot_value *label;
3491 if (level->type == CTL_VAR)
3492 label = pivot_value_new_variable (var);
3493 else if (level->type == CTL_CATEGORY)
3495 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3496 label = ctables_category_create_label (cv->category,
3502 if (k == n_levels - 1)
3503 prev_leaf = pivot_category_create_leaf (parent, label);
3505 groups[k] = pivot_category_create_group__ (parent, label);
3509 cell->axes[a].leaf = prev_leaf;
3516 for (size_t i = 0; i < t->n_sections; i++)
3518 struct ctables_section *s = &t->sections[i];
3520 struct ctables_cell *cell;
3521 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3526 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3527 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3528 for (size_t j = 0; j < specs->n; j++)
3531 size_t n_dindexes = 0;
3533 if (summary_dimension)
3534 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3536 if (categories_dimension)
3538 const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3539 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3540 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3541 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3542 assert (ctv != NULL);
3543 dindexes[n_dindexes++] = ctv->leaf;
3546 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3549 int leaf = cell->axes[a].leaf;
3550 if (a == t->summary_axis && !summary_dimension)
3552 dindexes[n_dindexes++] = leaf;
3555 double d = (cell->postcompute
3556 ? ctables_cell_calculate_postcompute (s, cell)
3557 : ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]));
3558 struct pivot_value *value = pivot_value_new_number (d);
3559 value->numeric.format = specs->specs[j].format;
3560 pivot_table_put (pt, dindexes, n_dindexes, value);
3565 pivot_table_submit (pt);
3569 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3571 enum pivot_axis_type label_pos = t->label_axis[a];
3575 t->clabels_from_axis = a;
3577 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3578 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3580 const struct ctables_stack *stack = &t->stacks[a];
3584 const struct ctables_nest *n0 = &stack->nests[0];
3586 const struct variable *v0 = n0->vars[n0->n - 1];
3587 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3588 t->clabels_example = v0;
3590 for (size_t i = 0; i < c0->n_cats; i++)
3591 if (c0->cats[i].type == CCT_FUNCTION)
3593 msg (SE, _("%s=%s is not allowed with sorting based "
3594 "on a summary function."),
3595 subcommand_name, pos_name);
3598 if (n0->n - 1 == n0->scale_idx)
3600 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3601 "but %s is a scale variable."),
3602 subcommand_name, pos_name, var_get_name (v0));
3606 for (size_t i = 1; i < stack->n; i++)
3608 const struct ctables_nest *ni = &stack->nests[i];
3610 const struct variable *vi = ni->vars[ni->n - 1];
3611 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3613 if (ni->n - 1 == ni->scale_idx)
3615 msg (SE, _("%s=%s requires the variables to be moved to be "
3616 "categorical, but %s is a scale variable."),
3617 subcommand_name, pos_name, var_get_name (vi));
3620 if (var_get_width (v0) != var_get_width (vi))
3622 msg (SE, _("%s=%s requires the variables to be "
3623 "moved to have the same width, but %s has "
3624 "width %d and %s has width %d."),
3625 subcommand_name, pos_name,
3626 var_get_name (v0), var_get_width (v0),
3627 var_get_name (vi), var_get_width (vi));
3630 if (!val_labs_equal (var_get_value_labels (v0),
3631 var_get_value_labels (vi)))
3633 msg (SE, _("%s=%s requires the variables to be "
3634 "moved to have the same value labels, but %s "
3635 "and %s have different value labels."),
3636 subcommand_name, pos_name,
3637 var_get_name (v0), var_get_name (vi));
3640 if (!ctables_categories_equal (c0, ci))
3642 msg (SE, _("%s=%s requires the variables to be "
3643 "moved to have the same category "
3644 "specifications, but %s and %s have different "
3645 "category specifications."),
3646 subcommand_name, pos_name,
3647 var_get_name (v0), var_get_name (vi));
3656 ctables_prepare_table (struct ctables_table *t)
3658 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3661 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3663 for (size_t j = 0; j < t->stacks[a].n; j++)
3665 struct ctables_nest *nest = &t->stacks[a].nests[j];
3666 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3668 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3669 nest->n_domains[dt] = 0;
3671 for (size_t k = 0; k < nest->n; k++)
3673 if (k == nest->scale_idx)
3682 if (a != PIVOT_AXIS_LAYER)
3689 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3690 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3691 : a == PIVOT_AXIS_ROW)
3693 if (k == nest->n - 1
3694 || (nest->scale_idx == nest->n - 1
3695 && k == nest->n - 2))
3701 if (a == PIVOT_AXIS_COLUMN)
3706 if (a == PIVOT_AXIS_ROW)
3711 nest->domains[dt][nest->n_domains[dt]++] = k;
3718 struct ctables_nest *nest = xmalloc (sizeof *nest);
3719 *nest = (struct ctables_nest) { .n = 0 };
3720 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3723 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3724 for (size_t i = 0; i < stack->n; i++)
3726 struct ctables_nest *nest = &stack->nests[i];
3727 if (!nest->specs[CSV_CELL].n)
3729 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3730 specs->specs = xmalloc (sizeof *specs->specs);
3733 enum ctables_summary_function function
3734 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3735 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3737 *specs->specs = (struct ctables_summary_spec) {
3738 .function = function,
3739 .format = ctables_summary_default_format (function, &var),
3740 .label = ctables_summary_default_label (function, 0),
3743 specs->var = nest->vars[0];
3745 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3746 &nest->specs[CSV_CELL]);
3748 else if (!nest->specs[CSV_TOTAL].n)
3749 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3750 &nest->specs[CSV_CELL]);
3753 struct ctables_summary_spec_set *merged = &t->summary_specs;
3754 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3756 for (size_t j = 0; j < stack->n; j++)
3758 const struct ctables_nest *nest = &stack->nests[j];
3760 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3761 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3766 struct merge_item min = items[0];
3767 for (size_t j = 1; j < n_left; j++)
3768 if (merge_item_compare_3way (&items[j], &min) < 0)
3771 if (merged->n >= merged->allocated)
3772 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3773 sizeof *merged->specs);
3774 merged->specs[merged->n++] = min.set->specs[min.ofs];
3776 for (size_t j = 0; j < n_left; )
3778 if (merge_item_compare_3way (&items[j], &min) == 0)
3780 struct merge_item *item = &items[j];
3781 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3782 if (++item->ofs >= item->set->n)
3784 items[j] = items[--n_left];
3793 for (size_t j = 0; j < merged->n; j++)
3794 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3796 for (size_t j = 0; j < stack->n; j++)
3798 const struct ctables_nest *nest = &stack->nests[j];
3799 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3801 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3802 for (size_t k = 0; k < specs->n; k++)
3803 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3804 specs->specs[k].axis_idx);
3810 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3811 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3815 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3816 enum pivot_axis_type a)
3818 struct ctables_stack *stack = &t->stacks[a];
3819 for (size_t i = 0; i < stack->n; i++)
3821 const struct ctables_nest *nest = &stack->nests[i];
3822 const struct variable *var = nest->vars[nest->n - 1];
3823 int width = var_get_width (var);
3824 const union value *value = case_data (c, var);
3826 if (var_is_numeric (var) && value->f == SYSMIS)
3829 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3833 unsigned int hash = value_hash (value, width, 0);
3835 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3838 clv = xmalloc (sizeof *clv);
3839 value_clone (&clv->value, value, width);
3840 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3846 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3848 const struct ctables_value *const *ap = a_;
3849 const struct ctables_value *const *bp = b_;
3850 const struct ctables_value *a = *ap;
3851 const struct ctables_value *b = *bp;
3852 const int *width = width_;
3853 return value_compare_3way (&a->value, &b->value, *width);
3857 ctables_sort_clabels_values (struct ctables_table *t)
3859 int width = var_get_width (t->clabels_example);
3861 size_t n = hmap_count (&t->clabels_values_map);
3862 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3864 struct ctables_value *clv;
3866 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3867 t->clabels_values[i++] = clv;
3868 t->n_clabels_values = n;
3871 sort (t->clabels_values, n, sizeof *t->clabels_values,
3872 compare_clabels_values_3way, &width);
3874 for (size_t i = 0; i < n; i++)
3875 t->clabels_values[i]->leaf = i;
3879 ctables_add_category_occurrences (const struct variable *var,
3880 struct hmap *occurrences,
3881 const struct ctables_categories *cats)
3883 const struct val_labs *val_labs = var_get_value_labels (var);
3885 for (size_t i = 0; i < cats->n_cats; i++)
3887 const struct ctables_category *c = &cats->cats[i];
3891 ctables_add_occurrence (var, &(const union value) { .f = c->number },
3899 assert (var_is_numeric (var));
3900 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3901 vl = val_labs_next (val_labs, vl))
3902 if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
3903 ctables_add_occurrence (var, &vl->value, occurrences);
3907 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3908 vl = val_labs_next (val_labs, vl))
3909 if (var_is_value_missing (var, &vl->value))
3910 ctables_add_occurrence (var, &vl->value, occurrences);
3914 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3915 vl = val_labs_next (val_labs, vl))
3916 ctables_add_occurrence (var, &vl->value, occurrences);
3919 case CCT_POSTCOMPUTE:
3929 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3930 vl = val_labs_next (val_labs, vl))
3931 if (c->include_missing || !var_is_value_missing (var, &vl->value))
3932 ctables_add_occurrence (var, &vl->value, occurrences);
3939 ctables_section_recurse_add_empty_categories (
3940 struct ctables_section *s,
3941 const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
3942 enum pivot_axis_type a, size_t a_idx)
3944 if (a >= PIVOT_N_AXES)
3945 ctables_cell_insert__ (s, c, cats);
3946 else if (!s->nests[a] || a_idx >= s->nests[a]->n)
3947 ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
3950 const struct variable *var = s->nests[a]->vars[a_idx];
3951 const struct ctables_categories *categories = s->table->categories[
3952 var_get_dict_index (var)];
3953 int width = var_get_width (var);
3954 const struct hmap *occurrences = &s->occurrences[a][a_idx];
3955 const struct ctables_section_value *sv;
3956 HMAP_FOR_EACH (sv, struct ctables_section_value, node, occurrences)
3958 union value *value = case_data_rw (c, var);
3959 value_destroy (value, width);
3960 value_clone (value, &sv->value, width);
3961 cats[a][a_idx] = ctables_categories_match (categories, value, var);
3962 assert (cats[a][a_idx] != NULL);
3963 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3966 for (size_t i = 0; i < categories->n_cats; i++)
3968 const struct ctables_category *cat = &categories->cats[i];
3969 if (cat->type == CCT_POSTCOMPUTE)
3971 printf ("%s:%d\n", __FILE__, __LINE__);
3972 cats[a][a_idx] = cat;
3973 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3980 ctables_section_add_empty_categories (struct ctables_section *s)
3982 bool show_empty = false;
3983 for (size_t a = 0; a < PIVOT_N_AXES; a++)
3985 for (size_t k = 0; k < s->nests[a]->n; k++)
3986 if (k != s->nests[a]->scale_idx)
3988 const struct variable *var = s->nests[a]->vars[k];
3989 const struct ctables_categories *cats = s->table->categories[
3990 var_get_dict_index (var)];
3991 if (cats->show_empty)
3994 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
4000 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
4001 struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
4002 ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
4007 ctables_execute (struct dataset *ds, struct ctables *ct)
4009 for (size_t i = 0; i < ct->n_tables; i++)
4011 struct ctables_table *t = ct->tables[i];
4012 t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
4013 MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
4014 MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
4015 sizeof *t->sections);
4016 size_t ix[PIVOT_N_AXES];
4017 ctables_table_add_section (t, 0, ix);
4020 struct casereader *input = proc_open (ds);
4021 bool warn_on_invalid = true;
4022 for (struct ccase *c = casereader_read (input); c;
4023 case_unref (c), c = casereader_read (input))
4025 double d_weight = dict_get_case_weight (dataset_dict (ds), c,
4027 double e_weight = (ct->e_weight
4028 ? var_force_valid_weight (ct->e_weight,
4029 case_num (c, ct->e_weight),
4033 for (size_t i = 0; i < ct->n_tables; i++)
4035 struct ctables_table *t = ct->tables[i];
4037 for (size_t j = 0; j < t->n_sections; j++)
4038 ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
4040 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4041 if (t->label_axis[a] != a)
4042 ctables_insert_clabels_values (t, c, a);
4045 casereader_destroy (input);
4047 for (size_t i = 0; i < ct->n_tables; i++)
4049 struct ctables_table *t = ct->tables[i];
4051 if (t->clabels_example)
4052 ctables_sort_clabels_values (t);
4054 for (size_t j = 0; j < t->n_sections; j++)
4055 ctables_section_add_empty_categories (&t->sections[j]);
4057 ctables_table_output (ct, ct->tables[i]);
4059 return proc_commit (ds);
4064 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
4067 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
4073 case CTPO_CAT_STRING:
4083 for (size_t i = 0; i < 2; i++)
4084 ctables_pcexpr_destroy (e->subs[i]);
4088 case CTPO_CAT_NUMBER:
4089 case CTPO_CAT_RANGE:
4090 case CTPO_CAT_MISSING:
4091 case CTPO_CAT_OTHERNM:
4092 case CTPO_CAT_SUBTOTAL:
4093 case CTPO_CAT_TOTAL:
4097 msg_location_destroy (e->location);
4102 static struct ctables_pcexpr *
4103 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
4104 struct ctables_pcexpr *sub0,
4105 struct ctables_pcexpr *sub1)
4107 struct ctables_pcexpr *e = xmalloc (sizeof *e);
4108 *e = (struct ctables_pcexpr) {
4110 .subs = { sub0, sub1 },
4111 .location = msg_location_merged (sub0->location, sub1->location),
4116 /* How to parse an operator. */
4119 enum token_type token;
4120 enum ctables_postcompute_op op;
4123 static const struct operator *
4124 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
4126 for (const struct operator *op = ops; op < ops + n_ops; op++)
4127 if (lex_token (lexer) == op->token)
4129 if (op->token != T_NEG_NUM)
4138 static struct ctables_pcexpr *
4139 parse_binary_operators__ (struct lexer *lexer,
4140 const struct operator ops[], size_t n_ops,
4141 parse_recursively_func *parse_next_level,
4142 const char *chain_warning,
4143 struct ctables_pcexpr *lhs)
4145 for (int op_count = 0; ; op_count++)
4147 const struct operator *op = match_operator (lexer, ops, n_ops);
4150 if (op_count > 1 && chain_warning)
4151 msg_at (SW, lhs->location, "%s", chain_warning);
4156 struct ctables_pcexpr *rhs = parse_next_level (lexer);
4159 ctables_pcexpr_destroy (lhs);
4163 lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
4167 static struct ctables_pcexpr *
4168 parse_binary_operators (struct lexer *lexer,
4169 const struct operator ops[], size_t n_ops,
4170 parse_recursively_func *parse_next_level,
4171 const char *chain_warning)
4173 struct ctables_pcexpr *lhs = parse_next_level (lexer);
4177 return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
4178 chain_warning, lhs);
4181 static struct ctables_pcexpr *parse_add (struct lexer *);
4183 static struct ctables_pcexpr
4184 ctpo_cat_range (double low, double high)
4186 return (struct ctables_pcexpr) {
4187 .op = CTPO_CAT_RANGE,
4188 .range = { low, high },
4192 static struct ctables_pcexpr *
4193 parse_primary (struct lexer *lexer)
4195 int start_ofs = lex_ofs (lexer);
4196 struct ctables_pcexpr e;
4197 if (lex_is_number (lexer))
4199 e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
4200 .number = lex_number (lexer) };
4203 else if (lex_match_id (lexer, "MISSING"))
4204 e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
4205 else if (lex_match_id (lexer, "OTHERNM"))
4206 e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
4207 else if (lex_match_id (lexer, "TOTAL"))
4208 e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
4209 else if (lex_match_id (lexer, "SUBTOTAL"))
4211 size_t subtotal_index = 0;
4212 if (lex_match (lexer, T_LBRACK))
4214 if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
4216 subtotal_index = lex_integer (lexer);
4218 if (!lex_force_match (lexer, T_RBRACK))
4221 e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
4222 .subtotal_index = subtotal_index };
4224 else if (lex_match (lexer, T_LBRACK))
4226 if (lex_match_id (lexer, "LO"))
4228 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
4230 e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
4233 else if (lex_is_number (lexer))
4235 double number = lex_number (lexer);
4237 if (lex_match_id (lexer, "THRU"))
4239 if (lex_match_id (lexer, "HI"))
4240 e = ctpo_cat_range (number, DBL_MAX);
4243 if (!lex_force_num (lexer))
4245 e = ctpo_cat_range (number, lex_number (lexer));
4250 e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
4253 else if (lex_is_string (lexer))
4255 e = (struct ctables_pcexpr) {
4256 .op = CTPO_CAT_STRING,
4257 .string = ss_xstrdup (lex_tokss (lexer)),
4263 lex_error (lexer, NULL);
4267 if (!lex_force_match (lexer, T_RBRACK))
4269 if (e.op == CTPO_CAT_STRING)
4274 else if (lex_match (lexer, T_LPAREN))
4276 struct ctables_pcexpr *ep = parse_add (lexer);
4279 if (!lex_force_match (lexer, T_RPAREN))
4281 ctables_pcexpr_destroy (ep);
4288 lex_error (lexer, NULL);
4292 e.location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
4293 return xmemdup (&e, sizeof e);
4296 static struct ctables_pcexpr *
4297 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
4298 struct lexer *lexer, int start_ofs)
4300 struct ctables_pcexpr *e = xmalloc (sizeof *e);
4301 *e = (struct ctables_pcexpr) {
4304 .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
4309 static struct ctables_pcexpr *
4310 parse_exp (struct lexer *lexer)
4312 static const struct operator op = { T_EXP, CTPO_POW };
4314 const char *chain_warning =
4315 _("The exponentiation operator (`**') is left-associative: "
4316 "`a**b**c' equals `(a**b)**c', not `a**(b**c)'. "
4317 "To disable this warning, insert parentheses.");
4319 if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
4320 return parse_binary_operators (lexer, &op, 1,
4321 parse_primary, chain_warning);
4323 /* Special case for situations like "-5**6", which must be parsed as
4326 int start_ofs = lex_ofs (lexer);
4327 struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
4328 *lhs = (struct ctables_pcexpr) {
4329 .op = CTPO_CONSTANT,
4330 .number = -lex_tokval (lexer),
4331 .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer)),
4335 struct ctables_pcexpr *node = parse_binary_operators__ (
4336 lexer, &op, 1, parse_primary, chain_warning, lhs);
4340 return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
4343 /* Parses the unary minus level. */
4344 static struct ctables_pcexpr *
4345 parse_neg (struct lexer *lexer)
4347 int start_ofs = lex_ofs (lexer);
4348 if (!lex_match (lexer, T_DASH))
4349 return parse_exp (lexer);
4351 struct ctables_pcexpr *inner = parse_neg (lexer);
4355 return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
4358 /* Parses the multiplication and division level. */
4359 static struct ctables_pcexpr *
4360 parse_mul (struct lexer *lexer)
4362 static const struct operator ops[] =
4364 { T_ASTERISK, CTPO_MUL },
4365 { T_SLASH, CTPO_DIV },
4368 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4372 /* Parses the addition and subtraction level. */
4373 static struct ctables_pcexpr *
4374 parse_add (struct lexer *lexer)
4376 static const struct operator ops[] =
4378 { T_PLUS, CTPO_ADD },
4379 { T_DASH, CTPO_SUB },
4380 { T_NEG_NUM, CTPO_ADD },
4383 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4387 static struct ctables_postcompute *
4388 ctables_find_postcompute (struct ctables *ct, const char *name)
4390 struct ctables_postcompute *pc;
4391 HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
4392 utf8_hash_case_string (name, 0), &ct->postcomputes)
4393 if (!utf8_strcasecmp (pc->name, name))
4399 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
4401 int pcompute_start = lex_ofs (lexer) - 1;
4403 if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
4406 char *name = ss_xstrdup (lex_tokss (lexer));
4409 if (!lex_force_match (lexer, T_EQUALS)
4410 || !lex_force_match_id (lexer, "EXPR")
4411 || !lex_force_match (lexer, T_LPAREN))
4417 int expr_start = lex_ofs (lexer);
4418 struct ctables_pcexpr *expr = parse_add (lexer);
4419 int expr_end = lex_ofs (lexer) - 1;
4420 if (!expr || !lex_force_match (lexer, T_RPAREN))
4425 int pcompute_end = lex_ofs (lexer) - 1;
4427 struct msg_location *location = lex_ofs_location (lexer, pcompute_start,
4430 struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
4433 msg_at (SW, location, _("New definition of &%s will override the "
4434 "previous definition."),
4436 msg_at (SN, pc->location, _("This is the previous definition."));
4438 ctables_pcexpr_destroy (pc->expr);
4439 msg_location_destroy (pc->location);
4444 pc = xmalloc (sizeof *pc);
4445 *pc = (struct ctables_postcompute) { .name = name };
4446 hmap_insert (&ct->postcomputes, &pc->hmap_node,
4447 utf8_hash_case_string (pc->name, 0));
4450 pc->location = location;
4452 pc->label = lex_ofs_representation (lexer, expr_start, expr_end);
4457 ctables_parse_pproperties_format (struct lexer *lexer,
4458 struct ctables_summary_spec_set *sss)
4460 *sss = (struct ctables_summary_spec_set) { .n = 0 };
4462 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4463 && !(lex_token (lexer) == T_ID
4464 && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4465 || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4466 lex_tokss (lexer)))))
4468 /* Parse function. */
4469 enum ctables_summary_function function;
4470 if (!parse_ctables_summary_function (lexer, &function))
4473 /* Parse percentile. */
4474 double percentile = 0;
4475 if (function == CTSF_PTILE)
4477 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4479 percentile = lex_number (lexer);
4484 struct fmt_spec format;
4485 if (!parse_format_specifier (lexer, &format)
4486 || !fmt_check_output (&format)
4487 || !fmt_check_type_compat (&format, VAL_NUMERIC))
4490 if (sss->n >= sss->allocated)
4491 sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4492 sizeof *sss->specs);
4493 sss->specs[sss->n++] = (struct ctables_summary_spec) {
4494 .function = function,
4495 .percentile = percentile,
4502 ctables_summary_spec_set_uninit (sss);
4507 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4509 struct ctables_postcompute **pcs = NULL;
4511 size_t allocated_pcs = 0;
4513 while (lex_match (lexer, T_AND))
4515 if (!lex_force_id (lexer))
4517 struct ctables_postcompute *pc
4518 = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4521 msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4526 if (n_pcs >= allocated_pcs)
4527 pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4531 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4533 if (lex_match_id (lexer, "LABEL"))
4535 lex_match (lexer, T_EQUALS);
4536 if (!lex_force_string (lexer))
4539 for (size_t i = 0; i < n_pcs; i++)
4541 free (pcs[i]->label);
4542 pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4547 else if (lex_match_id (lexer, "FORMAT"))
4549 lex_match (lexer, T_EQUALS);
4551 struct ctables_summary_spec_set sss;
4552 if (!ctables_parse_pproperties_format (lexer, &sss))
4555 for (size_t i = 0; i < n_pcs; i++)
4558 ctables_summary_spec_set_uninit (pcs[i]->specs);
4560 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4561 ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4563 ctables_summary_spec_set_uninit (&sss);
4565 else if (lex_match_id (lexer, "HIDESOURCECATS"))
4567 lex_match (lexer, T_EQUALS);
4568 bool hide_source_cats;
4569 if (!parse_bool (lexer, &hide_source_cats))
4571 for (size_t i = 0; i < n_pcs; i++)
4572 pcs[i]->hide_source_cats = hide_source_cats;
4576 lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4589 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4591 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4592 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4593 enum settings_value_show tvars = settings_get_show_variables ();
4594 for (size_t i = 0; i < n_vars; i++)
4595 vlabels[i] = (enum ctables_vlabel) tvars;
4597 struct ctables *ct = xmalloc (sizeof *ct);
4598 *ct = (struct ctables) {
4599 .dict = dataset_dict (ds),
4600 .look = pivot_table_look_unshare (pivot_table_look_ref (
4601 pivot_table_look_get_default ())),
4603 .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
4604 .hide_threshold = 5,
4606 ct->look->omit_empty = false;
4608 if (!lex_force_match (lexer, T_SLASH))
4611 while (!lex_match_id (lexer, "TABLE"))
4613 if (lex_match_id (lexer, "FORMAT"))
4615 double widths[2] = { SYSMIS, SYSMIS };
4616 double units_per_inch = 72.0;
4618 while (lex_token (lexer) != T_SLASH)
4620 if (lex_match_id (lexer, "MINCOLWIDTH"))
4622 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4625 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4627 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4630 else if (lex_match_id (lexer, "UNITS"))
4632 lex_match (lexer, T_EQUALS);
4633 if (lex_match_id (lexer, "POINTS"))
4634 units_per_inch = 72.0;
4635 else if (lex_match_id (lexer, "INCHES"))
4636 units_per_inch = 1.0;
4637 else if (lex_match_id (lexer, "CM"))
4638 units_per_inch = 2.54;
4641 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4645 else if (lex_match_id (lexer, "EMPTY"))
4650 lex_match (lexer, T_EQUALS);
4651 if (lex_match_id (lexer, "ZERO"))
4653 /* Nothing to do. */
4655 else if (lex_match_id (lexer, "BLANK"))
4656 ct->zero = xstrdup ("");
4657 else if (lex_force_string (lexer))
4659 ct->zero = ss_xstrdup (lex_tokss (lexer));
4665 else if (lex_match_id (lexer, "MISSING"))
4667 lex_match (lexer, T_EQUALS);
4668 if (!lex_force_string (lexer))
4672 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4673 ? ss_xstrdup (lex_tokss (lexer))
4679 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4680 "UNITS", "EMPTY", "MISSING");
4685 if (widths[0] != SYSMIS && widths[1] != SYSMIS
4686 && widths[0] > widths[1])
4688 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4692 for (size_t i = 0; i < 2; i++)
4693 if (widths[i] != SYSMIS)
4695 int *wr = ct->look->width_ranges[TABLE_HORZ];
4696 wr[i] = widths[i] / units_per_inch * 96.0;
4701 else if (lex_match_id (lexer, "VLABELS"))
4703 if (!lex_force_match_id (lexer, "VARIABLES"))
4705 lex_match (lexer, T_EQUALS);
4707 struct variable **vars;
4709 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4713 if (!lex_force_match_id (lexer, "DISPLAY"))
4718 lex_match (lexer, T_EQUALS);
4720 enum ctables_vlabel vlabel;
4721 if (lex_match_id (lexer, "DEFAULT"))
4722 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4723 else if (lex_match_id (lexer, "NAME"))
4725 else if (lex_match_id (lexer, "LABEL"))
4726 vlabel = CTVL_LABEL;
4727 else if (lex_match_id (lexer, "BOTH"))
4729 else if (lex_match_id (lexer, "NONE"))
4733 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4739 for (size_t i = 0; i < n_vars; i++)
4740 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4743 else if (lex_match_id (lexer, "MRSETS"))
4745 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4747 lex_match (lexer, T_EQUALS);
4748 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4751 else if (lex_match_id (lexer, "SMISSING"))
4753 if (lex_match_id (lexer, "VARIABLE"))
4754 ct->smissing_listwise = false;
4755 else if (lex_match_id (lexer, "LISTWISE"))
4756 ct->smissing_listwise = true;
4759 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4763 else if (lex_match_id (lexer, "PCOMPUTE"))
4765 if (!ctables_parse_pcompute (lexer, ct))
4768 else if (lex_match_id (lexer, "PPROPERTIES"))
4770 if (!ctables_parse_pproperties (lexer, ct))
4773 else if (lex_match_id (lexer, "WEIGHT"))
4775 if (!lex_force_match_id (lexer, "VARIABLE"))
4777 lex_match (lexer, T_EQUALS);
4778 ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4782 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
4784 if (!lex_force_match_id (lexer, "COUNT"))
4786 lex_match (lexer, T_EQUALS);
4787 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
4789 ct->hide_threshold = lex_integer (lexer);
4794 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4795 "SMISSING", "PCOMPUTE", "PPROPERTIES",
4796 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4800 if (!lex_force_match (lexer, T_SLASH))
4804 size_t allocated_tables = 0;
4807 if (ct->n_tables >= allocated_tables)
4808 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4809 sizeof *ct->tables);
4811 struct ctables_category *cat = xmalloc (sizeof *cat);
4812 *cat = (struct ctables_category) {
4814 .include_missing = false,
4815 .sort_ascending = true,
4818 struct ctables_categories *c = xmalloc (sizeof *c);
4819 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4820 *c = (struct ctables_categories) {
4827 struct ctables_categories **categories = xnmalloc (n_vars,
4828 sizeof *categories);
4829 for (size_t i = 0; i < n_vars; i++)
4832 struct ctables_table *t = xmalloc (sizeof *t);
4833 *t = (struct ctables_table) {
4835 .slabels_axis = PIVOT_AXIS_COLUMN,
4836 .slabels_visible = true,
4837 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
4839 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
4840 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
4841 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
4843 .clabels_from_axis = PIVOT_AXIS_LAYER,
4844 .categories = categories,
4845 .n_categories = n_vars,
4848 ct->tables[ct->n_tables++] = t;
4850 lex_match (lexer, T_EQUALS);
4851 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
4853 if (lex_match (lexer, T_BY))
4855 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4856 ct, t, PIVOT_AXIS_COLUMN))
4859 if (lex_match (lexer, T_BY))
4861 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4862 ct, t, PIVOT_AXIS_LAYER))
4867 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
4868 && !t->axes[PIVOT_AXIS_LAYER])
4870 lex_error (lexer, _("At least one variable must be specified."));
4874 const struct ctables_axis *scales[PIVOT_N_AXES];
4875 size_t n_scales = 0;
4876 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4878 scales[a] = find_scale (t->axes[a]);
4884 msg (SE, _("Scale variables may appear only on one axis."));
4885 if (scales[PIVOT_AXIS_ROW])
4886 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
4887 _("This scale variable appears on the rows axis."));
4888 if (scales[PIVOT_AXIS_COLUMN])
4889 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
4890 _("This scale variable appears on the columns axis."));
4891 if (scales[PIVOT_AXIS_LAYER])
4892 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
4893 _("This scale variable appears on the layer axis."));
4897 const struct ctables_axis *summaries[PIVOT_N_AXES];
4898 size_t n_summaries = 0;
4899 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4901 summaries[a] = (scales[a]
4903 : find_categorical_summary_spec (t->axes[a]));
4907 if (n_summaries > 1)
4909 msg (SE, _("Summaries may appear only on one axis."));
4910 if (summaries[PIVOT_AXIS_ROW])
4911 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
4912 _("This variable on the rows axis has a summary."));
4913 if (summaries[PIVOT_AXIS_COLUMN])
4914 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
4915 _("This variable on the columns axis has a summary."));
4916 if (summaries[PIVOT_AXIS_LAYER])
4917 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
4918 _("This variable on the layers axis has a summary."));
4921 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4922 if (n_summaries ? summaries[a] : t->axes[a])
4924 t->summary_axis = a;
4928 if (lex_token (lexer) == T_ENDCMD)
4930 if (!ctables_prepare_table (t))
4934 if (!lex_force_match (lexer, T_SLASH))
4937 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
4939 if (lex_match_id (lexer, "SLABELS"))
4941 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4943 if (lex_match_id (lexer, "POSITION"))
4945 lex_match (lexer, T_EQUALS);
4946 if (lex_match_id (lexer, "COLUMN"))
4947 t->slabels_axis = PIVOT_AXIS_COLUMN;
4948 else if (lex_match_id (lexer, "ROW"))
4949 t->slabels_axis = PIVOT_AXIS_ROW;
4950 else if (lex_match_id (lexer, "LAYER"))
4951 t->slabels_axis = PIVOT_AXIS_LAYER;
4954 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
4958 else if (lex_match_id (lexer, "VISIBLE"))
4960 lex_match (lexer, T_EQUALS);
4961 if (!parse_bool (lexer, &t->slabels_visible))
4966 lex_error_expecting (lexer, "POSITION", "VISIBLE");
4971 else if (lex_match_id (lexer, "CLABELS"))
4973 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4975 if (lex_match_id (lexer, "AUTO"))
4977 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
4978 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
4980 else if (lex_match_id (lexer, "ROWLABELS"))
4982 lex_match (lexer, T_EQUALS);
4983 if (lex_match_id (lexer, "OPPOSITE"))
4984 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
4985 else if (lex_match_id (lexer, "LAYER"))
4986 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
4989 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4993 else if (lex_match_id (lexer, "COLLABELS"))
4995 lex_match (lexer, T_EQUALS);
4996 if (lex_match_id (lexer, "OPPOSITE"))
4997 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
4998 else if (lex_match_id (lexer, "LAYER"))
4999 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
5002 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5008 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
5014 else if (lex_match_id (lexer, "CRITERIA"))
5016 if (!lex_force_match_id (lexer, "CILEVEL"))
5018 lex_match (lexer, T_EQUALS);
5020 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
5022 t->cilevel = lex_number (lexer);
5025 else if (lex_match_id (lexer, "CATEGORIES"))
5027 if (!ctables_table_parse_categories (lexer, dataset_dict (ds),
5031 else if (lex_match_id (lexer, "TITLES"))
5036 if (lex_match_id (lexer, "CAPTION"))
5037 textp = &t->caption;
5038 else if (lex_match_id (lexer, "CORNER"))
5040 else if (lex_match_id (lexer, "TITLE"))
5044 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
5047 lex_match (lexer, T_EQUALS);
5049 struct string s = DS_EMPTY_INITIALIZER;
5050 while (lex_is_string (lexer))
5052 if (!ds_is_empty (&s))
5053 ds_put_byte (&s, ' ');
5054 ds_put_substring (&s, lex_tokss (lexer));
5058 *textp = ds_steal_cstr (&s);
5060 while (lex_token (lexer) != T_SLASH
5061 && lex_token (lexer) != T_ENDCMD);
5063 else if (lex_match_id (lexer, "SIGTEST"))
5067 t->chisq = xmalloc (sizeof *t->chisq);
5068 *t->chisq = (struct ctables_chisq) {
5070 .include_mrsets = true,
5071 .all_visible = true,
5077 if (lex_match_id (lexer, "TYPE"))
5079 lex_match (lexer, T_EQUALS);
5080 if (!lex_force_match_id (lexer, "CHISQUARE"))
5083 else if (lex_match_id (lexer, "ALPHA"))
5085 lex_match (lexer, T_EQUALS);
5086 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
5088 t->chisq->alpha = lex_number (lexer);
5091 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5093 lex_match (lexer, T_EQUALS);
5094 if (parse_bool (lexer, &t->chisq->include_mrsets))
5097 else if (lex_match_id (lexer, "CATEGORIES"))
5099 lex_match (lexer, T_EQUALS);
5100 if (lex_match_id (lexer, "ALLVISIBLE"))
5101 t->chisq->all_visible = true;
5102 else if (lex_match_id (lexer, "SUBTOTALS"))
5103 t->chisq->all_visible = false;
5106 lex_error_expecting (lexer,
5107 "ALLVISIBLE", "SUBTOTALS");
5113 lex_error_expecting (lexer, "TYPE", "ALPHA",
5114 "INCLUDEMRSETS", "CATEGORIES");
5118 while (lex_token (lexer) != T_SLASH
5119 && lex_token (lexer) != T_ENDCMD);
5121 else if (lex_match_id (lexer, "COMPARETEST"))
5125 t->pairwise = xmalloc (sizeof *t->pairwise);
5126 *t->pairwise = (struct ctables_pairwise) {
5128 .alpha = { .05, .05 },
5129 .adjust = BONFERRONI,
5130 .include_mrsets = true,
5131 .meansvariance_allcats = true,
5132 .all_visible = true,
5141 if (lex_match_id (lexer, "TYPE"))
5143 lex_match (lexer, T_EQUALS);
5144 if (lex_match_id (lexer, "PROP"))
5145 t->pairwise->type = PROP;
5146 else if (lex_match_id (lexer, "MEAN"))
5147 t->pairwise->type = MEAN;
5150 lex_error_expecting (lexer, "PROP", "MEAN");
5154 else if (lex_match_id (lexer, "ALPHA"))
5156 lex_match (lexer, T_EQUALS);
5158 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5160 double a0 = lex_number (lexer);
5163 lex_match (lexer, T_COMMA);
5164 if (lex_is_number (lexer))
5166 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5168 double a1 = lex_number (lexer);
5171 t->pairwise->alpha[0] = MIN (a0, a1);
5172 t->pairwise->alpha[1] = MAX (a0, a1);
5175 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
5177 else if (lex_match_id (lexer, "ADJUST"))
5179 lex_match (lexer, T_EQUALS);
5180 if (lex_match_id (lexer, "BONFERRONI"))
5181 t->pairwise->adjust = BONFERRONI;
5182 else if (lex_match_id (lexer, "BH"))
5183 t->pairwise->adjust = BH;
5184 else if (lex_match_id (lexer, "NONE"))
5185 t->pairwise->adjust = 0;
5188 lex_error_expecting (lexer, "BONFERRONI", "BH",
5193 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5195 lex_match (lexer, T_EQUALS);
5196 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
5199 else if (lex_match_id (lexer, "MEANSVARIANCE"))
5201 lex_match (lexer, T_EQUALS);
5202 if (lex_match_id (lexer, "ALLCATS"))
5203 t->pairwise->meansvariance_allcats = true;
5204 else if (lex_match_id (lexer, "TESTEDCATS"))
5205 t->pairwise->meansvariance_allcats = false;
5208 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
5212 else if (lex_match_id (lexer, "CATEGORIES"))
5214 lex_match (lexer, T_EQUALS);
5215 if (lex_match_id (lexer, "ALLVISIBLE"))
5216 t->pairwise->all_visible = true;
5217 else if (lex_match_id (lexer, "SUBTOTALS"))
5218 t->pairwise->all_visible = false;
5221 lex_error_expecting (lexer, "ALLVISIBLE",
5226 else if (lex_match_id (lexer, "MERGE"))
5228 lex_match (lexer, T_EQUALS);
5229 if (!parse_bool (lexer, &t->pairwise->merge))
5232 else if (lex_match_id (lexer, "STYLE"))
5234 lex_match (lexer, T_EQUALS);
5235 if (lex_match_id (lexer, "APA"))
5236 t->pairwise->apa_style = true;
5237 else if (lex_match_id (lexer, "SIMPLE"))
5238 t->pairwise->apa_style = false;
5241 lex_error_expecting (lexer, "APA", "SIMPLE");
5245 else if (lex_match_id (lexer, "SHOWSIG"))
5247 lex_match (lexer, T_EQUALS);
5248 if (!parse_bool (lexer, &t->pairwise->show_sig))
5253 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
5254 "INCLUDEMRSETS", "MEANSVARIANCE",
5255 "CATEGORIES", "MERGE", "STYLE",
5260 while (lex_token (lexer) != T_SLASH
5261 && lex_token (lexer) != T_ENDCMD);
5265 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
5266 "CRITERIA", "CATEGORIES", "TITLES",
5267 "SIGTEST", "COMPARETEST");
5271 if (!lex_match (lexer, T_SLASH))
5275 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
5276 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
5278 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
5282 if (!ctables_prepare_table (t))
5285 while (lex_token (lexer) != T_ENDCMD);
5287 bool ok = ctables_execute (ds, ct);
5288 ctables_destroy (ct);
5289 return ok ? CMD_SUCCESS : CMD_FAILURE;
5292 ctables_destroy (ct);