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/data-out.h"
25 #include "data/dataset.h"
26 #include "data/dictionary.h"
27 #include "data/mrset.h"
28 #include "data/subcase.h"
29 #include "data/value-labels.h"
30 #include "language/command.h"
31 #include "language/lexer/format-parser.h"
32 #include "language/lexer/lexer.h"
33 #include "language/lexer/variable-parser.h"
34 #include "libpspp/array.h"
35 #include "libpspp/assertion.h"
36 #include "libpspp/hash-functions.h"
37 #include "libpspp/hmap.h"
38 #include "libpspp/i18n.h"
39 #include "libpspp/message.h"
40 #include "libpspp/string-array.h"
41 #include "math/mode.h"
42 #include "math/moments.h"
43 #include "math/percentiles.h"
44 #include "math/sort.h"
45 #include "output/pivot-table.h"
47 #include "gl/minmax.h"
48 #include "gl/xalloc.h"
51 #define _(msgid) gettext (msgid)
52 #define N_(msgid) (msgid)
56 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
57 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
58 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
59 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
63 - unweighted summaries (U*)
64 - lower confidence limits (*.LCL)
65 - upper confidence limits (*.UCL)
66 - standard error (*.SE)
69 /* All variables. */ \
70 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
71 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
72 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
85 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
86 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
87 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
88 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
89 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
90 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
91 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
92 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
94 /* Scale variables, totals, and subtotals. */ \
95 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
98 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
99 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
100 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
101 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
102 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
103 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
104 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
105 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
106 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
107 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
108 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
109 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
110 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
111 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
112 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
113 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
114 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
115 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
116 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
117 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
119 /* Multiple response sets. */ \
120 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
121 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
134 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
135 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
140 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
141 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
143 enum ctables_summary_function
145 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
151 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
152 N_CTSF_FUNCTIONS = SUMMARIES
156 static bool ctables_summary_function_is_count (enum ctables_summary_function);
158 enum ctables_domain_type
160 /* Within a section, where stacked variables divide one section from
162 CTDT_TABLE, /* All layers of a whole section. */
163 CTDT_LAYER, /* One layer within a section. */
164 CTDT_LAYERROW, /* Row in one layer within a section. */
165 CTDT_LAYERCOL, /* Column in one layer within a section. */
167 /* Within a subtable, where a subtable pairs an innermost row variable with
168 an innermost column variable within a single layer. */
169 CTDT_SUBTABLE, /* Whole subtable. */
170 CTDT_ROW, /* Row within a subtable. */
171 CTDT_COL, /* Column within a subtable. */
175 struct ctables_domain
177 struct hmap_node node;
179 const struct ctables_cell *example;
181 double d_valid; /* Dictionary weight. */
183 double e_valid; /* Effective weight */
187 enum ctables_summary_variant
196 /* In struct ctables_section's 'cells' hmap. Indexed by all the values in
197 all the axes (except the scalar variable, if any). */
198 struct hmap_node node;
200 /* The domains that contain this cell. */
201 bool contributes_to_domains;
202 struct ctables_domain *domains[N_CTDTS];
206 enum ctables_summary_variant sv;
208 struct ctables_cell_axis
210 struct ctables_cell_value
212 const struct ctables_category *category;
220 union ctables_summary *summaries;
225 const struct dictionary *dict;
226 struct pivot_table_look *look;
228 /* CTABLES has a number of extra formats that we implement via custom
229 currency specifications on an alternate fmt_settings. */
230 #define CTEF_NEGPAREN FMT_CCA
231 #define CTEF_NEQUAL FMT_CCB
232 #define CTEF_PAREN FMT_CCC
233 #define CTEF_PCTPAREN FMT_CCD
234 struct fmt_settings ctables_formats;
236 /* If this is NULL, zeros are displayed using the normal print format.
237 Otherwise, this string is displayed. */
240 /* If this is NULL, missing values are displayed using the normal print
241 format. Otherwise, this string is displayed. */
244 /* Indexed by variable dictionary index. */
245 enum ctables_vlabel *vlabels;
247 struct hmap postcomputes; /* Contains "struct ctables_postcompute"s. */
249 bool mrsets_count_duplicates; /* MRSETS. */
250 bool smissing_listwise; /* SMISSING. */
251 struct variable *e_weight; /* WEIGHT. */
252 int hide_threshold; /* HIDESMALLCOUNTS. */
254 struct ctables_table **tables;
258 static struct ctables_postcompute *ctables_find_postcompute (struct ctables *,
261 struct ctables_postcompute
263 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
264 char *name; /* Name, without leading &. */
266 struct msg_location *location; /* Location of definition. */
267 struct ctables_pcexpr *expr;
269 struct ctables_summary_spec_set *specs;
270 bool hide_source_cats;
273 struct ctables_pcexpr
283 enum ctables_postcompute_op
286 CTPO_CONSTANT, /* 5 */
287 CTPO_CAT_NUMBER, /* [5] */
288 CTPO_CAT_STRING, /* ["STRING"] */
289 CTPO_CAT_RANGE, /* [LO THRU 5] */
290 CTPO_CAT_MISSING, /* MISSING */
291 CTPO_CAT_OTHERNM, /* OTHERNM */
292 CTPO_CAT_SUBTOTAL, /* SUBTOTAL */
293 CTPO_CAT_TOTAL, /* TOTAL */
307 /* CTPO_CAT_NUMBER. */
310 /* CTPO_CAT_STRING. */
313 /* CTPO_CAT_RANGE. */
316 /* CTPO_CAT_SUBTOTAL. */
317 size_t subtotal_index;
319 /* Two elements: CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW.
320 One element: CTPO_NEG. */
321 struct ctables_pcexpr *subs[2];
324 /* Source location. */
325 struct msg_location *location;
328 static void ctables_pcexpr_destroy (struct ctables_pcexpr *);
329 static struct ctables_pcexpr *ctables_pcexpr_allocate_binary (
330 enum ctables_postcompute_op, struct ctables_pcexpr *sub0,
331 struct ctables_pcexpr *sub1);
333 struct ctables_summary_spec_set
335 struct ctables_summary_spec *specs;
339 struct variable *var;
342 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
343 const struct ctables_summary_spec_set *);
344 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
346 /* A nested sequence of variables, e.g. a > b > c. */
349 struct variable **vars;
352 size_t *domains[N_CTDTS];
353 size_t n_domains[N_CTDTS];
355 struct ctables_summary_spec_set specs[N_CSVS];
358 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
361 struct ctables_nest *nests;
367 struct hmap_node node;
372 struct ctables_occurrence
374 struct hmap_node node;
378 struct ctables_section
380 struct ctables_table *table;
381 struct ctables_nest *nests[PIVOT_N_AXES];
382 struct hmap *occurrences[PIVOT_N_AXES];
383 struct hmap cells; /* Contains "struct ctable_cell"s. */
384 struct hmap domains[N_CTDTS]; /* Contains "struct ctable_domain"s. */
389 struct ctables *ctables;
390 struct ctables_axis *axes[PIVOT_N_AXES];
391 struct ctables_stack stacks[PIVOT_N_AXES];
392 struct ctables_section *sections;
394 enum pivot_axis_type summary_axis;
395 struct ctables_summary_spec_set summary_specs;
397 const struct variable *clabels_example;
398 struct hmap clabels_values_map;
399 struct ctables_value **clabels_values;
400 size_t n_clabels_values;
402 enum pivot_axis_type slabels_axis;
403 bool slabels_visible;
405 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
407 Most commonly, label_axis[a] == a, and in particular we always have
408 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
410 If ROWLABELS or COLLABELS is specified, then one of
411 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
412 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
414 enum pivot_axis_type label_axis[PIVOT_N_AXES];
415 enum pivot_axis_type clabels_from_axis;
417 /* Indexed by variable dictionary index. */
418 struct ctables_categories **categories;
427 struct ctables_chisq *chisq;
428 struct ctables_pairwise *pairwise;
436 struct variable *var;
437 const struct mrset *mrset;
441 static const struct fmt_spec *
442 ctables_var_get_print_format (const struct ctables_var *var)
444 return (var->is_mrset
445 ? var_get_print_format (var->mrset->vars[0])
446 : var_get_print_format (var->var));
450 ctables_var_name (const struct ctables_var *var)
452 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
455 struct ctables_categories
458 struct ctables_category *cats;
463 struct ctables_category
465 enum ctables_category_type
467 /* Explicit category lists. */
475 /* Totals and subtotals. */
479 /* Implicit category lists. */
486 struct ctables_category *subtotal;
492 double number; /* CCT_NUMBER. */
493 char *string; /* CCT_STRING. */
494 double range[2]; /* CCT_RANGE. */
498 char *total_label; /* CCT_SUBTOTAL, CCT_TOTAL. */
499 bool hide_subcategories; /* CCT_SUBTOTAL. */
502 const struct ctables_postcompute *pc; /* CCT_POSTCOMPUTE. */
504 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
507 bool include_missing;
511 enum ctables_summary_function sort_function;
512 struct variable *sort_var;
517 /* Source location. This is null for CCT_TOTAL, CCT_VALUE, CCT_LABEL,
519 struct msg_location *location;
523 ctables_category_uninit (struct ctables_category *cat)
534 case CCT_POSTCOMPUTE:
543 free (cat->total_label);
554 ctables_category_equal (const struct ctables_category *a,
555 const struct ctables_category *b)
557 if (a->type != b->type)
563 return a->number == b->number;
566 return strcmp (a->string, b->string);
569 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
575 case CCT_POSTCOMPUTE:
576 return a->pc == b->pc;
580 return !strcmp (a->total_label, b->total_label);
585 return (a->include_missing == b->include_missing
586 && a->sort_ascending == b->sort_ascending
587 && a->sort_function == b->sort_function
588 && a->sort_var == b->sort_var
589 && a->percentile == b->percentile);
596 ctables_categories_unref (struct ctables_categories *c)
601 assert (c->n_refs > 0);
605 for (size_t i = 0; i < c->n_cats; i++)
606 ctables_category_uninit (&c->cats[i]);
612 ctables_categories_equal (const struct ctables_categories *a,
613 const struct ctables_categories *b)
615 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
618 for (size_t i = 0; i < a->n_cats; i++)
619 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
625 /* Chi-square test (SIGTEST). */
633 /* Pairwise comparison test (COMPARETEST). */
634 struct ctables_pairwise
636 enum { PROP, MEAN } type;
639 bool meansvariance_allcats;
641 enum { BONFERRONI = 1, BH } adjust;
665 struct ctables_var var;
667 struct ctables_summary_spec_set specs[N_CSVS];
671 struct ctables_axis *subs[2];
674 struct msg_location *loc;
677 static void ctables_axis_destroy (struct ctables_axis *);
686 enum ctables_function_availability
688 CTFA_ALL, /* Any variables. */
689 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
690 CTFA_MRSETS, /* Only multiple-response sets */
693 struct ctables_summary_spec
695 enum ctables_summary_function function;
696 double percentile; /* CTSF_PTILE only. */
699 struct fmt_spec format;
700 bool is_ctables_format; /* Is 'format' one of CTEF_*? */
706 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
707 const struct ctables_summary_spec *src)
710 dst->label = xstrdup (src->label);
714 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
721 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
722 const struct ctables_summary_spec_set *src)
724 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
725 for (size_t i = 0; i < src->n; i++)
726 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
728 *dst = (struct ctables_summary_spec_set) {
737 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
739 for (size_t i = 0; i < set->n; i++)
740 ctables_summary_spec_uninit (&set->specs[i]);
745 parse_col_width (struct lexer *lexer, const char *name, double *width)
747 lex_match (lexer, T_EQUALS);
748 if (lex_match_id (lexer, "DEFAULT"))
750 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
752 *width = lex_number (lexer);
762 parse_bool (struct lexer *lexer, bool *b)
764 if (lex_match_id (lexer, "NO"))
766 else if (lex_match_id (lexer, "YES"))
770 lex_error_expecting (lexer, "YES", "NO");
776 static enum ctables_function_availability
777 ctables_function_availability (enum ctables_summary_function f)
779 static enum ctables_function_availability availability[] = {
780 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
785 return availability[f];
789 ctables_summary_function_is_count (enum ctables_summary_function f)
791 static const bool is_count[N_CTSF_FUNCTIONS] = {
793 [CTSF_ECOUNT] = true,
794 [CTSF_ROWPCT_COUNT] = true,
795 [CTSF_COLPCT_COUNT] = true,
796 [CTSF_TABLEPCT_COUNT] = true,
797 [CTSF_SUBTABLEPCT_COUNT] = true,
798 [CTSF_LAYERPCT_COUNT] = true,
799 [CTSF_LAYERROWPCT_COUNT] = true,
800 [CTSF_LAYERCOLPCT_COUNT] = true,
801 [CTSF_ROWPCT_RESPONSES_COUNT] = true,
802 [CTSF_COLPCT_RESPONSES_COUNT] = true,
803 [CTSF_TABLEPCT_RESPONSES_COUNT] = true,
804 [CTSF_SUBTABLEPCT_RESPONSES_COUNT] = true,
805 [CTSF_LAYERPCT_RESPONSES_COUNT] = true,
806 [CTSF_LAYERROWPCT_RESPONSES_COUNT] = true,
807 [CTSF_LAYERCOLPCT_RESPONSES_COUNT] = true,
808 [CTSF_ROWPCT_COUNT_RESPONSES] = true,
809 [CTSF_COLPCT_COUNT_RESPONSES] = true,
810 [CTSF_TABLEPCT_COUNT_RESPONSES] = true,
811 [CTSF_SUBTABLEPCT_COUNT_RESPONSES] = true,
812 [CTSF_LAYERPCT_COUNT_RESPONSES] = true,
813 [CTSF_LAYERROWPCT_COUNT_RESPONSES] = true,
814 [CTSF_LAYERCOLPCT_COUNT_RESPONSES] = true,
821 parse_ctables_summary_function (struct lexer *lexer,
822 enum ctables_summary_function *f)
826 enum ctables_summary_function function;
827 struct substring name;
829 static struct pair names[] = {
830 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
831 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
834 /* The .COUNT suffix may be omitted. */
835 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
836 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
837 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
838 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
839 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
840 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
841 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
845 if (!lex_force_id (lexer))
848 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
849 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
851 *f = names[i].function;
856 lex_error (lexer, _("Expecting summary function name."));
861 ctables_axis_destroy (struct ctables_axis *axis)
869 for (size_t i = 0; i < N_CSVS; i++)
870 ctables_summary_spec_set_uninit (&axis->specs[i]);
875 ctables_axis_destroy (axis->subs[0]);
876 ctables_axis_destroy (axis->subs[1]);
879 msg_location_destroy (axis->loc);
883 static struct ctables_axis *
884 ctables_axis_new_nonterminal (enum ctables_axis_op op,
885 struct ctables_axis *sub0,
886 struct ctables_axis *sub1,
887 struct lexer *lexer, int start_ofs)
889 struct ctables_axis *axis = xmalloc (sizeof *axis);
890 *axis = (struct ctables_axis) {
892 .subs = { sub0, sub1 },
893 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
898 struct ctables_axis_parse_ctx
901 struct dictionary *dict;
903 struct ctables_table *t;
906 static struct fmt_spec
907 ctables_summary_default_format (enum ctables_summary_function function,
908 const struct ctables_var *var)
910 static const enum ctables_format default_formats[] = {
911 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
915 switch (default_formats[function])
918 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
921 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
924 return *ctables_var_get_print_format (var);
932 ctables_summary_default_label (enum ctables_summary_function function,
935 static const char *default_labels[] = {
936 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
941 return (function == CTSF_PTILE
942 ? xasprintf (_("Percentile %.2f"), percentile)
943 : xstrdup (gettext (default_labels[function])));
947 ctables_summary_function_name (enum ctables_summary_function function)
949 static const char *names[] = {
950 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
954 return names[function];
958 add_summary_spec (struct ctables_axis *axis,
959 enum ctables_summary_function function, double percentile,
960 const char *label, const struct fmt_spec *format,
961 bool is_ctables_format, const struct msg_location *loc,
962 enum ctables_summary_variant sv)
964 if (axis->op == CTAO_VAR)
966 const char *function_name = ctables_summary_function_name (function);
967 const char *var_name = ctables_var_name (&axis->var);
968 switch (ctables_function_availability (function))
971 if (!axis->var.is_mrset)
973 msg_at (SE, loc, _("Summary function %s applies only to multiple "
974 "response sets."), function_name);
975 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
985 _("Summary function %s applies only to scale variables."),
987 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
997 struct ctables_summary_spec_set *set = &axis->specs[sv];
998 if (set->n >= set->allocated)
999 set->specs = x2nrealloc (set->specs, &set->allocated,
1000 sizeof *set->specs);
1002 struct ctables_summary_spec *dst = &set->specs[set->n++];
1003 *dst = (struct ctables_summary_spec) {
1004 .function = function,
1005 .percentile = percentile,
1006 .label = xstrdup (label),
1007 .format = (format ? *format
1008 : ctables_summary_default_format (function, &axis->var)),
1009 .is_ctables_format = is_ctables_format,
1015 for (size_t i = 0; i < 2; i++)
1016 if (!add_summary_spec (axis->subs[i], function, percentile, label,
1017 format, is_ctables_format, loc, sv))
1023 static struct ctables_axis *ctables_axis_parse_stack (
1024 struct ctables_axis_parse_ctx *);
1027 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
1028 struct ctables_var *var)
1030 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
1032 *var = (struct ctables_var) {
1034 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
1038 lex_error (lexer, _("'%s' does not name a multiple-response set "
1039 "in the active file dictionary."),
1040 lex_tokcstr (lexer));
1048 *var = (struct ctables_var) {
1050 .var = parse_variable (lexer, dict),
1052 return var->var != NULL;
1056 static struct ctables_axis *
1057 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
1059 if (lex_match (ctx->lexer, T_LPAREN))
1061 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
1062 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
1064 ctables_axis_destroy (sub);
1070 if (!lex_force_id (ctx->lexer))
1073 int start_ofs = lex_ofs (ctx->lexer);
1074 struct ctables_var var;
1075 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
1078 struct ctables_axis *axis = xmalloc (sizeof *axis);
1079 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
1081 /* XXX should figure out default measures by reading data */
1082 axis->scale = (var.is_mrset ? false
1083 : lex_match_phrase (ctx->lexer, "[S]") ? true
1084 : lex_match_phrase (ctx->lexer, "[C]") ? false
1085 : var_get_measure (var.var) == MEASURE_SCALE);
1086 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
1087 lex_ofs (ctx->lexer) - 1);
1092 has_digit (const char *s)
1094 return s[strcspn (s, "0123456789")] != '\0';
1098 parse_ctables_format_specifier (struct lexer *lexer, struct fmt_spec *format,
1099 bool *is_ctables_format)
1101 char type[FMT_TYPE_LEN_MAX + 1];
1102 if (!parse_abstract_format_specifier__ (lexer, type, &format->w, &format->d))
1105 if (!strcasecmp (type, "NEGPAREN"))
1106 format->type = CTEF_NEGPAREN;
1107 else if (!strcasecmp (type, "NEQUAL"))
1108 format->type = CTEF_NEQUAL;
1109 else if (!strcasecmp (type, "PAREN"))
1110 format->type = CTEF_PAREN;
1111 else if (!strcasecmp (type, "PCTPAREN"))
1112 format->type = CTEF_PCTPAREN;
1115 *is_ctables_format = false;
1116 return (parse_format_specifier (lexer, format)
1117 && fmt_check_output (format)
1118 && fmt_check_type_compat (format, VAL_NUMERIC));
1123 msg (SE, _("Output format %s requires width 2 or greater."), type);
1126 else if (format->d > format->w - 1)
1128 msg (SE, _("Output format %s requires width greater than decimals."),
1134 *is_ctables_format = true;
1139 static struct ctables_axis *
1140 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
1142 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
1143 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
1146 enum ctables_summary_variant sv = CSV_CELL;
1149 int start_ofs = lex_ofs (ctx->lexer);
1151 /* Parse function. */
1152 enum ctables_summary_function function;
1153 if (!parse_ctables_summary_function (ctx->lexer, &function))
1156 /* Parse percentile. */
1157 double percentile = 0;
1158 if (function == CTSF_PTILE)
1160 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1162 percentile = lex_number (ctx->lexer);
1163 lex_get (ctx->lexer);
1168 if (lex_is_string (ctx->lexer))
1170 label = ss_xstrdup (lex_tokss (ctx->lexer));
1171 lex_get (ctx->lexer);
1174 label = ctables_summary_default_label (function, percentile);
1177 struct fmt_spec format;
1178 const struct fmt_spec *formatp;
1179 bool is_ctables_format = false;
1180 if (lex_token (ctx->lexer) == T_ID
1181 && has_digit (lex_tokcstr (ctx->lexer)))
1183 if (!parse_ctables_format_specifier (ctx->lexer, &format,
1184 &is_ctables_format))
1194 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1195 lex_ofs (ctx->lexer) - 1);
1196 add_summary_spec (sub, function, percentile, label, formatp,
1197 is_ctables_format, loc, sv);
1199 msg_location_destroy (loc);
1201 lex_match (ctx->lexer, T_COMMA);
1202 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1204 if (!lex_force_match (ctx->lexer, T_LBRACK))
1208 else if (lex_match (ctx->lexer, T_RBRACK))
1210 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1217 ctables_axis_destroy (sub);
1221 static const struct ctables_axis *
1222 find_scale (const struct ctables_axis *axis)
1226 else if (axis->op == CTAO_VAR)
1230 assert (!axis->var.is_mrset);
1238 for (size_t i = 0; i < 2; i++)
1240 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1248 static const struct ctables_axis *
1249 find_categorical_summary_spec (const struct ctables_axis *axis)
1253 else if (axis->op == CTAO_VAR)
1254 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1257 for (size_t i = 0; i < 2; i++)
1259 const struct ctables_axis *sum
1260 = find_categorical_summary_spec (axis->subs[i]);
1268 static struct ctables_axis *
1269 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1271 int start_ofs = lex_ofs (ctx->lexer);
1272 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1276 while (lex_match (ctx->lexer, T_GT))
1278 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1282 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1283 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1285 const struct ctables_axis *outer_scale = find_scale (lhs);
1286 const struct ctables_axis *inner_scale = find_scale (rhs);
1287 if (outer_scale && inner_scale)
1289 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1290 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1291 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1292 ctables_axis_destroy (nest);
1296 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1299 msg_at (SE, nest->loc,
1300 _("Summaries may only be requested for categorical variables "
1301 "at the innermost nesting level."));
1302 msg_at (SN, outer_sum->loc,
1303 _("This outer categorical variable has a summary."));
1304 ctables_axis_destroy (nest);
1314 static struct ctables_axis *
1315 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1317 int start_ofs = lex_ofs (ctx->lexer);
1318 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1322 while (lex_match (ctx->lexer, T_PLUS))
1324 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1328 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1329 ctx->lexer, start_ofs);
1336 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1337 struct ctables *ct, struct ctables_table *t,
1338 enum pivot_axis_type a)
1340 if (lex_token (lexer) == T_BY
1341 || lex_token (lexer) == T_SLASH
1342 || lex_token (lexer) == T_ENDCMD)
1345 struct ctables_axis_parse_ctx ctx = {
1351 t->axes[a] = ctables_axis_parse_stack (&ctx);
1352 return t->axes[a] != NULL;
1356 ctables_chisq_destroy (struct ctables_chisq *chisq)
1362 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1368 ctables_table_destroy (struct ctables_table *t)
1373 for (size_t i = 0; i < t->n_categories; i++)
1374 ctables_categories_unref (t->categories[i]);
1375 free (t->categories);
1377 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1378 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1379 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1383 ctables_chisq_destroy (t->chisq);
1384 ctables_pairwise_destroy (t->pairwise);
1389 ctables_destroy (struct ctables *ct)
1394 pivot_table_look_unref (ct->look);
1398 for (size_t i = 0; i < ct->n_tables; i++)
1399 ctables_table_destroy (ct->tables[i]);
1404 static struct ctables_category
1405 cct_range (double low, double high)
1407 return (struct ctables_category) {
1409 .range = { low, high }
1414 ctables_table_parse_subtotal (struct lexer *lexer, bool hide_subcategories,
1415 struct ctables_category *cat)
1418 if (lex_match (lexer, T_EQUALS))
1420 if (!lex_force_string (lexer))
1423 total_label = ss_xstrdup (lex_tokss (lexer));
1427 total_label = xstrdup (_("Subtotal"));
1429 *cat = (struct ctables_category) {
1430 .type = CCT_SUBTOTAL,
1431 .hide_subcategories = hide_subcategories,
1432 .total_label = total_label
1438 ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
1439 struct ctables_category *cat)
1441 if (lex_match_id (lexer, "OTHERNM"))
1442 *cat = (struct ctables_category) { .type = CCT_OTHERNM };
1443 else if (lex_match_id (lexer, "MISSING"))
1444 *cat = (struct ctables_category) { .type = CCT_MISSING };
1445 else if (lex_match_id (lexer, "SUBTOTAL"))
1446 return ctables_table_parse_subtotal (lexer, false, cat);
1447 else if (lex_match_id (lexer, "HSUBTOTAL"))
1448 return ctables_table_parse_subtotal (lexer, true, cat);
1449 else if (lex_match_id (lexer, "LO"))
1451 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1453 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1456 else if (lex_is_number (lexer))
1458 double number = lex_number (lexer);
1460 if (lex_match_id (lexer, "THRU"))
1462 if (lex_match_id (lexer, "HI"))
1463 *cat = cct_range (number, DBL_MAX);
1466 if (!lex_force_num (lexer))
1468 *cat = cct_range (number, lex_number (lexer));
1473 *cat = (struct ctables_category) {
1478 else if (lex_is_string (lexer))
1480 *cat = (struct ctables_category) {
1482 .string = ss_xstrdup (lex_tokss (lexer)),
1486 else if (lex_match (lexer, T_AND))
1488 if (!lex_force_id (lexer))
1490 struct ctables_postcompute *pc = ctables_find_postcompute (
1491 ct, lex_tokcstr (lexer));
1494 struct msg_location *loc = lex_get_location (lexer, -1, 0);
1495 msg_at (SE, loc, _("Unknown postcompute &%s."),
1496 lex_tokcstr (lexer));
1497 msg_location_destroy (loc);
1502 *cat = (struct ctables_category) { .type = CCT_POSTCOMPUTE, .pc = pc };
1506 lex_error (lexer, NULL);
1513 static struct ctables_category *
1514 ctables_find_category_for_postcompute (const struct ctables_categories *cats,
1515 const struct ctables_pcexpr *e)
1517 struct ctables_category *best = NULL;
1518 size_t n_subtotals = 0;
1519 for (size_t i = 0; i < cats->n_cats; i++)
1521 struct ctables_category *cat = &cats->cats[i];
1524 case CTPO_CAT_NUMBER:
1525 if (cat->type == CCT_NUMBER && cat->number == e->number)
1529 case CTPO_CAT_STRING:
1530 if (cat->type == CCT_STRING && !strcmp (cat->string, e->string))
1534 case CTPO_CAT_RANGE:
1535 if (cat->type == CCT_RANGE
1536 && cat->range[0] == e->range[0]
1537 && cat->range[1] == e->range[1])
1541 case CTPO_CAT_MISSING:
1542 if (cat->type == CCT_MISSING)
1546 case CTPO_CAT_OTHERNM:
1547 if (cat->type == CCT_OTHERNM)
1551 case CTPO_CAT_SUBTOTAL:
1552 if (cat->type == CCT_SUBTOTAL)
1555 if (e->subtotal_index == n_subtotals)
1557 else if (e->subtotal_index == 0)
1562 case CTPO_CAT_TOTAL:
1563 if (cat->type == CCT_TOTAL)
1577 if (e->op == CTPO_CAT_SUBTOTAL && e->subtotal_index == 0 && n_subtotals > 1)
1583 ctables_recursive_check_postcompute (const struct ctables_pcexpr *e,
1584 struct ctables_category *pc_cat,
1585 const struct ctables_categories *cats,
1586 const struct msg_location *cats_location)
1590 case CTPO_CAT_NUMBER:
1591 case CTPO_CAT_STRING:
1592 case CTPO_CAT_RANGE:
1593 case CTPO_CAT_MISSING:
1594 case CTPO_CAT_OTHERNM:
1595 case CTPO_CAT_SUBTOTAL:
1596 case CTPO_CAT_TOTAL:
1598 struct ctables_category *cat = ctables_find_category_for_postcompute (
1602 if (e->op == CTPO_CAT_SUBTOTAL && e->subtotal_index == 0)
1604 size_t n_subtotals = 0;
1605 for (size_t i = 0; i < cats->n_cats; i++)
1606 n_subtotals += cats->cats[i].type == CCT_SUBTOTAL;
1607 if (n_subtotals > 1)
1609 msg_at (SE, cats_location,
1610 ngettext ("These categories include %zu instance "
1611 "of SUBTOTAL or HSUBTOTAL, so references "
1612 "from computed categories must refer to "
1613 "subtotals by position.",
1614 "These categories include %zu instances "
1615 "of SUBTOTAL or HSUBTOTAL, so references "
1616 "from computed categories must refer to "
1617 "subtotals by position.",
1620 msg_at (SN, e->location,
1621 _("This is the reference that lacks a position."));
1626 msg_at (SE, pc_cat->location,
1627 _("Computed category &%s references a category not included "
1628 "in the category list."),
1630 msg_at (SN, e->location, _("This is the missing category."));
1631 msg_at (SN, cats_location,
1632 _("To fix the problem, add the missing category to the "
1633 "list of categories here."));
1636 if (pc_cat->pc->hide_source_cats)
1650 for (size_t i = 0; i < 2; i++)
1651 if (e->subs[i] && !ctables_recursive_check_postcompute (
1652 e->subs[i], pc_cat, cats, cats_location))
1662 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1663 struct ctables *ct, struct ctables_table *t)
1665 if (!lex_match_id (lexer, "VARIABLES"))
1667 lex_match (lexer, T_EQUALS);
1669 struct variable **vars;
1671 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1674 struct ctables_categories *c = xmalloc (sizeof *c);
1675 *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
1676 for (size_t i = 0; i < n_vars; i++)
1678 struct ctables_categories **cp
1679 = &t->categories[var_get_dict_index (vars[i])];
1680 ctables_categories_unref (*cp);
1685 size_t allocated_cats = 0;
1686 if (lex_match (lexer, T_LBRACK))
1688 int cats_start_ofs = lex_ofs (lexer);
1691 if (c->n_cats >= allocated_cats)
1692 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1694 int start_ofs = lex_ofs (lexer);
1695 struct ctables_category *cat = &c->cats[c->n_cats];
1696 if (!ctables_table_parse_explicit_category (lexer, ct, cat))
1698 cat->location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
1701 lex_match (lexer, T_COMMA);
1703 while (!lex_match (lexer, T_RBRACK));
1705 struct msg_location *cats_location
1706 = lex_ofs_location (lexer, cats_start_ofs, lex_ofs (lexer) - 1);
1707 for (size_t i = 0; i < c->n_cats; i++)
1709 struct ctables_category *cat = &c->cats[i];
1710 if (cat->type == CCT_POSTCOMPUTE
1711 && !ctables_recursive_check_postcompute (cat->pc->expr, cat,
1717 struct ctables_category cat = {
1719 .include_missing = false,
1720 .sort_ascending = true,
1722 bool show_totals = false;
1723 char *total_label = NULL;
1724 bool totals_before = false;
1725 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1727 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1729 lex_match (lexer, T_EQUALS);
1730 if (lex_match_id (lexer, "A"))
1731 cat.sort_ascending = true;
1732 else if (lex_match_id (lexer, "D"))
1733 cat.sort_ascending = false;
1736 lex_error_expecting (lexer, "A", "D");
1740 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1742 lex_match (lexer, T_EQUALS);
1743 if (lex_match_id (lexer, "VALUE"))
1744 cat.type = CCT_VALUE;
1745 else if (lex_match_id (lexer, "LABEL"))
1746 cat.type = CCT_LABEL;
1749 cat.type = CCT_FUNCTION;
1750 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1753 if (lex_match (lexer, T_LPAREN))
1755 cat.sort_var = parse_variable (lexer, dict);
1759 if (cat.sort_function == CTSF_PTILE)
1761 lex_match (lexer, T_COMMA);
1762 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1764 cat.percentile = lex_number (lexer);
1768 if (!lex_force_match (lexer, T_RPAREN))
1771 else if (ctables_function_availability (cat.sort_function)
1774 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1779 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1781 lex_match (lexer, T_EQUALS);
1782 if (lex_match_id (lexer, "INCLUDE"))
1783 cat.include_missing = true;
1784 else if (lex_match_id (lexer, "EXCLUDE"))
1785 cat.include_missing = false;
1788 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1792 else if (lex_match_id (lexer, "TOTAL"))
1794 lex_match (lexer, T_EQUALS);
1795 if (!parse_bool (lexer, &show_totals))
1798 else if (lex_match_id (lexer, "LABEL"))
1800 lex_match (lexer, T_EQUALS);
1801 if (!lex_force_string (lexer))
1804 total_label = ss_xstrdup (lex_tokss (lexer));
1807 else if (lex_match_id (lexer, "POSITION"))
1809 lex_match (lexer, T_EQUALS);
1810 if (lex_match_id (lexer, "BEFORE"))
1811 totals_before = true;
1812 else if (lex_match_id (lexer, "AFTER"))
1813 totals_before = false;
1816 lex_error_expecting (lexer, "BEFORE", "AFTER");
1820 else if (lex_match_id (lexer, "EMPTY"))
1822 lex_match (lexer, T_EQUALS);
1823 if (lex_match_id (lexer, "INCLUDE"))
1824 c->show_empty = true;
1825 else if (lex_match_id (lexer, "EXCLUDE"))
1826 c->show_empty = false;
1829 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1836 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1837 "TOTAL", "LABEL", "POSITION", "EMPTY");
1839 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1846 if (c->n_cats >= allocated_cats)
1847 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1848 c->cats[c->n_cats++] = cat;
1853 if (c->n_cats >= allocated_cats)
1854 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1856 struct ctables_category *totals;
1859 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1860 totals = &c->cats[0];
1863 totals = &c->cats[c->n_cats];
1866 *totals = (struct ctables_category) {
1868 .total_label = total_label ? total_label : xstrdup (_("Total")),
1872 struct ctables_category *subtotal = NULL;
1873 for (size_t i = totals_before ? 0 : c->n_cats;
1874 totals_before ? i < c->n_cats : i-- > 0;
1875 totals_before ? i++ : 0)
1877 struct ctables_category *cat = &c->cats[i];
1885 cat->subtotal = subtotal;
1888 case CCT_POSTCOMPUTE:
1907 ctables_nest_uninit (struct ctables_nest *nest)
1914 ctables_stack_uninit (struct ctables_stack *stack)
1918 for (size_t i = 0; i < stack->n; i++)
1919 ctables_nest_uninit (&stack->nests[i]);
1920 free (stack->nests);
1924 static struct ctables_stack
1925 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1932 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1933 for (size_t i = 0; i < s0.n; i++)
1934 for (size_t j = 0; j < s1.n; j++)
1936 const struct ctables_nest *a = &s0.nests[i];
1937 const struct ctables_nest *b = &s1.nests[j];
1939 size_t allocate = a->n + b->n;
1940 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1941 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1943 for (size_t k = 0; k < a->n; k++)
1944 vars[n++] = a->vars[k];
1945 for (size_t k = 0; k < b->n; k++)
1946 vars[n++] = b->vars[k];
1947 assert (n == allocate);
1949 const struct ctables_nest *summary_src;
1950 if (!a->specs[CSV_CELL].var)
1952 else if (!b->specs[CSV_CELL].var)
1957 struct ctables_nest *new = &stack.nests[stack.n++];
1958 *new = (struct ctables_nest) {
1960 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1961 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1965 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1966 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1968 ctables_stack_uninit (&s0);
1969 ctables_stack_uninit (&s1);
1973 static struct ctables_stack
1974 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1976 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1977 for (size_t i = 0; i < s0.n; i++)
1978 stack.nests[stack.n++] = s0.nests[i];
1979 for (size_t i = 0; i < s1.n; i++)
1980 stack.nests[stack.n++] = s1.nests[i];
1981 assert (stack.n == s0.n + s1.n);
1987 static struct ctables_stack
1988 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1991 return (struct ctables_stack) { .n = 0 };
1996 assert (!a->var.is_mrset);
1998 struct variable **vars = xmalloc (sizeof *vars);
2001 struct ctables_nest *nest = xmalloc (sizeof *nest);
2002 *nest = (struct ctables_nest) {
2005 .scale_idx = a->scale ? 0 : SIZE_MAX,
2007 if (a->specs[CSV_CELL].n || a->scale)
2008 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
2010 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
2011 nest->specs[sv].var = a->var.var;
2013 return (struct ctables_stack) { .nests = nest, .n = 1 };
2016 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
2017 enumerate_fts (axis_type, a->subs[1]));
2020 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
2021 enumerate_fts (axis_type, a->subs[1]));
2027 union ctables_summary
2029 /* COUNT, VALIDN, TOTALN. */
2036 /* MINIMUM, MAXIMUM, RANGE. */
2043 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
2044 struct moments1 *moments;
2046 /* MEDIAN, MODE, PTILE. */
2049 struct casewriter *writer;
2054 /* XXX multiple response */
2058 ctables_summary_init (union ctables_summary *s,
2059 const struct ctables_summary_spec *ss)
2061 switch (ss->function)
2065 case CTSF_ROWPCT_COUNT:
2066 case CTSF_COLPCT_COUNT:
2067 case CTSF_TABLEPCT_COUNT:
2068 case CTSF_SUBTABLEPCT_COUNT:
2069 case CTSF_LAYERPCT_COUNT:
2070 case CTSF_LAYERROWPCT_COUNT:
2071 case CTSF_LAYERCOLPCT_COUNT:
2072 case CTSF_ROWPCT_VALIDN:
2073 case CTSF_COLPCT_VALIDN:
2074 case CTSF_TABLEPCT_VALIDN:
2075 case CTSF_SUBTABLEPCT_VALIDN:
2076 case CTSF_LAYERPCT_VALIDN:
2077 case CTSF_LAYERROWPCT_VALIDN:
2078 case CTSF_LAYERCOLPCT_VALIDN:
2079 case CTSF_ROWPCT_TOTALN:
2080 case CTSF_COLPCT_TOTALN:
2081 case CTSF_TABLEPCT_TOTALN:
2082 case CTSF_SUBTABLEPCT_TOTALN:
2083 case CTSF_LAYERPCT_TOTALN:
2084 case CTSF_LAYERROWPCT_TOTALN:
2085 case CTSF_LAYERCOLPCT_TOTALN:
2091 s->missing = s->valid = 0;
2097 s->min = s->max = SYSMIS;
2105 case CTSF_ROWPCT_SUM:
2106 case CTSF_COLPCT_SUM:
2107 case CTSF_TABLEPCT_SUM:
2108 case CTSF_SUBTABLEPCT_SUM:
2109 case CTSF_LAYERPCT_SUM:
2110 case CTSF_LAYERROWPCT_SUM:
2111 case CTSF_LAYERCOLPCT_SUM:
2112 s->moments = moments1_create (MOMENT_VARIANCE);
2119 struct caseproto *proto = caseproto_create ();
2120 proto = caseproto_add_width (proto, 0);
2121 proto = caseproto_add_width (proto, 0);
2123 struct subcase ordering;
2124 subcase_init (&ordering, 0, 0, SC_ASCEND);
2125 s->writer = sort_create_writer (&ordering, proto);
2126 subcase_uninit (&ordering);
2127 caseproto_unref (proto);
2134 case CTSF_RESPONSES:
2135 case CTSF_ROWPCT_RESPONSES:
2136 case CTSF_COLPCT_RESPONSES:
2137 case CTSF_TABLEPCT_RESPONSES:
2138 case CTSF_SUBTABLEPCT_RESPONSES:
2139 case CTSF_LAYERPCT_RESPONSES:
2140 case CTSF_LAYERROWPCT_RESPONSES:
2141 case CTSF_LAYERCOLPCT_RESPONSES:
2142 case CTSF_ROWPCT_RESPONSES_COUNT:
2143 case CTSF_COLPCT_RESPONSES_COUNT:
2144 case CTSF_TABLEPCT_RESPONSES_COUNT:
2145 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2146 case CTSF_LAYERPCT_RESPONSES_COUNT:
2147 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2148 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2149 case CTSF_ROWPCT_COUNT_RESPONSES:
2150 case CTSF_COLPCT_COUNT_RESPONSES:
2151 case CTSF_TABLEPCT_COUNT_RESPONSES:
2152 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2153 case CTSF_LAYERPCT_COUNT_RESPONSES:
2154 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2155 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2161 ctables_summary_uninit (union ctables_summary *s,
2162 const struct ctables_summary_spec *ss)
2164 switch (ss->function)
2168 case CTSF_ROWPCT_COUNT:
2169 case CTSF_COLPCT_COUNT:
2170 case CTSF_TABLEPCT_COUNT:
2171 case CTSF_SUBTABLEPCT_COUNT:
2172 case CTSF_LAYERPCT_COUNT:
2173 case CTSF_LAYERROWPCT_COUNT:
2174 case CTSF_LAYERCOLPCT_COUNT:
2175 case CTSF_ROWPCT_VALIDN:
2176 case CTSF_COLPCT_VALIDN:
2177 case CTSF_TABLEPCT_VALIDN:
2178 case CTSF_SUBTABLEPCT_VALIDN:
2179 case CTSF_LAYERPCT_VALIDN:
2180 case CTSF_LAYERROWPCT_VALIDN:
2181 case CTSF_LAYERCOLPCT_VALIDN:
2182 case CTSF_ROWPCT_TOTALN:
2183 case CTSF_COLPCT_TOTALN:
2184 case CTSF_TABLEPCT_TOTALN:
2185 case CTSF_SUBTABLEPCT_TOTALN:
2186 case CTSF_LAYERPCT_TOTALN:
2187 case CTSF_LAYERROWPCT_TOTALN:
2188 case CTSF_LAYERCOLPCT_TOTALN:
2206 case CTSF_ROWPCT_SUM:
2207 case CTSF_COLPCT_SUM:
2208 case CTSF_TABLEPCT_SUM:
2209 case CTSF_SUBTABLEPCT_SUM:
2210 case CTSF_LAYERPCT_SUM:
2211 case CTSF_LAYERROWPCT_SUM:
2212 case CTSF_LAYERCOLPCT_SUM:
2213 moments1_destroy (s->moments);
2219 casewriter_destroy (s->writer);
2222 case CTSF_RESPONSES:
2223 case CTSF_ROWPCT_RESPONSES:
2224 case CTSF_COLPCT_RESPONSES:
2225 case CTSF_TABLEPCT_RESPONSES:
2226 case CTSF_SUBTABLEPCT_RESPONSES:
2227 case CTSF_LAYERPCT_RESPONSES:
2228 case CTSF_LAYERROWPCT_RESPONSES:
2229 case CTSF_LAYERCOLPCT_RESPONSES:
2230 case CTSF_ROWPCT_RESPONSES_COUNT:
2231 case CTSF_COLPCT_RESPONSES_COUNT:
2232 case CTSF_TABLEPCT_RESPONSES_COUNT:
2233 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2234 case CTSF_LAYERPCT_RESPONSES_COUNT:
2235 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2236 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2237 case CTSF_ROWPCT_COUNT_RESPONSES:
2238 case CTSF_COLPCT_COUNT_RESPONSES:
2239 case CTSF_TABLEPCT_COUNT_RESPONSES:
2240 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2241 case CTSF_LAYERPCT_COUNT_RESPONSES:
2242 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2243 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2249 ctables_summary_add (union ctables_summary *s,
2250 const struct ctables_summary_spec *ss,
2251 const struct variable *var, const union value *value,
2252 double d_weight, double e_weight)
2254 switch (ss->function)
2259 if (var_is_value_missing (var, value))
2260 s->missing += d_weight;
2262 s->valid += d_weight;
2266 case CTSF_ROWPCT_COUNT:
2267 case CTSF_COLPCT_COUNT:
2268 case CTSF_TABLEPCT_COUNT:
2269 case CTSF_SUBTABLEPCT_COUNT:
2270 case CTSF_LAYERPCT_COUNT:
2271 case CTSF_LAYERROWPCT_COUNT:
2272 case CTSF_LAYERCOLPCT_COUNT:
2273 case CTSF_ROWPCT_VALIDN:
2274 case CTSF_COLPCT_VALIDN:
2275 case CTSF_TABLEPCT_VALIDN:
2276 case CTSF_SUBTABLEPCT_VALIDN:
2277 case CTSF_LAYERPCT_VALIDN:
2278 case CTSF_LAYERROWPCT_VALIDN:
2279 case CTSF_LAYERCOLPCT_VALIDN:
2280 case CTSF_ROWPCT_TOTALN:
2281 case CTSF_COLPCT_TOTALN:
2282 case CTSF_TABLEPCT_TOTALN:
2283 case CTSF_SUBTABLEPCT_TOTALN:
2284 case CTSF_LAYERPCT_TOTALN:
2285 case CTSF_LAYERROWPCT_TOTALN:
2286 case CTSF_LAYERCOLPCT_TOTALN:
2290 if (var_is_value_missing (var, value))
2291 s->missing += e_weight;
2293 s->valid += e_weight;
2299 if (!var_is_value_missing (var, value))
2301 assert (!var_is_alpha (var)); /* XXX? */
2302 if (s->min == SYSMIS || value->f < s->min)
2304 if (s->max == SYSMIS || value->f > s->max)
2314 case CTSF_ROWPCT_SUM:
2315 case CTSF_COLPCT_SUM:
2316 case CTSF_TABLEPCT_SUM:
2317 case CTSF_SUBTABLEPCT_SUM:
2318 case CTSF_LAYERPCT_SUM:
2319 case CTSF_LAYERROWPCT_SUM:
2320 case CTSF_LAYERCOLPCT_SUM:
2321 if (!var_is_value_missing (var, value))
2322 moments1_add (s->moments, value->f, e_weight);
2328 if (var_is_value_missing (var, value))
2330 s->ovalid += e_weight;
2332 struct ccase *c = case_create (casewriter_get_proto (s->writer));
2333 *case_num_rw_idx (c, 0) = value->f;
2334 *case_num_rw_idx (c, 1) = e_weight;
2335 casewriter_write (s->writer, c);
2339 case CTSF_RESPONSES:
2340 case CTSF_ROWPCT_RESPONSES:
2341 case CTSF_COLPCT_RESPONSES:
2342 case CTSF_TABLEPCT_RESPONSES:
2343 case CTSF_SUBTABLEPCT_RESPONSES:
2344 case CTSF_LAYERPCT_RESPONSES:
2345 case CTSF_LAYERROWPCT_RESPONSES:
2346 case CTSF_LAYERCOLPCT_RESPONSES:
2347 case CTSF_ROWPCT_RESPONSES_COUNT:
2348 case CTSF_COLPCT_RESPONSES_COUNT:
2349 case CTSF_TABLEPCT_RESPONSES_COUNT:
2350 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2351 case CTSF_LAYERPCT_RESPONSES_COUNT:
2352 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2353 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2354 case CTSF_ROWPCT_COUNT_RESPONSES:
2355 case CTSF_COLPCT_COUNT_RESPONSES:
2356 case CTSF_TABLEPCT_COUNT_RESPONSES:
2357 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2358 case CTSF_LAYERPCT_COUNT_RESPONSES:
2359 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2360 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2365 static enum ctables_domain_type
2366 ctables_function_domain (enum ctables_summary_function function)
2388 case CTSF_RESPONSES:
2391 case CTSF_COLPCT_COUNT:
2392 case CTSF_COLPCT_COUNT_RESPONSES:
2393 case CTSF_COLPCT_RESPONSES:
2394 case CTSF_COLPCT_RESPONSES_COUNT:
2395 case CTSF_COLPCT_SUM:
2396 case CTSF_COLPCT_TOTALN:
2397 case CTSF_COLPCT_VALIDN:
2400 case CTSF_LAYERCOLPCT_COUNT:
2401 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2402 case CTSF_LAYERCOLPCT_RESPONSES:
2403 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2404 case CTSF_LAYERCOLPCT_SUM:
2405 case CTSF_LAYERCOLPCT_TOTALN:
2406 case CTSF_LAYERCOLPCT_VALIDN:
2407 return CTDT_LAYERCOL;
2409 case CTSF_LAYERPCT_COUNT:
2410 case CTSF_LAYERPCT_COUNT_RESPONSES:
2411 case CTSF_LAYERPCT_RESPONSES:
2412 case CTSF_LAYERPCT_RESPONSES_COUNT:
2413 case CTSF_LAYERPCT_SUM:
2414 case CTSF_LAYERPCT_TOTALN:
2415 case CTSF_LAYERPCT_VALIDN:
2418 case CTSF_LAYERROWPCT_COUNT:
2419 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2420 case CTSF_LAYERROWPCT_RESPONSES:
2421 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2422 case CTSF_LAYERROWPCT_SUM:
2423 case CTSF_LAYERROWPCT_TOTALN:
2424 case CTSF_LAYERROWPCT_VALIDN:
2425 return CTDT_LAYERROW;
2427 case CTSF_ROWPCT_COUNT:
2428 case CTSF_ROWPCT_COUNT_RESPONSES:
2429 case CTSF_ROWPCT_RESPONSES:
2430 case CTSF_ROWPCT_RESPONSES_COUNT:
2431 case CTSF_ROWPCT_SUM:
2432 case CTSF_ROWPCT_TOTALN:
2433 case CTSF_ROWPCT_VALIDN:
2436 case CTSF_SUBTABLEPCT_COUNT:
2437 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2438 case CTSF_SUBTABLEPCT_RESPONSES:
2439 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2440 case CTSF_SUBTABLEPCT_SUM:
2441 case CTSF_SUBTABLEPCT_TOTALN:
2442 case CTSF_SUBTABLEPCT_VALIDN:
2443 return CTDT_SUBTABLE;
2445 case CTSF_TABLEPCT_COUNT:
2446 case CTSF_TABLEPCT_COUNT_RESPONSES:
2447 case CTSF_TABLEPCT_RESPONSES:
2448 case CTSF_TABLEPCT_RESPONSES_COUNT:
2449 case CTSF_TABLEPCT_SUM:
2450 case CTSF_TABLEPCT_TOTALN:
2451 case CTSF_TABLEPCT_VALIDN:
2459 ctables_summary_value (const struct ctables_cell *cell,
2460 union ctables_summary *s,
2461 const struct ctables_summary_spec *ss)
2463 switch (ss->function)
2469 case CTSF_ROWPCT_COUNT:
2470 case CTSF_COLPCT_COUNT:
2471 case CTSF_TABLEPCT_COUNT:
2472 case CTSF_SUBTABLEPCT_COUNT:
2473 case CTSF_LAYERPCT_COUNT:
2474 case CTSF_LAYERROWPCT_COUNT:
2475 case CTSF_LAYERCOLPCT_COUNT:
2477 enum ctables_domain_type d = ctables_function_domain (ss->function);
2478 return (cell->domains[d]->e_valid
2479 ? s->valid / cell->domains[d]->e_valid * 100
2483 case CTSF_ROWPCT_VALIDN:
2484 case CTSF_COLPCT_VALIDN:
2485 case CTSF_TABLEPCT_VALIDN:
2486 case CTSF_SUBTABLEPCT_VALIDN:
2487 case CTSF_LAYERPCT_VALIDN:
2488 case CTSF_LAYERROWPCT_VALIDN:
2489 case CTSF_LAYERCOLPCT_VALIDN:
2490 case CTSF_ROWPCT_TOTALN:
2491 case CTSF_COLPCT_TOTALN:
2492 case CTSF_TABLEPCT_TOTALN:
2493 case CTSF_SUBTABLEPCT_TOTALN:
2494 case CTSF_LAYERPCT_TOTALN:
2495 case CTSF_LAYERROWPCT_TOTALN:
2496 case CTSF_LAYERCOLPCT_TOTALN:
2504 return s->valid + s->missing;
2517 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2522 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2528 double weight, variance;
2529 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2530 return calc_semean (variance, weight);
2536 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2537 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2542 double weight, mean;
2543 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2544 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2550 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2554 case CTSF_ROWPCT_SUM:
2555 case CTSF_COLPCT_SUM:
2556 case CTSF_TABLEPCT_SUM:
2557 case CTSF_SUBTABLEPCT_SUM:
2558 case CTSF_LAYERPCT_SUM:
2559 case CTSF_LAYERROWPCT_SUM:
2560 case CTSF_LAYERCOLPCT_SUM:
2567 struct casereader *reader = casewriter_make_reader (s->writer);
2570 struct percentile *ptile = percentile_create (
2571 ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2572 struct order_stats *os = &ptile->parent;
2573 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2574 s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2575 statistic_destroy (&ptile->parent.parent);
2582 struct casereader *reader = casewriter_make_reader (s->writer);
2585 struct mode *mode = mode_create ();
2586 struct order_stats *os = &mode->parent;
2587 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2588 s->ovalue = mode->mode;
2589 statistic_destroy (&mode->parent.parent);
2593 case CTSF_RESPONSES:
2594 case CTSF_ROWPCT_RESPONSES:
2595 case CTSF_COLPCT_RESPONSES:
2596 case CTSF_TABLEPCT_RESPONSES:
2597 case CTSF_SUBTABLEPCT_RESPONSES:
2598 case CTSF_LAYERPCT_RESPONSES:
2599 case CTSF_LAYERROWPCT_RESPONSES:
2600 case CTSF_LAYERCOLPCT_RESPONSES:
2601 case CTSF_ROWPCT_RESPONSES_COUNT:
2602 case CTSF_COLPCT_RESPONSES_COUNT:
2603 case CTSF_TABLEPCT_RESPONSES_COUNT:
2604 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2605 case CTSF_LAYERPCT_RESPONSES_COUNT:
2606 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2607 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2608 case CTSF_ROWPCT_COUNT_RESPONSES:
2609 case CTSF_COLPCT_COUNT_RESPONSES:
2610 case CTSF_TABLEPCT_COUNT_RESPONSES:
2611 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2612 case CTSF_LAYERPCT_COUNT_RESPONSES:
2613 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2614 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2621 struct ctables_cell_sort_aux
2623 const struct ctables_nest *nest;
2624 enum pivot_axis_type a;
2628 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2630 const struct ctables_cell_sort_aux *aux = aux_;
2631 struct ctables_cell *const *ap = a_;
2632 struct ctables_cell *const *bp = b_;
2633 const struct ctables_cell *a = *ap;
2634 const struct ctables_cell *b = *bp;
2636 const struct ctables_nest *nest = aux->nest;
2637 for (size_t i = 0; i < nest->n; i++)
2638 if (i != nest->scale_idx)
2640 const struct variable *var = nest->vars[i];
2641 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2642 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2643 if (a_cv->category != b_cv->category)
2644 return a_cv->category > b_cv->category ? 1 : -1;
2646 const union value *a_val = &a_cv->value;
2647 const union value *b_val = &b_cv->value;
2648 switch (a_cv->category->type)
2654 case CCT_POSTCOMPUTE:
2655 /* Must be equal. */
2662 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2670 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2672 return a_cv->category->sort_ascending ? cmp : -cmp;
2678 const char *a_label = var_lookup_value_label (var, a_val);
2679 const char *b_label = var_lookup_value_label (var, b_val);
2681 ? (b_label ? strcmp (a_label, b_label) : 1)
2682 : (b_label ? -1 : value_compare_3way (
2683 a_val, b_val, var_get_width (var))));
2685 return a_cv->category->sort_ascending ? cmp : -cmp;
2699 For each ctables_table:
2700 For each combination of row vars:
2701 For each combination of column vars:
2702 For each combination of layer vars:
2704 Make a table of row values:
2705 Sort entries by row values
2706 Assign a 0-based index to each actual value
2707 Construct a dimension
2708 Make a table of column values
2709 Make a table of layer values
2711 Fill the table entry using the indexes from before.
2714 static struct ctables_domain *
2715 ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
2716 enum ctables_domain_type domain)
2719 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2721 const struct ctables_nest *nest = s->nests[a];
2722 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2724 size_t v_idx = nest->domains[domain][i];
2725 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2726 var_get_width (nest->vars[v_idx]), hash);
2730 struct ctables_domain *d;
2731 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &s->domains[domain])
2733 const struct ctables_cell *df = d->example;
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_domains[domain]; i++)
2739 size_t v_idx = nest->domains[domain][i];
2740 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2741 &cell->axes[a].cvs[v_idx].value,
2742 var_get_width (nest->vars[v_idx])))
2751 d = xmalloc (sizeof *d);
2752 *d = (struct ctables_domain) { .example = cell };
2753 hmap_insert (&s->domains[domain], &d->node, hash);
2757 static const struct ctables_category *
2758 ctables_categories_match (const struct ctables_categories *c,
2759 const union value *v, const struct variable *var)
2761 const struct ctables_category *othernm = NULL;
2762 for (size_t i = c->n_cats; i-- > 0; )
2764 const struct ctables_category *cat = &c->cats[i];
2768 if (cat->number == v->f)
2776 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2777 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2782 if (var_is_value_missing (var, v))
2786 case CCT_POSTCOMPUTE:
2801 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2806 return var_is_value_missing (var, v) ? NULL : othernm;
2809 static const struct ctables_category *
2810 ctables_categories_total (const struct ctables_categories *c)
2812 const struct ctables_category *first = &c->cats[0];
2813 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2814 return (first->type == CCT_TOTAL ? first
2815 : last->type == CCT_TOTAL ? last
2819 static struct ctables_cell *
2820 ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
2821 const struct ctables_category *cats[PIVOT_N_AXES][10])
2824 enum ctables_summary_variant sv = CSV_CELL;
2825 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2827 const struct ctables_nest *nest = s->nests[a];
2828 for (size_t i = 0; i < nest->n; i++)
2829 if (i != nest->scale_idx)
2831 hash = hash_pointer (cats[a][i], hash);
2832 if (cats[a][i]->type != CCT_TOTAL
2833 && cats[a][i]->type != CCT_SUBTOTAL
2834 && cats[a][i]->type != CCT_POSTCOMPUTE)
2835 hash = value_hash (case_data (c, nest->vars[i]),
2836 var_get_width (nest->vars[i]), hash);
2842 struct ctables_cell *cell;
2843 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &s->cells)
2845 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2847 const struct ctables_nest *nest = s->nests[a];
2848 for (size_t i = 0; i < nest->n; i++)
2849 if (i != nest->scale_idx
2850 && (cats[a][i] != cell->axes[a].cvs[i].category
2851 || (cats[a][i]->type != CCT_TOTAL
2852 && cats[a][i]->type != CCT_SUBTOTAL
2853 && cats[a][i]->type != CCT_POSTCOMPUTE
2854 && !value_equal (case_data (c, nest->vars[i]),
2855 &cell->axes[a].cvs[i].value,
2856 var_get_width (nest->vars[i])))))
2865 cell = xmalloc (sizeof *cell);
2868 cell->contributes_to_domains = true;
2869 cell->postcompute = false;
2870 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2872 const struct ctables_nest *nest = s->nests[a];
2873 cell->axes[a].cvs = (nest->n
2874 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2876 for (size_t i = 0; i < nest->n; i++)
2878 const struct ctables_category *cat = cats[a][i];
2879 if (i != nest->scale_idx)
2881 const struct ctables_category *subtotal = cat->subtotal;
2882 if (cat->hide || (subtotal && subtotal->hide_subcategories))
2885 if (cat->type == CCT_TOTAL
2886 || cat->type == CCT_SUBTOTAL
2887 || cat->type == CCT_POSTCOMPUTE)
2888 cell->contributes_to_domains = false;
2889 if (cat->type == CCT_POSTCOMPUTE)
2890 cell->postcompute = true;
2893 cell->axes[a].cvs[i].category = cat;
2894 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2895 var_get_width (nest->vars[i]));
2899 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2900 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2901 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2902 for (size_t i = 0; i < specs->n; i++)
2903 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2904 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2905 cell->domains[dt] = ctables_domain_insert (s, cell, dt);
2906 hmap_insert (&s->cells, &cell->node, hash);
2911 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
2912 const struct ctables_category *cats[PIVOT_N_AXES][10],
2913 double d_weight, double e_weight)
2915 struct ctables_cell *cell = ctables_cell_insert__ (s, c, cats);
2916 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2918 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2919 for (size_t i = 0; i < specs->n; i++)
2920 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2921 case_data (c, specs->var), d_weight, e_weight);
2922 if (cell->contributes_to_domains)
2924 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2926 cell->domains[dt]->d_valid += d_weight;
2927 cell->domains[dt]->e_valid += e_weight;
2933 recurse_totals (struct ctables_section *s, const struct ccase *c,
2934 const struct ctables_category *cats[PIVOT_N_AXES][10],
2935 double d_weight, double e_weight,
2936 enum pivot_axis_type start_axis, size_t start_nest)
2938 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2940 const struct ctables_nest *nest = s->nests[a];
2941 for (size_t i = start_nest; i < nest->n; i++)
2943 if (i == nest->scale_idx)
2946 const struct variable *var = nest->vars[i];
2948 const struct ctables_category *total = ctables_categories_total (
2949 s->table->categories[var_get_dict_index (var)]);
2952 const struct ctables_category *save = cats[a][i];
2954 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2955 recurse_totals (s, c, cats, d_weight, e_weight, a, i + 1);
2964 recurse_subtotals (struct ctables_section *s, const struct ccase *c,
2965 const struct ctables_category *cats[PIVOT_N_AXES][10],
2966 double d_weight, double e_weight,
2967 enum pivot_axis_type start_axis, size_t start_nest)
2969 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2971 const struct ctables_nest *nest = s->nests[a];
2972 for (size_t i = start_nest; i < nest->n; i++)
2974 if (i == nest->scale_idx)
2977 const struct ctables_category *save = cats[a][i];
2980 cats[a][i] = save->subtotal;
2981 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2982 recurse_subtotals (s, c, cats, d_weight, e_weight, a, i + 1);
2991 ctables_add_occurrence (const struct variable *var,
2992 const union value *value,
2993 struct hmap *occurrences)
2995 int width = var_get_width (var);
2996 unsigned int hash = value_hash (value, width, 0);
2998 struct ctables_occurrence *o;
2999 HMAP_FOR_EACH_WITH_HASH (o, struct ctables_occurrence, node, hash,
3001 if (value_equal (value, &o->value, width))
3004 o = xmalloc (sizeof *o);
3005 value_clone (&o->value, value, width);
3006 hmap_insert (occurrences, &o->node, hash);
3010 ctables_cell_insert (struct ctables_section *s,
3011 const struct ccase *c,
3012 double d_weight, double e_weight)
3014 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
3015 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3017 const struct ctables_nest *nest = s->nests[a];
3018 for (size_t i = 0; i < nest->n; i++)
3020 if (i == nest->scale_idx)
3023 const struct variable *var = nest->vars[i];
3024 const union value *value = case_data (c, var);
3026 if (var_is_numeric (var) && value->f == SYSMIS)
3029 cats[a][i] = ctables_categories_match (
3030 s->table->categories[var_get_dict_index (var)], value, var);
3036 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3038 const struct ctables_nest *nest = s->nests[a];
3039 for (size_t i = 0; i < nest->n; i++)
3040 if (i != nest->scale_idx)
3042 const struct variable *var = nest->vars[i];
3043 const union value *value = case_data (c, var);
3044 ctables_add_occurrence (var, value, &s->occurrences[a][i]);
3048 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
3050 recurse_totals (s, c, cats, d_weight, e_weight, 0, 0);
3051 recurse_subtotals (s, c, cats, d_weight, e_weight, 0, 0);
3056 const struct ctables_summary_spec_set *set;
3061 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
3063 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
3064 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
3065 if (as->function != bs->function)
3066 return as->function > bs->function ? 1 : -1;
3067 else if (as->percentile != bs->percentile)
3068 return as->percentile < bs->percentile ? 1 : -1;
3069 return strcmp (as->label, bs->label);
3072 static struct pivot_value *
3073 ctables_category_create_label (const struct ctables_category *cat,
3074 const struct variable *var,
3075 const union value *value)
3077 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL
3078 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
3079 : cat->type == CCT_POSTCOMPUTE && cat->pc->label
3080 ? pivot_value_new_user_text (cat->pc->label, SIZE_MAX)
3081 : pivot_value_new_var_value (var, value));
3084 static struct ctables_value *
3085 ctables_value_find__ (struct ctables_table *t, const union value *value,
3086 int width, unsigned int hash)
3088 struct ctables_value *clv;
3089 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
3090 hash, &t->clabels_values_map)
3091 if (value_equal (value, &clv->value, width))
3097 ctables_value_insert (struct ctables_table *t, const union value *value,
3100 unsigned int hash = value_hash (value, width, 0);
3101 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3104 clv = xmalloc (sizeof *clv);
3105 value_clone (&clv->value, value, width);
3106 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3110 static struct ctables_value *
3111 ctables_value_find (struct ctables_table *t,
3112 const union value *value, int width)
3114 return ctables_value_find__ (t, value, width,
3115 value_hash (value, width, 0));
3119 ctables_table_add_section (struct ctables_table *t, enum pivot_axis_type a,
3120 size_t ix[PIVOT_N_AXES])
3122 if (a < PIVOT_N_AXES)
3124 size_t limit = MAX (t->stacks[a].n, 1);
3125 for (ix[a] = 0; ix[a] < limit; ix[a]++)
3126 ctables_table_add_section (t, a + 1, ix);
3130 struct ctables_section *s = &t->sections[t->n_sections++];
3131 *s = (struct ctables_section) {
3133 .cells = HMAP_INITIALIZER (s->cells),
3135 for (a = 0; a < PIVOT_N_AXES; a++)
3138 struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
3140 s->occurrences[a] = xnmalloc (nest->n, sizeof *s->occurrences[a]);
3141 for (size_t i = 0; i < nest->n; i++)
3142 hmap_init (&s->occurrences[a][i]);
3144 for (size_t i = 0; i < N_CTDTS; i++)
3145 hmap_init (&s->domains[i]);
3150 ctpo_add (double a, double b)
3156 ctpo_sub (double a, double b)
3162 ctpo_mul (double a, double b)
3168 ctpo_div (double a, double b)
3170 return b ? a / b : SYSMIS;
3174 ctpo_pow (double a, double b)
3176 int save_errno = errno;
3178 double result = pow (a, b);
3186 ctpo_neg (double a, double b UNUSED)
3191 struct ctables_pcexpr_evaluate_ctx
3193 const struct ctables_cell *cell;
3194 const struct ctables_section *section;
3195 const struct ctables_categories *cats;
3196 enum pivot_axis_type pc_a;
3200 static double ctables_pcexpr_evaluate (
3201 const struct ctables_pcexpr_evaluate_ctx *, const struct ctables_pcexpr *);
3204 ctables_pcexpr_evaluate_nonterminal (
3205 const struct ctables_pcexpr_evaluate_ctx *ctx,
3206 const struct ctables_pcexpr *e, size_t n_args,
3207 double evaluate (double, double))
3209 double args[2] = { 0, 0 };
3210 for (size_t i = 0; i < n_args; i++)
3212 args[i] = ctables_pcexpr_evaluate (ctx, e->subs[i]);
3213 if (!isfinite (args[i]) || args[i] == SYSMIS)
3216 return evaluate (args[0], args[1]);
3220 ctables_pcexpr_evaluate_category (const struct ctables_pcexpr_evaluate_ctx *ctx,
3221 const struct ctables_cell_value *pc_cv)
3223 const struct ctables_section *s = ctx->section;
3226 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3228 const struct ctables_nest *nest = s->nests[a];
3229 for (size_t i = 0; i < nest->n; i++)
3230 if (i != nest->scale_idx)
3232 const struct ctables_cell_value *cv
3233 = (a == ctx->pc_a && i == ctx->pc_a_idx ? pc_cv
3234 : &ctx->cell->axes[a].cvs[i]);
3235 hash = hash_pointer (cv->category, hash);
3236 if (cv->category->type != CCT_TOTAL
3237 && cv->category->type != CCT_SUBTOTAL
3238 && cv->category->type != CCT_POSTCOMPUTE)
3239 hash = value_hash (&cv->value,
3240 var_get_width (nest->vars[i]), hash);
3244 struct ctables_cell *tc;
3245 HMAP_FOR_EACH_WITH_HASH (tc, struct ctables_cell, node, hash, &s->cells)
3247 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3249 const struct ctables_nest *nest = s->nests[a];
3250 for (size_t i = 0; i < nest->n; i++)
3251 if (i != nest->scale_idx)
3253 const struct ctables_cell_value *p_cv
3254 = (a == ctx->pc_a && i == ctx->pc_a_idx ? pc_cv
3255 : &ctx->cell->axes[a].cvs[i]);
3256 const struct ctables_cell_value *t_cv = &tc->axes[a].cvs[i];
3257 if (p_cv->category != t_cv->category
3258 || (p_cv->category->type != CCT_TOTAL
3259 && p_cv->category->type != CCT_SUBTOTAL
3260 && p_cv->category->type != CCT_POSTCOMPUTE
3261 && !value_equal (&p_cv->value,
3263 var_get_width (nest->vars[i]))))
3275 const struct ctables_table *t = s->table;
3276 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3277 const struct ctables_summary_spec_set *specs = &specs_nest->specs[tc->sv];
3278 size_t j = 0 /* XXX */;
3279 return ctables_summary_value (tc, &tc->summaries[j], &specs->specs[j]);
3283 ctables_pcexpr_evaluate (const struct ctables_pcexpr_evaluate_ctx *ctx,
3284 const struct ctables_pcexpr *e)
3291 case CTPO_CAT_RANGE:
3293 struct ctables_cell_value cv = {
3294 .category = ctables_find_category_for_postcompute (ctx->cats, e)
3296 assert (cv.category != NULL);
3298 struct hmap *occurrences = &ctx->section->occurrences[ctx->pc_a][ctx->pc_a_idx];
3299 const struct ctables_occurrence *o;
3302 const struct variable *var = ctx->section->nests[ctx->pc_a]->vars[ctx->pc_a_idx];
3303 HMAP_FOR_EACH (o, struct ctables_occurrence, node, occurrences)
3304 if (ctables_categories_match (ctx->cats, &o->value, var) == cv.category)
3306 cv.value = o->value;
3307 sum += ctables_pcexpr_evaluate_category (ctx, &cv);
3312 case CTPO_CAT_NUMBER:
3313 case CTPO_CAT_STRING:
3314 case CTPO_CAT_MISSING:
3315 case CTPO_CAT_OTHERNM:
3316 case CTPO_CAT_SUBTOTAL:
3317 case CTPO_CAT_TOTAL:
3319 struct ctables_cell_value cv = {
3320 .category = ctables_find_category_for_postcompute (ctx->cats, e),
3321 .value = { .f = e->number },
3323 assert (cv.category != NULL);
3324 return ctables_pcexpr_evaluate_category (ctx, &cv);
3328 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_add);
3331 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_sub);
3334 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_mul);
3337 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_div);
3340 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_pow);
3343 return ctables_pcexpr_evaluate_nonterminal (ctx, e, 1, ctpo_neg);
3350 ctables_cell_calculate_postcompute (const struct ctables_section *s,
3351 const struct ctables_cell *cell)
3353 enum pivot_axis_type pc_a;
3355 const struct ctables_postcompute *pc;
3356 for (pc_a = 0; ; pc_a++)
3358 assert (pc_a < PIVOT_N_AXES);
3359 for (pc_a_idx = 0; pc_a_idx < s->nests[pc_a]->n; pc_a_idx++)
3361 const struct ctables_cell_value *cv = &cell->axes[pc_a].cvs[pc_a_idx];
3362 if (cv->category->type == CCT_POSTCOMPUTE)
3364 pc = cv->category->pc;
3371 const struct variable *var = s->nests[pc_a]->vars[pc_a_idx];
3372 const struct ctables_categories *cats = s->table->categories[
3373 var_get_dict_index (var)];
3374 struct ctables_pcexpr_evaluate_ctx ctx = {
3379 .pc_a_idx = pc_a_idx,
3381 return ctables_pcexpr_evaluate (&ctx, pc->expr);
3385 ctables_table_output (struct ctables *ct, struct ctables_table *t)
3387 struct pivot_table *pt = pivot_table_create__ (
3389 ? pivot_value_new_user_text (t->title, SIZE_MAX)
3390 : pivot_value_new_text (N_("Custom Tables"))),
3393 pivot_table_set_caption (
3394 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
3396 pivot_table_set_caption (
3397 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
3399 bool summary_dimension = (t->summary_axis != t->slabels_axis
3400 || (!t->slabels_visible
3401 && t->summary_specs.n > 1));
3402 if (summary_dimension)
3404 struct pivot_dimension *d = pivot_dimension_create (
3405 pt, t->slabels_axis, N_("Statistics"));
3406 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3407 if (!t->slabels_visible)
3408 d->hide_all_labels = true;
3409 for (size_t i = 0; i < specs->n; i++)
3410 pivot_category_create_leaf (
3411 d->root, pivot_value_new_text (specs->specs[i].label));
3414 bool categories_dimension = t->clabels_example != NULL;
3415 if (categories_dimension)
3417 struct pivot_dimension *d = pivot_dimension_create (
3418 pt, t->label_axis[t->clabels_from_axis],
3419 t->clabels_from_axis == PIVOT_AXIS_ROW
3420 ? N_("Row Categories")
3421 : N_("Column Categories"));
3422 const struct variable *var = t->clabels_example;
3423 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
3424 for (size_t i = 0; i < t->n_clabels_values; i++)
3426 const struct ctables_value *value = t->clabels_values[i];
3427 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
3428 assert (cat != NULL);
3429 pivot_category_create_leaf (d->root, ctables_category_create_label (
3430 cat, t->clabels_example, &value->value));
3434 pivot_table_set_look (pt, ct->look);
3435 struct pivot_dimension *d[PIVOT_N_AXES];
3436 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3438 static const char *names[] = {
3439 [PIVOT_AXIS_ROW] = N_("Rows"),
3440 [PIVOT_AXIS_COLUMN] = N_("Columns"),
3441 [PIVOT_AXIS_LAYER] = N_("Layers"),
3443 d[a] = (t->axes[a] || a == t->summary_axis
3444 ? pivot_dimension_create (pt, a, names[a])
3449 assert (t->axes[a]);
3451 for (size_t i = 0; i < t->stacks[a].n; i++)
3453 struct ctables_nest *nest = &t->stacks[a].nests[i];
3454 struct ctables_section **sections = xnmalloc (t->n_sections,
3456 size_t n_sections = 0;
3458 size_t n_total_cells = 0;
3459 size_t max_depth = 0;
3460 for (size_t j = 0; j < t->n_sections; j++)
3461 if (t->sections[j].nests[a] == nest)
3463 struct ctables_section *s = &t->sections[j];
3464 sections[n_sections++] = s;
3465 n_total_cells += s->cells.count;
3467 size_t depth = s->nests[a]->n;
3468 max_depth = MAX (depth, max_depth);
3471 struct ctables_cell **sorted = xnmalloc (n_total_cells,
3473 size_t n_sorted = 0;
3475 for (size_t j = 0; j < n_sections; j++)
3477 struct ctables_section *s = sections[j];
3479 struct ctables_cell *cell;
3480 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3482 sorted[n_sorted++] = cell;
3483 assert (n_sorted <= n_total_cells);
3486 struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
3487 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
3489 struct ctables_level
3491 enum ctables_level_type
3493 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
3494 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
3495 CTL_SUMMARY, /* Summary functions. */
3499 enum settings_value_show vlabel; /* CTL_VAR only. */
3502 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
3503 size_t n_levels = 0;
3504 for (size_t k = 0; k < nest->n; k++)
3506 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
3507 if (vlabel != CTVL_NONE)
3509 levels[n_levels++] = (struct ctables_level) {
3511 .vlabel = (enum settings_value_show) vlabel,
3516 if (nest->scale_idx != k
3517 && (k != nest->n - 1 || t->label_axis[a] == a))
3519 levels[n_levels++] = (struct ctables_level) {
3520 .type = CTL_CATEGORY,
3526 if (!summary_dimension && a == t->slabels_axis)
3528 levels[n_levels++] = (struct ctables_level) {
3529 .type = CTL_SUMMARY,
3530 .var_idx = SIZE_MAX,
3534 /* Pivot categories:
3536 - variable label for nest->vars[0], if vlabel != CTVL_NONE
3537 - category for nest->vars[0], if nest->scale_idx != 0
3538 - variable label for nest->vars[1], if vlabel != CTVL_NONE
3539 - category for nest->vars[1], if nest->scale_idx != 1
3541 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
3542 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
3543 - summary function, if 'a == t->slabels_axis && a ==
3546 Additional dimensions:
3548 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
3550 - If 't->label_axis[b] == a' for some 'b != a', add a category
3555 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
3557 for (size_t j = 0; j < n_sorted; j++)
3559 struct ctables_cell *cell = sorted[j];
3560 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
3562 size_t n_common = 0;
3565 for (; n_common < n_levels; n_common++)
3567 const struct ctables_level *level = &levels[n_common];
3568 if (level->type == CTL_CATEGORY)
3570 size_t var_idx = level->var_idx;
3571 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3572 if (prev->axes[a].cvs[var_idx].category != c)
3574 else if (c->type != CCT_SUBTOTAL
3575 && c->type != CCT_TOTAL
3576 && c->type != CCT_POSTCOMPUTE
3577 && !value_equal (&prev->axes[a].cvs[var_idx].value,
3578 &cell->axes[a].cvs[var_idx].value,
3579 var_get_type (nest->vars[var_idx])))
3585 for (size_t k = n_common; k < n_levels; k++)
3587 const struct ctables_level *level = &levels[k];
3588 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3589 if (level->type == CTL_SUMMARY)
3591 assert (k == n_levels - 1);
3593 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3594 for (size_t m = 0; m < specs->n; m++)
3596 int leaf = pivot_category_create_leaf (
3597 parent, pivot_value_new_text (specs->specs[m].label));
3604 const struct variable *var = nest->vars[level->var_idx];
3605 struct pivot_value *label;
3606 if (level->type == CTL_VAR)
3608 label = pivot_value_new_variable (var);
3609 label->variable.show = level->vlabel;
3611 else if (level->type == CTL_CATEGORY)
3613 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3614 label = ctables_category_create_label (cv->category,
3620 if (k == n_levels - 1)
3621 prev_leaf = pivot_category_create_leaf (parent, label);
3623 groups[k] = pivot_category_create_group__ (parent, label);
3627 cell->axes[a].leaf = prev_leaf;
3634 for (size_t i = 0; i < t->n_sections; i++)
3636 struct ctables_section *s = &t->sections[i];
3638 struct ctables_cell *cell;
3639 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3644 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3645 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3646 for (size_t j = 0; j < specs->n; j++)
3649 size_t n_dindexes = 0;
3651 if (summary_dimension)
3652 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3654 if (categories_dimension)
3656 const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3657 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3658 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3659 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3662 dindexes[n_dindexes++] = ctv->leaf;
3665 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3668 int leaf = cell->axes[a].leaf;
3669 if (a == t->summary_axis && !summary_dimension)
3671 dindexes[n_dindexes++] = leaf;
3674 const struct ctables_summary_spec *ss = &specs->specs[j];
3676 double d = (cell->postcompute
3677 ? ctables_cell_calculate_postcompute (s, cell)
3678 : ctables_summary_value (cell, &cell->summaries[j], ss));
3679 struct pivot_value *value;
3680 if (ct->hide_threshold != 0
3681 && d < ct->hide_threshold
3682 && (cell->postcompute
3684 : ctables_summary_function_is_count (ss->function)))
3686 value = pivot_value_new_user_text_nocopy (
3687 xasprintf ("<%d", ct->hide_threshold));
3689 else if (d == 0 && ct->zero)
3690 value = pivot_value_new_user_text (ct->zero, SIZE_MAX);
3691 else if (d == SYSMIS && ct->missing)
3692 value = pivot_value_new_user_text (ct->missing, SIZE_MAX);
3693 else if (specs->specs[j].is_ctables_format)
3695 char *s = data_out_stretchy (&(union value) { .f = d },
3697 &specs->specs[j].format,
3698 &ct->ctables_formats, NULL);
3699 value = pivot_value_new_user_text_nocopy (s);
3703 value = pivot_value_new_number (d);
3704 value->numeric.format = specs->specs[j].format;
3706 pivot_table_put (pt, dindexes, n_dindexes, value);
3711 pivot_table_submit (pt);
3715 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3717 enum pivot_axis_type label_pos = t->label_axis[a];
3721 t->clabels_from_axis = a;
3723 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3724 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3726 const struct ctables_stack *stack = &t->stacks[a];
3730 const struct ctables_nest *n0 = &stack->nests[0];
3732 const struct variable *v0 = n0->vars[n0->n - 1];
3733 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3734 t->clabels_example = v0;
3736 for (size_t i = 0; i < c0->n_cats; i++)
3737 if (c0->cats[i].type == CCT_FUNCTION)
3739 msg (SE, _("%s=%s is not allowed with sorting based "
3740 "on a summary function."),
3741 subcommand_name, pos_name);
3744 if (n0->n - 1 == n0->scale_idx)
3746 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3747 "but %s is a scale variable."),
3748 subcommand_name, pos_name, var_get_name (v0));
3752 for (size_t i = 1; i < stack->n; i++)
3754 const struct ctables_nest *ni = &stack->nests[i];
3756 const struct variable *vi = ni->vars[ni->n - 1];
3757 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3759 if (ni->n - 1 == ni->scale_idx)
3761 msg (SE, _("%s=%s requires the variables to be moved to be "
3762 "categorical, but %s is a scale variable."),
3763 subcommand_name, pos_name, var_get_name (vi));
3766 if (var_get_width (v0) != var_get_width (vi))
3768 msg (SE, _("%s=%s requires the variables to be "
3769 "moved to have the same width, but %s has "
3770 "width %d and %s has width %d."),
3771 subcommand_name, pos_name,
3772 var_get_name (v0), var_get_width (v0),
3773 var_get_name (vi), var_get_width (vi));
3776 if (!val_labs_equal (var_get_value_labels (v0),
3777 var_get_value_labels (vi)))
3779 msg (SE, _("%s=%s requires the variables to be "
3780 "moved to have the same value labels, but %s "
3781 "and %s have different value labels."),
3782 subcommand_name, pos_name,
3783 var_get_name (v0), var_get_name (vi));
3786 if (!ctables_categories_equal (c0, ci))
3788 msg (SE, _("%s=%s requires the variables to be "
3789 "moved to have the same category "
3790 "specifications, but %s and %s have different "
3791 "category specifications."),
3792 subcommand_name, pos_name,
3793 var_get_name (v0), var_get_name (vi));
3802 ctables_prepare_table (struct ctables_table *t)
3804 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3807 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3809 for (size_t j = 0; j < t->stacks[a].n; j++)
3811 struct ctables_nest *nest = &t->stacks[a].nests[j];
3812 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3814 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3815 nest->n_domains[dt] = 0;
3817 for (size_t k = 0; k < nest->n; k++)
3819 if (k == nest->scale_idx)
3828 if (a != PIVOT_AXIS_LAYER)
3835 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3836 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3837 : a == PIVOT_AXIS_ROW)
3839 if (k == nest->n - 1
3840 || (nest->scale_idx == nest->n - 1
3841 && k == nest->n - 2))
3847 if (a == PIVOT_AXIS_COLUMN)
3852 if (a == PIVOT_AXIS_ROW)
3857 nest->domains[dt][nest->n_domains[dt]++] = k;
3864 struct ctables_nest *nest = xmalloc (sizeof *nest);
3865 *nest = (struct ctables_nest) { .n = 0 };
3866 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3869 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3870 for (size_t i = 0; i < stack->n; i++)
3872 struct ctables_nest *nest = &stack->nests[i];
3873 if (!nest->specs[CSV_CELL].n)
3875 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3876 specs->specs = xmalloc (sizeof *specs->specs);
3879 enum ctables_summary_function function
3880 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3881 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3883 *specs->specs = (struct ctables_summary_spec) {
3884 .function = function,
3885 .format = ctables_summary_default_format (function, &var),
3886 .label = ctables_summary_default_label (function, 0),
3889 specs->var = nest->vars[0];
3891 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3892 &nest->specs[CSV_CELL]);
3894 else if (!nest->specs[CSV_TOTAL].n)
3895 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3896 &nest->specs[CSV_CELL]);
3899 struct ctables_summary_spec_set *merged = &t->summary_specs;
3900 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3902 for (size_t j = 0; j < stack->n; j++)
3904 const struct ctables_nest *nest = &stack->nests[j];
3906 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3907 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3912 struct merge_item min = items[0];
3913 for (size_t j = 1; j < n_left; j++)
3914 if (merge_item_compare_3way (&items[j], &min) < 0)
3917 if (merged->n >= merged->allocated)
3918 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3919 sizeof *merged->specs);
3920 merged->specs[merged->n++] = min.set->specs[min.ofs];
3922 for (size_t j = 0; j < n_left; )
3924 if (merge_item_compare_3way (&items[j], &min) == 0)
3926 struct merge_item *item = &items[j];
3927 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3928 if (++item->ofs >= item->set->n)
3930 items[j] = items[--n_left];
3939 for (size_t j = 0; j < merged->n; j++)
3940 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3942 for (size_t j = 0; j < stack->n; j++)
3944 const struct ctables_nest *nest = &stack->nests[j];
3945 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3947 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3948 for (size_t k = 0; k < specs->n; k++)
3949 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3950 specs->specs[k].axis_idx);
3956 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3957 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3961 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3962 enum pivot_axis_type a)
3964 struct ctables_stack *stack = &t->stacks[a];
3965 for (size_t i = 0; i < stack->n; i++)
3967 const struct ctables_nest *nest = &stack->nests[i];
3968 const struct variable *var = nest->vars[nest->n - 1];
3969 const union value *value = case_data (c, var);
3971 if (var_is_numeric (var) && value->f == SYSMIS)
3974 if (ctables_categories_match (t->categories [var_get_dict_index (var)],
3976 ctables_value_insert (t, value, var_get_width (var));
3981 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3983 const struct ctables_value *const *ap = a_;
3984 const struct ctables_value *const *bp = b_;
3985 const struct ctables_value *a = *ap;
3986 const struct ctables_value *b = *bp;
3987 const int *width = width_;
3988 return value_compare_3way (&a->value, &b->value, *width);
3992 ctables_sort_clabels_values (struct ctables_table *t)
3994 const struct variable *v0 = t->clabels_example;
3995 int width = var_get_width (v0);
3997 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
4000 const struct val_labs *val_labs = var_get_value_labels (v0);
4001 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4002 vl = val_labs_next (val_labs, vl))
4003 if (ctables_categories_match (c0, &vl->value, v0))
4004 ctables_value_insert (t, &vl->value, width);
4007 size_t n = hmap_count (&t->clabels_values_map);
4008 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
4010 struct ctables_value *clv;
4012 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
4013 t->clabels_values[i++] = clv;
4014 t->n_clabels_values = n;
4017 sort (t->clabels_values, n, sizeof *t->clabels_values,
4018 compare_clabels_values_3way, &width);
4020 for (size_t i = 0; i < n; i++)
4021 t->clabels_values[i]->leaf = i;
4025 ctables_add_category_occurrences (const struct variable *var,
4026 struct hmap *occurrences,
4027 const struct ctables_categories *cats)
4029 const struct val_labs *val_labs = var_get_value_labels (var);
4031 for (size_t i = 0; i < cats->n_cats; i++)
4033 const struct ctables_category *c = &cats->cats[i];
4037 ctables_add_occurrence (var, &(const union value) { .f = c->number },
4045 assert (var_is_numeric (var));
4046 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4047 vl = val_labs_next (val_labs, vl))
4048 if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
4049 ctables_add_occurrence (var, &vl->value, occurrences);
4053 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4054 vl = val_labs_next (val_labs, vl))
4055 if (var_is_value_missing (var, &vl->value))
4056 ctables_add_occurrence (var, &vl->value, occurrences);
4060 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4061 vl = val_labs_next (val_labs, vl))
4062 ctables_add_occurrence (var, &vl->value, occurrences);
4065 case CCT_POSTCOMPUTE:
4075 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4076 vl = val_labs_next (val_labs, vl))
4077 if (c->include_missing || !var_is_value_missing (var, &vl->value))
4078 ctables_add_occurrence (var, &vl->value, occurrences);
4085 ctables_section_recurse_add_empty_categories (
4086 struct ctables_section *s,
4087 const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
4088 enum pivot_axis_type a, size_t a_idx)
4090 if (a >= PIVOT_N_AXES)
4091 ctables_cell_insert__ (s, c, cats);
4092 else if (!s->nests[a] || a_idx >= s->nests[a]->n)
4093 ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
4096 const struct variable *var = s->nests[a]->vars[a_idx];
4097 const struct ctables_categories *categories = s->table->categories[
4098 var_get_dict_index (var)];
4099 int width = var_get_width (var);
4100 const struct hmap *occurrences = &s->occurrences[a][a_idx];
4101 const struct ctables_occurrence *o;
4102 HMAP_FOR_EACH (o, struct ctables_occurrence, node, occurrences)
4104 union value *value = case_data_rw (c, var);
4105 value_destroy (value, width);
4106 value_clone (value, &o->value, width);
4107 cats[a][a_idx] = ctables_categories_match (categories, value, var);
4108 assert (cats[a][a_idx] != NULL);
4109 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
4112 for (size_t i = 0; i < categories->n_cats; i++)
4114 const struct ctables_category *cat = &categories->cats[i];
4115 if (cat->type == CCT_POSTCOMPUTE)
4117 cats[a][a_idx] = cat;
4118 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
4125 ctables_section_add_empty_categories (struct ctables_section *s)
4127 bool show_empty = false;
4128 for (size_t a = 0; a < PIVOT_N_AXES; a++)
4130 for (size_t k = 0; k < s->nests[a]->n; k++)
4131 if (k != s->nests[a]->scale_idx)
4133 const struct variable *var = s->nests[a]->vars[k];
4134 const struct ctables_categories *cats = s->table->categories[
4135 var_get_dict_index (var)];
4136 if (cats->show_empty)
4139 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
4145 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
4146 struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
4147 ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
4152 ctables_execute (struct dataset *ds, struct ctables *ct)
4154 for (size_t i = 0; i < ct->n_tables; i++)
4156 struct ctables_table *t = ct->tables[i];
4157 t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
4158 MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
4159 MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
4160 sizeof *t->sections);
4161 size_t ix[PIVOT_N_AXES];
4162 ctables_table_add_section (t, 0, ix);
4165 struct casereader *input = proc_open (ds);
4166 bool warn_on_invalid = true;
4167 for (struct ccase *c = casereader_read (input); c;
4168 case_unref (c), c = casereader_read (input))
4170 double d_weight = dict_get_case_weight (dataset_dict (ds), c,
4172 double e_weight = (ct->e_weight
4173 ? var_force_valid_weight (ct->e_weight,
4174 case_num (c, ct->e_weight),
4178 for (size_t i = 0; i < ct->n_tables; i++)
4180 struct ctables_table *t = ct->tables[i];
4182 for (size_t j = 0; j < t->n_sections; j++)
4183 ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
4185 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4186 if (t->label_axis[a] != a)
4187 ctables_insert_clabels_values (t, c, a);
4190 casereader_destroy (input);
4192 for (size_t i = 0; i < ct->n_tables; i++)
4194 struct ctables_table *t = ct->tables[i];
4196 if (t->clabels_example)
4197 ctables_sort_clabels_values (t);
4199 for (size_t j = 0; j < t->n_sections; j++)
4200 ctables_section_add_empty_categories (&t->sections[j]);
4202 ctables_table_output (ct, ct->tables[i]);
4204 return proc_commit (ds);
4209 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
4212 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
4218 case CTPO_CAT_STRING:
4228 for (size_t i = 0; i < 2; i++)
4229 ctables_pcexpr_destroy (e->subs[i]);
4233 case CTPO_CAT_NUMBER:
4234 case CTPO_CAT_RANGE:
4235 case CTPO_CAT_MISSING:
4236 case CTPO_CAT_OTHERNM:
4237 case CTPO_CAT_SUBTOTAL:
4238 case CTPO_CAT_TOTAL:
4242 msg_location_destroy (e->location);
4247 static struct ctables_pcexpr *
4248 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
4249 struct ctables_pcexpr *sub0,
4250 struct ctables_pcexpr *sub1)
4252 struct ctables_pcexpr *e = xmalloc (sizeof *e);
4253 *e = (struct ctables_pcexpr) {
4255 .subs = { sub0, sub1 },
4256 .location = msg_location_merged (sub0->location, sub1->location),
4261 /* How to parse an operator. */
4264 enum token_type token;
4265 enum ctables_postcompute_op op;
4268 static const struct operator *
4269 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
4271 for (const struct operator *op = ops; op < ops + n_ops; op++)
4272 if (lex_token (lexer) == op->token)
4274 if (op->token != T_NEG_NUM)
4283 static struct ctables_pcexpr *
4284 parse_binary_operators__ (struct lexer *lexer,
4285 const struct operator ops[], size_t n_ops,
4286 parse_recursively_func *parse_next_level,
4287 const char *chain_warning,
4288 struct ctables_pcexpr *lhs)
4290 for (int op_count = 0; ; op_count++)
4292 const struct operator *op = match_operator (lexer, ops, n_ops);
4295 if (op_count > 1 && chain_warning)
4296 msg_at (SW, lhs->location, "%s", chain_warning);
4301 struct ctables_pcexpr *rhs = parse_next_level (lexer);
4304 ctables_pcexpr_destroy (lhs);
4308 lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
4312 static struct ctables_pcexpr *
4313 parse_binary_operators (struct lexer *lexer,
4314 const struct operator ops[], size_t n_ops,
4315 parse_recursively_func *parse_next_level,
4316 const char *chain_warning)
4318 struct ctables_pcexpr *lhs = parse_next_level (lexer);
4322 return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
4323 chain_warning, lhs);
4326 static struct ctables_pcexpr *parse_add (struct lexer *);
4328 static struct ctables_pcexpr
4329 ctpo_cat_range (double low, double high)
4331 return (struct ctables_pcexpr) {
4332 .op = CTPO_CAT_RANGE,
4333 .range = { low, high },
4337 static struct ctables_pcexpr *
4338 parse_primary (struct lexer *lexer)
4340 int start_ofs = lex_ofs (lexer);
4341 struct ctables_pcexpr e;
4342 if (lex_is_number (lexer))
4344 e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
4345 .number = lex_number (lexer) };
4348 else if (lex_match_id (lexer, "MISSING"))
4349 e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
4350 else if (lex_match_id (lexer, "OTHERNM"))
4351 e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
4352 else if (lex_match_id (lexer, "TOTAL"))
4353 e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
4354 else if (lex_match_id (lexer, "SUBTOTAL"))
4356 size_t subtotal_index = 0;
4357 if (lex_match (lexer, T_LBRACK))
4359 if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
4361 subtotal_index = lex_integer (lexer);
4363 if (!lex_force_match (lexer, T_RBRACK))
4366 e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
4367 .subtotal_index = subtotal_index };
4369 else if (lex_match (lexer, T_LBRACK))
4371 if (lex_match_id (lexer, "LO"))
4373 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
4375 e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
4378 else if (lex_is_number (lexer))
4380 double number = lex_number (lexer);
4382 if (lex_match_id (lexer, "THRU"))
4384 if (lex_match_id (lexer, "HI"))
4385 e = ctpo_cat_range (number, DBL_MAX);
4388 if (!lex_force_num (lexer))
4390 e = ctpo_cat_range (number, lex_number (lexer));
4395 e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
4398 else if (lex_is_string (lexer))
4400 e = (struct ctables_pcexpr) {
4401 .op = CTPO_CAT_STRING,
4402 .string = ss_xstrdup (lex_tokss (lexer)),
4408 lex_error (lexer, NULL);
4412 if (!lex_force_match (lexer, T_RBRACK))
4414 if (e.op == CTPO_CAT_STRING)
4419 else if (lex_match (lexer, T_LPAREN))
4421 struct ctables_pcexpr *ep = parse_add (lexer);
4424 if (!lex_force_match (lexer, T_RPAREN))
4426 ctables_pcexpr_destroy (ep);
4433 lex_error (lexer, NULL);
4437 e.location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
4438 return xmemdup (&e, sizeof e);
4441 static struct ctables_pcexpr *
4442 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
4443 struct lexer *lexer, int start_ofs)
4445 struct ctables_pcexpr *e = xmalloc (sizeof *e);
4446 *e = (struct ctables_pcexpr) {
4449 .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
4454 static struct ctables_pcexpr *
4455 parse_exp (struct lexer *lexer)
4457 static const struct operator op = { T_EXP, CTPO_POW };
4459 const char *chain_warning =
4460 _("The exponentiation operator (`**') is left-associative: "
4461 "`a**b**c' equals `(a**b)**c', not `a**(b**c)'. "
4462 "To disable this warning, insert parentheses.");
4464 if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
4465 return parse_binary_operators (lexer, &op, 1,
4466 parse_primary, chain_warning);
4468 /* Special case for situations like "-5**6", which must be parsed as
4471 int start_ofs = lex_ofs (lexer);
4472 struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
4473 *lhs = (struct ctables_pcexpr) {
4474 .op = CTPO_CONSTANT,
4475 .number = -lex_tokval (lexer),
4476 .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer)),
4480 struct ctables_pcexpr *node = parse_binary_operators__ (
4481 lexer, &op, 1, parse_primary, chain_warning, lhs);
4485 return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
4488 /* Parses the unary minus level. */
4489 static struct ctables_pcexpr *
4490 parse_neg (struct lexer *lexer)
4492 int start_ofs = lex_ofs (lexer);
4493 if (!lex_match (lexer, T_DASH))
4494 return parse_exp (lexer);
4496 struct ctables_pcexpr *inner = parse_neg (lexer);
4500 return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
4503 /* Parses the multiplication and division level. */
4504 static struct ctables_pcexpr *
4505 parse_mul (struct lexer *lexer)
4507 static const struct operator ops[] =
4509 { T_ASTERISK, CTPO_MUL },
4510 { T_SLASH, CTPO_DIV },
4513 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4517 /* Parses the addition and subtraction level. */
4518 static struct ctables_pcexpr *
4519 parse_add (struct lexer *lexer)
4521 static const struct operator ops[] =
4523 { T_PLUS, CTPO_ADD },
4524 { T_DASH, CTPO_SUB },
4525 { T_NEG_NUM, CTPO_ADD },
4528 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4532 static struct ctables_postcompute *
4533 ctables_find_postcompute (struct ctables *ct, const char *name)
4535 struct ctables_postcompute *pc;
4536 HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
4537 utf8_hash_case_string (name, 0), &ct->postcomputes)
4538 if (!utf8_strcasecmp (pc->name, name))
4544 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
4546 int pcompute_start = lex_ofs (lexer) - 1;
4548 if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
4551 char *name = ss_xstrdup (lex_tokss (lexer));
4554 if (!lex_force_match (lexer, T_EQUALS)
4555 || !lex_force_match_id (lexer, "EXPR")
4556 || !lex_force_match (lexer, T_LPAREN))
4562 int expr_start = lex_ofs (lexer);
4563 struct ctables_pcexpr *expr = parse_add (lexer);
4564 int expr_end = lex_ofs (lexer) - 1;
4565 if (!expr || !lex_force_match (lexer, T_RPAREN))
4570 int pcompute_end = lex_ofs (lexer) - 1;
4572 struct msg_location *location = lex_ofs_location (lexer, pcompute_start,
4575 struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
4578 msg_at (SW, location, _("New definition of &%s will override the "
4579 "previous definition."),
4581 msg_at (SN, pc->location, _("This is the previous definition."));
4583 ctables_pcexpr_destroy (pc->expr);
4584 msg_location_destroy (pc->location);
4589 pc = xmalloc (sizeof *pc);
4590 *pc = (struct ctables_postcompute) { .name = name };
4591 hmap_insert (&ct->postcomputes, &pc->hmap_node,
4592 utf8_hash_case_string (pc->name, 0));
4595 pc->location = location;
4597 pc->label = lex_ofs_representation (lexer, expr_start, expr_end);
4602 ctables_parse_pproperties_format (struct lexer *lexer,
4603 struct ctables_summary_spec_set *sss)
4605 *sss = (struct ctables_summary_spec_set) { .n = 0 };
4607 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4608 && !(lex_token (lexer) == T_ID
4609 && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4610 || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4611 lex_tokss (lexer)))))
4613 /* Parse function. */
4614 enum ctables_summary_function function;
4615 if (!parse_ctables_summary_function (lexer, &function))
4618 /* Parse percentile. */
4619 double percentile = 0;
4620 if (function == CTSF_PTILE)
4622 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4624 percentile = lex_number (lexer);
4629 struct fmt_spec format;
4630 if (!parse_format_specifier (lexer, &format)
4631 || !fmt_check_output (&format)
4632 || !fmt_check_type_compat (&format, VAL_NUMERIC))
4635 if (sss->n >= sss->allocated)
4636 sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4637 sizeof *sss->specs);
4638 sss->specs[sss->n++] = (struct ctables_summary_spec) {
4639 .function = function,
4640 .percentile = percentile,
4647 ctables_summary_spec_set_uninit (sss);
4652 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4654 struct ctables_postcompute **pcs = NULL;
4656 size_t allocated_pcs = 0;
4658 while (lex_match (lexer, T_AND))
4660 if (!lex_force_id (lexer))
4662 struct ctables_postcompute *pc
4663 = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4666 msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4671 if (n_pcs >= allocated_pcs)
4672 pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4676 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4678 if (lex_match_id (lexer, "LABEL"))
4680 lex_match (lexer, T_EQUALS);
4681 if (!lex_force_string (lexer))
4684 for (size_t i = 0; i < n_pcs; i++)
4686 free (pcs[i]->label);
4687 pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4692 else if (lex_match_id (lexer, "FORMAT"))
4694 lex_match (lexer, T_EQUALS);
4696 struct ctables_summary_spec_set sss;
4697 if (!ctables_parse_pproperties_format (lexer, &sss))
4700 for (size_t i = 0; i < n_pcs; i++)
4703 ctables_summary_spec_set_uninit (pcs[i]->specs);
4705 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4706 ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4708 ctables_summary_spec_set_uninit (&sss);
4710 else if (lex_match_id (lexer, "HIDESOURCECATS"))
4712 lex_match (lexer, T_EQUALS);
4713 bool hide_source_cats;
4714 if (!parse_bool (lexer, &hide_source_cats))
4716 for (size_t i = 0; i < n_pcs; i++)
4717 pcs[i]->hide_source_cats = hide_source_cats;
4721 lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4734 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4736 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4737 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4738 enum settings_value_show tvars = settings_get_show_variables ();
4739 for (size_t i = 0; i < n_vars; i++)
4740 vlabels[i] = (enum ctables_vlabel) tvars;
4742 struct pivot_table_look *look = pivot_table_look_unshare (
4743 pivot_table_look_ref (pivot_table_look_get_default ()));
4744 look->omit_empty = false;
4746 struct ctables *ct = xmalloc (sizeof *ct);
4747 *ct = (struct ctables) {
4748 .dict = dataset_dict (ds),
4750 .ctables_formats = FMT_SETTINGS_INIT,
4752 .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
4758 const char *dot_string;
4759 const char *comma_string;
4761 static const struct ctf ctfs[4] = {
4762 { CTEF_NEGPAREN, "(,,,)", "(...)" },
4763 { CTEF_NEQUAL, "-,N=,,", "-.N=.." },
4764 { CTEF_PAREN, "-,(,),", "-.(.)." },
4765 { CTEF_PCTPAREN, "-,(,%),", "-.(.%)." },
4767 bool is_dot = settings_get_fmt_settings ()->decimal == '.';
4768 for (size_t i = 0; i < 4; i++)
4770 const char *s = is_dot ? ctfs[i].dot_string : ctfs[i].comma_string;
4771 fmt_settings_set_cc (&ct->ctables_formats, ctfs[i].type,
4772 fmt_number_style_from_string (s));
4775 if (!lex_force_match (lexer, T_SLASH))
4778 while (!lex_match_id (lexer, "TABLE"))
4780 if (lex_match_id (lexer, "FORMAT"))
4782 double widths[2] = { SYSMIS, SYSMIS };
4783 double units_per_inch = 72.0;
4785 while (lex_token (lexer) != T_SLASH)
4787 if (lex_match_id (lexer, "MINCOLWIDTH"))
4789 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4792 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4794 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4797 else if (lex_match_id (lexer, "UNITS"))
4799 lex_match (lexer, T_EQUALS);
4800 if (lex_match_id (lexer, "POINTS"))
4801 units_per_inch = 72.0;
4802 else if (lex_match_id (lexer, "INCHES"))
4803 units_per_inch = 1.0;
4804 else if (lex_match_id (lexer, "CM"))
4805 units_per_inch = 2.54;
4808 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4812 else if (lex_match_id (lexer, "EMPTY"))
4817 lex_match (lexer, T_EQUALS);
4818 if (lex_match_id (lexer, "ZERO"))
4820 /* Nothing to do. */
4822 else if (lex_match_id (lexer, "BLANK"))
4823 ct->zero = xstrdup ("");
4824 else if (lex_force_string (lexer))
4826 ct->zero = ss_xstrdup (lex_tokss (lexer));
4832 else if (lex_match_id (lexer, "MISSING"))
4834 lex_match (lexer, T_EQUALS);
4835 if (!lex_force_string (lexer))
4839 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4840 ? ss_xstrdup (lex_tokss (lexer))
4846 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4847 "UNITS", "EMPTY", "MISSING");
4852 if (widths[0] != SYSMIS && widths[1] != SYSMIS
4853 && widths[0] > widths[1])
4855 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4859 for (size_t i = 0; i < 2; i++)
4860 if (widths[i] != SYSMIS)
4862 int *wr = ct->look->width_ranges[TABLE_HORZ];
4863 wr[i] = widths[i] / units_per_inch * 96.0;
4868 else if (lex_match_id (lexer, "VLABELS"))
4870 if (!lex_force_match_id (lexer, "VARIABLES"))
4872 lex_match (lexer, T_EQUALS);
4874 struct variable **vars;
4876 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4880 if (!lex_force_match_id (lexer, "DISPLAY"))
4885 lex_match (lexer, T_EQUALS);
4887 enum ctables_vlabel vlabel;
4888 if (lex_match_id (lexer, "DEFAULT"))
4889 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4890 else if (lex_match_id (lexer, "NAME"))
4892 else if (lex_match_id (lexer, "LABEL"))
4893 vlabel = CTVL_LABEL;
4894 else if (lex_match_id (lexer, "BOTH"))
4896 else if (lex_match_id (lexer, "NONE"))
4900 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4906 for (size_t i = 0; i < n_vars; i++)
4907 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4910 else if (lex_match_id (lexer, "MRSETS"))
4912 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4914 lex_match (lexer, T_EQUALS);
4915 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4918 else if (lex_match_id (lexer, "SMISSING"))
4920 if (lex_match_id (lexer, "VARIABLE"))
4921 ct->smissing_listwise = false;
4922 else if (lex_match_id (lexer, "LISTWISE"))
4923 ct->smissing_listwise = true;
4926 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4930 else if (lex_match_id (lexer, "PCOMPUTE"))
4932 if (!ctables_parse_pcompute (lexer, ct))
4935 else if (lex_match_id (lexer, "PPROPERTIES"))
4937 if (!ctables_parse_pproperties (lexer, ct))
4940 else if (lex_match_id (lexer, "WEIGHT"))
4942 if (!lex_force_match_id (lexer, "VARIABLE"))
4944 lex_match (lexer, T_EQUALS);
4945 ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4949 else if (lex_match_id (lexer, " HIDESMALLCOUNTS"))
4951 if (lex_match_id (lexer, "COUNT"))
4953 lex_match (lexer, T_EQUALS);
4954 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT",
4957 ct->hide_threshold = lex_integer (lexer);
4960 else if (ct->hide_threshold == 0)
4961 ct->hide_threshold = 5;
4965 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4966 "SMISSING", "PCOMPUTE", "PPROPERTIES",
4967 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4971 if (!lex_force_match (lexer, T_SLASH))
4975 size_t allocated_tables = 0;
4978 if (ct->n_tables >= allocated_tables)
4979 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4980 sizeof *ct->tables);
4982 struct ctables_category *cat = xmalloc (sizeof *cat);
4983 *cat = (struct ctables_category) {
4985 .include_missing = false,
4986 .sort_ascending = true,
4989 struct ctables_categories *c = xmalloc (sizeof *c);
4990 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4991 *c = (struct ctables_categories) {
4998 struct ctables_categories **categories = xnmalloc (n_vars,
4999 sizeof *categories);
5000 for (size_t i = 0; i < n_vars; i++)
5003 struct ctables_table *t = xmalloc (sizeof *t);
5004 *t = (struct ctables_table) {
5006 .slabels_axis = PIVOT_AXIS_COLUMN,
5007 .slabels_visible = true,
5008 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
5010 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
5011 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
5012 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
5014 .clabels_from_axis = PIVOT_AXIS_LAYER,
5015 .categories = categories,
5016 .n_categories = n_vars,
5019 ct->tables[ct->n_tables++] = t;
5021 lex_match (lexer, T_EQUALS);
5022 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
5024 if (lex_match (lexer, T_BY))
5026 if (!ctables_axis_parse (lexer, dataset_dict (ds),
5027 ct, t, PIVOT_AXIS_COLUMN))
5030 if (lex_match (lexer, T_BY))
5032 if (!ctables_axis_parse (lexer, dataset_dict (ds),
5033 ct, t, PIVOT_AXIS_LAYER))
5038 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
5039 && !t->axes[PIVOT_AXIS_LAYER])
5041 lex_error (lexer, _("At least one variable must be specified."));
5045 const struct ctables_axis *scales[PIVOT_N_AXES];
5046 size_t n_scales = 0;
5047 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
5049 scales[a] = find_scale (t->axes[a]);
5055 msg (SE, _("Scale variables may appear only on one axis."));
5056 if (scales[PIVOT_AXIS_ROW])
5057 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
5058 _("This scale variable appears on the rows axis."));
5059 if (scales[PIVOT_AXIS_COLUMN])
5060 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
5061 _("This scale variable appears on the columns axis."));
5062 if (scales[PIVOT_AXIS_LAYER])
5063 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
5064 _("This scale variable appears on the layer axis."));
5068 const struct ctables_axis *summaries[PIVOT_N_AXES];
5069 size_t n_summaries = 0;
5070 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
5072 summaries[a] = (scales[a]
5074 : find_categorical_summary_spec (t->axes[a]));
5078 if (n_summaries > 1)
5080 msg (SE, _("Summaries may appear only on one axis."));
5081 if (summaries[PIVOT_AXIS_ROW])
5082 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
5083 _("This variable on the rows axis has a summary."));
5084 if (summaries[PIVOT_AXIS_COLUMN])
5085 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
5086 _("This variable on the columns axis has a summary."));
5087 if (summaries[PIVOT_AXIS_LAYER])
5088 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
5089 _("This variable on the layers axis has a summary."));
5092 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
5093 if (n_summaries ? summaries[a] : t->axes[a])
5095 t->summary_axis = a;
5099 if (lex_token (lexer) == T_ENDCMD)
5101 if (!ctables_prepare_table (t))
5105 if (!lex_force_match (lexer, T_SLASH))
5108 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
5110 if (lex_match_id (lexer, "SLABELS"))
5112 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
5114 if (lex_match_id (lexer, "POSITION"))
5116 lex_match (lexer, T_EQUALS);
5117 if (lex_match_id (lexer, "COLUMN"))
5118 t->slabels_axis = PIVOT_AXIS_COLUMN;
5119 else if (lex_match_id (lexer, "ROW"))
5120 t->slabels_axis = PIVOT_AXIS_ROW;
5121 else if (lex_match_id (lexer, "LAYER"))
5122 t->slabels_axis = PIVOT_AXIS_LAYER;
5125 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
5129 else if (lex_match_id (lexer, "VISIBLE"))
5131 lex_match (lexer, T_EQUALS);
5132 if (!parse_bool (lexer, &t->slabels_visible))
5137 lex_error_expecting (lexer, "POSITION", "VISIBLE");
5142 else if (lex_match_id (lexer, "CLABELS"))
5144 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
5146 if (lex_match_id (lexer, "AUTO"))
5148 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
5149 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
5151 else if (lex_match_id (lexer, "ROWLABELS"))
5153 lex_match (lexer, T_EQUALS);
5154 if (lex_match_id (lexer, "OPPOSITE"))
5155 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
5156 else if (lex_match_id (lexer, "LAYER"))
5157 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
5160 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5164 else if (lex_match_id (lexer, "COLLABELS"))
5166 lex_match (lexer, T_EQUALS);
5167 if (lex_match_id (lexer, "OPPOSITE"))
5168 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
5169 else if (lex_match_id (lexer, "LAYER"))
5170 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
5173 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5179 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
5185 else if (lex_match_id (lexer, "CRITERIA"))
5187 if (!lex_force_match_id (lexer, "CILEVEL"))
5189 lex_match (lexer, T_EQUALS);
5191 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
5193 t->cilevel = lex_number (lexer);
5196 else if (lex_match_id (lexer, "CATEGORIES"))
5198 if (!ctables_table_parse_categories (lexer, dataset_dict (ds),
5202 else if (lex_match_id (lexer, "TITLES"))
5207 if (lex_match_id (lexer, "CAPTION"))
5208 textp = &t->caption;
5209 else if (lex_match_id (lexer, "CORNER"))
5211 else if (lex_match_id (lexer, "TITLE"))
5215 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
5218 lex_match (lexer, T_EQUALS);
5220 struct string s = DS_EMPTY_INITIALIZER;
5221 while (lex_is_string (lexer))
5223 if (!ds_is_empty (&s))
5224 ds_put_byte (&s, ' ');
5225 ds_put_substring (&s, lex_tokss (lexer));
5229 *textp = ds_steal_cstr (&s);
5231 while (lex_token (lexer) != T_SLASH
5232 && lex_token (lexer) != T_ENDCMD);
5234 else if (lex_match_id (lexer, "SIGTEST"))
5238 t->chisq = xmalloc (sizeof *t->chisq);
5239 *t->chisq = (struct ctables_chisq) {
5241 .include_mrsets = true,
5242 .all_visible = true,
5248 if (lex_match_id (lexer, "TYPE"))
5250 lex_match (lexer, T_EQUALS);
5251 if (!lex_force_match_id (lexer, "CHISQUARE"))
5254 else if (lex_match_id (lexer, "ALPHA"))
5256 lex_match (lexer, T_EQUALS);
5257 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
5259 t->chisq->alpha = lex_number (lexer);
5262 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5264 lex_match (lexer, T_EQUALS);
5265 if (parse_bool (lexer, &t->chisq->include_mrsets))
5268 else if (lex_match_id (lexer, "CATEGORIES"))
5270 lex_match (lexer, T_EQUALS);
5271 if (lex_match_id (lexer, "ALLVISIBLE"))
5272 t->chisq->all_visible = true;
5273 else if (lex_match_id (lexer, "SUBTOTALS"))
5274 t->chisq->all_visible = false;
5277 lex_error_expecting (lexer,
5278 "ALLVISIBLE", "SUBTOTALS");
5284 lex_error_expecting (lexer, "TYPE", "ALPHA",
5285 "INCLUDEMRSETS", "CATEGORIES");
5289 while (lex_token (lexer) != T_SLASH
5290 && lex_token (lexer) != T_ENDCMD);
5292 else if (lex_match_id (lexer, "COMPARETEST"))
5296 t->pairwise = xmalloc (sizeof *t->pairwise);
5297 *t->pairwise = (struct ctables_pairwise) {
5299 .alpha = { .05, .05 },
5300 .adjust = BONFERRONI,
5301 .include_mrsets = true,
5302 .meansvariance_allcats = true,
5303 .all_visible = true,
5312 if (lex_match_id (lexer, "TYPE"))
5314 lex_match (lexer, T_EQUALS);
5315 if (lex_match_id (lexer, "PROP"))
5316 t->pairwise->type = PROP;
5317 else if (lex_match_id (lexer, "MEAN"))
5318 t->pairwise->type = MEAN;
5321 lex_error_expecting (lexer, "PROP", "MEAN");
5325 else if (lex_match_id (lexer, "ALPHA"))
5327 lex_match (lexer, T_EQUALS);
5329 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5331 double a0 = lex_number (lexer);
5334 lex_match (lexer, T_COMMA);
5335 if (lex_is_number (lexer))
5337 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5339 double a1 = lex_number (lexer);
5342 t->pairwise->alpha[0] = MIN (a0, a1);
5343 t->pairwise->alpha[1] = MAX (a0, a1);
5346 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
5348 else if (lex_match_id (lexer, "ADJUST"))
5350 lex_match (lexer, T_EQUALS);
5351 if (lex_match_id (lexer, "BONFERRONI"))
5352 t->pairwise->adjust = BONFERRONI;
5353 else if (lex_match_id (lexer, "BH"))
5354 t->pairwise->adjust = BH;
5355 else if (lex_match_id (lexer, "NONE"))
5356 t->pairwise->adjust = 0;
5359 lex_error_expecting (lexer, "BONFERRONI", "BH",
5364 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5366 lex_match (lexer, T_EQUALS);
5367 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
5370 else if (lex_match_id (lexer, "MEANSVARIANCE"))
5372 lex_match (lexer, T_EQUALS);
5373 if (lex_match_id (lexer, "ALLCATS"))
5374 t->pairwise->meansvariance_allcats = true;
5375 else if (lex_match_id (lexer, "TESTEDCATS"))
5376 t->pairwise->meansvariance_allcats = false;
5379 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
5383 else if (lex_match_id (lexer, "CATEGORIES"))
5385 lex_match (lexer, T_EQUALS);
5386 if (lex_match_id (lexer, "ALLVISIBLE"))
5387 t->pairwise->all_visible = true;
5388 else if (lex_match_id (lexer, "SUBTOTALS"))
5389 t->pairwise->all_visible = false;
5392 lex_error_expecting (lexer, "ALLVISIBLE",
5397 else if (lex_match_id (lexer, "MERGE"))
5399 lex_match (lexer, T_EQUALS);
5400 if (!parse_bool (lexer, &t->pairwise->merge))
5403 else if (lex_match_id (lexer, "STYLE"))
5405 lex_match (lexer, T_EQUALS);
5406 if (lex_match_id (lexer, "APA"))
5407 t->pairwise->apa_style = true;
5408 else if (lex_match_id (lexer, "SIMPLE"))
5409 t->pairwise->apa_style = false;
5412 lex_error_expecting (lexer, "APA", "SIMPLE");
5416 else if (lex_match_id (lexer, "SHOWSIG"))
5418 lex_match (lexer, T_EQUALS);
5419 if (!parse_bool (lexer, &t->pairwise->show_sig))
5424 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
5425 "INCLUDEMRSETS", "MEANSVARIANCE",
5426 "CATEGORIES", "MERGE", "STYLE",
5431 while (lex_token (lexer) != T_SLASH
5432 && lex_token (lexer) != T_ENDCMD);
5436 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
5437 "CRITERIA", "CATEGORIES", "TITLES",
5438 "SIGTEST", "COMPARETEST");
5442 if (!lex_match (lexer, T_SLASH))
5446 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
5447 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
5449 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
5453 if (!ctables_prepare_table (t))
5456 while (lex_token (lexer) != T_ENDCMD);
5458 bool ok = ctables_execute (ds, ct);
5459 ctables_destroy (ct);
5460 return ok ? CMD_SUCCESS : CMD_FAILURE;
5463 ctables_destroy (ct);