1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2021 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "data/casereader.h"
22 #include "data/casewriter.h"
23 #include "data/dataset.h"
24 #include "data/dictionary.h"
25 #include "data/mrset.h"
26 #include "data/subcase.h"
27 #include "data/value-labels.h"
28 #include "language/command.h"
29 #include "language/lexer/format-parser.h"
30 #include "language/lexer/lexer.h"
31 #include "language/lexer/variable-parser.h"
32 #include "libpspp/array.h"
33 #include "libpspp/assertion.h"
34 #include "libpspp/hash-functions.h"
35 #include "libpspp/hmap.h"
36 #include "libpspp/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/string-array.h"
39 #include "math/mode.h"
40 #include "math/moments.h"
41 #include "math/percentiles.h"
42 #include "math/sort.h"
43 #include "output/pivot-table.h"
45 #include "gl/minmax.h"
46 #include "gl/xalloc.h"
49 #define _(msgid) gettext (msgid)
50 #define N_(msgid) (msgid)
54 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
55 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
56 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
57 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
61 - unweighted summaries (U*)
62 - lower confidence limits (*.LCL)
63 - upper confidence limits (*.UCL)
64 - standard error (*.SE)
67 /* All variables. */ \
68 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
69 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
70 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
71 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
72 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
85 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
86 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
87 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
88 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
89 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
90 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
92 /* Scale variables, totals, and subtotals. */ \
93 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
94 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
95 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
98 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
99 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
100 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
101 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
102 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
103 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
104 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
105 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
106 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
107 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
108 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
109 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
110 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
111 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
112 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
113 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
114 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
115 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
117 /* Multiple response sets. */ \
118 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
119 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
120 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
121 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
134 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
135 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
141 enum ctables_summary_function
143 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
149 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
150 N_CTSF_FUNCTIONS = SUMMARIES
154 enum ctables_domain_type
156 /* Within a section, where stacked variables divide one section from
158 CTDT_TABLE, /* All layers of a whole section. */
159 CTDT_LAYER, /* One layer within a section. */
160 CTDT_LAYERROW, /* Row in one layer within a section. */
161 CTDT_LAYERCOL, /* Column in one layer within a section. */
163 /* Within a subtable, where a subtable pairs an innermost row variable with
164 an innermost column variable within a single layer. */
165 CTDT_SUBTABLE, /* Whole subtable. */
166 CTDT_ROW, /* Row within a subtable. */
167 CTDT_COL, /* Column within a subtable. */
171 struct ctables_domain
173 struct hmap_node node;
175 const struct ctables_cell *example;
177 double d_valid; /* Dictionary weight. */
179 double e_valid; /* Effective weight */
183 enum ctables_summary_variant
192 /* In struct ctables_section's 'cells' hmap. Indexed by all the values in
193 all the axes (except the scalar variable, if any). */
194 struct hmap_node node;
196 /* The domains that contain this cell. */
197 bool contributes_to_domains;
198 struct ctables_domain *domains[N_CTDTS];
201 enum ctables_summary_variant sv;
203 struct ctables_cell_axis
205 struct ctables_cell_value
207 const struct ctables_category *category;
215 union ctables_summary *summaries;
220 const struct dictionary *dict;
221 struct pivot_table_look *look;
223 /* If this is NULL, zeros are displayed using the normal print format.
224 Otherwise, this string is displayed. */
227 /* If this is NULL, missing values are displayed using the normal print
228 format. Otherwise, this string is displayed. */
231 /* Indexed by variable dictionary index. */
232 enum ctables_vlabel *vlabels;
234 struct hmap postcomputes; /* Contains "struct ctables_postcompute"s. */
236 bool mrsets_count_duplicates; /* MRSETS. */
237 bool smissing_listwise; /* SMISSING. */
238 struct variable *e_weight; /* WEIGHT. */
239 int hide_threshold; /* HIDESMALLCOUNTS. */
241 struct ctables_table **tables;
245 struct ctables_postcompute
247 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
248 char *name; /* Name, without leading &. */
250 struct msg_location *location; /* Location of definition. */
251 struct ctables_pcexpr *expr;
253 struct ctables_summary_spec_set *specs;
254 bool hide_source_cats;
257 struct ctables_pcexpr
267 enum ctables_postcompute_op
270 CTPO_CONSTANT, /* 5 */
271 CTPO_CAT_NUMBER, /* [5] */
272 CTPO_CAT_STRING, /* ["STRING"] */
273 CTPO_CAT_RANGE, /* [LO THRU 5] */
274 CTPO_CAT_MISSING, /* MISSING */
275 CTPO_CAT_OTHERNM, /* OTHERNM */
276 CTPO_CAT_SUBTOTAL, /* SUBTOTAL */
277 CTPO_CAT_TOTAL, /* TOTAL */
291 /* CTPO_CAT_NUMBER. */
294 /* CTPO_CAT_STRING. */
297 /* CTPO_CAT_RANGE. */
300 /* CTPO_CAT_SUBTOTAL. */
301 size_t subtotal_index;
303 /* Two elements: CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW.
304 One element: CTPO_NEG. */
305 struct ctables_pcexpr *subs[2];
308 /* Source location. */
310 struct msg_location *location;
313 static void ctables_pcexpr_destroy (struct ctables_pcexpr *);
314 static struct ctables_pcexpr *ctables_pcexpr_allocate_binary (
315 enum ctables_postcompute_op, struct ctables_pcexpr *sub0,
316 struct ctables_pcexpr *sub1);
318 struct ctables_summary_spec_set
320 struct ctables_summary_spec *specs;
324 struct variable *var;
327 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
328 const struct ctables_summary_spec_set *);
329 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
331 /* A nested sequence of variables, e.g. a > b > c. */
334 struct variable **vars;
337 size_t *domains[N_CTDTS];
338 size_t n_domains[N_CTDTS];
340 struct ctables_summary_spec_set specs[N_CSVS];
343 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
346 struct ctables_nest *nests;
352 struct hmap_node node;
357 struct ctables_section_value
359 struct hmap_node node;
363 struct ctables_section
365 struct ctables_table *table;
366 struct ctables_nest *nests[PIVOT_N_AXES];
367 struct hmap *occurrences[PIVOT_N_AXES];
368 struct hmap cells; /* Contains "struct ctable_cell"s. */
369 struct hmap domains[N_CTDTS]; /* Contains "struct ctable_domain"s. */
374 struct ctables *ctables;
375 struct ctables_axis *axes[PIVOT_N_AXES];
376 struct ctables_stack stacks[PIVOT_N_AXES];
377 struct ctables_section *sections;
379 enum pivot_axis_type summary_axis;
380 struct ctables_summary_spec_set summary_specs;
382 const struct variable *clabels_example;
383 struct hmap clabels_values_map;
384 struct ctables_value **clabels_values;
385 size_t n_clabels_values;
387 enum pivot_axis_type slabels_axis;
388 bool slabels_visible;
390 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
392 Most commonly, label_axis[a] == a, and in particular we always have
393 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
395 If ROWLABELS or COLLABELS is specified, then one of
396 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
397 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
399 enum pivot_axis_type label_axis[PIVOT_N_AXES];
400 enum pivot_axis_type clabels_from_axis;
402 /* Indexed by variable dictionary index. */
403 struct ctables_categories **categories;
412 struct ctables_chisq *chisq;
413 struct ctables_pairwise *pairwise;
421 struct variable *var;
422 const struct mrset *mrset;
426 static const struct fmt_spec *
427 ctables_var_get_print_format (const struct ctables_var *var)
429 return (var->is_mrset
430 ? var_get_print_format (var->mrset->vars[0])
431 : var_get_print_format (var->var));
435 ctables_var_name (const struct ctables_var *var)
437 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
440 struct ctables_categories
443 struct ctables_category *cats;
448 struct ctables_category
450 enum ctables_category_type
452 /* Explicit category lists. */
459 /* Totals and subtotals. */
464 /* Implicit category lists. */
471 struct ctables_category *subtotal;
475 double number; /* CCT_NUMBER. */
476 char *string; /* CCT_STRING. */
477 double range[2]; /* CCT_RANGE. */
478 char *total_label; /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
480 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
483 bool include_missing;
487 enum ctables_summary_function sort_function;
488 struct variable *sort_var;
495 ctables_category_uninit (struct ctables_category *cat)
515 free (cat->total_label);
526 ctables_category_equal (const struct ctables_category *a,
527 const struct ctables_category *b)
529 if (a->type != b->type)
535 return a->number == b->number;
538 return strcmp (a->string, b->string);
541 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
550 return !strcmp (a->total_label, b->total_label);
555 return (a->include_missing == b->include_missing
556 && a->sort_ascending == b->sort_ascending
557 && a->sort_function == b->sort_function
558 && a->sort_var == b->sort_var
559 && a->percentile == b->percentile);
566 ctables_categories_unref (struct ctables_categories *c)
571 assert (c->n_refs > 0);
575 for (size_t i = 0; i < c->n_cats; i++)
576 ctables_category_uninit (&c->cats[i]);
582 ctables_categories_equal (const struct ctables_categories *a,
583 const struct ctables_categories *b)
585 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
588 for (size_t i = 0; i < a->n_cats; i++)
589 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
595 /* Chi-square test (SIGTEST). */
603 /* Pairwise comparison test (COMPARETEST). */
604 struct ctables_pairwise
606 enum { PROP, MEAN } type;
609 bool meansvariance_allcats;
611 enum { BONFERRONI = 1, BH } adjust;
635 struct ctables_var var;
637 struct ctables_summary_spec_set specs[N_CSVS];
641 struct ctables_axis *subs[2];
644 struct msg_location *loc;
647 static void ctables_axis_destroy (struct ctables_axis *);
656 enum ctables_function_availability
658 CTFA_ALL, /* Any variables. */
659 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
660 CTFA_MRSETS, /* Only multiple-response sets */
663 struct ctables_summary_spec
665 enum ctables_summary_function function;
666 double percentile; /* CTSF_PTILE only. */
668 struct fmt_spec format; /* XXX extra CTABLES formats */
673 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
674 const struct ctables_summary_spec *src)
677 dst->label = xstrdup (src->label);
681 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
688 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
689 const struct ctables_summary_spec_set *src)
691 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
692 for (size_t i = 0; i < src->n; i++)
693 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
695 *dst = (struct ctables_summary_spec_set) {
704 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
706 for (size_t i = 0; i < set->n; i++)
707 ctables_summary_spec_uninit (&set->specs[i]);
712 parse_col_width (struct lexer *lexer, const char *name, double *width)
714 lex_match (lexer, T_EQUALS);
715 if (lex_match_id (lexer, "DEFAULT"))
717 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
719 *width = lex_number (lexer);
729 parse_bool (struct lexer *lexer, bool *b)
731 if (lex_match_id (lexer, "NO"))
733 else if (lex_match_id (lexer, "YES"))
737 lex_error_expecting (lexer, "YES", "NO");
743 static enum ctables_function_availability
744 ctables_function_availability (enum ctables_summary_function f)
746 static enum ctables_function_availability availability[] = {
747 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
752 return availability[f];
756 parse_ctables_summary_function (struct lexer *lexer,
757 enum ctables_summary_function *f)
761 enum ctables_summary_function function;
762 struct substring name;
764 static struct pair names[] = {
765 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
766 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
769 /* The .COUNT suffix may be omitted. */
770 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
771 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
772 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
773 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
774 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
775 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
776 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
780 if (!lex_force_id (lexer))
783 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
784 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
786 *f = names[i].function;
791 lex_error (lexer, _("Expecting summary function name."));
796 ctables_axis_destroy (struct ctables_axis *axis)
804 for (size_t i = 0; i < N_CSVS; i++)
805 ctables_summary_spec_set_uninit (&axis->specs[i]);
810 ctables_axis_destroy (axis->subs[0]);
811 ctables_axis_destroy (axis->subs[1]);
814 msg_location_destroy (axis->loc);
818 static struct ctables_axis *
819 ctables_axis_new_nonterminal (enum ctables_axis_op op,
820 struct ctables_axis *sub0,
821 struct ctables_axis *sub1,
822 struct lexer *lexer, int start_ofs)
824 struct ctables_axis *axis = xmalloc (sizeof *axis);
825 *axis = (struct ctables_axis) {
827 .subs = { sub0, sub1 },
828 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
833 struct ctables_axis_parse_ctx
836 struct dictionary *dict;
838 struct ctables_table *t;
841 static struct fmt_spec
842 ctables_summary_default_format (enum ctables_summary_function function,
843 const struct ctables_var *var)
845 static const enum ctables_format default_formats[] = {
846 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
850 switch (default_formats[function])
853 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
856 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
859 return *ctables_var_get_print_format (var);
867 ctables_summary_default_label (enum ctables_summary_function function,
870 static const char *default_labels[] = {
871 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
876 return (function == CTSF_PTILE
877 ? xasprintf (_("Percentile %.2f"), percentile)
878 : xstrdup (gettext (default_labels[function])));
882 ctables_summary_function_name (enum ctables_summary_function function)
884 static const char *names[] = {
885 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
889 return names[function];
893 add_summary_spec (struct ctables_axis *axis,
894 enum ctables_summary_function function, double percentile,
895 const char *label, const struct fmt_spec *format,
896 const struct msg_location *loc, enum ctables_summary_variant sv)
898 if (axis->op == CTAO_VAR)
900 const char *function_name = ctables_summary_function_name (function);
901 const char *var_name = ctables_var_name (&axis->var);
902 switch (ctables_function_availability (function))
905 if (!axis->var.is_mrset)
907 msg_at (SE, loc, _("Summary function %s applies only to multiple "
908 "response sets."), function_name);
909 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
919 _("Summary function %s applies only to scale variables."),
921 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
931 struct ctables_summary_spec_set *set = &axis->specs[sv];
932 if (set->n >= set->allocated)
933 set->specs = x2nrealloc (set->specs, &set->allocated,
936 struct ctables_summary_spec *dst = &set->specs[set->n++];
937 *dst = (struct ctables_summary_spec) {
938 .function = function,
939 .percentile = percentile,
940 .label = xstrdup (label),
941 .format = (format ? *format
942 : ctables_summary_default_format (function, &axis->var)),
948 for (size_t i = 0; i < 2; i++)
949 if (!add_summary_spec (axis->subs[i], function, percentile, label,
956 static struct ctables_axis *ctables_axis_parse_stack (
957 struct ctables_axis_parse_ctx *);
960 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
961 struct ctables_var *var)
963 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
965 *var = (struct ctables_var) {
967 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
971 lex_error (lexer, _("'%s' does not name a multiple-response set "
972 "in the active file dictionary."),
973 lex_tokcstr (lexer));
981 *var = (struct ctables_var) {
983 .var = parse_variable (lexer, dict),
985 return var->var != NULL;
989 static struct ctables_axis *
990 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
992 if (lex_match (ctx->lexer, T_LPAREN))
994 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
995 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
997 ctables_axis_destroy (sub);
1003 if (!lex_force_id (ctx->lexer))
1006 int start_ofs = lex_ofs (ctx->lexer);
1007 struct ctables_var var;
1008 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
1011 struct ctables_axis *axis = xmalloc (sizeof *axis);
1012 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
1014 /* XXX should figure out default measures by reading data */
1015 axis->scale = (var.is_mrset ? false
1016 : lex_match_phrase (ctx->lexer, "[S]") ? true
1017 : lex_match_phrase (ctx->lexer, "[C]") ? false
1018 : var_get_measure (var.var) == MEASURE_SCALE);
1019 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
1020 lex_ofs (ctx->lexer) - 1);
1025 has_digit (const char *s)
1027 return s[strcspn (s, "0123456789")] != '\0';
1030 static struct ctables_axis *
1031 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
1033 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
1034 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
1037 enum ctables_summary_variant sv = CSV_CELL;
1040 int start_ofs = lex_ofs (ctx->lexer);
1042 /* Parse function. */
1043 enum ctables_summary_function function;
1044 if (!parse_ctables_summary_function (ctx->lexer, &function))
1047 /* Parse percentile. */
1048 double percentile = 0;
1049 if (function == CTSF_PTILE)
1051 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1053 percentile = lex_number (ctx->lexer);
1054 lex_get (ctx->lexer);
1059 if (lex_is_string (ctx->lexer))
1061 label = ss_xstrdup (lex_tokss (ctx->lexer));
1062 lex_get (ctx->lexer);
1065 label = ctables_summary_default_label (function, percentile);
1068 struct fmt_spec format;
1069 const struct fmt_spec *formatp;
1070 if (lex_token (ctx->lexer) == T_ID
1071 && has_digit (lex_tokcstr (ctx->lexer)))
1073 if (!parse_format_specifier (ctx->lexer, &format)
1074 || !fmt_check_output (&format)
1075 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1085 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1086 lex_ofs (ctx->lexer) - 1);
1087 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1089 msg_location_destroy (loc);
1091 lex_match (ctx->lexer, T_COMMA);
1092 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1094 if (!lex_force_match (ctx->lexer, T_LBRACK))
1098 else if (lex_match (ctx->lexer, T_RBRACK))
1100 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1107 ctables_axis_destroy (sub);
1111 static const struct ctables_axis *
1112 find_scale (const struct ctables_axis *axis)
1116 else if (axis->op == CTAO_VAR)
1120 assert (!axis->var.is_mrset);
1128 for (size_t i = 0; i < 2; i++)
1130 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1138 static const struct ctables_axis *
1139 find_categorical_summary_spec (const struct ctables_axis *axis)
1143 else if (axis->op == CTAO_VAR)
1144 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1147 for (size_t i = 0; i < 2; i++)
1149 const struct ctables_axis *sum
1150 = find_categorical_summary_spec (axis->subs[i]);
1158 static struct ctables_axis *
1159 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1161 int start_ofs = lex_ofs (ctx->lexer);
1162 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1166 while (lex_match (ctx->lexer, T_GT))
1168 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1172 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1173 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1175 const struct ctables_axis *outer_scale = find_scale (lhs);
1176 const struct ctables_axis *inner_scale = find_scale (rhs);
1177 if (outer_scale && inner_scale)
1179 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1180 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1181 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1182 ctables_axis_destroy (nest);
1186 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1189 msg_at (SE, nest->loc,
1190 _("Summaries may only be requested for categorical variables "
1191 "at the innermost nesting level."));
1192 msg_at (SN, outer_sum->loc,
1193 _("This outer categorical variable has a summary."));
1194 ctables_axis_destroy (nest);
1204 static struct ctables_axis *
1205 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1207 int start_ofs = lex_ofs (ctx->lexer);
1208 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1212 while (lex_match (ctx->lexer, T_PLUS))
1214 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1218 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1219 ctx->lexer, start_ofs);
1226 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1227 struct ctables *ct, struct ctables_table *t,
1228 enum pivot_axis_type a)
1230 if (lex_token (lexer) == T_BY
1231 || lex_token (lexer) == T_SLASH
1232 || lex_token (lexer) == T_ENDCMD)
1235 struct ctables_axis_parse_ctx ctx = {
1241 t->axes[a] = ctables_axis_parse_stack (&ctx);
1242 return t->axes[a] != NULL;
1246 ctables_chisq_destroy (struct ctables_chisq *chisq)
1252 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1258 ctables_table_destroy (struct ctables_table *t)
1263 for (size_t i = 0; i < t->n_categories; i++)
1264 ctables_categories_unref (t->categories[i]);
1265 free (t->categories);
1267 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1268 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1269 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1273 ctables_chisq_destroy (t->chisq);
1274 ctables_pairwise_destroy (t->pairwise);
1279 ctables_destroy (struct ctables *ct)
1284 pivot_table_look_unref (ct->look);
1288 for (size_t i = 0; i < ct->n_tables; i++)
1289 ctables_table_destroy (ct->tables[i]);
1294 static struct ctables_category
1295 cct_range (double low, double high)
1297 return (struct ctables_category) {
1299 .range = { low, high }
1304 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1305 struct ctables_table *t)
1307 if (!lex_match_id (lexer, "VARIABLES"))
1309 lex_match (lexer, T_EQUALS);
1311 struct variable **vars;
1313 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1316 struct ctables_categories *c = xmalloc (sizeof *c);
1317 *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
1318 for (size_t i = 0; i < n_vars; i++)
1320 struct ctables_categories **cp
1321 = &t->categories[var_get_dict_index (vars[i])];
1322 ctables_categories_unref (*cp);
1327 size_t allocated_cats = 0;
1328 if (lex_match (lexer, T_LBRACK))
1332 if (c->n_cats >= allocated_cats)
1333 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1335 struct ctables_category *cat = &c->cats[c->n_cats];
1336 if (lex_match_id (lexer, "OTHERNM"))
1337 cat->type = CCT_OTHERNM;
1338 else if (lex_match_id (lexer, "MISSING"))
1339 cat->type = CCT_MISSING;
1340 else if (lex_match_id (lexer, "SUBTOTAL"))
1341 *cat = (struct ctables_category)
1342 { .type = CCT_SUBTOTAL, .total_label = NULL };
1343 else if (lex_match_id (lexer, "HSUBTOTAL"))
1344 *cat = (struct ctables_category)
1345 { .type = CCT_HSUBTOTAL, .total_label = NULL };
1346 else if (lex_match_id (lexer, "LO"))
1348 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1350 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1353 else if (lex_is_number (lexer))
1355 double number = lex_number (lexer);
1357 if (lex_match_id (lexer, "THRU"))
1359 if (lex_match_id (lexer, "HI"))
1360 *cat = cct_range (number, DBL_MAX);
1363 if (!lex_force_num (lexer))
1365 *cat = cct_range (number, lex_number (lexer));
1370 *cat = (struct ctables_category) {
1375 else if (lex_is_string (lexer))
1377 *cat = (struct ctables_category) {
1379 .string = ss_xstrdup (lex_tokss (lexer)),
1385 lex_error (lexer, NULL);
1389 if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1391 if (lex_match (lexer, T_EQUALS))
1393 if (!lex_force_string (lexer))
1396 cat->total_label = ss_xstrdup (lex_tokss (lexer));
1400 cat->total_label = xstrdup (_("Subtotal"));
1404 lex_match (lexer, T_COMMA);
1406 while (!lex_match (lexer, T_RBRACK));
1409 struct ctables_category cat = {
1411 .include_missing = false,
1412 .sort_ascending = true,
1414 bool show_totals = false;
1415 char *total_label = NULL;
1416 bool totals_before = false;
1417 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1419 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1421 lex_match (lexer, T_EQUALS);
1422 if (lex_match_id (lexer, "A"))
1423 cat.sort_ascending = true;
1424 else if (lex_match_id (lexer, "D"))
1425 cat.sort_ascending = false;
1428 lex_error_expecting (lexer, "A", "D");
1432 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1434 lex_match (lexer, T_EQUALS);
1435 if (lex_match_id (lexer, "VALUE"))
1436 cat.type = CCT_VALUE;
1437 else if (lex_match_id (lexer, "LABEL"))
1438 cat.type = CCT_LABEL;
1441 cat.type = CCT_FUNCTION;
1442 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1445 if (lex_match (lexer, T_LPAREN))
1447 cat.sort_var = parse_variable (lexer, dict);
1451 if (cat.sort_function == CTSF_PTILE)
1453 lex_match (lexer, T_COMMA);
1454 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1456 cat.percentile = lex_number (lexer);
1460 if (!lex_force_match (lexer, T_RPAREN))
1463 else if (ctables_function_availability (cat.sort_function)
1466 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1471 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1473 lex_match (lexer, T_EQUALS);
1474 if (lex_match_id (lexer, "INCLUDE"))
1475 cat.include_missing = true;
1476 else if (lex_match_id (lexer, "EXCLUDE"))
1477 cat.include_missing = false;
1480 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1484 else if (lex_match_id (lexer, "TOTAL"))
1486 lex_match (lexer, T_EQUALS);
1487 if (!parse_bool (lexer, &show_totals))
1490 else if (lex_match_id (lexer, "LABEL"))
1492 lex_match (lexer, T_EQUALS);
1493 if (!lex_force_string (lexer))
1496 total_label = ss_xstrdup (lex_tokss (lexer));
1499 else if (lex_match_id (lexer, "POSITION"))
1501 lex_match (lexer, T_EQUALS);
1502 if (lex_match_id (lexer, "BEFORE"))
1503 totals_before = true;
1504 else if (lex_match_id (lexer, "AFTER"))
1505 totals_before = false;
1508 lex_error_expecting (lexer, "BEFORE", "AFTER");
1512 else if (lex_match_id (lexer, "EMPTY"))
1514 lex_match (lexer, T_EQUALS);
1515 if (lex_match_id (lexer, "INCLUDE"))
1516 c->show_empty = true;
1517 else if (lex_match_id (lexer, "EXCLUDE"))
1518 c->show_empty = false;
1521 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1528 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1529 "TOTAL", "LABEL", "POSITION", "EMPTY");
1531 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1538 if (c->n_cats >= allocated_cats)
1539 c->cats = x2nrealloc (c->cats, &allocated_cats,
1541 c->cats[c->n_cats++] = cat;
1546 if (c->n_cats >= allocated_cats)
1547 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1549 struct ctables_category *totals;
1552 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1553 totals = &c->cats[0];
1556 totals = &c->cats[c->n_cats];
1559 *totals = (struct ctables_category) {
1561 .total_label = total_label ? total_label : xstrdup (_("Total")),
1565 struct ctables_category *subtotal = NULL;
1566 for (size_t i = totals_before ? 0 : c->n_cats;
1567 totals_before ? i < c->n_cats : i-- > 0;
1568 totals_before ? i++ : 0)
1570 struct ctables_category *cat = &c->cats[i];
1578 cat->subtotal = subtotal;
1598 ctables_nest_uninit (struct ctables_nest *nest)
1605 ctables_stack_uninit (struct ctables_stack *stack)
1609 for (size_t i = 0; i < stack->n; i++)
1610 ctables_nest_uninit (&stack->nests[i]);
1611 free (stack->nests);
1615 static struct ctables_stack
1616 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1623 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1624 for (size_t i = 0; i < s0.n; i++)
1625 for (size_t j = 0; j < s1.n; j++)
1627 const struct ctables_nest *a = &s0.nests[i];
1628 const struct ctables_nest *b = &s1.nests[j];
1630 size_t allocate = a->n + b->n;
1631 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1632 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1634 for (size_t k = 0; k < a->n; k++)
1635 vars[n++] = a->vars[k];
1636 for (size_t k = 0; k < b->n; k++)
1637 vars[n++] = b->vars[k];
1638 assert (n == allocate);
1640 const struct ctables_nest *summary_src;
1641 if (!a->specs[CSV_CELL].var)
1643 else if (!b->specs[CSV_CELL].var)
1648 struct ctables_nest *new = &stack.nests[stack.n++];
1649 *new = (struct ctables_nest) {
1651 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1652 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1656 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1657 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1659 ctables_stack_uninit (&s0);
1660 ctables_stack_uninit (&s1);
1664 static struct ctables_stack
1665 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1667 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1668 for (size_t i = 0; i < s0.n; i++)
1669 stack.nests[stack.n++] = s0.nests[i];
1670 for (size_t i = 0; i < s1.n; i++)
1671 stack.nests[stack.n++] = s1.nests[i];
1672 assert (stack.n == s0.n + s1.n);
1678 static struct ctables_stack
1679 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1682 return (struct ctables_stack) { .n = 0 };
1687 assert (!a->var.is_mrset);
1689 struct variable **vars = xmalloc (sizeof *vars);
1692 struct ctables_nest *nest = xmalloc (sizeof *nest);
1693 *nest = (struct ctables_nest) {
1696 .scale_idx = a->scale ? 0 : SIZE_MAX,
1698 if (a->specs[CSV_CELL].n || a->scale)
1699 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1701 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1702 nest->specs[sv].var = a->var.var;
1704 return (struct ctables_stack) { .nests = nest, .n = 1 };
1707 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1708 enumerate_fts (axis_type, a->subs[1]));
1711 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1712 enumerate_fts (axis_type, a->subs[1]));
1718 union ctables_summary
1720 /* COUNT, VALIDN, TOTALN. */
1727 /* MINIMUM, MAXIMUM, RANGE. */
1734 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1735 struct moments1 *moments;
1737 /* MEDIAN, MODE, PTILE. */
1740 struct casewriter *writer;
1745 /* XXX multiple response */
1749 ctables_summary_init (union ctables_summary *s,
1750 const struct ctables_summary_spec *ss)
1752 switch (ss->function)
1756 case CTSF_ROWPCT_COUNT:
1757 case CTSF_COLPCT_COUNT:
1758 case CTSF_TABLEPCT_COUNT:
1759 case CTSF_SUBTABLEPCT_COUNT:
1760 case CTSF_LAYERPCT_COUNT:
1761 case CTSF_LAYERROWPCT_COUNT:
1762 case CTSF_LAYERCOLPCT_COUNT:
1763 case CTSF_ROWPCT_VALIDN:
1764 case CTSF_COLPCT_VALIDN:
1765 case CTSF_TABLEPCT_VALIDN:
1766 case CTSF_SUBTABLEPCT_VALIDN:
1767 case CTSF_LAYERPCT_VALIDN:
1768 case CTSF_LAYERROWPCT_VALIDN:
1769 case CTSF_LAYERCOLPCT_VALIDN:
1770 case CTSF_ROWPCT_TOTALN:
1771 case CTSF_COLPCT_TOTALN:
1772 case CTSF_TABLEPCT_TOTALN:
1773 case CTSF_SUBTABLEPCT_TOTALN:
1774 case CTSF_LAYERPCT_TOTALN:
1775 case CTSF_LAYERROWPCT_TOTALN:
1776 case CTSF_LAYERCOLPCT_TOTALN:
1782 s->missing = s->valid = 0;
1788 s->min = s->max = SYSMIS;
1796 case CTSF_ROWPCT_SUM:
1797 case CTSF_COLPCT_SUM:
1798 case CTSF_TABLEPCT_SUM:
1799 case CTSF_SUBTABLEPCT_SUM:
1800 case CTSF_LAYERPCT_SUM:
1801 case CTSF_LAYERROWPCT_SUM:
1802 case CTSF_LAYERCOLPCT_SUM:
1803 s->moments = moments1_create (MOMENT_VARIANCE);
1810 struct caseproto *proto = caseproto_create ();
1811 proto = caseproto_add_width (proto, 0);
1812 proto = caseproto_add_width (proto, 0);
1814 struct subcase ordering;
1815 subcase_init (&ordering, 0, 0, SC_ASCEND);
1816 s->writer = sort_create_writer (&ordering, proto);
1817 subcase_uninit (&ordering);
1818 caseproto_unref (proto);
1825 case CTSF_RESPONSES:
1826 case CTSF_ROWPCT_RESPONSES:
1827 case CTSF_COLPCT_RESPONSES:
1828 case CTSF_TABLEPCT_RESPONSES:
1829 case CTSF_SUBTABLEPCT_RESPONSES:
1830 case CTSF_LAYERPCT_RESPONSES:
1831 case CTSF_LAYERROWPCT_RESPONSES:
1832 case CTSF_LAYERCOLPCT_RESPONSES:
1833 case CTSF_ROWPCT_RESPONSES_COUNT:
1834 case CTSF_COLPCT_RESPONSES_COUNT:
1835 case CTSF_TABLEPCT_RESPONSES_COUNT:
1836 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1837 case CTSF_LAYERPCT_RESPONSES_COUNT:
1838 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1839 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1840 case CTSF_ROWPCT_COUNT_RESPONSES:
1841 case CTSF_COLPCT_COUNT_RESPONSES:
1842 case CTSF_TABLEPCT_COUNT_RESPONSES:
1843 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1844 case CTSF_LAYERPCT_COUNT_RESPONSES:
1845 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1846 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1852 ctables_summary_uninit (union ctables_summary *s,
1853 const struct ctables_summary_spec *ss)
1855 switch (ss->function)
1859 case CTSF_ROWPCT_COUNT:
1860 case CTSF_COLPCT_COUNT:
1861 case CTSF_TABLEPCT_COUNT:
1862 case CTSF_SUBTABLEPCT_COUNT:
1863 case CTSF_LAYERPCT_COUNT:
1864 case CTSF_LAYERROWPCT_COUNT:
1865 case CTSF_LAYERCOLPCT_COUNT:
1866 case CTSF_ROWPCT_VALIDN:
1867 case CTSF_COLPCT_VALIDN:
1868 case CTSF_TABLEPCT_VALIDN:
1869 case CTSF_SUBTABLEPCT_VALIDN:
1870 case CTSF_LAYERPCT_VALIDN:
1871 case CTSF_LAYERROWPCT_VALIDN:
1872 case CTSF_LAYERCOLPCT_VALIDN:
1873 case CTSF_ROWPCT_TOTALN:
1874 case CTSF_COLPCT_TOTALN:
1875 case CTSF_TABLEPCT_TOTALN:
1876 case CTSF_SUBTABLEPCT_TOTALN:
1877 case CTSF_LAYERPCT_TOTALN:
1878 case CTSF_LAYERROWPCT_TOTALN:
1879 case CTSF_LAYERCOLPCT_TOTALN:
1897 case CTSF_ROWPCT_SUM:
1898 case CTSF_COLPCT_SUM:
1899 case CTSF_TABLEPCT_SUM:
1900 case CTSF_SUBTABLEPCT_SUM:
1901 case CTSF_LAYERPCT_SUM:
1902 case CTSF_LAYERROWPCT_SUM:
1903 case CTSF_LAYERCOLPCT_SUM:
1904 moments1_destroy (s->moments);
1910 casewriter_destroy (s->writer);
1913 case CTSF_RESPONSES:
1914 case CTSF_ROWPCT_RESPONSES:
1915 case CTSF_COLPCT_RESPONSES:
1916 case CTSF_TABLEPCT_RESPONSES:
1917 case CTSF_SUBTABLEPCT_RESPONSES:
1918 case CTSF_LAYERPCT_RESPONSES:
1919 case CTSF_LAYERROWPCT_RESPONSES:
1920 case CTSF_LAYERCOLPCT_RESPONSES:
1921 case CTSF_ROWPCT_RESPONSES_COUNT:
1922 case CTSF_COLPCT_RESPONSES_COUNT:
1923 case CTSF_TABLEPCT_RESPONSES_COUNT:
1924 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1925 case CTSF_LAYERPCT_RESPONSES_COUNT:
1926 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1927 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1928 case CTSF_ROWPCT_COUNT_RESPONSES:
1929 case CTSF_COLPCT_COUNT_RESPONSES:
1930 case CTSF_TABLEPCT_COUNT_RESPONSES:
1931 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1932 case CTSF_LAYERPCT_COUNT_RESPONSES:
1933 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1934 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1940 ctables_summary_add (union ctables_summary *s,
1941 const struct ctables_summary_spec *ss,
1942 const struct variable *var, const union value *value,
1943 double d_weight, double e_weight)
1945 switch (ss->function)
1950 if (var_is_value_missing (var, value))
1951 s->missing += d_weight;
1953 s->valid += d_weight;
1957 case CTSF_ROWPCT_COUNT:
1958 case CTSF_COLPCT_COUNT:
1959 case CTSF_TABLEPCT_COUNT:
1960 case CTSF_SUBTABLEPCT_COUNT:
1961 case CTSF_LAYERPCT_COUNT:
1962 case CTSF_LAYERROWPCT_COUNT:
1963 case CTSF_LAYERCOLPCT_COUNT:
1964 case CTSF_ROWPCT_VALIDN:
1965 case CTSF_COLPCT_VALIDN:
1966 case CTSF_TABLEPCT_VALIDN:
1967 case CTSF_SUBTABLEPCT_VALIDN:
1968 case CTSF_LAYERPCT_VALIDN:
1969 case CTSF_LAYERROWPCT_VALIDN:
1970 case CTSF_LAYERCOLPCT_VALIDN:
1971 case CTSF_ROWPCT_TOTALN:
1972 case CTSF_COLPCT_TOTALN:
1973 case CTSF_TABLEPCT_TOTALN:
1974 case CTSF_SUBTABLEPCT_TOTALN:
1975 case CTSF_LAYERPCT_TOTALN:
1976 case CTSF_LAYERROWPCT_TOTALN:
1977 case CTSF_LAYERCOLPCT_TOTALN:
1981 if (var_is_value_missing (var, value))
1982 s->missing += e_weight;
1984 s->valid += e_weight;
1990 if (!var_is_value_missing (var, value))
1992 assert (!var_is_alpha (var)); /* XXX? */
1993 if (s->min == SYSMIS || value->f < s->min)
1995 if (s->max == SYSMIS || value->f > s->max)
2005 case CTSF_ROWPCT_SUM:
2006 case CTSF_COLPCT_SUM:
2007 case CTSF_TABLEPCT_SUM:
2008 case CTSF_SUBTABLEPCT_SUM:
2009 case CTSF_LAYERPCT_SUM:
2010 case CTSF_LAYERROWPCT_SUM:
2011 case CTSF_LAYERCOLPCT_SUM:
2012 if (!var_is_value_missing (var, value))
2013 moments1_add (s->moments, value->f, e_weight);
2019 if (var_is_value_missing (var, value))
2021 s->ovalid += e_weight;
2023 struct ccase *c = case_create (casewriter_get_proto (s->writer));
2024 *case_num_rw_idx (c, 0) = value->f;
2025 *case_num_rw_idx (c, 1) = e_weight;
2026 casewriter_write (s->writer, c);
2030 case CTSF_RESPONSES:
2031 case CTSF_ROWPCT_RESPONSES:
2032 case CTSF_COLPCT_RESPONSES:
2033 case CTSF_TABLEPCT_RESPONSES:
2034 case CTSF_SUBTABLEPCT_RESPONSES:
2035 case CTSF_LAYERPCT_RESPONSES:
2036 case CTSF_LAYERROWPCT_RESPONSES:
2037 case CTSF_LAYERCOLPCT_RESPONSES:
2038 case CTSF_ROWPCT_RESPONSES_COUNT:
2039 case CTSF_COLPCT_RESPONSES_COUNT:
2040 case CTSF_TABLEPCT_RESPONSES_COUNT:
2041 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2042 case CTSF_LAYERPCT_RESPONSES_COUNT:
2043 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2044 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2045 case CTSF_ROWPCT_COUNT_RESPONSES:
2046 case CTSF_COLPCT_COUNT_RESPONSES:
2047 case CTSF_TABLEPCT_COUNT_RESPONSES:
2048 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2049 case CTSF_LAYERPCT_COUNT_RESPONSES:
2050 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2051 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2056 static enum ctables_domain_type
2057 ctables_function_domain (enum ctables_summary_function function)
2079 case CTSF_RESPONSES:
2082 case CTSF_COLPCT_COUNT:
2083 case CTSF_COLPCT_COUNT_RESPONSES:
2084 case CTSF_COLPCT_RESPONSES:
2085 case CTSF_COLPCT_RESPONSES_COUNT:
2086 case CTSF_COLPCT_SUM:
2087 case CTSF_COLPCT_TOTALN:
2088 case CTSF_COLPCT_VALIDN:
2091 case CTSF_LAYERCOLPCT_COUNT:
2092 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2093 case CTSF_LAYERCOLPCT_RESPONSES:
2094 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2095 case CTSF_LAYERCOLPCT_SUM:
2096 case CTSF_LAYERCOLPCT_TOTALN:
2097 case CTSF_LAYERCOLPCT_VALIDN:
2098 return CTDT_LAYERCOL;
2100 case CTSF_LAYERPCT_COUNT:
2101 case CTSF_LAYERPCT_COUNT_RESPONSES:
2102 case CTSF_LAYERPCT_RESPONSES:
2103 case CTSF_LAYERPCT_RESPONSES_COUNT:
2104 case CTSF_LAYERPCT_SUM:
2105 case CTSF_LAYERPCT_TOTALN:
2106 case CTSF_LAYERPCT_VALIDN:
2109 case CTSF_LAYERROWPCT_COUNT:
2110 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2111 case CTSF_LAYERROWPCT_RESPONSES:
2112 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2113 case CTSF_LAYERROWPCT_SUM:
2114 case CTSF_LAYERROWPCT_TOTALN:
2115 case CTSF_LAYERROWPCT_VALIDN:
2116 return CTDT_LAYERROW;
2118 case CTSF_ROWPCT_COUNT:
2119 case CTSF_ROWPCT_COUNT_RESPONSES:
2120 case CTSF_ROWPCT_RESPONSES:
2121 case CTSF_ROWPCT_RESPONSES_COUNT:
2122 case CTSF_ROWPCT_SUM:
2123 case CTSF_ROWPCT_TOTALN:
2124 case CTSF_ROWPCT_VALIDN:
2127 case CTSF_SUBTABLEPCT_COUNT:
2128 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2129 case CTSF_SUBTABLEPCT_RESPONSES:
2130 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2131 case CTSF_SUBTABLEPCT_SUM:
2132 case CTSF_SUBTABLEPCT_TOTALN:
2133 case CTSF_SUBTABLEPCT_VALIDN:
2134 return CTDT_SUBTABLE;
2136 case CTSF_TABLEPCT_COUNT:
2137 case CTSF_TABLEPCT_COUNT_RESPONSES:
2138 case CTSF_TABLEPCT_RESPONSES:
2139 case CTSF_TABLEPCT_RESPONSES_COUNT:
2140 case CTSF_TABLEPCT_SUM:
2141 case CTSF_TABLEPCT_TOTALN:
2142 case CTSF_TABLEPCT_VALIDN:
2150 ctables_summary_value (const struct ctables_cell *cell,
2151 union ctables_summary *s,
2152 const struct ctables_summary_spec *ss)
2154 switch (ss->function)
2160 case CTSF_ROWPCT_COUNT:
2161 case CTSF_COLPCT_COUNT:
2162 case CTSF_TABLEPCT_COUNT:
2163 case CTSF_SUBTABLEPCT_COUNT:
2164 case CTSF_LAYERPCT_COUNT:
2165 case CTSF_LAYERROWPCT_COUNT:
2166 case CTSF_LAYERCOLPCT_COUNT:
2168 enum ctables_domain_type d = ctables_function_domain (ss->function);
2169 return (cell->domains[d]->e_valid
2170 ? s->valid / cell->domains[d]->e_valid * 100
2174 case CTSF_ROWPCT_VALIDN:
2175 case CTSF_COLPCT_VALIDN:
2176 case CTSF_TABLEPCT_VALIDN:
2177 case CTSF_SUBTABLEPCT_VALIDN:
2178 case CTSF_LAYERPCT_VALIDN:
2179 case CTSF_LAYERROWPCT_VALIDN:
2180 case CTSF_LAYERCOLPCT_VALIDN:
2181 case CTSF_ROWPCT_TOTALN:
2182 case CTSF_COLPCT_TOTALN:
2183 case CTSF_TABLEPCT_TOTALN:
2184 case CTSF_SUBTABLEPCT_TOTALN:
2185 case CTSF_LAYERPCT_TOTALN:
2186 case CTSF_LAYERROWPCT_TOTALN:
2187 case CTSF_LAYERCOLPCT_TOTALN:
2195 return s->valid + s->missing;
2208 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2213 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2219 double weight, variance;
2220 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2221 return calc_semean (variance, weight);
2227 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2228 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2233 double weight, mean;
2234 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2235 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2241 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2245 case CTSF_ROWPCT_SUM:
2246 case CTSF_COLPCT_SUM:
2247 case CTSF_TABLEPCT_SUM:
2248 case CTSF_SUBTABLEPCT_SUM:
2249 case CTSF_LAYERPCT_SUM:
2250 case CTSF_LAYERROWPCT_SUM:
2251 case CTSF_LAYERCOLPCT_SUM:
2258 struct casereader *reader = casewriter_make_reader (s->writer);
2261 struct percentile *ptile = percentile_create (
2262 ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2263 struct order_stats *os = &ptile->parent;
2264 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2265 s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2266 statistic_destroy (&ptile->parent.parent);
2273 struct casereader *reader = casewriter_make_reader (s->writer);
2276 struct mode *mode = mode_create ();
2277 struct order_stats *os = &mode->parent;
2278 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2279 s->ovalue = mode->mode;
2280 statistic_destroy (&mode->parent.parent);
2284 case CTSF_RESPONSES:
2285 case CTSF_ROWPCT_RESPONSES:
2286 case CTSF_COLPCT_RESPONSES:
2287 case CTSF_TABLEPCT_RESPONSES:
2288 case CTSF_SUBTABLEPCT_RESPONSES:
2289 case CTSF_LAYERPCT_RESPONSES:
2290 case CTSF_LAYERROWPCT_RESPONSES:
2291 case CTSF_LAYERCOLPCT_RESPONSES:
2292 case CTSF_ROWPCT_RESPONSES_COUNT:
2293 case CTSF_COLPCT_RESPONSES_COUNT:
2294 case CTSF_TABLEPCT_RESPONSES_COUNT:
2295 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2296 case CTSF_LAYERPCT_RESPONSES_COUNT:
2297 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2298 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2299 case CTSF_ROWPCT_COUNT_RESPONSES:
2300 case CTSF_COLPCT_COUNT_RESPONSES:
2301 case CTSF_TABLEPCT_COUNT_RESPONSES:
2302 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2303 case CTSF_LAYERPCT_COUNT_RESPONSES:
2304 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2305 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2312 struct ctables_cell_sort_aux
2314 const struct ctables_nest *nest;
2315 enum pivot_axis_type a;
2319 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2321 const struct ctables_cell_sort_aux *aux = aux_;
2322 struct ctables_cell *const *ap = a_;
2323 struct ctables_cell *const *bp = b_;
2324 const struct ctables_cell *a = *ap;
2325 const struct ctables_cell *b = *bp;
2327 const struct ctables_nest *nest = aux->nest;
2328 for (size_t i = 0; i < nest->n; i++)
2329 if (i != nest->scale_idx)
2331 const struct variable *var = nest->vars[i];
2332 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2333 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2334 if (a_cv->category != b_cv->category)
2335 return a_cv->category > b_cv->category ? 1 : -1;
2337 const union value *a_val = &a_cv->value;
2338 const union value *b_val = &b_cv->value;
2339 switch (a_cv->category->type)
2346 /* Must be equal. */
2353 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2361 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2363 return a_cv->category->sort_ascending ? cmp : -cmp;
2369 const char *a_label = var_lookup_value_label (var, a_val);
2370 const char *b_label = var_lookup_value_label (var, b_val);
2372 ? (b_label ? strcmp (a_label, b_label) : 1)
2373 : (b_label ? -1 : value_compare_3way (
2374 a_val, b_val, var_get_width (var))));
2376 return a_cv->category->sort_ascending ? cmp : -cmp;
2390 For each ctables_table:
2391 For each combination of row vars:
2392 For each combination of column vars:
2393 For each combination of layer vars:
2395 Make a table of row values:
2396 Sort entries by row values
2397 Assign a 0-based index to each actual value
2398 Construct a dimension
2399 Make a table of column values
2400 Make a table of layer values
2402 Fill the table entry using the indexes from before.
2405 static struct ctables_domain *
2406 ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
2407 enum ctables_domain_type domain)
2410 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2412 const struct ctables_nest *nest = s->nests[a];
2413 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2415 size_t v_idx = nest->domains[domain][i];
2416 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2417 var_get_width (nest->vars[v_idx]), hash);
2421 struct ctables_domain *d;
2422 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &s->domains[domain])
2424 const struct ctables_cell *df = d->example;
2425 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2427 const struct ctables_nest *nest = s->nests[a];
2428 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2430 size_t v_idx = nest->domains[domain][i];
2431 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2432 &cell->axes[a].cvs[v_idx].value,
2433 var_get_width (nest->vars[v_idx])))
2442 d = xmalloc (sizeof *d);
2443 *d = (struct ctables_domain) { .example = cell };
2444 hmap_insert (&s->domains[domain], &d->node, hash);
2448 static const struct ctables_category *
2449 ctables_categories_match (const struct ctables_categories *c,
2450 const union value *v, const struct variable *var)
2452 const struct ctables_category *othernm = NULL;
2453 for (size_t i = c->n_cats; i-- > 0; )
2455 const struct ctables_category *cat = &c->cats[i];
2459 if (cat->number == v->f)
2467 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2468 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2473 if (var_is_value_missing (var, v))
2490 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2495 return var_is_value_missing (var, v) ? NULL : othernm;
2498 static const struct ctables_category *
2499 ctables_categories_total (const struct ctables_categories *c)
2501 const struct ctables_category *first = &c->cats[0];
2502 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2503 return (first->type == CCT_TOTAL ? first
2504 : last->type == CCT_TOTAL ? last
2508 static struct ctables_cell *
2509 ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
2510 const struct ctables_category *cats[PIVOT_N_AXES][10])
2512 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2515 enum ctables_summary_variant sv = CSV_CELL;
2516 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2518 const struct ctables_nest *nest = s->nests[a];
2519 for (size_t i = 0; i < nest->n; i++)
2520 if (i != nest->scale_idx)
2522 hash = hash_pointer (cats[a][i], hash);
2523 if (cats[a][i]->type != CCT_TOTAL
2524 && cats[a][i]->type != CCT_SUBTOTAL
2525 && cats[a][i]->type != CCT_HSUBTOTAL)
2526 hash = value_hash (case_data (c, nest->vars[i]),
2527 var_get_width (nest->vars[i]), hash);
2533 struct ctables_cell *cell;
2534 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &s->cells)
2536 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2538 const struct ctables_nest *nest = s->nests[a];
2539 for (size_t i = 0; i < nest->n; i++)
2540 if (i != nest->scale_idx
2541 && (cats[a][i] != cell->axes[a].cvs[i].category
2542 || (cats[a][i]->type != CCT_TOTAL
2543 && cats[a][i]->type != CCT_SUBTOTAL
2544 && cats[a][i]->type != CCT_HSUBTOTAL
2545 && !value_equal (case_data (c, nest->vars[i]),
2546 &cell->axes[a].cvs[i].value,
2547 var_get_width (nest->vars[i])))))
2556 cell = xmalloc (sizeof *cell);
2559 cell->contributes_to_domains = true;
2560 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2562 const struct ctables_nest *nest = s->nests[a];
2563 cell->axes[a].cvs = (nest->n
2564 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2566 for (size_t i = 0; i < nest->n; i++)
2568 const struct ctables_category *cat = cats[a][i];
2570 if (i != nest->scale_idx)
2572 const struct ctables_category *subtotal = cat->subtotal;
2573 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2576 if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2577 cell->contributes_to_domains = false;
2580 cell->axes[a].cvs[i].category = cat;
2581 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2582 var_get_width (nest->vars[i]));
2586 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2587 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2588 for (size_t i = 0; i < specs->n; i++)
2589 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2590 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2591 cell->domains[dt] = ctables_domain_insert (s, cell, dt);
2592 hmap_insert (&s->cells, &cell->node, hash);
2597 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
2598 const struct ctables_category *cats[PIVOT_N_AXES][10],
2599 double d_weight, double e_weight)
2601 struct ctables_cell *cell = ctables_cell_insert__ (s, c, cats);
2602 const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2604 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2605 for (size_t i = 0; i < specs->n; i++)
2606 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2607 case_data (c, specs->var), d_weight, e_weight);
2608 if (cell->contributes_to_domains)
2610 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2612 cell->domains[dt]->d_valid += d_weight;
2613 cell->domains[dt]->e_valid += e_weight;
2619 recurse_totals (struct ctables_section *s, const struct ccase *c,
2620 const struct ctables_category *cats[PIVOT_N_AXES][10],
2621 double d_weight, double e_weight,
2622 enum pivot_axis_type start_axis, size_t start_nest)
2624 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2626 const struct ctables_nest *nest = s->nests[a];
2627 for (size_t i = start_nest; i < nest->n; i++)
2629 if (i == nest->scale_idx)
2632 const struct variable *var = nest->vars[i];
2634 const struct ctables_category *total = ctables_categories_total (
2635 s->table->categories[var_get_dict_index (var)]);
2638 const struct ctables_category *save = cats[a][i];
2640 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2641 recurse_totals (s, c, cats, d_weight, e_weight, a, i + 1);
2650 recurse_subtotals (struct ctables_section *s, const struct ccase *c,
2651 const struct ctables_category *cats[PIVOT_N_AXES][10],
2652 double d_weight, double e_weight,
2653 enum pivot_axis_type start_axis, size_t start_nest)
2655 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2657 const struct ctables_nest *nest = s->nests[a];
2658 for (size_t i = start_nest; i < nest->n; i++)
2660 if (i == nest->scale_idx)
2663 const struct ctables_category *save = cats[a][i];
2666 cats[a][i] = save->subtotal;
2667 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2668 recurse_subtotals (s, c, cats, d_weight, e_weight, a, i + 1);
2677 ctables_add_occurrence (const struct variable *var,
2678 const union value *value,
2679 struct hmap *occurrences)
2681 int width = var_get_width (var);
2682 unsigned int hash = value_hash (value, width, 0);
2684 struct ctables_section_value *sv;
2685 HMAP_FOR_EACH_WITH_HASH (sv, struct ctables_section_value, node, hash,
2687 if (value_equal (value, &sv->value, width))
2690 sv = xmalloc (sizeof *sv);
2691 value_clone (&sv->value, value, width);
2692 hmap_insert (occurrences, &sv->node, hash);
2696 ctables_cell_insert (struct ctables_section *s,
2697 const struct ccase *c,
2698 double d_weight, double e_weight)
2700 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
2701 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2703 const struct ctables_nest *nest = s->nests[a];
2704 for (size_t i = 0; i < nest->n; i++)
2706 if (i == nest->scale_idx)
2709 const struct variable *var = nest->vars[i];
2710 const union value *value = case_data (c, var);
2712 if (var_is_numeric (var) && value->f == SYSMIS)
2715 cats[a][i] = ctables_categories_match (
2716 s->table->categories[var_get_dict_index (var)], value, var);
2722 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2724 const struct ctables_nest *nest = s->nests[a];
2725 for (size_t i = 0; i < nest->n; i++)
2726 if (i != nest->scale_idx)
2728 const struct variable *var = nest->vars[i];
2729 const union value *value = case_data (c, var);
2730 ctables_add_occurrence (var, value, &s->occurrences[a][i]);
2734 ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2736 recurse_totals (s, c, cats, d_weight, e_weight, 0, 0);
2737 recurse_subtotals (s, c, cats, d_weight, e_weight, 0, 0);
2742 const struct ctables_summary_spec_set *set;
2747 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2749 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2750 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2751 if (as->function != bs->function)
2752 return as->function > bs->function ? 1 : -1;
2753 else if (as->percentile != bs->percentile)
2754 return as->percentile < bs->percentile ? 1 : -1;
2755 return strcmp (as->label, bs->label);
2758 static struct pivot_value *
2759 ctables_category_create_label (const struct ctables_category *cat,
2760 const struct variable *var,
2761 const union value *value)
2763 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2764 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2765 : pivot_value_new_var_value (var, value));
2768 static struct ctables_value *
2769 ctables_value_find__ (struct ctables_table *t, const union value *value,
2770 int width, unsigned int hash)
2772 struct ctables_value *clv;
2773 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2774 hash, &t->clabels_values_map)
2775 if (value_equal (value, &clv->value, width))
2780 static struct ctables_value *
2781 ctables_value_find (struct ctables_table *t,
2782 const union value *value, int width)
2784 return ctables_value_find__ (t, value, width,
2785 value_hash (value, width, 0));
2789 ctables_table_add_section (struct ctables_table *t, enum pivot_axis_type a,
2790 size_t ix[PIVOT_N_AXES])
2792 if (a < PIVOT_N_AXES)
2794 size_t limit = MAX (t->stacks[a].n, 1);
2795 for (ix[a] = 0; ix[a] < limit; ix[a]++)
2796 ctables_table_add_section (t, a + 1, ix);
2800 struct ctables_section *s = &t->sections[t->n_sections++];
2801 *s = (struct ctables_section) {
2803 .cells = HMAP_INITIALIZER (s->cells),
2805 for (a = 0; a < PIVOT_N_AXES; a++)
2808 struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2810 s->occurrences[a] = xnmalloc (nest->n, sizeof *s->occurrences[a]);
2811 for (size_t i = 0; i < nest->n; i++)
2812 hmap_init (&s->occurrences[a][i]);
2814 for (size_t i = 0; i < N_CTDTS; i++)
2815 hmap_init (&s->domains[i]);
2820 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2822 struct pivot_table *pt = pivot_table_create__ (
2824 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2825 : pivot_value_new_text (N_("Custom Tables"))),
2828 pivot_table_set_caption (
2829 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2831 pivot_table_set_caption (
2832 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2834 bool summary_dimension = (t->summary_axis != t->slabels_axis
2835 || (!t->slabels_visible
2836 && t->summary_specs.n > 1));
2837 if (summary_dimension)
2839 struct pivot_dimension *d = pivot_dimension_create (
2840 pt, t->slabels_axis, N_("Statistics"));
2841 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2842 if (!t->slabels_visible)
2843 d->hide_all_labels = true;
2844 for (size_t i = 0; i < specs->n; i++)
2845 pivot_category_create_leaf (
2846 d->root, pivot_value_new_text (specs->specs[i].label));
2849 bool categories_dimension = t->clabels_example != NULL;
2850 if (categories_dimension)
2852 struct pivot_dimension *d = pivot_dimension_create (
2853 pt, t->label_axis[t->clabels_from_axis],
2854 t->clabels_from_axis == PIVOT_AXIS_ROW
2855 ? N_("Row Categories")
2856 : N_("Column Categories"));
2857 const struct variable *var = t->clabels_example;
2858 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2859 for (size_t i = 0; i < t->n_clabels_values; i++)
2861 const struct ctables_value *value = t->clabels_values[i];
2862 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2863 assert (cat != NULL);
2864 pivot_category_create_leaf (d->root, ctables_category_create_label (
2865 cat, t->clabels_example, &value->value));
2869 pivot_table_set_look (pt, ct->look);
2870 struct pivot_dimension *d[PIVOT_N_AXES];
2871 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2873 static const char *names[] = {
2874 [PIVOT_AXIS_ROW] = N_("Rows"),
2875 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2876 [PIVOT_AXIS_LAYER] = N_("Layers"),
2878 d[a] = (t->axes[a] || a == t->summary_axis
2879 ? pivot_dimension_create (pt, a, names[a])
2884 assert (t->axes[a]);
2886 for (size_t i = 0; i < t->stacks[a].n; i++)
2888 struct ctables_nest *nest = &t->stacks[a].nests[i];
2889 struct ctables_section **sections = xnmalloc (t->n_sections,
2891 size_t n_sections = 0;
2893 size_t n_total_cells = 0;
2894 size_t max_depth = 0;
2895 for (size_t j = 0; j < t->n_sections; j++)
2896 if (t->sections[j].nests[a] == nest)
2898 struct ctables_section *s = &t->sections[j];
2899 sections[n_sections++] = s;
2900 n_total_cells += s->cells.count;
2902 size_t depth = s->nests[a]->n;
2903 max_depth = MAX (depth, max_depth);
2906 struct ctables_cell **sorted = xnmalloc (n_total_cells,
2908 size_t n_sorted = 0;
2910 for (size_t j = 0; j < n_sections; j++)
2912 struct ctables_section *s = sections[j];
2914 struct ctables_cell *cell;
2915 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
2917 sorted[n_sorted++] = cell;
2918 assert (n_sorted <= n_total_cells);
2921 struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
2922 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2924 struct ctables_level
2926 enum ctables_level_type
2928 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2929 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2930 CTL_SUMMARY, /* Summary functions. */
2936 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2937 size_t n_levels = 0;
2938 for (size_t k = 0; k < nest->n; k++)
2940 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2941 if (vlabel != CTVL_NONE)
2943 levels[n_levels++] = (struct ctables_level) {
2949 if (nest->scale_idx != k
2950 && (k != nest->n - 1 || t->label_axis[a] == a))
2952 levels[n_levels++] = (struct ctables_level) {
2953 .type = CTL_CATEGORY,
2959 if (!summary_dimension && a == t->slabels_axis)
2961 levels[n_levels++] = (struct ctables_level) {
2962 .type = CTL_SUMMARY,
2963 .var_idx = SIZE_MAX,
2967 /* Pivot categories:
2969 - variable label for nest->vars[0], if vlabel != CTVL_NONE
2970 - category for nest->vars[0], if nest->scale_idx != 0
2971 - variable label for nest->vars[1], if vlabel != CTVL_NONE
2972 - category for nest->vars[1], if nest->scale_idx != 1
2974 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2975 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2976 - summary function, if 'a == t->slabels_axis && a ==
2979 Additional dimensions:
2981 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2983 - If 't->label_axis[b] == a' for some 'b != a', add a category
2988 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2990 for (size_t j = 0; j < n_sorted; j++)
2992 struct ctables_cell *cell = sorted[j];
2993 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2995 size_t n_common = 0;
2998 for (; n_common < n_levels; n_common++)
3000 const struct ctables_level *level = &levels[n_common];
3001 if (level->type == CTL_CATEGORY)
3003 size_t var_idx = level->var_idx;
3004 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3005 if (prev->axes[a].cvs[var_idx].category != c)
3007 else if (c->type != CCT_SUBTOTAL
3008 && c->type != CCT_HSUBTOTAL
3009 && c->type != CCT_TOTAL
3010 && !value_equal (&prev->axes[a].cvs[var_idx].value,
3011 &cell->axes[a].cvs[var_idx].value,
3012 var_get_type (nest->vars[var_idx])))
3018 for (size_t k = n_common; k < n_levels; k++)
3020 const struct ctables_level *level = &levels[k];
3021 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3022 if (level->type == CTL_SUMMARY)
3024 assert (k == n_levels - 1);
3026 const struct ctables_summary_spec_set *specs = &t->summary_specs;
3027 for (size_t m = 0; m < specs->n; m++)
3029 int leaf = pivot_category_create_leaf (
3030 parent, pivot_value_new_text (specs->specs[m].label));
3037 const struct variable *var = nest->vars[level->var_idx];
3038 struct pivot_value *label;
3039 if (level->type == CTL_VAR)
3040 label = pivot_value_new_variable (var);
3041 else if (level->type == CTL_CATEGORY)
3043 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3044 label = ctables_category_create_label (cv->category,
3050 if (k == n_levels - 1)
3051 prev_leaf = pivot_category_create_leaf (parent, label);
3053 groups[k] = pivot_category_create_group__ (parent, label);
3057 cell->axes[a].leaf = prev_leaf;
3064 for (size_t i = 0; i < t->n_sections; i++)
3066 struct ctables_section *s = &t->sections[i];
3068 struct ctables_cell *cell;
3069 HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3074 const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3075 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3076 for (size_t j = 0; j < specs->n; j++)
3079 size_t n_dindexes = 0;
3081 if (summary_dimension)
3082 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3084 if (categories_dimension)
3086 const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3087 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3088 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3089 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3090 assert (ctv != NULL);
3091 dindexes[n_dindexes++] = ctv->leaf;
3094 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3097 int leaf = cell->axes[a].leaf;
3098 if (a == t->summary_axis && !summary_dimension)
3100 dindexes[n_dindexes++] = leaf;
3103 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
3104 struct pivot_value *value = pivot_value_new_number (d);
3105 value->numeric.format = specs->specs[j].format;
3106 pivot_table_put (pt, dindexes, n_dindexes, value);
3111 pivot_table_submit (pt);
3115 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3117 enum pivot_axis_type label_pos = t->label_axis[a];
3121 t->clabels_from_axis = a;
3123 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3124 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3126 const struct ctables_stack *stack = &t->stacks[a];
3130 const struct ctables_nest *n0 = &stack->nests[0];
3132 const struct variable *v0 = n0->vars[n0->n - 1];
3133 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3134 t->clabels_example = v0;
3136 for (size_t i = 0; i < c0->n_cats; i++)
3137 if (c0->cats[i].type == CCT_FUNCTION)
3139 msg (SE, _("%s=%s is not allowed with sorting based "
3140 "on a summary function."),
3141 subcommand_name, pos_name);
3144 if (n0->n - 1 == n0->scale_idx)
3146 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3147 "but %s is a scale variable."),
3148 subcommand_name, pos_name, var_get_name (v0));
3152 for (size_t i = 1; i < stack->n; i++)
3154 const struct ctables_nest *ni = &stack->nests[i];
3156 const struct variable *vi = ni->vars[ni->n - 1];
3157 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3159 if (ni->n - 1 == ni->scale_idx)
3161 msg (SE, _("%s=%s requires the variables to be moved to be "
3162 "categorical, but %s is a scale variable."),
3163 subcommand_name, pos_name, var_get_name (vi));
3166 if (var_get_width (v0) != var_get_width (vi))
3168 msg (SE, _("%s=%s requires the variables to be "
3169 "moved to have the same width, but %s has "
3170 "width %d and %s has width %d."),
3171 subcommand_name, pos_name,
3172 var_get_name (v0), var_get_width (v0),
3173 var_get_name (vi), var_get_width (vi));
3176 if (!val_labs_equal (var_get_value_labels (v0),
3177 var_get_value_labels (vi)))
3179 msg (SE, _("%s=%s requires the variables to be "
3180 "moved to have the same value labels, but %s "
3181 "and %s have different value labels."),
3182 subcommand_name, pos_name,
3183 var_get_name (v0), var_get_name (vi));
3186 if (!ctables_categories_equal (c0, ci))
3188 msg (SE, _("%s=%s requires the variables to be "
3189 "moved to have the same category "
3190 "specifications, but %s and %s have different "
3191 "category specifications."),
3192 subcommand_name, pos_name,
3193 var_get_name (v0), var_get_name (vi));
3202 ctables_prepare_table (struct ctables_table *t)
3204 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3207 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3209 for (size_t j = 0; j < t->stacks[a].n; j++)
3211 struct ctables_nest *nest = &t->stacks[a].nests[j];
3212 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3214 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3215 nest->n_domains[dt] = 0;
3217 for (size_t k = 0; k < nest->n; k++)
3219 if (k == nest->scale_idx)
3228 if (a != PIVOT_AXIS_LAYER)
3235 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3236 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3237 : a == PIVOT_AXIS_ROW)
3239 if (k == nest->n - 1
3240 || (nest->scale_idx == nest->n - 1
3241 && k == nest->n - 2))
3247 if (a == PIVOT_AXIS_COLUMN)
3252 if (a == PIVOT_AXIS_ROW)
3257 nest->domains[dt][nest->n_domains[dt]++] = k;
3264 struct ctables_nest *nest = xmalloc (sizeof *nest);
3265 *nest = (struct ctables_nest) { .n = 0 };
3266 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3269 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3270 for (size_t i = 0; i < stack->n; i++)
3272 struct ctables_nest *nest = &stack->nests[i];
3273 if (!nest->specs[CSV_CELL].n)
3275 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3276 specs->specs = xmalloc (sizeof *specs->specs);
3279 enum ctables_summary_function function
3280 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3281 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3283 *specs->specs = (struct ctables_summary_spec) {
3284 .function = function,
3285 .format = ctables_summary_default_format (function, &var),
3286 .label = ctables_summary_default_label (function, 0),
3289 specs->var = nest->vars[0];
3291 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3292 &nest->specs[CSV_CELL]);
3294 else if (!nest->specs[CSV_TOTAL].n)
3295 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3296 &nest->specs[CSV_CELL]);
3299 struct ctables_summary_spec_set *merged = &t->summary_specs;
3300 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3302 for (size_t j = 0; j < stack->n; j++)
3304 const struct ctables_nest *nest = &stack->nests[j];
3306 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3307 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3312 struct merge_item min = items[0];
3313 for (size_t j = 1; j < n_left; j++)
3314 if (merge_item_compare_3way (&items[j], &min) < 0)
3317 if (merged->n >= merged->allocated)
3318 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3319 sizeof *merged->specs);
3320 merged->specs[merged->n++] = min.set->specs[min.ofs];
3322 for (size_t j = 0; j < n_left; )
3324 if (merge_item_compare_3way (&items[j], &min) == 0)
3326 struct merge_item *item = &items[j];
3327 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3328 if (++item->ofs >= item->set->n)
3330 items[j] = items[--n_left];
3339 for (size_t j = 0; j < merged->n; j++)
3340 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3342 for (size_t j = 0; j < stack->n; j++)
3344 const struct ctables_nest *nest = &stack->nests[j];
3345 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3347 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3348 for (size_t k = 0; k < specs->n; k++)
3349 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3350 specs->specs[k].axis_idx);
3356 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3357 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3361 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3362 enum pivot_axis_type a)
3364 struct ctables_stack *stack = &t->stacks[a];
3365 for (size_t i = 0; i < stack->n; i++)
3367 const struct ctables_nest *nest = &stack->nests[i];
3368 const struct variable *var = nest->vars[nest->n - 1];
3369 int width = var_get_width (var);
3370 const union value *value = case_data (c, var);
3372 if (var_is_numeric (var) && value->f == SYSMIS)
3375 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3379 unsigned int hash = value_hash (value, width, 0);
3381 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3384 clv = xmalloc (sizeof *clv);
3385 value_clone (&clv->value, value, width);
3386 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3392 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3394 const struct ctables_value *const *ap = a_;
3395 const struct ctables_value *const *bp = b_;
3396 const struct ctables_value *a = *ap;
3397 const struct ctables_value *b = *bp;
3398 const int *width = width_;
3399 return value_compare_3way (&a->value, &b->value, *width);
3403 ctables_sort_clabels_values (struct ctables_table *t)
3405 int width = var_get_width (t->clabels_example);
3407 size_t n = hmap_count (&t->clabels_values_map);
3408 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3410 struct ctables_value *clv;
3412 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3413 t->clabels_values[i++] = clv;
3414 t->n_clabels_values = n;
3417 sort (t->clabels_values, n, sizeof *t->clabels_values,
3418 compare_clabels_values_3way, &width);
3420 for (size_t i = 0; i < n; i++)
3421 t->clabels_values[i]->leaf = i;
3425 ctables_add_category_occurrences (const struct variable *var,
3426 struct hmap *occurrences,
3427 const struct ctables_categories *cats)
3429 const struct val_labs *val_labs = var_get_value_labels (var);
3431 for (size_t i = 0; i < cats->n_cats; i++)
3433 const struct ctables_category *c = &cats->cats[i];
3437 ctables_add_occurrence (var, &(const union value) { .f = c->number },
3445 assert (var_is_numeric (var));
3446 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3447 vl = val_labs_next (val_labs, vl))
3448 if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
3449 ctables_add_occurrence (var, &vl->value, occurrences);
3453 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3454 vl = val_labs_next (val_labs, vl))
3455 if (var_is_value_missing (var, &vl->value))
3456 ctables_add_occurrence (var, &vl->value, occurrences);
3460 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3461 vl = val_labs_next (val_labs, vl))
3462 ctables_add_occurrence (var, &vl->value, occurrences);
3473 for (const struct val_lab *vl = val_labs_first (val_labs); vl;
3474 vl = val_labs_next (val_labs, vl))
3475 if (c->include_missing || !var_is_value_missing (var, &vl->value))
3476 ctables_add_occurrence (var, &vl->value, occurrences);
3483 ctables_section_recurse_add_empty_categories (
3484 struct ctables_section *s,
3485 const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
3486 enum pivot_axis_type a, size_t a_idx)
3488 if (a >= PIVOT_N_AXES)
3489 ctables_cell_insert__ (s, c, cats);
3490 else if (!s->nests[a] || a_idx >= s->nests[a]->n)
3491 ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
3494 const struct variable *var = s->nests[a]->vars[a_idx];
3495 int width = var_get_width (var);
3496 const struct hmap *occurrences = &s->occurrences[a][a_idx];
3497 const struct ctables_section_value *sv;
3498 HMAP_FOR_EACH (sv, struct ctables_section_value, node, occurrences)
3500 union value *value = case_data_rw (c, var);
3501 value_destroy (value, width);
3502 value_clone (value, &sv->value, width);
3503 cats[a][a_idx] = ctables_categories_match (
3504 s->table->categories[var_get_dict_index (var)], value, var);
3505 assert (cats[a][a_idx] != NULL);
3506 ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
3512 ctables_section_add_empty_categories (struct ctables_section *s)
3514 bool show_empty = false;
3515 for (size_t a = 0; a < PIVOT_N_AXES; a++)
3517 for (size_t k = 0; k < s->nests[a]->n; k++)
3518 if (k != s->nests[a]->scale_idx)
3520 const struct variable *var = s->nests[a]->vars[k];
3521 const struct ctables_categories *cats = s->table->categories[
3522 var_get_dict_index (var)];
3523 if (cats->show_empty)
3526 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
3532 const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
3533 struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
3534 ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
3539 ctables_execute (struct dataset *ds, struct ctables *ct)
3541 for (size_t i = 0; i < ct->n_tables; i++)
3543 struct ctables_table *t = ct->tables[i];
3544 t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
3545 MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
3546 MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
3547 sizeof *t->sections);
3548 size_t ix[PIVOT_N_AXES];
3549 ctables_table_add_section (t, 0, ix);
3552 struct casereader *input = proc_open (ds);
3553 bool warn_on_invalid = true;
3554 for (struct ccase *c = casereader_read (input); c;
3555 case_unref (c), c = casereader_read (input))
3557 double d_weight = dict_get_case_weight (dataset_dict (ds), c,
3559 double e_weight = (ct->e_weight
3560 ? var_force_valid_weight (ct->e_weight,
3561 case_num (c, ct->e_weight),
3565 for (size_t i = 0; i < ct->n_tables; i++)
3567 struct ctables_table *t = ct->tables[i];
3569 for (size_t j = 0; j < t->n_sections; j++)
3570 ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
3572 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3573 if (t->label_axis[a] != a)
3574 ctables_insert_clabels_values (t, c, a);
3577 casereader_destroy (input);
3579 for (size_t i = 0; i < ct->n_tables; i++)
3581 struct ctables_table *t = ct->tables[i];
3583 if (t->clabels_example)
3584 ctables_sort_clabels_values (t);
3586 for (size_t j = 0; j < t->n_sections; j++)
3587 ctables_section_add_empty_categories (&t->sections[j]);
3589 ctables_table_output (ct, ct->tables[i]);
3591 return proc_commit (ds);
3596 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
3599 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
3605 case CTPO_CAT_STRING:
3615 for (size_t i = 0; i < 2; i++)
3616 ctables_pcexpr_destroy (e->subs[i]);
3620 case CTPO_CAT_NUMBER:
3621 case CTPO_CAT_RANGE:
3622 case CTPO_CAT_MISSING:
3623 case CTPO_CAT_OTHERNM:
3624 case CTPO_CAT_SUBTOTAL:
3625 case CTPO_CAT_TOTAL:
3629 msg_location_destroy (e->location);
3634 static struct ctables_pcexpr *
3635 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
3636 struct ctables_pcexpr *sub0,
3637 struct ctables_pcexpr *sub1)
3639 struct ctables_pcexpr *e = xmalloc (sizeof *e);
3640 *e = (struct ctables_pcexpr) {
3642 .subs = { sub0, sub1 },
3643 .ofs = { sub0->ofs[0], sub1->ofs[1] }
3648 static struct msg_location *
3649 ctables_pcexpr_location (struct lexer *lexer, const struct ctables_pcexpr *e_)
3653 struct ctables_pcexpr *e = CONST_CAST (struct ctables_pcexpr *, e_);
3654 e->location = lex_ofs_location (lexer, e->ofs[0], e->ofs[1]);
3656 return e_->location;
3659 /* How to parse an operator. */
3662 enum token_type token;
3663 enum ctables_postcompute_op op;
3666 static const struct operator *
3667 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
3669 for (const struct operator *op = ops; op < ops + n_ops; op++)
3670 if (lex_token (lexer) == op->token)
3672 if (op->token != T_NEG_NUM)
3681 static struct ctables_pcexpr *
3682 parse_binary_operators__ (struct lexer *lexer,
3683 const struct operator ops[], size_t n_ops,
3684 parse_recursively_func *parse_next_level,
3685 const char *chain_warning,
3686 struct ctables_pcexpr *lhs)
3688 for (int op_count = 0; ; op_count++)
3690 const struct operator *op = match_operator (lexer, ops, n_ops);
3693 if (op_count > 1 && chain_warning)
3694 msg_at (SW, ctables_pcexpr_location (lexer, lhs),
3695 "%s", chain_warning);
3700 struct ctables_pcexpr *rhs = parse_next_level (lexer);
3703 ctables_pcexpr_destroy (lhs);
3707 lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
3711 static struct ctables_pcexpr *
3712 parse_binary_operators (struct lexer *lexer,
3713 const struct operator ops[], size_t n_ops,
3714 parse_recursively_func *parse_next_level,
3715 const char *chain_warning)
3717 struct ctables_pcexpr *lhs = parse_next_level (lexer);
3721 return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
3722 chain_warning, lhs);
3725 static struct ctables_pcexpr *parse_add (struct lexer *);
3727 static struct ctables_pcexpr
3728 ctpo_cat_range (double low, double high)
3730 return (struct ctables_pcexpr) {
3731 .op = CTPO_CAT_RANGE,
3732 .range = { low, high },
3736 static struct ctables_pcexpr *
3737 parse_primary (struct lexer *lexer)
3739 int start_ofs = lex_ofs (lexer);
3740 struct ctables_pcexpr e;
3741 if (lex_is_number (lexer))
3743 e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
3744 .number = lex_number (lexer) };
3747 else if (lex_match_id (lexer, "MISSING"))
3748 e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
3749 else if (lex_match_id (lexer, "OTHERNM"))
3750 e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
3751 else if (lex_match_id (lexer, "TOTAL"))
3752 e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
3753 else if (lex_match_id (lexer, "SUBTOTAL"))
3755 size_t subtotal_index = 0;
3756 if (lex_match (lexer, T_LBRACK))
3758 if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
3760 subtotal_index = lex_integer (lexer);
3762 if (!lex_force_match (lexer, T_RBRACK))
3765 e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
3766 .subtotal_index = subtotal_index };
3768 else if (lex_match (lexer, T_LBRACK))
3770 if (lex_match_id (lexer, "LO"))
3772 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
3774 e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
3777 else if (lex_is_number (lexer))
3779 double number = lex_number (lexer);
3781 if (lex_match_id (lexer, "THRU"))
3783 if (lex_match_id (lexer, "HI"))
3784 e = ctpo_cat_range (number, DBL_MAX);
3787 if (!lex_force_num (lexer))
3789 e = ctpo_cat_range (number, lex_number (lexer));
3794 e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
3797 else if (lex_is_string (lexer))
3799 e = (struct ctables_pcexpr) {
3800 .op = CTPO_CAT_STRING,
3801 .string = ss_xstrdup (lex_tokss (lexer)),
3807 lex_error (lexer, NULL);
3811 if (!lex_force_match (lexer, T_RBRACK))
3813 if (e.op == CTPO_CAT_STRING)
3818 else if (lex_match (lexer, T_LPAREN))
3820 struct ctables_pcexpr *ep = parse_add (lexer);
3823 if (!lex_force_match (lexer, T_RPAREN))
3825 ctables_pcexpr_destroy (ep);
3832 lex_error (lexer, NULL);
3836 e.ofs[0] = start_ofs;
3837 e.ofs[1] = lex_ofs (lexer) - 1;
3838 return xmemdup (&e, sizeof e);
3841 static struct ctables_pcexpr *
3842 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
3843 struct lexer *lexer, int start_ofs)
3845 struct ctables_pcexpr *e = xmalloc (sizeof *e);
3846 *e = (struct ctables_pcexpr) {
3849 .ofs = { start_ofs, lex_ofs (lexer) - 1 },
3854 static struct ctables_pcexpr *
3855 parse_exp (struct lexer *lexer)
3857 static const struct operator op = { T_EXP, CTPO_POW };
3859 const char *chain_warning =
3860 _("The exponentiation operator (`**') is left-associative: "
3861 "`a**b**c' equals `(a**b)**c', not `a**(b**c)'. "
3862 "To disable this warning, insert parentheses.");
3864 if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
3865 return parse_binary_operators (lexer, &op, 1,
3866 parse_primary, chain_warning);
3868 /* Special case for situations like "-5**6", which must be parsed as
3871 int start_ofs = lex_ofs (lexer);
3872 struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
3873 *lhs = (struct ctables_pcexpr) {
3874 .op = CTPO_CONSTANT,
3875 .number = -lex_tokval (lexer),
3876 .ofs = { start_ofs, lex_ofs (lexer) },
3880 struct ctables_pcexpr *node = parse_binary_operators__ (
3881 lexer, &op, 1, parse_primary, chain_warning, lhs);
3885 return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
3888 /* Parses the unary minus level. */
3889 static struct ctables_pcexpr *
3890 parse_neg (struct lexer *lexer)
3892 int start_ofs = lex_ofs (lexer);
3893 if (!lex_match (lexer, T_DASH))
3894 return parse_exp (lexer);
3896 struct ctables_pcexpr *inner = parse_neg (lexer);
3900 return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
3903 /* Parses the multiplication and division level. */
3904 static struct ctables_pcexpr *
3905 parse_mul (struct lexer *lexer)
3907 static const struct operator ops[] =
3909 { T_ASTERISK, CTPO_MUL },
3910 { T_SLASH, CTPO_DIV },
3913 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
3917 /* Parses the addition and subtraction level. */
3918 static struct ctables_pcexpr *
3919 parse_add (struct lexer *lexer)
3921 static const struct operator ops[] =
3923 { T_PLUS, CTPO_ADD },
3924 { T_DASH, CTPO_SUB },
3925 { T_NEG_NUM, CTPO_ADD },
3928 return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
3932 static struct ctables_postcompute *
3933 ctables_find_postcompute (struct ctables *ct, const char *name)
3935 struct ctables_postcompute *pc;
3936 HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
3937 utf8_hash_case_string (name, 0), &ct->postcomputes)
3938 if (!utf8_strcasecmp (pc->name, name))
3944 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
3946 int start_ofs = lex_ofs (lexer) - 1;
3948 if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
3951 char *name = ss_xstrdup (lex_tokss (lexer));
3954 if (!lex_force_match (lexer, T_EQUALS)
3955 || !lex_force_match_id (lexer, "EXPR")
3956 || !lex_force_match (lexer, T_LPAREN))
3962 struct ctables_pcexpr *expr = parse_add (lexer);
3963 if (!expr || !lex_force_match (lexer, T_RPAREN))
3969 struct msg_location *location = lex_ofs_location (lexer, start_ofs,
3970 lex_ofs (lexer) - 1);
3972 struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
3975 msg_at (SW, location, _("New definition of &%s will override the "
3976 "previous definition."),
3978 msg_at (SN, pc->location, _("This is the previous definition."));
3980 ctables_pcexpr_destroy (pc->expr);
3981 msg_location_destroy (pc->location);
3986 pc = xmalloc (sizeof *pc);
3987 *pc = (struct ctables_postcompute) { .name = name };
3988 hmap_insert (&ct->postcomputes, &pc->hmap_node,
3989 utf8_hash_case_string (pc->name, 0));
3992 pc->location = location;
3997 ctables_parse_pproperties_format (struct lexer *lexer,
3998 struct ctables_summary_spec_set *sss)
4000 *sss = (struct ctables_summary_spec_set) { .n = 0 };
4002 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4003 && !(lex_token (lexer) == T_ID
4004 && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4005 || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4006 lex_tokss (lexer)))))
4008 /* Parse function. */
4009 enum ctables_summary_function function;
4010 if (!parse_ctables_summary_function (lexer, &function))
4013 /* Parse percentile. */
4014 double percentile = 0;
4015 if (function == CTSF_PTILE)
4017 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4019 percentile = lex_number (lexer);
4024 struct fmt_spec format;
4025 if (!parse_format_specifier (lexer, &format)
4026 || !fmt_check_output (&format)
4027 || !fmt_check_type_compat (&format, VAL_NUMERIC))
4030 if (sss->n >= sss->allocated)
4031 sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4032 sizeof *sss->specs);
4033 sss->specs[sss->n++] = (struct ctables_summary_spec) {
4034 .function = function,
4035 .percentile = percentile,
4042 ctables_summary_spec_set_uninit (sss);
4047 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4049 struct ctables_postcompute **pcs = NULL;
4051 size_t allocated_pcs = 0;
4053 while (lex_match (lexer, T_AND))
4055 if (!lex_force_id (lexer))
4057 struct ctables_postcompute *pc
4058 = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4061 msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4066 if (n_pcs >= allocated_pcs)
4067 pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4071 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4073 if (lex_match_id (lexer, "LABEL"))
4075 lex_match (lexer, T_EQUALS);
4076 if (!lex_force_string (lexer))
4079 for (size_t i = 0; i < n_pcs; i++)
4081 free (pcs[i]->label);
4082 pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4087 else if (lex_match_id (lexer, "FORMAT"))
4089 lex_match (lexer, T_EQUALS);
4091 struct ctables_summary_spec_set sss;
4092 if (!ctables_parse_pproperties_format (lexer, &sss))
4095 for (size_t i = 0; i < n_pcs; i++)
4098 ctables_summary_spec_set_uninit (pcs[i]->specs);
4100 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4101 ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4103 ctables_summary_spec_set_uninit (&sss);
4105 else if (lex_match_id (lexer, "HIDESOURCECATS"))
4107 lex_match (lexer, T_EQUALS);
4108 bool hide_source_cats;
4109 if (!parse_bool (lexer, &hide_source_cats))
4111 for (size_t i = 0; i < n_pcs; i++)
4112 pcs[i]->hide_source_cats = hide_source_cats;
4116 lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4129 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4131 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4132 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4133 enum settings_value_show tvars = settings_get_show_variables ();
4134 for (size_t i = 0; i < n_vars; i++)
4135 vlabels[i] = (enum ctables_vlabel) tvars;
4137 struct ctables *ct = xmalloc (sizeof *ct);
4138 *ct = (struct ctables) {
4139 .dict = dataset_dict (ds),
4140 .look = pivot_table_look_unshare (pivot_table_look_ref (
4141 pivot_table_look_get_default ())),
4143 .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
4144 .hide_threshold = 5,
4146 ct->look->omit_empty = false;
4148 if (!lex_force_match (lexer, T_SLASH))
4151 while (!lex_match_id (lexer, "TABLE"))
4153 if (lex_match_id (lexer, "FORMAT"))
4155 double widths[2] = { SYSMIS, SYSMIS };
4156 double units_per_inch = 72.0;
4158 while (lex_token (lexer) != T_SLASH)
4160 if (lex_match_id (lexer, "MINCOLWIDTH"))
4162 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4165 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4167 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4170 else if (lex_match_id (lexer, "UNITS"))
4172 lex_match (lexer, T_EQUALS);
4173 if (lex_match_id (lexer, "POINTS"))
4174 units_per_inch = 72.0;
4175 else if (lex_match_id (lexer, "INCHES"))
4176 units_per_inch = 1.0;
4177 else if (lex_match_id (lexer, "CM"))
4178 units_per_inch = 2.54;
4181 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4185 else if (lex_match_id (lexer, "EMPTY"))
4190 lex_match (lexer, T_EQUALS);
4191 if (lex_match_id (lexer, "ZERO"))
4193 /* Nothing to do. */
4195 else if (lex_match_id (lexer, "BLANK"))
4196 ct->zero = xstrdup ("");
4197 else if (lex_force_string (lexer))
4199 ct->zero = ss_xstrdup (lex_tokss (lexer));
4205 else if (lex_match_id (lexer, "MISSING"))
4207 lex_match (lexer, T_EQUALS);
4208 if (!lex_force_string (lexer))
4212 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4213 ? ss_xstrdup (lex_tokss (lexer))
4219 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4220 "UNITS", "EMPTY", "MISSING");
4225 if (widths[0] != SYSMIS && widths[1] != SYSMIS
4226 && widths[0] > widths[1])
4228 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4232 for (size_t i = 0; i < 2; i++)
4233 if (widths[i] != SYSMIS)
4235 int *wr = ct->look->width_ranges[TABLE_HORZ];
4236 wr[i] = widths[i] / units_per_inch * 96.0;
4241 else if (lex_match_id (lexer, "VLABELS"))
4243 if (!lex_force_match_id (lexer, "VARIABLES"))
4245 lex_match (lexer, T_EQUALS);
4247 struct variable **vars;
4249 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4253 if (!lex_force_match_id (lexer, "DISPLAY"))
4258 lex_match (lexer, T_EQUALS);
4260 enum ctables_vlabel vlabel;
4261 if (lex_match_id (lexer, "DEFAULT"))
4262 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4263 else if (lex_match_id (lexer, "NAME"))
4265 else if (lex_match_id (lexer, "LABEL"))
4266 vlabel = CTVL_LABEL;
4267 else if (lex_match_id (lexer, "BOTH"))
4269 else if (lex_match_id (lexer, "NONE"))
4273 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4279 for (size_t i = 0; i < n_vars; i++)
4280 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4283 else if (lex_match_id (lexer, "MRSETS"))
4285 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4287 lex_match (lexer, T_EQUALS);
4288 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4291 else if (lex_match_id (lexer, "SMISSING"))
4293 if (lex_match_id (lexer, "VARIABLE"))
4294 ct->smissing_listwise = false;
4295 else if (lex_match_id (lexer, "LISTWISE"))
4296 ct->smissing_listwise = true;
4299 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4303 else if (lex_match_id (lexer, "PCOMPUTE"))
4305 if (!ctables_parse_pcompute (lexer, ct))
4308 else if (lex_match_id (lexer, "PPROPERTIES"))
4310 if (!ctables_parse_pproperties (lexer, ct))
4313 else if (lex_match_id (lexer, "WEIGHT"))
4315 if (!lex_force_match_id (lexer, "VARIABLE"))
4317 lex_match (lexer, T_EQUALS);
4318 ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4322 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
4324 if (!lex_force_match_id (lexer, "COUNT"))
4326 lex_match (lexer, T_EQUALS);
4327 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
4329 ct->hide_threshold = lex_integer (lexer);
4334 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4335 "SMISSING", "PCOMPUTE", "PPROPERTIES",
4336 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4340 if (!lex_force_match (lexer, T_SLASH))
4344 size_t allocated_tables = 0;
4347 if (ct->n_tables >= allocated_tables)
4348 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4349 sizeof *ct->tables);
4351 struct ctables_category *cat = xmalloc (sizeof *cat);
4352 *cat = (struct ctables_category) {
4354 .include_missing = false,
4355 .sort_ascending = true,
4358 struct ctables_categories *c = xmalloc (sizeof *c);
4359 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4360 *c = (struct ctables_categories) {
4367 struct ctables_categories **categories = xnmalloc (n_vars,
4368 sizeof *categories);
4369 for (size_t i = 0; i < n_vars; i++)
4372 struct ctables_table *t = xmalloc (sizeof *t);
4373 *t = (struct ctables_table) {
4375 .slabels_axis = PIVOT_AXIS_COLUMN,
4376 .slabels_visible = true,
4377 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
4379 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
4380 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
4381 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
4383 .clabels_from_axis = PIVOT_AXIS_LAYER,
4384 .categories = categories,
4385 .n_categories = n_vars,
4388 ct->tables[ct->n_tables++] = t;
4390 lex_match (lexer, T_EQUALS);
4391 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
4393 if (lex_match (lexer, T_BY))
4395 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4396 ct, t, PIVOT_AXIS_COLUMN))
4399 if (lex_match (lexer, T_BY))
4401 if (!ctables_axis_parse (lexer, dataset_dict (ds),
4402 ct, t, PIVOT_AXIS_LAYER))
4407 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
4408 && !t->axes[PIVOT_AXIS_LAYER])
4410 lex_error (lexer, _("At least one variable must be specified."));
4414 const struct ctables_axis *scales[PIVOT_N_AXES];
4415 size_t n_scales = 0;
4416 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4418 scales[a] = find_scale (t->axes[a]);
4424 msg (SE, _("Scale variables may appear only on one axis."));
4425 if (scales[PIVOT_AXIS_ROW])
4426 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
4427 _("This scale variable appears on the rows axis."));
4428 if (scales[PIVOT_AXIS_COLUMN])
4429 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
4430 _("This scale variable appears on the columns axis."));
4431 if (scales[PIVOT_AXIS_LAYER])
4432 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
4433 _("This scale variable appears on the layer axis."));
4437 const struct ctables_axis *summaries[PIVOT_N_AXES];
4438 size_t n_summaries = 0;
4439 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4441 summaries[a] = (scales[a]
4443 : find_categorical_summary_spec (t->axes[a]));
4447 if (n_summaries > 1)
4449 msg (SE, _("Summaries may appear only on one axis."));
4450 if (summaries[PIVOT_AXIS_ROW])
4451 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
4452 _("This variable on the rows axis has a summary."));
4453 if (summaries[PIVOT_AXIS_COLUMN])
4454 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
4455 _("This variable on the columns axis has a summary."));
4456 if (summaries[PIVOT_AXIS_LAYER])
4457 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
4458 _("This variable on the layers axis has a summary."));
4461 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4462 if (n_summaries ? summaries[a] : t->axes[a])
4464 t->summary_axis = a;
4468 if (lex_token (lexer) == T_ENDCMD)
4470 if (!ctables_prepare_table (t))
4474 if (!lex_force_match (lexer, T_SLASH))
4477 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
4479 if (lex_match_id (lexer, "SLABELS"))
4481 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4483 if (lex_match_id (lexer, "POSITION"))
4485 lex_match (lexer, T_EQUALS);
4486 if (lex_match_id (lexer, "COLUMN"))
4487 t->slabels_axis = PIVOT_AXIS_COLUMN;
4488 else if (lex_match_id (lexer, "ROW"))
4489 t->slabels_axis = PIVOT_AXIS_ROW;
4490 else if (lex_match_id (lexer, "LAYER"))
4491 t->slabels_axis = PIVOT_AXIS_LAYER;
4494 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
4498 else if (lex_match_id (lexer, "VISIBLE"))
4500 lex_match (lexer, T_EQUALS);
4501 if (!parse_bool (lexer, &t->slabels_visible))
4506 lex_error_expecting (lexer, "POSITION", "VISIBLE");
4511 else if (lex_match_id (lexer, "CLABELS"))
4513 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4515 if (lex_match_id (lexer, "AUTO"))
4517 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
4518 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
4520 else if (lex_match_id (lexer, "ROWLABELS"))
4522 lex_match (lexer, T_EQUALS);
4523 if (lex_match_id (lexer, "OPPOSITE"))
4524 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
4525 else if (lex_match_id (lexer, "LAYER"))
4526 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
4529 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4533 else if (lex_match_id (lexer, "COLLABELS"))
4535 lex_match (lexer, T_EQUALS);
4536 if (lex_match_id (lexer, "OPPOSITE"))
4537 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
4538 else if (lex_match_id (lexer, "LAYER"))
4539 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
4542 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
4548 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
4554 else if (lex_match_id (lexer, "CRITERIA"))
4556 if (!lex_force_match_id (lexer, "CILEVEL"))
4558 lex_match (lexer, T_EQUALS);
4560 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
4562 t->cilevel = lex_number (lexer);
4565 else if (lex_match_id (lexer, "CATEGORIES"))
4567 if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
4570 else if (lex_match_id (lexer, "TITLES"))
4575 if (lex_match_id (lexer, "CAPTION"))
4576 textp = &t->caption;
4577 else if (lex_match_id (lexer, "CORNER"))
4579 else if (lex_match_id (lexer, "TITLE"))
4583 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
4586 lex_match (lexer, T_EQUALS);
4588 struct string s = DS_EMPTY_INITIALIZER;
4589 while (lex_is_string (lexer))
4591 if (!ds_is_empty (&s))
4592 ds_put_byte (&s, ' ');
4593 ds_put_substring (&s, lex_tokss (lexer));
4597 *textp = ds_steal_cstr (&s);
4599 while (lex_token (lexer) != T_SLASH
4600 && lex_token (lexer) != T_ENDCMD);
4602 else if (lex_match_id (lexer, "SIGTEST"))
4606 t->chisq = xmalloc (sizeof *t->chisq);
4607 *t->chisq = (struct ctables_chisq) {
4609 .include_mrsets = true,
4610 .all_visible = true,
4616 if (lex_match_id (lexer, "TYPE"))
4618 lex_match (lexer, T_EQUALS);
4619 if (!lex_force_match_id (lexer, "CHISQUARE"))
4622 else if (lex_match_id (lexer, "ALPHA"))
4624 lex_match (lexer, T_EQUALS);
4625 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
4627 t->chisq->alpha = lex_number (lexer);
4630 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
4632 lex_match (lexer, T_EQUALS);
4633 if (parse_bool (lexer, &t->chisq->include_mrsets))
4636 else if (lex_match_id (lexer, "CATEGORIES"))
4638 lex_match (lexer, T_EQUALS);
4639 if (lex_match_id (lexer, "ALLVISIBLE"))
4640 t->chisq->all_visible = true;
4641 else if (lex_match_id (lexer, "SUBTOTALS"))
4642 t->chisq->all_visible = false;
4645 lex_error_expecting (lexer,
4646 "ALLVISIBLE", "SUBTOTALS");
4652 lex_error_expecting (lexer, "TYPE", "ALPHA",
4653 "INCLUDEMRSETS", "CATEGORIES");
4657 while (lex_token (lexer) != T_SLASH
4658 && lex_token (lexer) != T_ENDCMD);
4660 else if (lex_match_id (lexer, "COMPARETEST"))
4664 t->pairwise = xmalloc (sizeof *t->pairwise);
4665 *t->pairwise = (struct ctables_pairwise) {
4667 .alpha = { .05, .05 },
4668 .adjust = BONFERRONI,
4669 .include_mrsets = true,
4670 .meansvariance_allcats = true,
4671 .all_visible = true,
4680 if (lex_match_id (lexer, "TYPE"))
4682 lex_match (lexer, T_EQUALS);
4683 if (lex_match_id (lexer, "PROP"))
4684 t->pairwise->type = PROP;
4685 else if (lex_match_id (lexer, "MEAN"))
4686 t->pairwise->type = MEAN;
4689 lex_error_expecting (lexer, "PROP", "MEAN");
4693 else if (lex_match_id (lexer, "ALPHA"))
4695 lex_match (lexer, T_EQUALS);
4697 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
4699 double a0 = lex_number (lexer);
4702 lex_match (lexer, T_COMMA);
4703 if (lex_is_number (lexer))
4705 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
4707 double a1 = lex_number (lexer);
4710 t->pairwise->alpha[0] = MIN (a0, a1);
4711 t->pairwise->alpha[1] = MAX (a0, a1);
4714 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
4716 else if (lex_match_id (lexer, "ADJUST"))
4718 lex_match (lexer, T_EQUALS);
4719 if (lex_match_id (lexer, "BONFERRONI"))
4720 t->pairwise->adjust = BONFERRONI;
4721 else if (lex_match_id (lexer, "BH"))
4722 t->pairwise->adjust = BH;
4723 else if (lex_match_id (lexer, "NONE"))
4724 t->pairwise->adjust = 0;
4727 lex_error_expecting (lexer, "BONFERRONI", "BH",
4732 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
4734 lex_match (lexer, T_EQUALS);
4735 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
4738 else if (lex_match_id (lexer, "MEANSVARIANCE"))
4740 lex_match (lexer, T_EQUALS);
4741 if (lex_match_id (lexer, "ALLCATS"))
4742 t->pairwise->meansvariance_allcats = true;
4743 else if (lex_match_id (lexer, "TESTEDCATS"))
4744 t->pairwise->meansvariance_allcats = false;
4747 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
4751 else if (lex_match_id (lexer, "CATEGORIES"))
4753 lex_match (lexer, T_EQUALS);
4754 if (lex_match_id (lexer, "ALLVISIBLE"))
4755 t->pairwise->all_visible = true;
4756 else if (lex_match_id (lexer, "SUBTOTALS"))
4757 t->pairwise->all_visible = false;
4760 lex_error_expecting (lexer, "ALLVISIBLE",
4765 else if (lex_match_id (lexer, "MERGE"))
4767 lex_match (lexer, T_EQUALS);
4768 if (!parse_bool (lexer, &t->pairwise->merge))
4771 else if (lex_match_id (lexer, "STYLE"))
4773 lex_match (lexer, T_EQUALS);
4774 if (lex_match_id (lexer, "APA"))
4775 t->pairwise->apa_style = true;
4776 else if (lex_match_id (lexer, "SIMPLE"))
4777 t->pairwise->apa_style = false;
4780 lex_error_expecting (lexer, "APA", "SIMPLE");
4784 else if (lex_match_id (lexer, "SHOWSIG"))
4786 lex_match (lexer, T_EQUALS);
4787 if (!parse_bool (lexer, &t->pairwise->show_sig))
4792 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
4793 "INCLUDEMRSETS", "MEANSVARIANCE",
4794 "CATEGORIES", "MERGE", "STYLE",
4799 while (lex_token (lexer) != T_SLASH
4800 && lex_token (lexer) != T_ENDCMD);
4804 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
4805 "CRITERIA", "CATEGORIES", "TITLES",
4806 "SIGTEST", "COMPARETEST");
4810 if (!lex_match (lexer, T_SLASH))
4814 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
4815 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
4817 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
4821 if (!ctables_prepare_table (t))
4824 while (lex_token (lexer) != T_ENDCMD);
4826 bool ok = ctables_execute (ds, ct);
4827 ctables_destroy (ct);
4828 return ok ? CMD_SUCCESS : CMD_FAILURE;
4831 ctables_destroy (ct);