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/dataset.h"
23 #include "data/dictionary.h"
24 #include "data/mrset.h"
25 #include "data/value-labels.h"
26 #include "language/command.h"
27 #include "language/lexer/format-parser.h"
28 #include "language/lexer/lexer.h"
29 #include "language/lexer/variable-parser.h"
30 #include "libpspp/array.h"
31 #include "libpspp/assertion.h"
32 #include "libpspp/hash-functions.h"
33 #include "libpspp/hmap.h"
34 #include "libpspp/message.h"
35 #include "libpspp/string-array.h"
36 #include "math/moments.h"
37 #include "output/pivot-table.h"
39 #include "gl/minmax.h"
40 #include "gl/xalloc.h"
43 #define _(msgid) gettext (msgid)
44 #define N_(msgid) (msgid)
48 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
49 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
50 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
51 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
55 - unweighted summaries (U*)
56 - lower confidence limits (*.LCL)
57 - upper confidence limits (*.UCL)
58 - standard error (*.SE)
61 /* All variables. */ \
62 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
63 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
64 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
65 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
66 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
67 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
68 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
69 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
70 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
71 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
72 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
86 /* Scale variables, totals, and subtotals. */ \
87 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
88 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
89 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
90 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
91 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
92 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
93 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
94 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
95 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
98 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
99 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
100 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
101 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
102 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
103 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
104 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
105 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
106 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
107 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
108 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
109 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
111 /* Multiple response sets. */ \
112 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
113 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
114 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
115 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
116 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
117 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
118 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
119 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
120 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
121 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
135 enum ctables_summary_function
137 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
143 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
144 N_CTSF_FUNCTIONS = SUMMARIES
148 enum ctables_domain_type
150 /* Within a section, where stacked variables divide one section from
152 CTDT_TABLE, /* All layers of a whole section. */
153 CTDT_LAYER, /* One layer within a section. */
154 CTDT_LAYERROW, /* Row in one layer within a section. */
155 CTDT_LAYERCOL, /* Column in one layer within a section. */
157 /* Within a subtable, where a subtable pairs an innermost row variable with
158 an innermost column variable within a single layer. */
159 CTDT_SUBTABLE, /* Whole subtable. */
160 CTDT_ROW, /* Row within a subtable. */
161 CTDT_COL, /* Column within a subtable. */
165 struct ctables_domain
167 struct hmap_node node;
169 const struct ctables_cell *example;
175 enum ctables_summary_variant
184 /* In struct ctables's 'cells' hmap. Indexed by all the values in all the
185 axes (except the scalar variable, if any). */
186 struct hmap_node node;
188 /* The domains that contain this cell. */
189 struct ctables_domain *domains[N_CTDTS];
192 enum ctables_summary_variant sv;
197 struct ctables_cell_value
199 const struct ctables_category *category;
207 union ctables_summary *summaries;
212 struct pivot_table_look *look;
214 /* If this is NULL, zeros are displayed using the normal print format.
215 Otherwise, this string is displayed. */
218 /* If this is NULL, missing values are displayed using the normal print
219 format. Otherwise, this string is displayed. */
222 /* Indexed by variable dictionary index. */
223 enum ctables_vlabel *vlabels;
225 bool mrsets_count_duplicates; /* MRSETS. */
226 bool smissing_listwise; /* SMISSING. */
227 struct variable *base_weight; /* WEIGHT. */
228 int hide_threshold; /* HIDESMALLCOUNTS. */
230 struct ctables_table **tables;
234 struct ctables_postcompute
236 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
237 const char *name; /* Name, without leading &. */
239 struct ctables_postcompute_expr *expr;
242 bool hide_source_cats;
245 struct ctables_postcompute_expr
247 enum ctables_postcompute_op
255 /* XXX SUBTOTAL and HSUBTOTAL */
268 /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
273 XXX what about string ranges? */
276 /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
277 struct ctables_postcompute_expr *subs[2];
281 struct ctables_summary_spec_set
283 struct ctables_summary_spec *specs;
287 struct variable *var;
290 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
291 const struct ctables_summary_spec_set *);
292 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
294 /* A nested sequence of variables, e.g. a > b > c. */
297 struct variable **vars;
300 size_t *domains[N_CTDTS];
301 size_t n_domains[N_CTDTS];
303 struct ctables_summary_spec_set specs[N_CSVS];
306 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
309 struct ctables_nest *nests;
315 struct hmap_node node;
322 struct ctables_axis *axes[PIVOT_N_AXES];
323 struct ctables_stack stacks[PIVOT_N_AXES];
324 enum pivot_axis_type summary_axis;
325 struct ctables_summary_spec_set summary_specs;
327 struct hmap domains[N_CTDTS];
329 const struct variable *clabels_example;
330 struct hmap clabels_values_map;
331 struct ctables_value **clabels_values;
332 size_t n_clabels_values;
334 enum pivot_axis_type slabels_axis;
335 bool slabels_visible;
337 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
339 Most commonly, label_axis[a] == a, and in particular we always have
340 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
342 If ROWLABELS or COLLABELS is specified, then one of
343 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
344 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
346 enum pivot_axis_type label_axis[PIVOT_N_AXES];
347 enum pivot_axis_type clabels_from_axis;
349 /* Indexed by variable dictionary index. */
350 struct ctables_categories **categories;
359 struct ctables_chisq *chisq;
360 struct ctables_pairwise *pairwise;
368 struct variable *var;
369 const struct mrset *mrset;
373 static const struct fmt_spec *
374 ctables_var_get_print_format (const struct ctables_var *var)
376 return (var->is_mrset
377 ? var_get_print_format (var->mrset->vars[0])
378 : var_get_print_format (var->var));
382 ctables_var_name (const struct ctables_var *var)
384 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
387 struct ctables_categories
390 struct ctables_category *cats;
395 struct ctables_category
397 enum ctables_category_type
415 struct ctables_category *subtotal;
419 double number; /* CCT_NUMBER. */
420 char *string; /* CCT_STRING. */
421 double range[2]; /* CCT_RANGE. */
422 char *total_label; /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
424 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
427 bool include_missing;
431 enum ctables_summary_function sort_function;
432 struct variable *sort_var;
439 ctables_category_uninit (struct ctables_category *cat)
459 free (cat->total_label);
470 ctables_category_equal (const struct ctables_category *a,
471 const struct ctables_category *b)
473 if (a->type != b->type)
479 return a->number == b->number;
482 return strcmp (a->string, b->string);
485 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
494 return !strcmp (a->total_label, b->total_label);
499 return (a->include_missing == b->include_missing
500 && a->sort_ascending == b->sort_ascending
501 && a->sort_function == b->sort_function
502 && a->sort_var == b->sort_var
503 && a->percentile == b->percentile);
510 ctables_categories_unref (struct ctables_categories *c)
515 assert (c->n_refs > 0);
519 for (size_t i = 0; i < c->n_cats; i++)
520 ctables_category_uninit (&c->cats[i]);
526 ctables_categories_equal (const struct ctables_categories *a,
527 const struct ctables_categories *b)
529 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
532 for (size_t i = 0; i < a->n_cats; i++)
533 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
539 /* Chi-square test (SIGTEST). */
547 /* Pairwise comparison test (COMPARETEST). */
548 struct ctables_pairwise
550 enum { PROP, MEAN } type;
553 bool meansvariance_allcats;
555 enum { BONFERRONI = 1, BH } adjust;
579 struct ctables_var var;
581 struct ctables_summary_spec_set specs[N_CSVS];
585 struct ctables_axis *subs[2];
588 struct msg_location *loc;
591 static void ctables_axis_destroy (struct ctables_axis *);
600 enum ctables_function_availability
602 CTFA_ALL, /* Any variables. */
603 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
604 CTFA_MRSETS, /* Only multiple-response sets */
607 struct ctables_summary_spec
609 enum ctables_summary_function function;
610 double percentile; /* CTSF_PTILE only. */
612 struct fmt_spec format; /* XXX extra CTABLES formats */
617 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
618 const struct ctables_summary_spec *src)
621 dst->label = xstrdup (src->label);
625 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
632 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
633 const struct ctables_summary_spec_set *src)
635 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
636 for (size_t i = 0; i < src->n; i++)
637 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
639 *dst = (struct ctables_summary_spec_set) {
648 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
650 for (size_t i = 0; i < set->n; i++)
651 ctables_summary_spec_uninit (&set->specs[i]);
656 parse_col_width (struct lexer *lexer, const char *name, double *width)
658 lex_match (lexer, T_EQUALS);
659 if (lex_match_id (lexer, "DEFAULT"))
661 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
663 *width = lex_number (lexer);
673 parse_bool (struct lexer *lexer, bool *b)
675 if (lex_match_id (lexer, "NO"))
677 else if (lex_match_id (lexer, "YES"))
681 lex_error_expecting (lexer, "YES", "NO");
687 static enum ctables_function_availability
688 ctables_function_availability (enum ctables_summary_function f)
690 static enum ctables_function_availability availability[] = {
691 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
696 return availability[f];
700 parse_ctables_summary_function (struct lexer *lexer,
701 enum ctables_summary_function *f)
705 enum ctables_summary_function function;
706 struct substring name;
708 static struct pair names[] = {
709 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
710 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
713 /* The .COUNT suffix may be omitted. */
714 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
715 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
716 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
717 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
718 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
719 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
720 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
724 if (!lex_force_id (lexer))
727 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
728 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
730 *f = names[i].function;
735 lex_error (lexer, _("Expecting summary function name."));
740 ctables_axis_destroy (struct ctables_axis *axis)
748 for (size_t i = 0; i < N_CSVS; i++)
749 ctables_summary_spec_set_uninit (&axis->specs[i]);
754 ctables_axis_destroy (axis->subs[0]);
755 ctables_axis_destroy (axis->subs[1]);
758 msg_location_destroy (axis->loc);
762 static struct ctables_axis *
763 ctables_axis_new_nonterminal (enum ctables_axis_op op,
764 struct ctables_axis *sub0,
765 struct ctables_axis *sub1,
766 struct lexer *lexer, int start_ofs)
768 struct ctables_axis *axis = xmalloc (sizeof *axis);
769 *axis = (struct ctables_axis) {
771 .subs = { sub0, sub1 },
772 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
777 struct ctables_axis_parse_ctx
780 struct dictionary *dict;
782 struct ctables_table *t;
785 static struct fmt_spec
786 ctables_summary_default_format (enum ctables_summary_function function,
787 const struct ctables_var *var)
789 static const enum ctables_format default_formats[] = {
790 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
794 switch (default_formats[function])
797 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
800 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
803 return *ctables_var_get_print_format (var);
811 ctables_summary_default_label (enum ctables_summary_function function,
814 static const char *default_labels[] = {
815 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
820 return (function == CTSF_PTILE
821 ? xasprintf (_("Percentile %.2f"), percentile)
822 : xstrdup (gettext (default_labels[function])));
826 ctables_summary_function_name (enum ctables_summary_function function)
828 static const char *names[] = {
829 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
833 return names[function];
837 add_summary_spec (struct ctables_axis *axis,
838 enum ctables_summary_function function, double percentile,
839 const char *label, const struct fmt_spec *format,
840 const struct msg_location *loc, enum ctables_summary_variant sv)
842 if (axis->op == CTAO_VAR)
844 const char *function_name = ctables_summary_function_name (function);
845 const char *var_name = ctables_var_name (&axis->var);
846 switch (ctables_function_availability (function))
849 if (!axis->var.is_mrset)
851 msg_at (SE, loc, _("Summary function %s applies only to multiple "
852 "response sets."), function_name);
853 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
863 _("Summary function %s applies only to scale variables."),
865 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
875 struct ctables_summary_spec_set *set = &axis->specs[sv];
876 if (set->n >= set->allocated)
877 set->specs = x2nrealloc (set->specs, &set->allocated,
880 struct ctables_summary_spec *dst = &set->specs[set->n++];
881 *dst = (struct ctables_summary_spec) {
882 .function = function,
883 .percentile = percentile,
884 .label = xstrdup (label),
885 .format = (format ? *format
886 : ctables_summary_default_format (function, &axis->var)),
892 for (size_t i = 0; i < 2; i++)
893 if (!add_summary_spec (axis->subs[i], function, percentile, label,
900 static struct ctables_axis *ctables_axis_parse_stack (
901 struct ctables_axis_parse_ctx *);
904 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
905 struct ctables_var *var)
907 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
909 *var = (struct ctables_var) {
911 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
915 lex_error (lexer, _("'%s' does not name a multiple-response set "
916 "in the active file dictionary."),
917 lex_tokcstr (lexer));
925 *var = (struct ctables_var) {
927 .var = parse_variable (lexer, dict),
929 return var->var != NULL;
933 static struct ctables_axis *
934 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
936 if (lex_match (ctx->lexer, T_LPAREN))
938 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
939 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
941 ctables_axis_destroy (sub);
947 if (!lex_force_id (ctx->lexer))
950 int start_ofs = lex_ofs (ctx->lexer);
951 struct ctables_var var;
952 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
955 struct ctables_axis *axis = xmalloc (sizeof *axis);
956 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
958 /* XXX should figure out default measures by reading data */
959 axis->scale = (var.is_mrset ? false
960 : lex_match_phrase (ctx->lexer, "[S]") ? true
961 : lex_match_phrase (ctx->lexer, "[C]") ? false
962 : var_get_measure (var.var) == MEASURE_SCALE);
963 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
964 lex_ofs (ctx->lexer) - 1);
969 has_digit (const char *s)
971 return s[strcspn (s, "0123456789")] != '\0';
974 static struct ctables_axis *
975 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
977 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
978 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
981 enum ctables_summary_variant sv = CSV_CELL;
984 int start_ofs = lex_ofs (ctx->lexer);
986 /* Parse function. */
987 enum ctables_summary_function function;
988 if (!parse_ctables_summary_function (ctx->lexer, &function))
991 /* Parse percentile. */
992 double percentile = 0;
993 if (function == CTSF_PTILE)
995 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
997 percentile = lex_number (ctx->lexer);
998 lex_get (ctx->lexer);
1003 if (lex_is_string (ctx->lexer))
1005 label = ss_xstrdup (lex_tokss (ctx->lexer));
1006 lex_get (ctx->lexer);
1009 label = ctables_summary_default_label (function, percentile);
1012 struct fmt_spec format;
1013 const struct fmt_spec *formatp;
1014 if (lex_token (ctx->lexer) == T_ID
1015 && has_digit (lex_tokcstr (ctx->lexer)))
1017 if (!parse_format_specifier (ctx->lexer, &format)
1018 || !fmt_check_output (&format)
1019 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1029 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1030 lex_ofs (ctx->lexer) - 1);
1031 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1033 msg_location_destroy (loc);
1035 lex_match (ctx->lexer, T_COMMA);
1036 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1038 if (!lex_force_match (ctx->lexer, T_LBRACK))
1042 else if (lex_match (ctx->lexer, T_RBRACK))
1044 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1051 ctables_axis_destroy (sub);
1055 static const struct ctables_axis *
1056 find_scale (const struct ctables_axis *axis)
1060 else if (axis->op == CTAO_VAR)
1064 assert (!axis->var.is_mrset);
1072 for (size_t i = 0; i < 2; i++)
1074 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1082 static const struct ctables_axis *
1083 find_categorical_summary_spec (const struct ctables_axis *axis)
1087 else if (axis->op == CTAO_VAR)
1088 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1091 for (size_t i = 0; i < 2; i++)
1093 const struct ctables_axis *sum
1094 = find_categorical_summary_spec (axis->subs[i]);
1102 static struct ctables_axis *
1103 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1105 int start_ofs = lex_ofs (ctx->lexer);
1106 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1110 while (lex_match (ctx->lexer, T_GT))
1112 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1116 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1117 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1119 const struct ctables_axis *outer_scale = find_scale (lhs);
1120 const struct ctables_axis *inner_scale = find_scale (rhs);
1121 if (outer_scale && inner_scale)
1123 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1124 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1125 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1126 ctables_axis_destroy (nest);
1130 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1133 msg_at (SE, nest->loc,
1134 _("Summaries may only be requested for categorical variables "
1135 "at the innermost nesting level."));
1136 msg_at (SN, outer_sum->loc,
1137 _("This outer categorical variable has a summary."));
1138 ctables_axis_destroy (nest);
1148 static struct ctables_axis *
1149 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1151 int start_ofs = lex_ofs (ctx->lexer);
1152 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1156 while (lex_match (ctx->lexer, T_PLUS))
1158 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1162 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1163 ctx->lexer, start_ofs);
1170 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1171 struct ctables *ct, struct ctables_table *t,
1172 enum pivot_axis_type a)
1174 if (lex_token (lexer) == T_BY
1175 || lex_token (lexer) == T_SLASH
1176 || lex_token (lexer) == T_ENDCMD)
1179 struct ctables_axis_parse_ctx ctx = {
1185 t->axes[a] = ctables_axis_parse_stack (&ctx);
1186 return t->axes[a] != NULL;
1190 ctables_chisq_destroy (struct ctables_chisq *chisq)
1196 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1202 ctables_table_destroy (struct ctables_table *t)
1207 for (size_t i = 0; i < t->n_categories; i++)
1208 ctables_categories_unref (t->categories[i]);
1209 free (t->categories);
1211 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1212 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1213 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1217 ctables_chisq_destroy (t->chisq);
1218 ctables_pairwise_destroy (t->pairwise);
1223 ctables_destroy (struct ctables *ct)
1228 pivot_table_look_unref (ct->look);
1232 for (size_t i = 0; i < ct->n_tables; i++)
1233 ctables_table_destroy (ct->tables[i]);
1238 static struct ctables_category
1239 cct_range (double low, double high)
1241 return (struct ctables_category) {
1243 .range = { low, high }
1248 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1249 struct ctables_table *t)
1251 if (!lex_match_id (lexer, "VARIABLES"))
1253 lex_match (lexer, T_EQUALS);
1255 struct variable **vars;
1257 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1260 struct ctables_categories *c = xmalloc (sizeof *c);
1261 *c = (struct ctables_categories) { .n_refs = n_vars };
1262 for (size_t i = 0; i < n_vars; i++)
1264 struct ctables_categories **cp
1265 = &t->categories[var_get_dict_index (vars[i])];
1266 ctables_categories_unref (*cp);
1271 size_t allocated_cats = 0;
1272 if (lex_match (lexer, T_LBRACK))
1276 if (c->n_cats >= allocated_cats)
1277 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1279 struct ctables_category *cat = &c->cats[c->n_cats];
1280 if (lex_match_id (lexer, "OTHERNM"))
1281 cat->type = CCT_OTHERNM;
1282 else if (lex_match_id (lexer, "MISSING"))
1283 cat->type = CCT_MISSING;
1284 else if (lex_match_id (lexer, "SUBTOTAL"))
1285 *cat = (struct ctables_category)
1286 { .type = CCT_SUBTOTAL, .total_label = NULL };
1287 else if (lex_match_id (lexer, "HSUBTOTAL"))
1288 *cat = (struct ctables_category)
1289 { .type = CCT_HSUBTOTAL, .total_label = NULL };
1290 else if (lex_match_id (lexer, "LO"))
1292 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1294 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1297 else if (lex_is_number (lexer))
1299 double number = lex_number (lexer);
1301 if (lex_match_id (lexer, "THRU"))
1303 cat->type = CCT_RANGE;
1304 cat->range[0] = number;
1305 if (lex_match_id (lexer, "HI"))
1306 *cat = cct_range (number, DBL_MAX);
1309 if (!lex_force_num (lexer))
1311 *cat = cct_range (number, lex_number (lexer));
1316 *cat = (struct ctables_category) {
1321 else if (lex_is_string (lexer))
1323 *cat = (struct ctables_category) {
1325 .string = ss_xstrdup (lex_tokss (lexer)),
1331 lex_error (lexer, NULL);
1335 if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1337 if (lex_match (lexer, T_EQUALS))
1339 if (!lex_force_string (lexer))
1342 cat->total_label = ss_xstrdup (lex_tokss (lexer));
1346 cat->total_label = xstrdup (_("Subtotal"));
1350 lex_match (lexer, T_COMMA);
1352 while (!lex_match (lexer, T_RBRACK));
1355 struct ctables_category cat = {
1357 .include_missing = false,
1358 .sort_ascending = true,
1360 bool show_totals = false;
1361 char *total_label = NULL;
1362 bool totals_before = false;
1363 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1365 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1367 lex_match (lexer, T_EQUALS);
1368 if (lex_match_id (lexer, "A"))
1369 cat.sort_ascending = true;
1370 else if (lex_match_id (lexer, "D"))
1371 cat.sort_ascending = false;
1374 lex_error_expecting (lexer, "A", "D");
1378 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1380 lex_match (lexer, T_EQUALS);
1381 if (lex_match_id (lexer, "VALUE"))
1382 cat.type = CCT_VALUE;
1383 else if (lex_match_id (lexer, "LABEL"))
1384 cat.type = CCT_LABEL;
1387 cat.type = CCT_FUNCTION;
1388 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1391 if (lex_match (lexer, T_LPAREN))
1393 cat.sort_var = parse_variable (lexer, dict);
1397 if (cat.sort_function == CTSF_PTILE)
1399 lex_match (lexer, T_COMMA);
1400 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1402 cat.percentile = lex_number (lexer);
1406 if (!lex_force_match (lexer, T_RPAREN))
1409 else if (ctables_function_availability (cat.sort_function)
1412 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1417 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1419 lex_match (lexer, T_EQUALS);
1420 if (lex_match_id (lexer, "INCLUDE"))
1421 cat.include_missing = true;
1422 else if (lex_match_id (lexer, "EXCLUDE"))
1423 cat.include_missing = false;
1426 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1430 else if (lex_match_id (lexer, "TOTAL"))
1432 lex_match (lexer, T_EQUALS);
1433 if (!parse_bool (lexer, &show_totals))
1436 else if (lex_match_id (lexer, "LABEL"))
1438 lex_match (lexer, T_EQUALS);
1439 if (!lex_force_string (lexer))
1442 total_label = ss_xstrdup (lex_tokss (lexer));
1445 else if (lex_match_id (lexer, "POSITION"))
1447 lex_match (lexer, T_EQUALS);
1448 if (lex_match_id (lexer, "BEFORE"))
1449 totals_before = true;
1450 else if (lex_match_id (lexer, "AFTER"))
1451 totals_before = false;
1454 lex_error_expecting (lexer, "BEFORE", "AFTER");
1458 else if (lex_match_id (lexer, "EMPTY"))
1460 lex_match (lexer, T_EQUALS);
1461 if (lex_match_id (lexer, "INCLUDE"))
1462 c->show_empty = true;
1463 else if (lex_match_id (lexer, "EXCLUDE"))
1464 c->show_empty = false;
1467 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1474 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1475 "TOTAL", "LABEL", "POSITION", "EMPTY");
1477 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1484 if (c->n_cats >= allocated_cats)
1485 c->cats = x2nrealloc (c->cats, &allocated_cats,
1487 c->cats[c->n_cats++] = cat;
1492 if (c->n_cats >= allocated_cats)
1493 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1495 struct ctables_category *totals;
1498 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1499 totals = &c->cats[0];
1502 totals = &c->cats[c->n_cats];
1505 *totals = (struct ctables_category) {
1507 .total_label = total_label ? total_label : xstrdup (_("Total")),
1511 struct ctables_category *subtotal = NULL;
1512 for (size_t i = totals_before ? 0 : c->n_cats;
1513 totals_before ? i < c->n_cats : i-- > 0;
1514 totals_before ? i++ : 0)
1516 struct ctables_category *cat = &c->cats[i];
1524 cat->subtotal = subtotal;
1544 ctables_nest_uninit (struct ctables_nest *nest)
1551 ctables_stack_uninit (struct ctables_stack *stack)
1555 for (size_t i = 0; i < stack->n; i++)
1556 ctables_nest_uninit (&stack->nests[i]);
1557 free (stack->nests);
1561 static struct ctables_stack
1562 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1569 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1570 for (size_t i = 0; i < s0.n; i++)
1571 for (size_t j = 0; j < s1.n; j++)
1573 const struct ctables_nest *a = &s0.nests[i];
1574 const struct ctables_nest *b = &s1.nests[j];
1576 size_t allocate = a->n + b->n;
1577 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1578 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1580 for (size_t k = 0; k < a->n; k++)
1581 vars[n++] = a->vars[k];
1582 for (size_t k = 0; k < b->n; k++)
1583 vars[n++] = b->vars[k];
1584 assert (n == allocate);
1586 const struct ctables_nest *summary_src;
1587 if (!a->specs[CSV_CELL].var)
1589 else if (!b->specs[CSV_CELL].var)
1594 struct ctables_nest *new = &stack.nests[stack.n++];
1595 *new = (struct ctables_nest) {
1597 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1598 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1602 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1603 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1605 ctables_stack_uninit (&s0);
1606 ctables_stack_uninit (&s1);
1610 static struct ctables_stack
1611 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1613 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1614 for (size_t i = 0; i < s0.n; i++)
1615 stack.nests[stack.n++] = s0.nests[i];
1616 for (size_t i = 0; i < s1.n; i++)
1617 stack.nests[stack.n++] = s1.nests[i];
1618 assert (stack.n == s0.n + s1.n);
1624 static struct ctables_stack
1625 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1628 return (struct ctables_stack) { .n = 0 };
1633 assert (!a->var.is_mrset);
1635 struct variable **vars = xmalloc (sizeof *vars);
1638 struct ctables_nest *nest = xmalloc (sizeof *nest);
1639 *nest = (struct ctables_nest) {
1642 .scale_idx = a->scale ? 0 : SIZE_MAX,
1644 if (a->specs[CSV_CELL].n || a->scale)
1645 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1647 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1648 nest->specs[sv].var = a->var.var;
1650 return (struct ctables_stack) { .nests = nest, .n = 1 };
1653 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1654 enumerate_fts (axis_type, a->subs[1]));
1657 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1658 enumerate_fts (axis_type, a->subs[1]));
1664 union ctables_summary
1666 /* COUNT, VALIDN, TOTALN. */
1673 /* MINIMUM, MAXIMUM, RANGE. */
1680 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1681 struct moments1 *moments;
1683 /* XXX percentiles, median, mode, multiple response */
1687 ctables_summary_init (union ctables_summary *s,
1688 const struct ctables_summary_spec *ss)
1690 switch (ss->function)
1694 case CTSF_ROWPCT_COUNT:
1695 case CTSF_COLPCT_COUNT:
1696 case CTSF_TABLEPCT_COUNT:
1697 case CTSF_SUBTABLEPCT_COUNT:
1698 case CTSF_LAYERPCT_COUNT:
1699 case CTSF_LAYERROWPCT_COUNT:
1700 case CTSF_LAYERCOLPCT_COUNT:
1701 case CTSF_ROWPCT_VALIDN:
1702 case CTSF_COLPCT_VALIDN:
1703 case CTSF_TABLEPCT_VALIDN:
1704 case CTSF_SUBTABLEPCT_VALIDN:
1705 case CTSF_LAYERPCT_VALIDN:
1706 case CTSF_LAYERROWPCT_VALIDN:
1707 case CTSF_LAYERCOLPCT_VALIDN:
1708 case CTSF_ROWPCT_TOTALN:
1709 case CTSF_COLPCT_TOTALN:
1710 case CTSF_TABLEPCT_TOTALN:
1711 case CTSF_SUBTABLEPCT_TOTALN:
1712 case CTSF_LAYERPCT_TOTALN:
1713 case CTSF_LAYERROWPCT_TOTALN:
1714 case CTSF_LAYERCOLPCT_TOTALN:
1719 s->missing = s->valid = 0;
1725 s->min = s->max = SYSMIS;
1733 case CTSF_ROWPCT_SUM:
1734 case CTSF_COLPCT_SUM:
1735 case CTSF_TABLEPCT_SUM:
1736 case CTSF_SUBTABLEPCT_SUM:
1737 case CTSF_LAYERPCT_SUM:
1738 case CTSF_LAYERROWPCT_SUM:
1739 case CTSF_LAYERCOLPCT_SUM:
1740 s->moments = moments1_create (MOMENT_VARIANCE);
1749 case CTSF_RESPONSES:
1750 case CTSF_ROWPCT_RESPONSES:
1751 case CTSF_COLPCT_RESPONSES:
1752 case CTSF_TABLEPCT_RESPONSES:
1753 case CTSF_SUBTABLEPCT_RESPONSES:
1754 case CTSF_LAYERPCT_RESPONSES:
1755 case CTSF_LAYERROWPCT_RESPONSES:
1756 case CTSF_LAYERCOLPCT_RESPONSES:
1757 case CTSF_ROWPCT_RESPONSES_COUNT:
1758 case CTSF_COLPCT_RESPONSES_COUNT:
1759 case CTSF_TABLEPCT_RESPONSES_COUNT:
1760 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1761 case CTSF_LAYERPCT_RESPONSES_COUNT:
1762 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1763 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1764 case CTSF_ROWPCT_COUNT_RESPONSES:
1765 case CTSF_COLPCT_COUNT_RESPONSES:
1766 case CTSF_TABLEPCT_COUNT_RESPONSES:
1767 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1768 case CTSF_LAYERPCT_COUNT_RESPONSES:
1769 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1770 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1776 ctables_summary_uninit (union ctables_summary *s,
1777 const struct ctables_summary_spec *ss)
1779 switch (ss->function)
1783 case CTSF_ROWPCT_COUNT:
1784 case CTSF_COLPCT_COUNT:
1785 case CTSF_TABLEPCT_COUNT:
1786 case CTSF_SUBTABLEPCT_COUNT:
1787 case CTSF_LAYERPCT_COUNT:
1788 case CTSF_LAYERROWPCT_COUNT:
1789 case CTSF_LAYERCOLPCT_COUNT:
1790 case CTSF_ROWPCT_VALIDN:
1791 case CTSF_COLPCT_VALIDN:
1792 case CTSF_TABLEPCT_VALIDN:
1793 case CTSF_SUBTABLEPCT_VALIDN:
1794 case CTSF_LAYERPCT_VALIDN:
1795 case CTSF_LAYERROWPCT_VALIDN:
1796 case CTSF_LAYERCOLPCT_VALIDN:
1797 case CTSF_ROWPCT_TOTALN:
1798 case CTSF_COLPCT_TOTALN:
1799 case CTSF_TABLEPCT_TOTALN:
1800 case CTSF_SUBTABLEPCT_TOTALN:
1801 case CTSF_LAYERPCT_TOTALN:
1802 case CTSF_LAYERROWPCT_TOTALN:
1803 case CTSF_LAYERCOLPCT_TOTALN:
1820 case CTSF_ROWPCT_SUM:
1821 case CTSF_COLPCT_SUM:
1822 case CTSF_TABLEPCT_SUM:
1823 case CTSF_SUBTABLEPCT_SUM:
1824 case CTSF_LAYERPCT_SUM:
1825 case CTSF_LAYERROWPCT_SUM:
1826 case CTSF_LAYERCOLPCT_SUM:
1827 moments1_destroy (s->moments);
1836 case CTSF_RESPONSES:
1837 case CTSF_ROWPCT_RESPONSES:
1838 case CTSF_COLPCT_RESPONSES:
1839 case CTSF_TABLEPCT_RESPONSES:
1840 case CTSF_SUBTABLEPCT_RESPONSES:
1841 case CTSF_LAYERPCT_RESPONSES:
1842 case CTSF_LAYERROWPCT_RESPONSES:
1843 case CTSF_LAYERCOLPCT_RESPONSES:
1844 case CTSF_ROWPCT_RESPONSES_COUNT:
1845 case CTSF_COLPCT_RESPONSES_COUNT:
1846 case CTSF_TABLEPCT_RESPONSES_COUNT:
1847 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1848 case CTSF_LAYERPCT_RESPONSES_COUNT:
1849 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1850 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1851 case CTSF_ROWPCT_COUNT_RESPONSES:
1852 case CTSF_COLPCT_COUNT_RESPONSES:
1853 case CTSF_TABLEPCT_COUNT_RESPONSES:
1854 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1855 case CTSF_LAYERPCT_COUNT_RESPONSES:
1856 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1857 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1863 ctables_summary_add (union ctables_summary *s,
1864 const struct ctables_summary_spec *ss,
1865 const struct variable *var, const union value *value,
1868 switch (ss->function)
1872 case CTSF_ROWPCT_COUNT:
1873 case CTSF_COLPCT_COUNT:
1874 case CTSF_TABLEPCT_COUNT:
1875 case CTSF_SUBTABLEPCT_COUNT:
1876 case CTSF_LAYERPCT_COUNT:
1877 case CTSF_LAYERROWPCT_COUNT:
1878 case CTSF_LAYERCOLPCT_COUNT:
1879 case CTSF_ROWPCT_VALIDN:
1880 case CTSF_COLPCT_VALIDN:
1881 case CTSF_TABLEPCT_VALIDN:
1882 case CTSF_SUBTABLEPCT_VALIDN:
1883 case CTSF_LAYERPCT_VALIDN:
1884 case CTSF_LAYERROWPCT_VALIDN:
1885 case CTSF_LAYERCOLPCT_VALIDN:
1886 case CTSF_ROWPCT_TOTALN:
1887 case CTSF_COLPCT_TOTALN:
1888 case CTSF_TABLEPCT_TOTALN:
1889 case CTSF_SUBTABLEPCT_TOTALN:
1890 case CTSF_LAYERPCT_TOTALN:
1891 case CTSF_LAYERROWPCT_TOTALN:
1892 case CTSF_LAYERCOLPCT_TOTALN:
1897 if (var_is_value_missing (var, value))
1898 s->missing += weight;
1906 if (!var_is_value_missing (var, value))
1908 assert (!var_is_alpha (var)); /* XXX? */
1909 if (s->min == SYSMIS || value->f < s->min)
1911 if (s->max == SYSMIS || value->f > s->max)
1921 case CTSF_ROWPCT_SUM:
1922 case CTSF_COLPCT_SUM:
1923 case CTSF_TABLEPCT_SUM:
1924 case CTSF_SUBTABLEPCT_SUM:
1925 case CTSF_LAYERPCT_SUM:
1926 case CTSF_LAYERROWPCT_SUM:
1927 case CTSF_LAYERCOLPCT_SUM:
1928 if (!var_is_value_missing (var, value))
1929 moments1_add (s->moments, value->f, weight);
1938 case CTSF_RESPONSES:
1939 case CTSF_ROWPCT_RESPONSES:
1940 case CTSF_COLPCT_RESPONSES:
1941 case CTSF_TABLEPCT_RESPONSES:
1942 case CTSF_SUBTABLEPCT_RESPONSES:
1943 case CTSF_LAYERPCT_RESPONSES:
1944 case CTSF_LAYERROWPCT_RESPONSES:
1945 case CTSF_LAYERCOLPCT_RESPONSES:
1946 case CTSF_ROWPCT_RESPONSES_COUNT:
1947 case CTSF_COLPCT_RESPONSES_COUNT:
1948 case CTSF_TABLEPCT_RESPONSES_COUNT:
1949 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1950 case CTSF_LAYERPCT_RESPONSES_COUNT:
1951 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1952 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1953 case CTSF_ROWPCT_COUNT_RESPONSES:
1954 case CTSF_COLPCT_COUNT_RESPONSES:
1955 case CTSF_TABLEPCT_COUNT_RESPONSES:
1956 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1957 case CTSF_LAYERPCT_COUNT_RESPONSES:
1958 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1959 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1965 ctables_summary_value (const struct ctables_cell *cell,
1966 union ctables_summary *s,
1967 const struct ctables_summary_spec *ss)
1969 switch (ss->function)
1975 case CTSF_SUBTABLEPCT_COUNT:
1976 return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
1978 case CTSF_ROWPCT_COUNT:
1979 return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
1981 case CTSF_COLPCT_COUNT:
1982 return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
1984 case CTSF_TABLEPCT_COUNT:
1985 return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
1987 case CTSF_LAYERPCT_COUNT:
1988 return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
1990 case CTSF_LAYERROWPCT_COUNT:
1991 return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
1993 case CTSF_LAYERCOLPCT_COUNT:
1994 return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
1996 case CTSF_ROWPCT_VALIDN:
1997 case CTSF_COLPCT_VALIDN:
1998 case CTSF_TABLEPCT_VALIDN:
1999 case CTSF_SUBTABLEPCT_VALIDN:
2000 case CTSF_LAYERPCT_VALIDN:
2001 case CTSF_LAYERROWPCT_VALIDN:
2002 case CTSF_LAYERCOLPCT_VALIDN:
2003 case CTSF_ROWPCT_TOTALN:
2004 case CTSF_COLPCT_TOTALN:
2005 case CTSF_TABLEPCT_TOTALN:
2006 case CTSF_SUBTABLEPCT_TOTALN:
2007 case CTSF_LAYERPCT_TOTALN:
2008 case CTSF_LAYERROWPCT_TOTALN:
2009 case CTSF_LAYERCOLPCT_TOTALN:
2014 return s->valid + s->missing;
2027 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2032 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2038 double weight, variance;
2039 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2040 return calc_semean (variance, weight);
2046 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2047 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2052 double weight, mean;
2053 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2054 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2060 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2064 case CTSF_ROWPCT_SUM:
2065 case CTSF_COLPCT_SUM:
2066 case CTSF_TABLEPCT_SUM:
2067 case CTSF_SUBTABLEPCT_SUM:
2068 case CTSF_LAYERPCT_SUM:
2069 case CTSF_LAYERROWPCT_SUM:
2070 case CTSF_LAYERCOLPCT_SUM:
2079 case CTSF_RESPONSES:
2080 case CTSF_ROWPCT_RESPONSES:
2081 case CTSF_COLPCT_RESPONSES:
2082 case CTSF_TABLEPCT_RESPONSES:
2083 case CTSF_SUBTABLEPCT_RESPONSES:
2084 case CTSF_LAYERPCT_RESPONSES:
2085 case CTSF_LAYERROWPCT_RESPONSES:
2086 case CTSF_LAYERCOLPCT_RESPONSES:
2087 case CTSF_ROWPCT_RESPONSES_COUNT:
2088 case CTSF_COLPCT_RESPONSES_COUNT:
2089 case CTSF_TABLEPCT_RESPONSES_COUNT:
2090 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2091 case CTSF_LAYERPCT_RESPONSES_COUNT:
2092 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2093 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2094 case CTSF_ROWPCT_COUNT_RESPONSES:
2095 case CTSF_COLPCT_COUNT_RESPONSES:
2096 case CTSF_TABLEPCT_COUNT_RESPONSES:
2097 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2098 case CTSF_LAYERPCT_COUNT_RESPONSES:
2099 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2100 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2107 struct ctables_cell_sort_aux
2109 const struct ctables_table *t;
2110 enum pivot_axis_type a;
2114 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2116 const struct ctables_cell_sort_aux *aux = aux_;
2117 struct ctables_cell *const *ap = a_;
2118 struct ctables_cell *const *bp = b_;
2119 const struct ctables_cell *a = *ap;
2120 const struct ctables_cell *b = *bp;
2122 size_t a_idx = a->axes[aux->a].nest_idx;
2123 size_t b_idx = b->axes[aux->a].nest_idx;
2125 return a_idx < b_idx ? -1 : 1;
2127 const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2128 for (size_t i = 0; i < nest->n; i++)
2129 if (i != nest->scale_idx)
2131 const struct variable *var = nest->vars[i];
2132 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2133 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2134 if (a_cv->category != b_cv->category)
2135 return a_cv->category > b_cv->category ? 1 : -1;
2137 const union value *a_val = &a_cv->value;
2138 const union value *b_val = &b_cv->value;
2139 switch (a_cv->category->type)
2146 /* Must be equal. */
2153 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2161 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2163 return a_cv->category->sort_ascending ? cmp : -cmp;
2169 const char *a_label = var_lookup_value_label (var, a_val);
2170 const char *b_label = var_lookup_value_label (var, b_val);
2172 ? (b_label ? strcmp (a_label, b_label) : 1)
2173 : (b_label ? -1 : value_compare_3way (
2174 a_val, b_val, var_get_width (var))));
2176 return a_cv->category->sort_ascending ? cmp : -cmp;
2190 For each ctables_table:
2191 For each combination of row vars:
2192 For each combination of column vars:
2193 For each combination of layer vars:
2195 Make a table of row values:
2196 Sort entries by row values
2197 Assign a 0-based index to each actual value
2198 Construct a dimension
2199 Make a table of column values
2200 Make a table of layer values
2202 Fill the table entry using the indexes from before.
2205 static struct ctables_domain *
2206 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2207 enum ctables_domain_type domain)
2210 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2212 size_t idx = cell->axes[a].nest_idx;
2213 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2214 hash = hash_int (idx, hash);
2215 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2217 size_t v_idx = nest->domains[domain][i];
2218 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2219 var_get_width (nest->vars[v_idx]), hash);
2223 struct ctables_domain *d;
2224 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2226 const struct ctables_cell *df = d->example;
2227 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2229 size_t idx = cell->axes[a].nest_idx;
2230 if (idx != df->axes[a].nest_idx)
2233 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2234 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2236 size_t v_idx = nest->domains[domain][i];
2237 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2238 &cell->axes[a].cvs[v_idx].value,
2239 var_get_width (nest->vars[v_idx])))
2248 d = xmalloc (sizeof *d);
2249 *d = (struct ctables_domain) { .example = cell };
2250 hmap_insert (&t->domains[domain], &d->node, hash);
2254 static const struct ctables_category *
2255 ctables_categories_match (const struct ctables_categories *c,
2256 const union value *v, const struct variable *var)
2258 const struct ctables_category *othernm = NULL;
2259 for (size_t i = c->n_cats; i-- > 0; )
2261 const struct ctables_category *cat = &c->cats[i];
2265 if (cat->number == v->f)
2273 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2274 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2279 if (var_is_value_missing (var, v))
2296 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2301 return var_is_value_missing (var, v) ? NULL : othernm;
2304 static const struct ctables_category *
2305 ctables_categories_total (const struct ctables_categories *c)
2307 const struct ctables_category *first = &c->cats[0];
2308 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2309 return (first->type == CCT_TOTAL ? first
2310 : last->type == CCT_TOTAL ? last
2314 static struct ctables_cell *
2315 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2316 size_t ix[PIVOT_N_AXES],
2317 const struct ctables_category *cats[PIVOT_N_AXES][10])
2319 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2322 enum ctables_summary_variant sv = CSV_CELL;
2323 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2325 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2326 hash = hash_int (ix[a], hash);
2327 for (size_t i = 0; i < nest->n; i++)
2328 if (i != nest->scale_idx)
2330 hash = hash_pointer (cats[a][i], hash);
2331 if (cats[a][i]->type != CCT_TOTAL
2332 && cats[a][i]->type != CCT_SUBTOTAL
2333 && cats[a][i]->type != CCT_HSUBTOTAL)
2334 hash = value_hash (case_data (c, nest->vars[i]),
2335 var_get_width (nest->vars[i]), hash);
2341 struct ctables_cell *cell;
2342 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2344 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2346 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2347 if (cell->axes[a].nest_idx != ix[a])
2349 for (size_t i = 0; i < nest->n; i++)
2350 if (i != nest->scale_idx
2351 && (cats[a][i] != cell->axes[a].cvs[i].category
2352 || (cats[a][i]->type != CCT_TOTAL
2353 && cats[a][i]->type != CCT_SUBTOTAL
2354 && cats[a][i]->type != CCT_HSUBTOTAL
2355 && !value_equal (case_data (c, nest->vars[i]),
2356 &cell->axes[a].cvs[i].value,
2357 var_get_width (nest->vars[i])))))
2366 cell = xmalloc (sizeof *cell);
2369 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2371 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2372 cell->axes[a].nest_idx = ix[a];
2373 cell->axes[a].cvs = (nest->n
2374 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2376 for (size_t i = 0; i < nest->n; i++)
2378 if (i != nest->scale_idx)
2380 const struct ctables_category *subtotal = cats[a][i]->subtotal;
2381 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2385 cell->axes[a].cvs[i].category = cats[a][i];
2386 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2387 var_get_width (nest->vars[i]));
2391 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2392 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2393 for (size_t i = 0; i < specs->n; i++)
2394 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2395 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2396 cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2397 hmap_insert (&t->cells, &cell->node, hash);
2402 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2403 size_t ix[PIVOT_N_AXES],
2404 const struct ctables_category *cats[PIVOT_N_AXES][10],
2407 struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2408 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2410 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2411 for (size_t i = 0; i < specs->n; i++)
2412 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2413 case_data (c, specs->var), weight);
2414 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2415 cell->domains[dt]->valid += weight;
2419 recurse_totals (struct ctables_table *t, const struct ccase *c,
2420 size_t ix[PIVOT_N_AXES],
2421 const struct ctables_category *cats[PIVOT_N_AXES][10],
2423 enum pivot_axis_type start_axis, size_t start_nest)
2425 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2427 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2428 for (size_t i = start_nest; i < nest->n; i++)
2430 if (i == nest->scale_idx)
2433 const struct variable *var = nest->vars[i];
2435 const struct ctables_category *total = ctables_categories_total (
2436 t->categories[var_get_dict_index (var)]);
2439 const struct ctables_category *save = cats[a][i];
2441 ctables_cell_add__ (t, c, ix, cats, weight);
2442 recurse_totals (t, c, ix, cats, weight, a, i + 1);
2451 recurse_subtotals (struct ctables_table *t, const struct ccase *c,
2452 size_t ix[PIVOT_N_AXES],
2453 const struct ctables_category *cats[PIVOT_N_AXES][10],
2455 enum pivot_axis_type start_axis, size_t start_nest)
2457 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2459 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2460 for (size_t i = start_nest; i < nest->n; i++)
2462 if (i == nest->scale_idx)
2465 const struct ctables_category *save = cats[a][i];
2468 cats[a][i] = save->subtotal;
2469 ctables_cell_add__ (t, c, ix, cats, weight);
2470 recurse_subtotals (t, c, ix, cats, weight, a, i + 1);
2479 ctables_cell_insert (struct ctables_table *t,
2480 const struct ccase *c,
2481 size_t ir, size_t ic, size_t il,
2484 size_t ix[PIVOT_N_AXES] = {
2485 [PIVOT_AXIS_ROW] = ir,
2486 [PIVOT_AXIS_COLUMN] = ic,
2487 [PIVOT_AXIS_LAYER] = il,
2490 const struct ctables_category *cats[PIVOT_N_AXES][10];
2491 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2493 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2494 for (size_t i = 0; i < nest->n; i++)
2496 if (i == nest->scale_idx)
2499 const struct variable *var = nest->vars[i];
2500 const union value *value = case_data (c, var);
2502 if (var_is_numeric (var) && value->f == SYSMIS)
2505 cats[a][i] = ctables_categories_match (
2506 t->categories[var_get_dict_index (var)], value, var);
2512 ctables_cell_add__ (t, c, ix, cats, weight);
2514 recurse_totals (t, c, ix, cats, weight, 0, 0);
2515 recurse_subtotals (t, c, ix, cats, weight, 0, 0);
2520 const struct ctables_summary_spec_set *set;
2525 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2527 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2528 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2529 if (as->function != bs->function)
2530 return as->function > bs->function ? 1 : -1;
2531 else if (as->percentile != bs->percentile)
2532 return as->percentile < bs->percentile ? 1 : -1;
2533 return strcmp (as->label, bs->label);
2536 static struct pivot_value *
2537 ctables_category_create_label (const struct ctables_category *cat,
2538 const struct variable *var,
2539 const union value *value)
2541 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2542 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2543 : pivot_value_new_var_value (var, value));
2546 static struct ctables_value *
2547 ctables_value_find__ (struct ctables_table *t, const union value *value,
2548 int width, unsigned int hash)
2550 struct ctables_value *clv;
2551 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2552 hash, &t->clabels_values_map)
2553 if (value_equal (value, &clv->value, width))
2558 static struct ctables_value *
2559 ctables_value_find (struct ctables_table *t,
2560 const union value *value, int width)
2562 return ctables_value_find__ (t, value, width,
2563 value_hash (value, width, 0));
2567 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2569 struct pivot_table *pt = pivot_table_create__ (
2571 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2572 : pivot_value_new_text (N_("Custom Tables"))),
2575 pivot_table_set_caption (
2576 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2578 pivot_table_set_caption (
2579 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2581 bool summary_dimension = (t->summary_axis != t->slabels_axis
2582 || (!t->slabels_visible
2583 && t->summary_specs.n > 1));
2584 if (summary_dimension)
2586 struct pivot_dimension *d = pivot_dimension_create (
2587 pt, t->slabels_axis, N_("Statistics"));
2588 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2589 if (!t->slabels_visible)
2590 d->hide_all_labels = true;
2591 for (size_t i = 0; i < specs->n; i++)
2592 pivot_category_create_leaf (
2593 d->root, pivot_value_new_text (specs->specs[i].label));
2596 bool categories_dimension = t->clabels_example != NULL;
2597 if (categories_dimension)
2599 struct pivot_dimension *d = pivot_dimension_create (
2600 pt, t->label_axis[t->clabels_from_axis],
2601 t->clabels_from_axis == PIVOT_AXIS_ROW
2602 ? N_("Row Categories")
2603 : N_("Column Categories"));
2604 const struct variable *var = t->clabels_example;
2605 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2606 for (size_t i = 0; i < t->n_clabels_values; i++)
2608 const struct ctables_value *value = t->clabels_values[i];
2609 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2610 assert (cat != NULL);
2611 pivot_category_create_leaf (d->root, ctables_category_create_label (
2612 cat, t->clabels_example, &value->value));
2616 pivot_table_set_look (pt, ct->look);
2617 struct pivot_dimension *d[PIVOT_N_AXES];
2618 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2620 static const char *names[] = {
2621 [PIVOT_AXIS_ROW] = N_("Rows"),
2622 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2623 [PIVOT_AXIS_LAYER] = N_("Layers"),
2625 d[a] = (t->axes[a] || a == t->summary_axis
2626 ? pivot_dimension_create (pt, a, names[a])
2631 assert (t->axes[a]);
2633 struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2634 size_t n_sorted = 0;
2636 struct ctables_cell *cell;
2637 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2639 sorted[n_sorted++] = cell;
2640 assert (n_sorted <= t->cells.count);
2642 struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2643 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2645 size_t max_depth = 0;
2646 for (size_t j = 0; j < t->stacks[a].n; j++)
2647 if (t->stacks[a].nests[j].n > max_depth)
2648 max_depth = t->stacks[a].nests[j].n;
2650 /* Pivot categories:
2652 - variable label for nest->vars[0], if vlabel != CTVL_NONE
2653 - category for nest->vars[0], if nest->scale_idx != 0
2654 - variable label for nest->vars[1], if vlabel != CTVL_NONE
2655 - category for nest->vars[1], if nest->scale_idx != 1
2657 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2658 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2659 - summary function, if 'a == t->slabels_axis && a ==
2662 Additional dimensions:
2664 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2666 - If 't->label_axis[b] == a' for some 'b != a', add a category
2670 struct ctables_level
2672 enum ctables_level_type
2674 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2675 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2676 CTL_SUMMARY, /* Summary functions. */
2682 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2683 size_t n_levels = 0;
2685 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2687 for (size_t j = 0; j < n_sorted; j++)
2689 struct ctables_cell *cell = sorted[j];
2690 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2691 const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2693 bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2697 for (size_t k = 0; k < nest->n; k++)
2699 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2700 if (vlabel != CTVL_NONE)
2702 levels[n_levels++] = (struct ctables_level) {
2708 if (nest->scale_idx != k
2709 && (k != nest->n - 1 || t->label_axis[a] == a))
2711 levels[n_levels++] = (struct ctables_level) {
2712 .type = CTL_CATEGORY,
2718 if (!summary_dimension && a == t->slabels_axis)
2720 levels[n_levels++] = (struct ctables_level) {
2721 .type = CTL_SUMMARY,
2722 .var_idx = SIZE_MAX,
2727 size_t n_common = 0;
2730 for (; n_common < n_levels; n_common++)
2732 const struct ctables_level *level = &levels[n_common];
2733 if (level->type == CTL_CATEGORY)
2735 size_t var_idx = level->var_idx;
2736 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
2737 if (prev->axes[a].cvs[var_idx].category != c)
2739 else if (c->type != CCT_SUBTOTAL
2740 && c->type != CCT_HSUBTOTAL
2741 && c->type != CCT_TOTAL
2742 && !value_equal (&prev->axes[a].cvs[var_idx].value,
2743 &cell->axes[a].cvs[var_idx].value,
2744 var_get_type (nest->vars[var_idx])))
2750 for (size_t k = n_common; k < n_levels; k++)
2752 const struct ctables_level *level = &levels[k];
2753 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2754 if (level->type == CTL_SUMMARY)
2756 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2757 for (size_t m = 0; m < specs->n; m++)
2759 int leaf = pivot_category_create_leaf (
2760 parent, pivot_value_new_text (specs->specs[m].label));
2767 const struct variable *var = nest->vars[level->var_idx];
2768 struct pivot_value *label;
2769 if (level->type == CTL_VAR)
2770 label = pivot_value_new_variable (var);
2771 else if (level->type == CTL_CATEGORY)
2773 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2774 label = ctables_category_create_label (cv->category,
2780 if (k == n_levels - 1)
2781 prev_leaf = pivot_category_create_leaf (parent, label);
2783 groups[k] = pivot_category_create_group__ (parent, label);
2787 cell->axes[a].leaf = prev_leaf;
2793 struct ctables_cell *cell;
2794 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2799 const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2800 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2801 for (size_t j = 0; j < specs->n; j++)
2804 size_t n_dindexes = 0;
2806 if (summary_dimension)
2807 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2809 if (categories_dimension)
2811 const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2812 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2813 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2814 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2815 assert (ctv != NULL);
2816 dindexes[n_dindexes++] = ctv->leaf;
2819 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2822 int leaf = cell->axes[a].leaf;
2823 if (a == t->summary_axis && !summary_dimension)
2825 dindexes[n_dindexes++] = leaf;
2828 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2829 struct pivot_value *value = pivot_value_new_number (d);
2830 value->numeric.format = specs->specs[j].format;
2831 pivot_table_put (pt, dindexes, n_dindexes, value);
2835 pivot_table_submit (pt);
2839 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2841 enum pivot_axis_type label_pos = t->label_axis[a];
2845 t->clabels_from_axis = a;
2847 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2848 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2850 const struct ctables_stack *stack = &t->stacks[a];
2854 const struct ctables_nest *n0 = &stack->nests[0];
2856 const struct variable *v0 = n0->vars[n0->n - 1];
2857 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2858 t->clabels_example = v0;
2860 for (size_t i = 0; i < c0->n_cats; i++)
2861 if (c0->cats[i].type == CCT_FUNCTION)
2863 msg (SE, _("%s=%s is not allowed with sorting based "
2864 "on a summary function."),
2865 subcommand_name, pos_name);
2868 if (n0->n - 1 == n0->scale_idx)
2870 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2871 "but %s is a scale variable."),
2872 subcommand_name, pos_name, var_get_name (v0));
2876 for (size_t i = 1; i < stack->n; i++)
2878 const struct ctables_nest *ni = &stack->nests[i];
2880 const struct variable *vi = ni->vars[ni->n - 1];
2881 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2883 if (ni->n - 1 == ni->scale_idx)
2885 msg (SE, _("%s=%s requires the variables to be moved to be "
2886 "categorical, but %s is a scale variable."),
2887 subcommand_name, pos_name, var_get_name (vi));
2890 if (var_get_width (v0) != var_get_width (vi))
2892 msg (SE, _("%s=%s requires the variables to be "
2893 "moved to have the same width, but %s has "
2894 "width %d and %s has width %d."),
2895 subcommand_name, pos_name,
2896 var_get_name (v0), var_get_width (v0),
2897 var_get_name (vi), var_get_width (vi));
2900 if (!val_labs_equal (var_get_value_labels (v0),
2901 var_get_value_labels (vi)))
2903 msg (SE, _("%s=%s requires the variables to be "
2904 "moved to have the same value labels, but %s "
2905 "and %s have different value labels."),
2906 subcommand_name, pos_name,
2907 var_get_name (v0), var_get_name (vi));
2910 if (!ctables_categories_equal (c0, ci))
2912 msg (SE, _("%s=%s requires the variables to be "
2913 "moved to have the same category "
2914 "specifications, but %s and %s have different "
2915 "category specifications."),
2916 subcommand_name, pos_name,
2917 var_get_name (v0), var_get_name (vi));
2926 ctables_prepare_table (struct ctables_table *t)
2928 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2931 t->stacks[a] = enumerate_fts (a, t->axes[a]);
2933 for (size_t j = 0; j < t->stacks[a].n; j++)
2935 struct ctables_nest *nest = &t->stacks[a].nests[j];
2936 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2938 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
2939 nest->n_domains[dt] = 0;
2941 for (size_t k = 0; k < nest->n; k++)
2943 if (k == nest->scale_idx)
2952 if (a != PIVOT_AXIS_LAYER)
2959 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2960 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2961 : a == PIVOT_AXIS_ROW)
2963 if (k == nest->n - 1
2964 || (nest->scale_idx == nest->n - 1
2965 && k == nest->n - 2))
2971 if (a == PIVOT_AXIS_COLUMN)
2976 if (a == PIVOT_AXIS_ROW)
2981 nest->domains[dt][nest->n_domains[dt]++] = k;
2988 struct ctables_nest *nest = xmalloc (sizeof *nest);
2989 *nest = (struct ctables_nest) { .n = 0 };
2990 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
2993 struct ctables_stack *stack = &t->stacks[t->summary_axis];
2994 for (size_t i = 0; i < stack->n; i++)
2996 struct ctables_nest *nest = &stack->nests[i];
2997 if (!nest->specs[CSV_CELL].n)
2999 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3000 specs->specs = xmalloc (sizeof *specs->specs);
3003 enum ctables_summary_function function
3004 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3005 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3007 *specs->specs = (struct ctables_summary_spec) {
3008 .function = function,
3009 .format = ctables_summary_default_format (function, &var),
3010 .label = ctables_summary_default_label (function, 0),
3013 specs->var = nest->vars[0];
3015 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3016 &nest->specs[CSV_CELL]);
3018 else if (!nest->specs[CSV_TOTAL].n)
3019 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3020 &nest->specs[CSV_CELL]);
3023 struct ctables_summary_spec_set *merged = &t->summary_specs;
3024 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3026 for (size_t j = 0; j < stack->n; j++)
3028 const struct ctables_nest *nest = &stack->nests[j];
3030 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3031 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3036 struct merge_item min = items[0];
3037 for (size_t j = 1; j < n_left; j++)
3038 if (merge_item_compare_3way (&items[j], &min) < 0)
3041 if (merged->n >= merged->allocated)
3042 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3043 sizeof *merged->specs);
3044 merged->specs[merged->n++] = min.set->specs[min.ofs];
3046 for (size_t j = 0; j < n_left; )
3048 if (merge_item_compare_3way (&items[j], &min) == 0)
3050 struct merge_item *item = &items[j];
3051 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3052 if (++item->ofs >= item->set->n)
3054 items[j] = items[--n_left];
3063 for (size_t j = 0; j < merged->n; j++)
3064 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3066 for (size_t j = 0; j < stack->n; j++)
3068 const struct ctables_nest *nest = &stack->nests[j];
3069 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3071 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3072 for (size_t k = 0; k < specs->n; k++)
3073 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3074 specs->specs[k].axis_idx);
3080 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3081 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3085 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3086 enum pivot_axis_type a)
3088 struct ctables_stack *stack = &t->stacks[a];
3089 for (size_t i = 0; i < stack->n; i++)
3091 const struct ctables_nest *nest = &stack->nests[i];
3092 const struct variable *var = nest->vars[nest->n - 1];
3093 int width = var_get_width (var);
3094 const union value *value = case_data (c, var);
3096 if (var_is_numeric (var) && value->f == SYSMIS)
3099 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3103 unsigned int hash = value_hash (value, width, 0);
3105 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3108 clv = xmalloc (sizeof *clv);
3109 value_clone (&clv->value, value, width);
3110 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3116 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3118 const struct ctables_value *const *ap = a_;
3119 const struct ctables_value *const *bp = b_;
3120 const struct ctables_value *a = *ap;
3121 const struct ctables_value *b = *bp;
3122 const int *width = width_;
3123 return value_compare_3way (&a->value, &b->value, *width);
3127 ctables_sort_clabels_values (struct ctables_table *t)
3129 int width = var_get_width (t->clabels_example);
3131 size_t n = hmap_count (&t->clabels_values_map);
3132 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3134 struct ctables_value *clv;
3136 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3137 t->clabels_values[i++] = clv;
3138 t->n_clabels_values = n;
3141 sort (t->clabels_values, n, sizeof *t->clabels_values,
3142 compare_clabels_values_3way, &width);
3144 for (size_t i = 0; i < n; i++)
3145 t->clabels_values[i]->leaf = i;
3149 ctables_execute (struct dataset *ds, struct ctables *ct)
3151 struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3154 bool warn_on_invalid = true;
3155 double total_weight = 0;
3156 for (struct ccase *c = casereader_read (input); c;
3157 case_unref (c), c = casereader_read (input))
3159 double weight = dict_get_case_weight (dataset_dict (ds), c,
3161 total_weight += weight;
3163 for (size_t i = 0; i < ct->n_tables; i++)
3165 struct ctables_table *t = ct->tables[i];
3167 for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3168 for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3169 for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3170 ctables_cell_insert (t, c, ir, ic, il, weight);
3172 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3173 if (t->label_axis[a] != a)
3174 ctables_insert_clabels_values (t, c, a);
3177 casereader_destroy (input);
3179 for (size_t i = 0; i < ct->n_tables; i++)
3181 struct ctables_table *t = ct->tables[i];
3183 if (t->clabels_example)
3184 ctables_sort_clabels_values (t);
3186 ctables_table_output (ct, ct->tables[i]);
3188 return proc_commit (ds);
3192 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3194 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3195 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3196 enum settings_value_show tvars = settings_get_show_variables ();
3197 for (size_t i = 0; i < n_vars; i++)
3198 vlabels[i] = (enum ctables_vlabel) tvars;
3200 struct ctables *ct = xmalloc (sizeof *ct);
3201 *ct = (struct ctables) {
3202 .look = pivot_table_look_unshare (pivot_table_look_ref (
3203 pivot_table_look_get_default ())),
3205 .hide_threshold = 5,
3207 ct->look->omit_empty = false;
3209 if (!lex_force_match (lexer, T_SLASH))
3212 while (!lex_match_id (lexer, "TABLE"))
3214 if (lex_match_id (lexer, "FORMAT"))
3216 double widths[2] = { SYSMIS, SYSMIS };
3217 double units_per_inch = 72.0;
3219 while (lex_token (lexer) != T_SLASH)
3221 if (lex_match_id (lexer, "MINCOLWIDTH"))
3223 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3226 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3228 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3231 else if (lex_match_id (lexer, "UNITS"))
3233 lex_match (lexer, T_EQUALS);
3234 if (lex_match_id (lexer, "POINTS"))
3235 units_per_inch = 72.0;
3236 else if (lex_match_id (lexer, "INCHES"))
3237 units_per_inch = 1.0;
3238 else if (lex_match_id (lexer, "CM"))
3239 units_per_inch = 2.54;
3242 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3246 else if (lex_match_id (lexer, "EMPTY"))
3251 lex_match (lexer, T_EQUALS);
3252 if (lex_match_id (lexer, "ZERO"))
3254 /* Nothing to do. */
3256 else if (lex_match_id (lexer, "BLANK"))
3257 ct->zero = xstrdup ("");
3258 else if (lex_force_string (lexer))
3260 ct->zero = ss_xstrdup (lex_tokss (lexer));
3266 else if (lex_match_id (lexer, "MISSING"))
3268 lex_match (lexer, T_EQUALS);
3269 if (!lex_force_string (lexer))
3273 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3274 ? ss_xstrdup (lex_tokss (lexer))
3280 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3281 "UNITS", "EMPTY", "MISSING");
3286 if (widths[0] != SYSMIS && widths[1] != SYSMIS
3287 && widths[0] > widths[1])
3289 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3293 for (size_t i = 0; i < 2; i++)
3294 if (widths[i] != SYSMIS)
3296 int *wr = ct->look->width_ranges[TABLE_HORZ];
3297 wr[i] = widths[i] / units_per_inch * 96.0;
3302 else if (lex_match_id (lexer, "VLABELS"))
3304 if (!lex_force_match_id (lexer, "VARIABLES"))
3306 lex_match (lexer, T_EQUALS);
3308 struct variable **vars;
3310 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3314 if (!lex_force_match_id (lexer, "DISPLAY"))
3319 lex_match (lexer, T_EQUALS);
3321 enum ctables_vlabel vlabel;
3322 if (lex_match_id (lexer, "DEFAULT"))
3323 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3324 else if (lex_match_id (lexer, "NAME"))
3326 else if (lex_match_id (lexer, "LABEL"))
3327 vlabel = CTVL_LABEL;
3328 else if (lex_match_id (lexer, "BOTH"))
3330 else if (lex_match_id (lexer, "NONE"))
3334 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3340 for (size_t i = 0; i < n_vars; i++)
3341 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3344 else if (lex_match_id (lexer, "MRSETS"))
3346 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3348 lex_match (lexer, T_EQUALS);
3349 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3352 else if (lex_match_id (lexer, "SMISSING"))
3354 if (lex_match_id (lexer, "VARIABLE"))
3355 ct->smissing_listwise = false;
3356 else if (lex_match_id (lexer, "LISTWISE"))
3357 ct->smissing_listwise = true;
3360 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3365 else if (lex_match_id (lexer, "WEIGHT"))
3367 if (!lex_force_match_id (lexer, "VARIABLE"))
3369 lex_match (lexer, T_EQUALS);
3370 ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3371 if (!ct->base_weight)
3374 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3376 if (!lex_force_match_id (lexer, "COUNT"))
3378 lex_match (lexer, T_EQUALS);
3379 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3381 ct->hide_threshold = lex_integer (lexer);
3386 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3387 "SMISSING", "PCOMPUTE", "PPROPERTIES",
3388 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3392 if (!lex_force_match (lexer, T_SLASH))
3396 size_t allocated_tables = 0;
3399 if (ct->n_tables >= allocated_tables)
3400 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3401 sizeof *ct->tables);
3403 struct ctables_category *cat = xmalloc (sizeof *cat);
3404 *cat = (struct ctables_category) {
3406 .include_missing = false,
3407 .sort_ascending = true,
3410 struct ctables_categories *c = xmalloc (sizeof *c);
3411 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3412 *c = (struct ctables_categories) {
3418 struct ctables_categories **categories = xnmalloc (n_vars,
3419 sizeof *categories);
3420 for (size_t i = 0; i < n_vars; i++)
3423 struct ctables_table *t = xmalloc (sizeof *t);
3424 *t = (struct ctables_table) {
3425 .cells = HMAP_INITIALIZER (t->cells),
3426 .slabels_axis = PIVOT_AXIS_COLUMN,
3427 .slabels_visible = true,
3428 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3430 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3431 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3432 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3434 .clabels_from_axis = PIVOT_AXIS_LAYER,
3435 .categories = categories,
3436 .n_categories = n_vars,
3439 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3440 hmap_init (&t->domains[dt]);
3441 ct->tables[ct->n_tables++] = t;
3443 lex_match (lexer, T_EQUALS);
3444 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3446 if (lex_match (lexer, T_BY))
3448 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3449 ct, t, PIVOT_AXIS_COLUMN))
3452 if (lex_match (lexer, T_BY))
3454 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3455 ct, t, PIVOT_AXIS_LAYER))
3460 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3461 && !t->axes[PIVOT_AXIS_LAYER])
3463 lex_error (lexer, _("At least one variable must be specified."));
3467 const struct ctables_axis *scales[PIVOT_N_AXES];
3468 size_t n_scales = 0;
3469 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3471 scales[a] = find_scale (t->axes[a]);
3477 msg (SE, _("Scale variables may appear only on one axis."));
3478 if (scales[PIVOT_AXIS_ROW])
3479 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3480 _("This scale variable appears on the rows axis."));
3481 if (scales[PIVOT_AXIS_COLUMN])
3482 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3483 _("This scale variable appears on the columns axis."));
3484 if (scales[PIVOT_AXIS_LAYER])
3485 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3486 _("This scale variable appears on the layer axis."));
3490 const struct ctables_axis *summaries[PIVOT_N_AXES];
3491 size_t n_summaries = 0;
3492 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3494 summaries[a] = (scales[a]
3496 : find_categorical_summary_spec (t->axes[a]));
3500 if (n_summaries > 1)
3502 msg (SE, _("Summaries may appear only on one axis."));
3503 if (summaries[PIVOT_AXIS_ROW])
3504 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3505 _("This variable on the rows axis has a summary."));
3506 if (summaries[PIVOT_AXIS_COLUMN])
3507 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3508 _("This variable on the columns axis has a summary."));
3509 if (summaries[PIVOT_AXIS_LAYER])
3510 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3511 _("This variable on the layers axis has a summary."));
3514 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3515 if (n_summaries ? summaries[a] : t->axes[a])
3517 t->summary_axis = a;
3521 if (lex_token (lexer) == T_ENDCMD)
3523 if (!ctables_prepare_table (t))
3527 if (!lex_force_match (lexer, T_SLASH))
3530 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3532 if (lex_match_id (lexer, "SLABELS"))
3534 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3536 if (lex_match_id (lexer, "POSITION"))
3538 lex_match (lexer, T_EQUALS);
3539 if (lex_match_id (lexer, "COLUMN"))
3540 t->slabels_axis = PIVOT_AXIS_COLUMN;
3541 else if (lex_match_id (lexer, "ROW"))
3542 t->slabels_axis = PIVOT_AXIS_ROW;
3543 else if (lex_match_id (lexer, "LAYER"))
3544 t->slabels_axis = PIVOT_AXIS_LAYER;
3547 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3551 else if (lex_match_id (lexer, "VISIBLE"))
3553 lex_match (lexer, T_EQUALS);
3554 if (!parse_bool (lexer, &t->slabels_visible))
3559 lex_error_expecting (lexer, "POSITION", "VISIBLE");
3564 else if (lex_match_id (lexer, "CLABELS"))
3566 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3568 if (lex_match_id (lexer, "AUTO"))
3570 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3571 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3573 else if (lex_match_id (lexer, "ROWLABELS"))
3575 lex_match (lexer, T_EQUALS);
3576 if (lex_match_id (lexer, "OPPOSITE"))
3577 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3578 else if (lex_match_id (lexer, "LAYER"))
3579 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3582 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3586 else if (lex_match_id (lexer, "COLLABELS"))
3588 lex_match (lexer, T_EQUALS);
3589 if (lex_match_id (lexer, "OPPOSITE"))
3590 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3591 else if (lex_match_id (lexer, "LAYER"))
3592 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3595 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3601 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3607 else if (lex_match_id (lexer, "CRITERIA"))
3609 if (!lex_force_match_id (lexer, "CILEVEL"))
3611 lex_match (lexer, T_EQUALS);
3613 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3615 t->cilevel = lex_number (lexer);
3618 else if (lex_match_id (lexer, "CATEGORIES"))
3620 if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3623 else if (lex_match_id (lexer, "TITLES"))
3628 if (lex_match_id (lexer, "CAPTION"))
3629 textp = &t->caption;
3630 else if (lex_match_id (lexer, "CORNER"))
3632 else if (lex_match_id (lexer, "TITLE"))
3636 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3639 lex_match (lexer, T_EQUALS);
3641 struct string s = DS_EMPTY_INITIALIZER;
3642 while (lex_is_string (lexer))
3644 if (!ds_is_empty (&s))
3645 ds_put_byte (&s, ' ');
3646 ds_put_substring (&s, lex_tokss (lexer));
3650 *textp = ds_steal_cstr (&s);
3652 while (lex_token (lexer) != T_SLASH
3653 && lex_token (lexer) != T_ENDCMD);
3655 else if (lex_match_id (lexer, "SIGTEST"))
3659 t->chisq = xmalloc (sizeof *t->chisq);
3660 *t->chisq = (struct ctables_chisq) {
3662 .include_mrsets = true,
3663 .all_visible = true,
3669 if (lex_match_id (lexer, "TYPE"))
3671 lex_match (lexer, T_EQUALS);
3672 if (!lex_force_match_id (lexer, "CHISQUARE"))
3675 else if (lex_match_id (lexer, "ALPHA"))
3677 lex_match (lexer, T_EQUALS);
3678 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3680 t->chisq->alpha = lex_number (lexer);
3683 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3685 lex_match (lexer, T_EQUALS);
3686 if (parse_bool (lexer, &t->chisq->include_mrsets))
3689 else if (lex_match_id (lexer, "CATEGORIES"))
3691 lex_match (lexer, T_EQUALS);
3692 if (lex_match_id (lexer, "ALLVISIBLE"))
3693 t->chisq->all_visible = true;
3694 else if (lex_match_id (lexer, "SUBTOTALS"))
3695 t->chisq->all_visible = false;
3698 lex_error_expecting (lexer,
3699 "ALLVISIBLE", "SUBTOTALS");
3705 lex_error_expecting (lexer, "TYPE", "ALPHA",
3706 "INCLUDEMRSETS", "CATEGORIES");
3710 while (lex_token (lexer) != T_SLASH
3711 && lex_token (lexer) != T_ENDCMD);
3713 else if (lex_match_id (lexer, "COMPARETEST"))
3717 t->pairwise = xmalloc (sizeof *t->pairwise);
3718 *t->pairwise = (struct ctables_pairwise) {
3720 .alpha = { .05, .05 },
3721 .adjust = BONFERRONI,
3722 .include_mrsets = true,
3723 .meansvariance_allcats = true,
3724 .all_visible = true,
3733 if (lex_match_id (lexer, "TYPE"))
3735 lex_match (lexer, T_EQUALS);
3736 if (lex_match_id (lexer, "PROP"))
3737 t->pairwise->type = PROP;
3738 else if (lex_match_id (lexer, "MEAN"))
3739 t->pairwise->type = MEAN;
3742 lex_error_expecting (lexer, "PROP", "MEAN");
3746 else if (lex_match_id (lexer, "ALPHA"))
3748 lex_match (lexer, T_EQUALS);
3750 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3752 double a0 = lex_number (lexer);
3755 lex_match (lexer, T_COMMA);
3756 if (lex_is_number (lexer))
3758 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3760 double a1 = lex_number (lexer);
3763 t->pairwise->alpha[0] = MIN (a0, a1);
3764 t->pairwise->alpha[1] = MAX (a0, a1);
3767 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3769 else if (lex_match_id (lexer, "ADJUST"))
3771 lex_match (lexer, T_EQUALS);
3772 if (lex_match_id (lexer, "BONFERRONI"))
3773 t->pairwise->adjust = BONFERRONI;
3774 else if (lex_match_id (lexer, "BH"))
3775 t->pairwise->adjust = BH;
3776 else if (lex_match_id (lexer, "NONE"))
3777 t->pairwise->adjust = 0;
3780 lex_error_expecting (lexer, "BONFERRONI", "BH",
3785 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3787 lex_match (lexer, T_EQUALS);
3788 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3791 else if (lex_match_id (lexer, "MEANSVARIANCE"))
3793 lex_match (lexer, T_EQUALS);
3794 if (lex_match_id (lexer, "ALLCATS"))
3795 t->pairwise->meansvariance_allcats = true;
3796 else if (lex_match_id (lexer, "TESTEDCATS"))
3797 t->pairwise->meansvariance_allcats = false;
3800 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3804 else if (lex_match_id (lexer, "CATEGORIES"))
3806 lex_match (lexer, T_EQUALS);
3807 if (lex_match_id (lexer, "ALLVISIBLE"))
3808 t->pairwise->all_visible = true;
3809 else if (lex_match_id (lexer, "SUBTOTALS"))
3810 t->pairwise->all_visible = false;
3813 lex_error_expecting (lexer, "ALLVISIBLE",
3818 else if (lex_match_id (lexer, "MERGE"))
3820 lex_match (lexer, T_EQUALS);
3821 if (!parse_bool (lexer, &t->pairwise->merge))
3824 else if (lex_match_id (lexer, "STYLE"))
3826 lex_match (lexer, T_EQUALS);
3827 if (lex_match_id (lexer, "APA"))
3828 t->pairwise->apa_style = true;
3829 else if (lex_match_id (lexer, "SIMPLE"))
3830 t->pairwise->apa_style = false;
3833 lex_error_expecting (lexer, "APA", "SIMPLE");
3837 else if (lex_match_id (lexer, "SHOWSIG"))
3839 lex_match (lexer, T_EQUALS);
3840 if (!parse_bool (lexer, &t->pairwise->show_sig))
3845 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3846 "INCLUDEMRSETS", "MEANSVARIANCE",
3847 "CATEGORIES", "MERGE", "STYLE",
3852 while (lex_token (lexer) != T_SLASH
3853 && lex_token (lexer) != T_ENDCMD);
3857 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3858 "CRITERIA", "CATEGORIES", "TITLES",
3859 "SIGTEST", "COMPARETEST");
3863 if (!lex_match (lexer, T_SLASH))
3867 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3868 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3870 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3874 if (!ctables_prepare_table (t))
3877 while (lex_token (lexer) != T_ENDCMD);
3879 bool ok = ctables_execute (ds, ct);
3880 ctables_destroy (ct);
3881 return ok ? CMD_SUCCESS : CMD_FAILURE;
3884 ctables_destroy (ct);