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_occurrence
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_occurrence *o;
2908 HMAP_FOR_EACH_WITH_HASH (o, struct ctables_occurrence, node, hash,
2910 if (value_equal (value, &o->value, width))
2913 o = xmalloc (sizeof *o);
2914 value_clone (&o->value, value, width);
2915 hmap_insert (occurrences, &o->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_cell_value *pc_cv)
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 (i != nest->scale_idx)
3127 const struct ctables_cell_value *cv
3128 = (a == ctx->pc_a && i == ctx->pc_a_idx ? pc_cv
3129 : &ctx->cell->axes[a].cvs[i]);
3130 hash = hash_pointer (cv->category, hash);
3131 if (cv->category->type != CCT_TOTAL
3132 && cv->category->type != CCT_SUBTOTAL
3133 && cv->category->type != CCT_POSTCOMPUTE)
3134 hash = value_hash (&cv->value,
3135 var_get_width (nest->vars[i]), hash);
3139 struct ctables_cell *tc;
3140 HMAP_FOR_EACH_WITH_HASH (tc, struct ctables_cell, node, hash, &s->cells)
3142 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3144 const struct ctables_nest *nest = s->nests[a];
3145 for (size_t i = 0; i < nest->n; i++)
3146 if (i != nest->scale_idx)
3148 const struct ctables_cell_value *p_cv
3149 = (a == ctx->pc_a && i == ctx->pc_a_idx ? pc_cv
3150 : &ctx->cell->axes[a].cvs[i]);
3151 const struct ctables_cell_value *t_cv = &tc->axes[a].cvs[i];
3152 if (p_cv->category != t_cv->category
3153 || (p_cv->category->type != CCT_TOTAL
3154 && p_cv->category->type != CCT_SUBTOTAL
3155 && p_cv->category->type != CCT_POSTCOMPUTE
3156 && !value_equal (&p_cv->value,
3158 var_get_width (nest->vars[i]))))
3170 const struct ctables_table *t = s->table;
3171 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3172 const struct ctables_summary_spec_set *specs = &specs_nest->specs[tc->sv];
3173 size_t j = 0 /* XXX */;
3174 return ctables_summary_value (tc, &tc->summaries[j], &specs->specs[j]);
3178 ctables_pcexpr_evaluate (const struct ctables_pcexpr_evaluate_ctx *ctx,
3179 const struct ctables_pcexpr *e)
3186 case CTPO_CAT_RANGE:
3188 struct ctables_cell_value cv = {
3189 .category = ctables_find_category_for_postcompute (ctx->cats, e)
3191 assert (cv.category != NULL);
3193 struct hmap *occurrences = &ctx->section->occurrences[ctx->pc_a][ctx->pc_a_idx];
3194 const struct ctables_occurrence *o;
3197 const struct variable *var = ctx->section->nests[ctx->pc_a]->vars[ctx->pc_a_idx];
3198 HMAP_FOR_EACH (o, struct ctables_occurrence, node, occurrences)
3199 if (ctables_categories_match (ctx->cats, &o->value, var) == cv.category)
3201 cv.value = o->value;
3202 sum += ctables_pcexpr_evaluate_category (ctx, &cv);
3207 case CTPO_CAT_NUMBER:
3208 case CTPO_CAT_STRING:
3209 case CTPO_CAT_MISSING:
3210 case CTPO_CAT_OTHERNM:
3211 case CTPO_CAT_SUBTOTAL:
3212 case CTPO_CAT_TOTAL:
3214 struct ctables_cell_value cv = {
3215 .category = ctables_find_category_for_postcompute (ctx->cats, e),
3216 .value = { .f = e->number },
3218 assert (cv.category != NULL);
3219 return ctables_pcexpr_evaluate_category (ctx, &cv);
3223 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_add);
3226 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_sub);
3229 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_mul);
3232 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_div);
3235 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_pow);
3238 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 1, ctpo_neg);
3245 ctables_cell_calculate_postcompute (const struct ctables_section *s,
3246 const struct ctables_cell *cell)
3248 enum pivot_axis_type pc_a;
3250 const struct ctables_postcompute *pc;
3251 for (pc_a = 0; ; pc_a++)
3253 assert (pc_a < PIVOT_N_AXES);
3254 for (pc_a_idx = 0; pc_a_idx < s->nests[pc_a]->n; pc_a_idx++)
3256 const struct ctables_cell_value *cv = &cell->axes[pc_a].cvs[pc_a_idx];
3257 if (cv->category->type == CCT_POSTCOMPUTE)
3259 pc = cv->category->pc;
3266 const struct variable *var = s->nests[pc_a]->vars[pc_a_idx];
3267 const struct ctables_categories *cats = s->table->categories[
3268 var_get_dict_index (var)];
3269 struct ctables_pcexpr_evaluate_ctx ctx = {
3274 .pc_a_idx = pc_a_idx,
3276 return ctables_pcexpr_evaluate (&ctx, pc->expr);
3280 ctables_table_output (struct ctables *ct, struct ctables_table *t)
3282 struct pivot_table *pt = pivot_table_create__ (
3284 ? pivot_value_new_user_text (t->title, SIZE_MAX)
3285 : pivot_value_new_text (N_("Custom Tables"))),
3288 pivot_table_set_caption (
3289 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
3291 pivot_table_set_caption (
3292 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
3294 bool summary_dimension = (t->summary_axis != t->slabels_axis
3295 || (!t->slabels_visible
3296 && t->summary_specs.n > 1));
3297 if (summary_dimension)
3299 struct pivot_dimension *d = pivot_dimension_create (
3300 pt, t->slabels_axis, N_("Statistics"));
3301 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3302 if (!t->slabels_visible)
3303 d->hide_all_labels = true;
3304 for (size_t i = 0; i < specs->n; i++)
3305 pivot_category_create_leaf (
3306 d->root, pivot_value_new_text (specs->specs[i].label));
3309 bool categories_dimension = t->clabels_example != NULL;
3310 if (categories_dimension)
3312 struct pivot_dimension *d = pivot_dimension_create (
3313 pt, t->label_axis[t->clabels_from_axis],
3314 t->clabels_from_axis == PIVOT_AXIS_ROW
3315 ? N_("Row Categories")
3316 : N_("Column Categories"));
3317 const struct variable *var = t->clabels_example;
3318 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
3319 for (size_t i = 0; i < t->n_clabels_values; i++)
3321 const struct ctables_value *value = t->clabels_values[i];
3322 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
3323 assert (cat != NULL);
3324 pivot_category_create_leaf (d->root, ctables_category_create_label (
3325 cat, t->clabels_example, &value->value));
3329 pivot_table_set_look (pt, ct->look);
3330 struct pivot_dimension *d[PIVOT_N_AXES];
3331 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3333 static const char *names[] = {
3334 [PIVOT_AXIS_ROW] = N_("Rows"),
3335 [PIVOT_AXIS_COLUMN] = N_("Columns"),
3336 [PIVOT_AXIS_LAYER] = N_("Layers"),
3338 d[a] = (t->axes[a] || a == t->summary_axis
3339 ? pivot_dimension_create (pt, a, names[a])
3344 assert (t->axes[a]);
3346 for (size_t i = 0; i < t->stacks[a].n; i++)
3348 struct ctables_nest *nest = &t->stacks[a].nests[i];
3349 struct ctables_section **sections = xnmalloc (t->n_sections,
3351 size_t n_sections = 0;
3353 size_t n_total_cells = 0;
3354 size_t max_depth = 0;
3355 for (size_t j = 0; j < t->n_sections; j++)
3356 if (t->sections[j].nests[a] == nest)
3358 struct ctables_section *s = &t->sections[j];
3359 sections[n_sections++] = s;
3360 n_total_cells += s->cells.count;
3362 size_t depth = s->nests[a]->n;
3363 max_depth = MAX (depth, max_depth);
3366 struct ctables_cell **sorted = xnmalloc (n_total_cells,
3368 size_t n_sorted = 0;
3370 for (size_t j = 0; j < n_sections; j++)
3372 struct ctables_section *s = sections[j];
3374 struct ctables_cell *cell;
3375 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3377 sorted[n_sorted++] = cell;
3378 assert (n_sorted <= n_total_cells);
3381 struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
3382 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
3384 struct ctables_level
3386 enum ctables_level_type
3388 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
3389 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
3390 CTL_SUMMARY, /* Summary functions. */
3396 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
3397 size_t n_levels = 0;
3398 for (size_t k = 0; k < nest->n; k++)
3400 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
3401 if (vlabel != CTVL_NONE)
3403 levels[n_levels++] = (struct ctables_level) {
3409 if (nest->scale_idx != k
3410 && (k != nest->n - 1 || t->label_axis[a] == a))
3412 levels[n_levels++] = (struct ctables_level) {
3413 .type = CTL_CATEGORY,
3419 if (!summary_dimension && a == t->slabels_axis)
3421 levels[n_levels++] = (struct ctables_level) {
3422 .type = CTL_SUMMARY,
3423 .var_idx = SIZE_MAX,
3427 /* Pivot categories:
3429 - variable label for nest->vars[0], if vlabel != CTVL_NONE
3430 - category for nest->vars[0], if nest->scale_idx != 0
3431 - variable label for nest->vars[1], if vlabel != CTVL_NONE
3432 - category for nest->vars[1], if nest->scale_idx != 1
3434 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
3435 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
3436 - summary function, if 'a == t->slabels_axis && a ==
3439 Additional dimensions:
3441 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
3443 - If 't->label_axis[b] == a' for some 'b != a', add a category
3448 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
3450 for (size_t j = 0; j < n_sorted; j++)
3452 struct ctables_cell *cell = sorted[j];
3453 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
3455 size_t n_common = 0;
3458 for (; n_common < n_levels; n_common++)
3460 const struct ctables_level *level = &levels[n_common];
3461 if (level->type == CTL_CATEGORY)
3463 size_t var_idx = level->var_idx;
3464 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3465 if (prev->axes[a].cvs[var_idx].category != c)
3467 else if (c->type != CCT_SUBTOTAL
3468 && c->type != CCT_TOTAL
3469 && c->type != CCT_POSTCOMPUTE
3470 && !value_equal (&prev->axes[a].cvs[var_idx].value,
3471 &cell->axes[a].cvs[var_idx].value,
3472 var_get_type (nest->vars[var_idx])))
3478 for (size_t k = n_common; k < n_levels; k++)
3480 const struct ctables_level *level = &levels[k];
3481 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3482 if (level->type == CTL_SUMMARY)
3484 assert (k == n_levels - 1);
3486 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3487 for (size_t m = 0; m < specs->n; m++)
3489 int leaf = pivot_category_create_leaf (
3490 parent, pivot_value_new_text (specs->specs[m].label));
3497 const struct variable *var = nest->vars[level->var_idx];
3498 struct pivot_value *label;
3499 if (level->type == CTL_VAR)
3500 label = pivot_value_new_variable (var);
3501 else if (level->type == CTL_CATEGORY)
3503 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3504 label = ctables_category_create_label (cv->category,
3510 if (k == n_levels - 1)
3511 prev_leaf = pivot_category_create_leaf (parent, label);
3513 groups[k] = pivot_category_create_group__ (parent, label);
3517 cell->axes[a].leaf = prev_leaf;
3524 for (size_t i = 0; i < t->n_sections; i++)
3526 struct ctables_section *s = &t->sections[i];
3528 struct ctables_cell *cell;
3529 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3534 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3535 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3536 for (size_t j = 0; j < specs->n; j++)
3539 size_t n_dindexes = 0;
3541 if (summary_dimension)
3542 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3544 if (categories_dimension)
3546 const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3547 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3548 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3549 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3550 assert (ctv != NULL);
3551 dindexes[n_dindexes++] = ctv->leaf;
3554 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3557 int leaf = cell->axes[a].leaf;
3558 if (a == t->summary_axis && !summary_dimension)
3560 dindexes[n_dindexes++] = leaf;
3563 double d = (cell->postcompute
3564 ? ctables_cell_calculate_postcompute (s, cell)
3565 : ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]));
3566 struct pivot_value *value = pivot_value_new_number (d);
3567 value->numeric.format = specs->specs[j].format;
3568 pivot_table_put (pt, dindexes, n_dindexes, value);
3573 pivot_table_submit (pt);
3577 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3579 enum pivot_axis_type label_pos = t->label_axis[a];
3583 t->clabels_from_axis = a;
3585 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3586 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3588 const struct ctables_stack *stack = &t->stacks[a];
3592 const struct ctables_nest *n0 = &stack->nests[0];
3594 const struct variable *v0 = n0->vars[n0->n - 1];
3595 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3596 t->clabels_example = v0;
3598 for (size_t i = 0; i < c0->n_cats; i++)
3599 if (c0->cats[i].type == CCT_FUNCTION)
3601 msg (SE, _("%s=%s is not allowed with sorting based "
3602 "on a summary function."),
3603 subcommand_name, pos_name);
3606 if (n0->n - 1 == n0->scale_idx)
3608 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3609 "but %s is a scale variable."),
3610 subcommand_name, pos_name, var_get_name (v0));
3614 for (size_t i = 1; i < stack->n; i++)
3616 const struct ctables_nest *ni = &stack->nests[i];
3618 const struct variable *vi = ni->vars[ni->n - 1];
3619 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3621 if (ni->n - 1 == ni->scale_idx)
3623 msg (SE, _("%s=%s requires the variables to be moved to be "
3624 "categorical, but %s is a scale variable."),
3625 subcommand_name, pos_name, var_get_name (vi));
3628 if (var_get_width (v0) != var_get_width (vi))
3630 msg (SE, _("%s=%s requires the variables to be "
3631 "moved to have the same width, but %s has "
3632 "width %d and %s has width %d."),
3633 subcommand_name, pos_name,
3634 var_get_name (v0), var_get_width (v0),
3635 var_get_name (vi), var_get_width (vi));
3638 if (!val_labs_equal (var_get_value_labels (v0),
3639 var_get_value_labels (vi)))
3641 msg (SE, _("%s=%s requires the variables to be "
3642 "moved to have the same value labels, but %s "
3643 "and %s have different value labels."),
3644 subcommand_name, pos_name,
3645 var_get_name (v0), var_get_name (vi));
3648 if (!ctables_categories_equal (c0, ci))
3650 msg (SE, _("%s=%s requires the variables to be "
3651 "moved to have the same category "
3652 "specifications, but %s and %s have different "
3653 "category specifications."),
3654 subcommand_name, pos_name,
3655 var_get_name (v0), var_get_name (vi));
3664 ctables_prepare_table (struct ctables_table *t)
3666 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3669 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3671 for (size_t j = 0; j < t->stacks[a].n; j++)
3673 struct ctables_nest *nest = &t->stacks[a].nests[j];
3674 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3676 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3677 nest->n_domains[dt] = 0;
3679 for (size_t k = 0; k < nest->n; k++)
3681 if (k == nest->scale_idx)
3690 if (a != PIVOT_AXIS_LAYER)
3697 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3698 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3699 : a == PIVOT_AXIS_ROW)
3701 if (k == nest->n - 1
3702 || (nest->scale_idx == nest->n - 1
3703 && k == nest->n - 2))
3709 if (a == PIVOT_AXIS_COLUMN)
3714 if (a == PIVOT_AXIS_ROW)
3719 nest->domains[dt][nest->n_domains[dt]++] = k;
3726 struct ctables_nest *nest = xmalloc (sizeof *nest);
3727 *nest = (struct ctables_nest) { .n = 0 };
3728 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3731 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3732 for (size_t i = 0; i < stack->n; i++)
3734 struct ctables_nest *nest = &stack->nests[i];
3735 if (!nest->specs[CSV_CELL].n)
3737 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3738 specs->specs = xmalloc (sizeof *specs->specs);
3741 enum ctables_summary_function function
3742 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3743 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3745 *specs->specs = (struct ctables_summary_spec) {
3746 .function = function,
3747 .format = ctables_summary_default_format (function, &var),
3748 .label = ctables_summary_default_label (function, 0),
3751 specs->var = nest->vars[0];
3753 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3754 &nest->specs[CSV_CELL]);
3756 else if (!nest->specs[CSV_TOTAL].n)
3757 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3758 &nest->specs[CSV_CELL]);
3761 struct ctables_summary_spec_set *merged = &t->summary_specs;
3762 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3764 for (size_t j = 0; j < stack->n; j++)
3766 const struct ctables_nest *nest = &stack->nests[j];
3768 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3769 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3774 struct merge_item min = items[0];
3775 for (size_t j = 1; j < n_left; j++)
3776 if (merge_item_compare_3way (&items[j], &min) < 0)
3779 if (merged->n >= merged->allocated)
3780 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3781 sizeof *merged->specs);
3782 merged->specs[merged->n++] = min.set->specs[min.ofs];
3784 for (size_t j = 0; j < n_left; )
3786 if (merge_item_compare_3way (&items[j], &min) == 0)
3788 struct merge_item *item = &items[j];
3789 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3790 if (++item->ofs >= item->set->n)
3792 items[j] = items[--n_left];
3801 for (size_t j = 0; j < merged->n; j++)
3802 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3804 for (size_t j = 0; j < stack->n; j++)
3806 const struct ctables_nest *nest = &stack->nests[j];
3807 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3809 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3810 for (size_t k = 0; k < specs->n; k++)
3811 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3812 specs->specs[k].axis_idx);
3818 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3819 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3823 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3824 enum pivot_axis_type a)
3826 struct ctables_stack *stack = &t->stacks[a];
3827 for (size_t i = 0; i < stack->n; i++)
3829 const struct ctables_nest *nest = &stack->nests[i];
3830 const struct variable *var = nest->vars[nest->n - 1];
3831 int width = var_get_width (var);
3832 const union value *value = case_data (c, var);
3834 if (var_is_numeric (var) && value->f == SYSMIS)
3837 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3841 unsigned int hash = value_hash (value, width, 0);
3843 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3846 clv = xmalloc (sizeof *clv);
3847 value_clone (&clv->value, value, width);
3848 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3854 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3856 const struct ctables_value *const *ap = a_;
3857 const struct ctables_value *const *bp = b_;
3858 const struct ctables_value *a = *ap;
3859 const struct ctables_value *b = *bp;
3860 const int *width = width_;
3861 return value_compare_3way (&a->value, &b->value, *width);
3865 ctables_sort_clabels_values (struct ctables_table *t)
3867 int width = var_get_width (t->clabels_example);
3869 size_t n = hmap_count (&t->clabels_values_map);
3870 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3872 struct ctables_value *clv;
3874 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3875 t->clabels_values[i++] = clv;
3876 t->n_clabels_values = n;
3879 sort (t->clabels_values, n, sizeof *t->clabels_values,
3880 compare_clabels_values_3way, &width);
3882 for (size_t i = 0; i < n; i++)
3883 t->clabels_values[i]->leaf = i;
3887 ctables_add_category_occurrences (const struct variable *var,
3888 struct hmap *occurrences,
3889 const struct ctables_categories *cats)
3891 const struct val_labs *val_labs = var_get_value_labels (var);
3893 for (size_t i = 0; i < cats->n_cats; i++)
3895 const struct ctables_category *c = &cats->cats[i];
3899 ctables_add_occurrence (var, &(const union value) { .f = c->number },
3907 assert (var_is_numeric (var));
3908 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3909 vl = val_labs_next (val_labs, vl))
3910 if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
3911 ctables_add_occurrence (var, &vl->value, occurrences);
3915 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3916 vl = val_labs_next (val_labs, vl))
3917 if (var_is_value_missing (var, &vl->value))
3918 ctables_add_occurrence (var, &vl->value, occurrences);
3922 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3923 vl = val_labs_next (val_labs, vl))
3924 ctables_add_occurrence (var, &vl->value, occurrences);
3927 case CCT_POSTCOMPUTE:
3937 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3938 vl = val_labs_next (val_labs, vl))
3939 if (c->include_missing || !var_is_value_missing (var, &vl->value))
3940 ctables_add_occurrence (var, &vl->value, occurrences);
3947 ctables_section_recurse_add_empty_categories (
3948 struct ctables_section *s,
3949 const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
3950 enum pivot_axis_type a, size_t a_idx)
3952 if (a >= PIVOT_N_AXES)
3953 ctables_cell_insert__ (s, c, cats);
3954 else if (!s->nests[a] || a_idx >= s->nests[a]->n)
3955 ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
3958 const struct variable *var = s->nests[a]->vars[a_idx];
3959 const struct ctables_categories *categories = s->table->categories[
3960 var_get_dict_index (var)];
3961 int width = var_get_width (var);
3962 const struct hmap *occurrences = &s->occurrences[a][a_idx];
3963 const struct ctables_occurrence *o;
3964 HMAP_FOR_EACH (o, struct ctables_occurrence, node, occurrences)
3966 union value *value = case_data_rw (c, var);
3967 value_destroy (value, width);
3968 value_clone (value, &o->value, width);
3969 cats[a][a_idx] = ctables_categories_match (categories, value, var);
3970 assert (cats[a][a_idx] != NULL);
3971 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3974 for (size_t i = 0; i < categories->n_cats; i++)
3976 const struct ctables_category *cat = &categories->cats[i];
3977 if (cat->type == CCT_POSTCOMPUTE)
3979 cats[a][a_idx] = cat;
3980 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3987 ctables_section_add_empty_categories (struct ctables_section *s)
3989 bool show_empty = false;
3990 for (size_t a = 0; a < PIVOT_N_AXES; a++)
3992 for (size_t k = 0; k < s->nests[a]->n; k++)
3993 if (k != s->nests[a]->scale_idx)
3995 const struct variable *var = s->nests[a]->vars[k];
3996 const struct ctables_categories *cats = s->table->categories[
3997 var_get_dict_index (var)];
3998 if (cats->show_empty)
4001 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
4007 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
4008 struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
4009 ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
4014 ctables_execute (struct dataset *ds, struct ctables *ct)
4016 for (size_t i = 0; i < ct->n_tables; i++)
4018 struct ctables_table *t = ct->tables[i];
4019 t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
4020 MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
4021 MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
4022 sizeof *t->sections);
4023 size_t ix[PIVOT_N_AXES];
4024 ctables_table_add_section (t, 0, ix);
4027 struct casereader *input = proc_open (ds);
4028 bool warn_on_invalid = true;
4029 for (struct ccase *c = casereader_read (input); c;
4030 case_unref (c), c = casereader_read (input))
4032 double d_weight = dict_get_case_weight (dataset_dict (ds), c,
4034 double e_weight = (ct->e_weight
4035 ? var_force_valid_weight (ct->e_weight,
4036 case_num (c, ct->e_weight),
4040 for (size_t i = 0; i < ct->n_tables; i++)
4042 struct ctables_table *t = ct->tables[i];
4044 for (size_t j = 0; j < t->n_sections; j++)
4045 ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
4047 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4048 if (t->label_axis[a] != a)
4049 ctables_insert_clabels_values (t, c, a);
4052 casereader_destroy (input);
4054 for (size_t i = 0; i < ct->n_tables; i++)
4056 struct ctables_table *t = ct->tables[i];
4058 if (t->clabels_example)
4059 ctables_sort_clabels_values (t);
4061 for (size_t j = 0; j < t->n_sections; j++)
4062 ctables_section_add_empty_categories (&t->sections[j]);
4064 ctables_table_output (ct, ct->tables[i]);
4066 return proc_commit (ds);
4071 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
4074 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
4080 case CTPO_CAT_STRING:
4090 for (size_t i = 0; i < 2; i++)
4091 ctables_pcexpr_destroy (e->subs[i]);
4095 case CTPO_CAT_NUMBER:
4096 case CTPO_CAT_RANGE:
4097 case CTPO_CAT_MISSING:
4098 case CTPO_CAT_OTHERNM:
4099 case CTPO_CAT_SUBTOTAL:
4100 case CTPO_CAT_TOTAL:
4104 msg_location_destroy (e->location);
4109 static struct ctables_pcexpr *
4110 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
4111 struct ctables_pcexpr *sub0,
4112 struct ctables_pcexpr *sub1)
4114 struct ctables_pcexpr *e = xmalloc (sizeof *e);
4115 *e = (struct ctables_pcexpr) {
4117 .subs = { sub0, sub1 },
4118 .location = msg_location_merged (sub0->location, sub1->location),
4123 /* How to parse an operator. */
4126 enum token_type token;
4127 enum ctables_postcompute_op op;
4130 static const struct operator *
4131 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
4133 for (const struct operator *op = ops; op < ops + n_ops; op++)
4134 if (lex_token (lexer) == op->token)
4136 if (op->token != T_NEG_NUM)
4145 static struct ctables_pcexpr *
4146 parse_binary_operators__ (struct lexer *lexer,
4147 const struct operator ops[], size_t n_ops,
4148 parse_recursively_func *parse_next_level,
4149 const char *chain_warning,
4150 struct ctables_pcexpr *lhs)
4152 for (int op_count = 0; ; op_count++)
4154 const struct operator *op = match_operator (lexer, ops, n_ops);
4157 if (op_count > 1 && chain_warning)
4158 msg_at (SW, lhs->location, "%s", chain_warning);
4163 struct ctables_pcexpr *rhs = parse_next_level (lexer);
4166 ctables_pcexpr_destroy (lhs);
4170 lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
4174 static struct ctables_pcexpr *
4175 parse_binary_operators (struct lexer *lexer,
4176 const struct operator ops[], size_t n_ops,
4177 parse_recursively_func *parse_next_level,
4178 const char *chain_warning)
4180 struct ctables_pcexpr *lhs = parse_next_level (lexer);
4184 return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
4185 chain_warning, lhs);
4188 static struct ctables_pcexpr *parse_add (struct lexer *);
4190 static struct ctables_pcexpr
4191 ctpo_cat_range (double low, double high)
4193 return (struct ctables_pcexpr) {
4194 .op = CTPO_CAT_RANGE,
4195 .range = { low, high },
4199 static struct ctables_pcexpr *
4200 parse_primary (struct lexer *lexer)
4202 int start_ofs = lex_ofs (lexer);
4203 struct ctables_pcexpr e;
4204 if (lex_is_number (lexer))
4206 e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
4207 .number = lex_number (lexer) };
4210 else if (lex_match_id (lexer, "MISSING"))
4211 e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
4212 else if (lex_match_id (lexer, "OTHERNM"))
4213 e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
4214 else if (lex_match_id (lexer, "TOTAL"))
4215 e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
4216 else if (lex_match_id (lexer, "SUBTOTAL"))
4218 size_t subtotal_index = 0;
4219 if (lex_match (lexer, T_LBRACK))
4221 if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
4223 subtotal_index = lex_integer (lexer);
4225 if (!lex_force_match (lexer, T_RBRACK))
4228 e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
4229 .subtotal_index = subtotal_index };
4231 else if (lex_match (lexer, T_LBRACK))
4233 if (lex_match_id (lexer, "LO"))
4235 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
4237 e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
4240 else if (lex_is_number (lexer))
4242 double number = lex_number (lexer);
4244 if (lex_match_id (lexer, "THRU"))
4246 if (lex_match_id (lexer, "HI"))
4247 e = ctpo_cat_range (number, DBL_MAX);
4250 if (!lex_force_num (lexer))
4252 e = ctpo_cat_range (number, lex_number (lexer));
4257 e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
4260 else if (lex_is_string (lexer))
4262 e = (struct ctables_pcexpr) {
4263 .op = CTPO_CAT_STRING,
4264 .string = ss_xstrdup (lex_tokss (lexer)),
4270 lex_error (lexer, NULL);
4274 if (!lex_force_match (lexer, T_RBRACK))
4276 if (e.op == CTPO_CAT_STRING)
4281 else if (lex_match (lexer, T_LPAREN))
4283 struct ctables_pcexpr *ep = parse_add (lexer);
4286 if (!lex_force_match (lexer, T_RPAREN))
4288 ctables_pcexpr_destroy (ep);
4295 lex_error (lexer, NULL);
4299 e.location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
4300 return xmemdup (&e, sizeof e);
4303 static struct ctables_pcexpr *
4304 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
4305 struct lexer *lexer, int start_ofs)
4307 struct ctables_pcexpr *e = xmalloc (sizeof *e);
4308 *e = (struct ctables_pcexpr) {
4311 .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
4316 static struct ctables_pcexpr *
4317 parse_exp (struct lexer *lexer)
4319 static const struct operator op = { T_EXP, CTPO_POW };
4321 const char *chain_warning =
4322 _("The exponentiation operator (`**') is left-associative: "
4323 "`a**b**c' equals `(a**b)**c', not `a**(b**c)'. "
4324 "To disable this warning, insert parentheses.");
4326 if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
4327 return parse_binary_operators (lexer, &op, 1,
4328 parse_primary, chain_warning);
4330 /* Special case for situations like "-5**6", which must be parsed as
4333 int start_ofs = lex_ofs (lexer);
4334 struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
4335 *lhs = (struct ctables_pcexpr) {
4336 .op = CTPO_CONSTANT,
4337 .number = -lex_tokval (lexer),
4338 .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer)),
4342 struct ctables_pcexpr *node = parse_binary_operators__ (
4343 lexer, &op, 1, parse_primary, chain_warning, lhs);
4347 return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
4350 /* Parses the unary minus level. */
4351 static struct ctables_pcexpr *
4352 parse_neg (struct lexer *lexer)
4354 int start_ofs = lex_ofs (lexer);
4355 if (!lex_match (lexer, T_DASH))
4356 return parse_exp (lexer);
4358 struct ctables_pcexpr *inner = parse_neg (lexer);
4362 return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
4365 /* Parses the multiplication and division level. */
4366 static struct ctables_pcexpr *
4367 parse_mul (struct lexer *lexer)
4369 static const struct operator ops[] =
4371 { T_ASTERISK, CTPO_MUL },
4372 { T_SLASH, CTPO_DIV },
4375 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4379 /* Parses the addition and subtraction level. */
4380 static struct ctables_pcexpr *
4381 parse_add (struct lexer *lexer)
4383 static const struct operator ops[] =
4385 { T_PLUS, CTPO_ADD },
4386 { T_DASH, CTPO_SUB },
4387 { T_NEG_NUM, CTPO_ADD },
4390 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4394 static struct ctables_postcompute *
4395 ctables_find_postcompute (struct ctables *ct, const char *name)
4397 struct ctables_postcompute *pc;
4398 HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
4399 utf8_hash_case_string (name, 0), &ct->postcomputes)
4400 if (!utf8_strcasecmp (pc->name, name))
4406 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
4408 int pcompute_start = lex_ofs (lexer) - 1;
4410 if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
4413 char *name = ss_xstrdup (lex_tokss (lexer));
4416 if (!lex_force_match (lexer, T_EQUALS)
4417 || !lex_force_match_id (lexer, "EXPR")
4418 || !lex_force_match (lexer, T_LPAREN))
4424 int expr_start = lex_ofs (lexer);
4425 struct ctables_pcexpr *expr = parse_add (lexer);
4426 int expr_end = lex_ofs (lexer) - 1;
4427 if (!expr || !lex_force_match (lexer, T_RPAREN))
4432 int pcompute_end = lex_ofs (lexer) - 1;
4434 struct msg_location *location = lex_ofs_location (lexer, pcompute_start,
4437 struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
4440 msg_at (SW, location, _("New definition of &%s will override the "
4441 "previous definition."),
4443 msg_at (SN, pc->location, _("This is the previous definition."));
4445 ctables_pcexpr_destroy (pc->expr);
4446 msg_location_destroy (pc->location);
4451 pc = xmalloc (sizeof *pc);
4452 *pc = (struct ctables_postcompute) { .name = name };
4453 hmap_insert (&ct->postcomputes, &pc->hmap_node,
4454 utf8_hash_case_string (pc->name, 0));
4457 pc->location = location;
4459 pc->label = lex_ofs_representation (lexer, expr_start, expr_end);
4464 ctables_parse_pproperties_format (struct lexer *lexer,
4465 struct ctables_summary_spec_set *sss)
4467 *sss = (struct ctables_summary_spec_set) { .n = 0 };
4469 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4470 && !(lex_token (lexer) == T_ID
4471 && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4472 || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4473 lex_tokss (lexer)))))
4475 /* Parse function. */
4476 enum ctables_summary_function function;
4477 if (!parse_ctables_summary_function (lexer, &function))
4480 /* Parse percentile. */
4481 double percentile = 0;
4482 if (function == CTSF_PTILE)
4484 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4486 percentile = lex_number (lexer);
4491 struct fmt_spec format;
4492 if (!parse_format_specifier (lexer, &format)
4493 || !fmt_check_output (&format)
4494 || !fmt_check_type_compat (&format, VAL_NUMERIC))
4497 if (sss->n >= sss->allocated)
4498 sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4499 sizeof *sss->specs);
4500 sss->specs[sss->n++] = (struct ctables_summary_spec) {
4501 .function = function,
4502 .percentile = percentile,
4509 ctables_summary_spec_set_uninit (sss);
4514 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4516 struct ctables_postcompute **pcs = NULL;
4518 size_t allocated_pcs = 0;
4520 while (lex_match (lexer, T_AND))
4522 if (!lex_force_id (lexer))
4524 struct ctables_postcompute *pc
4525 = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4528 msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4533 if (n_pcs >= allocated_pcs)
4534 pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4538 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4540 if (lex_match_id (lexer, "LABEL"))
4542 lex_match (lexer, T_EQUALS);
4543 if (!lex_force_string (lexer))
4546 for (size_t i = 0; i < n_pcs; i++)
4548 free (pcs[i]->label);
4549 pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4554 else if (lex_match_id (lexer, "FORMAT"))
4556 lex_match (lexer, T_EQUALS);
4558 struct ctables_summary_spec_set sss;
4559 if (!ctables_parse_pproperties_format (lexer, &sss))
4562 for (size_t i = 0; i < n_pcs; i++)
4565 ctables_summary_spec_set_uninit (pcs[i]->specs);
4567 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4568 ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4570 ctables_summary_spec_set_uninit (&sss);
4572 else if (lex_match_id (lexer, "HIDESOURCECATS"))
4574 lex_match (lexer, T_EQUALS);
4575 bool hide_source_cats;
4576 if (!parse_bool (lexer, &hide_source_cats))
4578 for (size_t i = 0; i < n_pcs; i++)
4579 pcs[i]->hide_source_cats = hide_source_cats;
4583 lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4596 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4598 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4599 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4600 enum settings_value_show tvars = settings_get_show_variables ();
4601 for (size_t i = 0; i < n_vars; i++)
4602 vlabels[i] = (enum ctables_vlabel) tvars;
4604 struct ctables *ct = xmalloc (sizeof *ct);
4605 *ct = (struct ctables) {
4606 .dict = dataset_dict (ds),
4607 .look = pivot_table_look_unshare (pivot_table_look_ref (
4608 pivot_table_look_get_default ())),
4610 .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
4611 .hide_threshold = 5,
4613 ct->look->omit_empty = false;
4615 if (!lex_force_match (lexer, T_SLASH))
4618 while (!lex_match_id (lexer, "TABLE"))
4620 if (lex_match_id (lexer, "FORMAT"))
4622 double widths[2] = { SYSMIS, SYSMIS };
4623 double units_per_inch = 72.0;
4625 while (lex_token (lexer) != T_SLASH)
4627 if (lex_match_id (lexer, "MINCOLWIDTH"))
4629 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4632 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4634 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4637 else if (lex_match_id (lexer, "UNITS"))
4639 lex_match (lexer, T_EQUALS);
4640 if (lex_match_id (lexer, "POINTS"))
4641 units_per_inch = 72.0;
4642 else if (lex_match_id (lexer, "INCHES"))
4643 units_per_inch = 1.0;
4644 else if (lex_match_id (lexer, "CM"))
4645 units_per_inch = 2.54;
4648 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4652 else if (lex_match_id (lexer, "EMPTY"))
4657 lex_match (lexer, T_EQUALS);
4658 if (lex_match_id (lexer, "ZERO"))
4660 /* Nothing to do. */
4662 else if (lex_match_id (lexer, "BLANK"))
4663 ct->zero = xstrdup ("");
4664 else if (lex_force_string (lexer))
4666 ct->zero = ss_xstrdup (lex_tokss (lexer));
4672 else if (lex_match_id (lexer, "MISSING"))
4674 lex_match (lexer, T_EQUALS);
4675 if (!lex_force_string (lexer))
4679 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4680 ? ss_xstrdup (lex_tokss (lexer))
4686 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4687 "UNITS", "EMPTY", "MISSING");
4692 if (widths[0] != SYSMIS && widths[1] != SYSMIS
4693 && widths[0] > widths[1])
4695 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4699 for (size_t i = 0; i < 2; i++)
4700 if (widths[i] != SYSMIS)
4702 int *wr = ct->look->width_ranges[TABLE_HORZ];
4703 wr[i] = widths[i] / units_per_inch * 96.0;
4708 else if (lex_match_id (lexer, "VLABELS"))
4710 if (!lex_force_match_id (lexer, "VARIABLES"))
4712 lex_match (lexer, T_EQUALS);
4714 struct variable **vars;
4716 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4720 if (!lex_force_match_id (lexer, "DISPLAY"))
4725 lex_match (lexer, T_EQUALS);
4727 enum ctables_vlabel vlabel;
4728 if (lex_match_id (lexer, "DEFAULT"))
4729 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4730 else if (lex_match_id (lexer, "NAME"))
4732 else if (lex_match_id (lexer, "LABEL"))
4733 vlabel = CTVL_LABEL;
4734 else if (lex_match_id (lexer, "BOTH"))
4736 else if (lex_match_id (lexer, "NONE"))
4740 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4746 for (size_t i = 0; i < n_vars; i++)
4747 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4750 else if (lex_match_id (lexer, "MRSETS"))
4752 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4754 lex_match (lexer, T_EQUALS);
4755 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4758 else if (lex_match_id (lexer, "SMISSING"))
4760 if (lex_match_id (lexer, "VARIABLE"))
4761 ct->smissing_listwise = false;
4762 else if (lex_match_id (lexer, "LISTWISE"))
4763 ct->smissing_listwise = true;
4766 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4770 else if (lex_match_id (lexer, "PCOMPUTE"))
4772 if (!ctables_parse_pcompute (lexer, ct))
4775 else if (lex_match_id (lexer, "PPROPERTIES"))
4777 if (!ctables_parse_pproperties (lexer, ct))
4780 else if (lex_match_id (lexer, "WEIGHT"))
4782 if (!lex_force_match_id (lexer, "VARIABLE"))
4784 lex_match (lexer, T_EQUALS);
4785 ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4789 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
4791 if (!lex_force_match_id (lexer, "COUNT"))
4793 lex_match (lexer, T_EQUALS);
4794 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
4796 ct->hide_threshold = lex_integer (lexer);
4801 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4802 "SMISSING", "PCOMPUTE", "PPROPERTIES",
4803 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4807 if (!lex_force_match (lexer, T_SLASH))
4811 size_t allocated_tables = 0;
4814 if (ct->n_tables >= allocated_tables)
4815 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4816 sizeof *ct->tables);
4818 struct ctables_category *cat = xmalloc (sizeof *cat);
4819 *cat = (struct ctables_category) {
4821 .include_missing = false,
4822 .sort_ascending = true,
4825 struct ctables_categories *c = xmalloc (sizeof *c);
4826 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4827 *c = (struct ctables_categories) {
4834 struct ctables_categories **categories = xnmalloc (n_vars,
4835 sizeof *categories);
4836 for (size_t i = 0; i < n_vars; i++)
4839 struct ctables_table *t = xmalloc (sizeof *t);
4840 *t = (struct ctables_table) {
4842 .slabels_axis = PIVOT_AXIS_COLUMN,
4843 .slabels_visible = true,
4844 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
4846 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
4847 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
4848 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
4850 .clabels_from_axis = PIVOT_AXIS_LAYER,
4851 .categories = categories,
4852 .n_categories = n_vars,
4855 ct->tables[ct->n_tables++] = t;
4857 lex_match (lexer, T_EQUALS);
4858 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
4860 if (lex_match (lexer, T_BY))
4862 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4863 ct, t, PIVOT_AXIS_COLUMN))
4866 if (lex_match (lexer, T_BY))
4868 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4869 ct, t, PIVOT_AXIS_LAYER))
4874 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
4875 && !t->axes[PIVOT_AXIS_LAYER])
4877 lex_error (lexer, _("At least one variable must be specified."));
4881 const struct ctables_axis *scales[PIVOT_N_AXES];
4882 size_t n_scales = 0;
4883 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4885 scales[a] = find_scale (t->axes[a]);
4891 msg (SE, _("Scale variables may appear only on one axis."));
4892 if (scales[PIVOT_AXIS_ROW])
4893 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
4894 _("This scale variable appears on the rows axis."));
4895 if (scales[PIVOT_AXIS_COLUMN])
4896 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
4897 _("This scale variable appears on the columns axis."));
4898 if (scales[PIVOT_AXIS_LAYER])
4899 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
4900 _("This scale variable appears on the layer axis."));
4904 const struct ctables_axis *summaries[PIVOT_N_AXES];
4905 size_t n_summaries = 0;
4906 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4908 summaries[a] = (scales[a]
4910 : find_categorical_summary_spec (t->axes[a]));
4914 if (n_summaries > 1)
4916 msg (SE, _("Summaries may appear only on one axis."));
4917 if (summaries[PIVOT_AXIS_ROW])
4918 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
4919 _("This variable on the rows axis has a summary."));
4920 if (summaries[PIVOT_AXIS_COLUMN])
4921 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
4922 _("This variable on the columns axis has a summary."));
4923 if (summaries[PIVOT_AXIS_LAYER])
4924 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
4925 _("This variable on the layers axis has a summary."));
4928 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4929 if (n_summaries ? summaries[a] : t->axes[a])
4931 t->summary_axis = a;
4935 if (lex_token (lexer) == T_ENDCMD)
4937 if (!ctables_prepare_table (t))
4941 if (!lex_force_match (lexer, T_SLASH))
4944 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
4946 if (lex_match_id (lexer, "SLABELS"))
4948 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4950 if (lex_match_id (lexer, "POSITION"))
4952 lex_match (lexer, T_EQUALS);
4953 if (lex_match_id (lexer, "COLUMN"))
4954 t->slabels_axis = PIVOT_AXIS_COLUMN;
4955 else if (lex_match_id (lexer, "ROW"))
4956 t->slabels_axis = PIVOT_AXIS_ROW;
4957 else if (lex_match_id (lexer, "LAYER"))
4958 t->slabels_axis = PIVOT_AXIS_LAYER;
4961 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
4965 else if (lex_match_id (lexer, "VISIBLE"))
4967 lex_match (lexer, T_EQUALS);
4968 if (!parse_bool (lexer, &t->slabels_visible))
4973 lex_error_expecting (lexer, "POSITION", "VISIBLE");
4978 else if (lex_match_id (lexer, "CLABELS"))
4980 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4982 if (lex_match_id (lexer, "AUTO"))
4984 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
4985 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
4987 else if (lex_match_id (lexer, "ROWLABELS"))
4989 lex_match (lexer, T_EQUALS);
4990 if (lex_match_id (lexer, "OPPOSITE"))
4991 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
4992 else if (lex_match_id (lexer, "LAYER"))
4993 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
4996 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5000 else if (lex_match_id (lexer, "COLLABELS"))
5002 lex_match (lexer, T_EQUALS);
5003 if (lex_match_id (lexer, "OPPOSITE"))
5004 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
5005 else if (lex_match_id (lexer, "LAYER"))
5006 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
5009 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5015 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
5021 else if (lex_match_id (lexer, "CRITERIA"))
5023 if (!lex_force_match_id (lexer, "CILEVEL"))
5025 lex_match (lexer, T_EQUALS);
5027 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
5029 t->cilevel = lex_number (lexer);
5032 else if (lex_match_id (lexer, "CATEGORIES"))
5034 if (!ctables_table_parse_categories (lexer, dataset_dict (ds),
5038 else if (lex_match_id (lexer, "TITLES"))
5043 if (lex_match_id (lexer, "CAPTION"))
5044 textp = &t->caption;
5045 else if (lex_match_id (lexer, "CORNER"))
5047 else if (lex_match_id (lexer, "TITLE"))
5051 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
5054 lex_match (lexer, T_EQUALS);
5056 struct string s = DS_EMPTY_INITIALIZER;
5057 while (lex_is_string (lexer))
5059 if (!ds_is_empty (&s))
5060 ds_put_byte (&s, ' ');
5061 ds_put_substring (&s, lex_tokss (lexer));
5065 *textp = ds_steal_cstr (&s);
5067 while (lex_token (lexer) != T_SLASH
5068 && lex_token (lexer) != T_ENDCMD);
5070 else if (lex_match_id (lexer, "SIGTEST"))
5074 t->chisq = xmalloc (sizeof *t->chisq);
5075 *t->chisq = (struct ctables_chisq) {
5077 .include_mrsets = true,
5078 .all_visible = true,
5084 if (lex_match_id (lexer, "TYPE"))
5086 lex_match (lexer, T_EQUALS);
5087 if (!lex_force_match_id (lexer, "CHISQUARE"))
5090 else if (lex_match_id (lexer, "ALPHA"))
5092 lex_match (lexer, T_EQUALS);
5093 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
5095 t->chisq->alpha = lex_number (lexer);
5098 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5100 lex_match (lexer, T_EQUALS);
5101 if (parse_bool (lexer, &t->chisq->include_mrsets))
5104 else if (lex_match_id (lexer, "CATEGORIES"))
5106 lex_match (lexer, T_EQUALS);
5107 if (lex_match_id (lexer, "ALLVISIBLE"))
5108 t->chisq->all_visible = true;
5109 else if (lex_match_id (lexer, "SUBTOTALS"))
5110 t->chisq->all_visible = false;
5113 lex_error_expecting (lexer,
5114 "ALLVISIBLE", "SUBTOTALS");
5120 lex_error_expecting (lexer, "TYPE", "ALPHA",
5121 "INCLUDEMRSETS", "CATEGORIES");
5125 while (lex_token (lexer) != T_SLASH
5126 && lex_token (lexer) != T_ENDCMD);
5128 else if (lex_match_id (lexer, "COMPARETEST"))
5132 t->pairwise = xmalloc (sizeof *t->pairwise);
5133 *t->pairwise = (struct ctables_pairwise) {
5135 .alpha = { .05, .05 },
5136 .adjust = BONFERRONI,
5137 .include_mrsets = true,
5138 .meansvariance_allcats = true,
5139 .all_visible = true,
5148 if (lex_match_id (lexer, "TYPE"))
5150 lex_match (lexer, T_EQUALS);
5151 if (lex_match_id (lexer, "PROP"))
5152 t->pairwise->type = PROP;
5153 else if (lex_match_id (lexer, "MEAN"))
5154 t->pairwise->type = MEAN;
5157 lex_error_expecting (lexer, "PROP", "MEAN");
5161 else if (lex_match_id (lexer, "ALPHA"))
5163 lex_match (lexer, T_EQUALS);
5165 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5167 double a0 = lex_number (lexer);
5170 lex_match (lexer, T_COMMA);
5171 if (lex_is_number (lexer))
5173 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5175 double a1 = lex_number (lexer);
5178 t->pairwise->alpha[0] = MIN (a0, a1);
5179 t->pairwise->alpha[1] = MAX (a0, a1);
5182 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
5184 else if (lex_match_id (lexer, "ADJUST"))
5186 lex_match (lexer, T_EQUALS);
5187 if (lex_match_id (lexer, "BONFERRONI"))
5188 t->pairwise->adjust = BONFERRONI;
5189 else if (lex_match_id (lexer, "BH"))
5190 t->pairwise->adjust = BH;
5191 else if (lex_match_id (lexer, "NONE"))
5192 t->pairwise->adjust = 0;
5195 lex_error_expecting (lexer, "BONFERRONI", "BH",
5200 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5202 lex_match (lexer, T_EQUALS);
5203 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
5206 else if (lex_match_id (lexer, "MEANSVARIANCE"))
5208 lex_match (lexer, T_EQUALS);
5209 if (lex_match_id (lexer, "ALLCATS"))
5210 t->pairwise->meansvariance_allcats = true;
5211 else if (lex_match_id (lexer, "TESTEDCATS"))
5212 t->pairwise->meansvariance_allcats = false;
5215 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
5219 else if (lex_match_id (lexer, "CATEGORIES"))
5221 lex_match (lexer, T_EQUALS);
5222 if (lex_match_id (lexer, "ALLVISIBLE"))
5223 t->pairwise->all_visible = true;
5224 else if (lex_match_id (lexer, "SUBTOTALS"))
5225 t->pairwise->all_visible = false;
5228 lex_error_expecting (lexer, "ALLVISIBLE",
5233 else if (lex_match_id (lexer, "MERGE"))
5235 lex_match (lexer, T_EQUALS);
5236 if (!parse_bool (lexer, &t->pairwise->merge))
5239 else if (lex_match_id (lexer, "STYLE"))
5241 lex_match (lexer, T_EQUALS);
5242 if (lex_match_id (lexer, "APA"))
5243 t->pairwise->apa_style = true;
5244 else if (lex_match_id (lexer, "SIMPLE"))
5245 t->pairwise->apa_style = false;
5248 lex_error_expecting (lexer, "APA", "SIMPLE");
5252 else if (lex_match_id (lexer, "SHOWSIG"))
5254 lex_match (lexer, T_EQUALS);
5255 if (!parse_bool (lexer, &t->pairwise->show_sig))
5260 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
5261 "INCLUDEMRSETS", "MEANSVARIANCE",
5262 "CATEGORIES", "MERGE", "STYLE",
5267 while (lex_token (lexer) != T_SLASH
5268 && lex_token (lexer) != T_ENDCMD);
5272 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
5273 "CRITERIA", "CATEGORIES", "TITLES",
5274 "SIGTEST", "COMPARETEST");
5278 if (!lex_match (lexer, T_SLASH))
5282 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
5283 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
5285 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
5289 if (!ctables_prepare_table (t))
5292 while (lex_token (lexer) != T_ENDCMD);
5294 bool ok = ctables_execute (ds, ct);
5295 ctables_destroy (ct);
5296 return ok ? CMD_SUCCESS : CMD_FAILURE;
5299 ctables_destroy (ct);