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 bool contributes_to_domains;
190 struct ctables_domain *domains[N_CTDTS];
193 enum ctables_summary_variant sv;
198 struct ctables_cell_value
200 const struct ctables_category *category;
208 union ctables_summary *summaries;
213 struct pivot_table_look *look;
215 /* If this is NULL, zeros are displayed using the normal print format.
216 Otherwise, this string is displayed. */
219 /* If this is NULL, missing values are displayed using the normal print
220 format. Otherwise, this string is displayed. */
223 /* Indexed by variable dictionary index. */
224 enum ctables_vlabel *vlabels;
226 bool mrsets_count_duplicates; /* MRSETS. */
227 bool smissing_listwise; /* SMISSING. */
228 struct variable *base_weight; /* WEIGHT. */
229 int hide_threshold; /* HIDESMALLCOUNTS. */
231 struct ctables_table **tables;
235 struct ctables_postcompute
237 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
238 const char *name; /* Name, without leading &. */
240 struct ctables_postcompute_expr *expr;
243 bool hide_source_cats;
246 struct ctables_postcompute_expr
248 enum ctables_postcompute_op
256 /* XXX SUBTOTAL and HSUBTOTAL */
269 /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
274 XXX what about string ranges? */
277 /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
278 struct ctables_postcompute_expr *subs[2];
282 struct ctables_summary_spec_set
284 struct ctables_summary_spec *specs;
288 struct variable *var;
291 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
292 const struct ctables_summary_spec_set *);
293 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
295 /* A nested sequence of variables, e.g. a > b > c. */
298 struct variable **vars;
301 size_t *domains[N_CTDTS];
302 size_t n_domains[N_CTDTS];
304 struct ctables_summary_spec_set specs[N_CSVS];
307 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
310 struct ctables_nest *nests;
316 struct hmap_node node;
323 struct ctables_axis *axes[PIVOT_N_AXES];
324 struct ctables_stack stacks[PIVOT_N_AXES];
325 enum pivot_axis_type summary_axis;
326 struct ctables_summary_spec_set summary_specs;
328 struct hmap domains[N_CTDTS];
330 const struct variable *clabels_example;
331 struct hmap clabels_values_map;
332 struct ctables_value **clabels_values;
333 size_t n_clabels_values;
335 enum pivot_axis_type slabels_axis;
336 bool slabels_visible;
338 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
340 Most commonly, label_axis[a] == a, and in particular we always have
341 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
343 If ROWLABELS or COLLABELS is specified, then one of
344 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
345 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
347 enum pivot_axis_type label_axis[PIVOT_N_AXES];
348 enum pivot_axis_type clabels_from_axis;
350 /* Indexed by variable dictionary index. */
351 struct ctables_categories **categories;
360 struct ctables_chisq *chisq;
361 struct ctables_pairwise *pairwise;
369 struct variable *var;
370 const struct mrset *mrset;
374 static const struct fmt_spec *
375 ctables_var_get_print_format (const struct ctables_var *var)
377 return (var->is_mrset
378 ? var_get_print_format (var->mrset->vars[0])
379 : var_get_print_format (var->var));
383 ctables_var_name (const struct ctables_var *var)
385 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
388 struct ctables_categories
391 struct ctables_category *cats;
396 struct ctables_category
398 enum ctables_category_type
416 struct ctables_category *subtotal;
420 double number; /* CCT_NUMBER. */
421 char *string; /* CCT_STRING. */
422 double range[2]; /* CCT_RANGE. */
423 char *total_label; /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
425 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
428 bool include_missing;
432 enum ctables_summary_function sort_function;
433 struct variable *sort_var;
440 ctables_category_uninit (struct ctables_category *cat)
460 free (cat->total_label);
471 ctables_category_equal (const struct ctables_category *a,
472 const struct ctables_category *b)
474 if (a->type != b->type)
480 return a->number == b->number;
483 return strcmp (a->string, b->string);
486 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
495 return !strcmp (a->total_label, b->total_label);
500 return (a->include_missing == b->include_missing
501 && a->sort_ascending == b->sort_ascending
502 && a->sort_function == b->sort_function
503 && a->sort_var == b->sort_var
504 && a->percentile == b->percentile);
511 ctables_categories_unref (struct ctables_categories *c)
516 assert (c->n_refs > 0);
520 for (size_t i = 0; i < c->n_cats; i++)
521 ctables_category_uninit (&c->cats[i]);
527 ctables_categories_equal (const struct ctables_categories *a,
528 const struct ctables_categories *b)
530 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
533 for (size_t i = 0; i < a->n_cats; i++)
534 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
540 /* Chi-square test (SIGTEST). */
548 /* Pairwise comparison test (COMPARETEST). */
549 struct ctables_pairwise
551 enum { PROP, MEAN } type;
554 bool meansvariance_allcats;
556 enum { BONFERRONI = 1, BH } adjust;
580 struct ctables_var var;
582 struct ctables_summary_spec_set specs[N_CSVS];
586 struct ctables_axis *subs[2];
589 struct msg_location *loc;
592 static void ctables_axis_destroy (struct ctables_axis *);
601 enum ctables_function_availability
603 CTFA_ALL, /* Any variables. */
604 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
605 CTFA_MRSETS, /* Only multiple-response sets */
608 struct ctables_summary_spec
610 enum ctables_summary_function function;
611 double percentile; /* CTSF_PTILE only. */
613 struct fmt_spec format; /* XXX extra CTABLES formats */
618 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
619 const struct ctables_summary_spec *src)
622 dst->label = xstrdup (src->label);
626 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
633 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
634 const struct ctables_summary_spec_set *src)
636 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
637 for (size_t i = 0; i < src->n; i++)
638 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
640 *dst = (struct ctables_summary_spec_set) {
649 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
651 for (size_t i = 0; i < set->n; i++)
652 ctables_summary_spec_uninit (&set->specs[i]);
657 parse_col_width (struct lexer *lexer, const char *name, double *width)
659 lex_match (lexer, T_EQUALS);
660 if (lex_match_id (lexer, "DEFAULT"))
662 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
664 *width = lex_number (lexer);
674 parse_bool (struct lexer *lexer, bool *b)
676 if (lex_match_id (lexer, "NO"))
678 else if (lex_match_id (lexer, "YES"))
682 lex_error_expecting (lexer, "YES", "NO");
688 static enum ctables_function_availability
689 ctables_function_availability (enum ctables_summary_function f)
691 static enum ctables_function_availability availability[] = {
692 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
697 return availability[f];
701 parse_ctables_summary_function (struct lexer *lexer,
702 enum ctables_summary_function *f)
706 enum ctables_summary_function function;
707 struct substring name;
709 static struct pair names[] = {
710 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
711 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
714 /* The .COUNT suffix may be omitted. */
715 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
716 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
717 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
718 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
719 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
720 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
721 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
725 if (!lex_force_id (lexer))
728 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
729 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
731 *f = names[i].function;
736 lex_error (lexer, _("Expecting summary function name."));
741 ctables_axis_destroy (struct ctables_axis *axis)
749 for (size_t i = 0; i < N_CSVS; i++)
750 ctables_summary_spec_set_uninit (&axis->specs[i]);
755 ctables_axis_destroy (axis->subs[0]);
756 ctables_axis_destroy (axis->subs[1]);
759 msg_location_destroy (axis->loc);
763 static struct ctables_axis *
764 ctables_axis_new_nonterminal (enum ctables_axis_op op,
765 struct ctables_axis *sub0,
766 struct ctables_axis *sub1,
767 struct lexer *lexer, int start_ofs)
769 struct ctables_axis *axis = xmalloc (sizeof *axis);
770 *axis = (struct ctables_axis) {
772 .subs = { sub0, sub1 },
773 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
778 struct ctables_axis_parse_ctx
781 struct dictionary *dict;
783 struct ctables_table *t;
786 static struct fmt_spec
787 ctables_summary_default_format (enum ctables_summary_function function,
788 const struct ctables_var *var)
790 static const enum ctables_format default_formats[] = {
791 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
795 switch (default_formats[function])
798 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
801 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
804 return *ctables_var_get_print_format (var);
812 ctables_summary_default_label (enum ctables_summary_function function,
815 static const char *default_labels[] = {
816 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
821 return (function == CTSF_PTILE
822 ? xasprintf (_("Percentile %.2f"), percentile)
823 : xstrdup (gettext (default_labels[function])));
827 ctables_summary_function_name (enum ctables_summary_function function)
829 static const char *names[] = {
830 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
834 return names[function];
838 add_summary_spec (struct ctables_axis *axis,
839 enum ctables_summary_function function, double percentile,
840 const char *label, const struct fmt_spec *format,
841 const struct msg_location *loc, enum ctables_summary_variant sv)
843 if (axis->op == CTAO_VAR)
845 const char *function_name = ctables_summary_function_name (function);
846 const char *var_name = ctables_var_name (&axis->var);
847 switch (ctables_function_availability (function))
850 if (!axis->var.is_mrset)
852 msg_at (SE, loc, _("Summary function %s applies only to multiple "
853 "response sets."), function_name);
854 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
864 _("Summary function %s applies only to scale variables."),
866 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
876 struct ctables_summary_spec_set *set = &axis->specs[sv];
877 if (set->n >= set->allocated)
878 set->specs = x2nrealloc (set->specs, &set->allocated,
881 struct ctables_summary_spec *dst = &set->specs[set->n++];
882 *dst = (struct ctables_summary_spec) {
883 .function = function,
884 .percentile = percentile,
885 .label = xstrdup (label),
886 .format = (format ? *format
887 : ctables_summary_default_format (function, &axis->var)),
893 for (size_t i = 0; i < 2; i++)
894 if (!add_summary_spec (axis->subs[i], function, percentile, label,
901 static struct ctables_axis *ctables_axis_parse_stack (
902 struct ctables_axis_parse_ctx *);
905 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
906 struct ctables_var *var)
908 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
910 *var = (struct ctables_var) {
912 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
916 lex_error (lexer, _("'%s' does not name a multiple-response set "
917 "in the active file dictionary."),
918 lex_tokcstr (lexer));
926 *var = (struct ctables_var) {
928 .var = parse_variable (lexer, dict),
930 return var->var != NULL;
934 static struct ctables_axis *
935 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
937 if (lex_match (ctx->lexer, T_LPAREN))
939 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
940 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
942 ctables_axis_destroy (sub);
948 if (!lex_force_id (ctx->lexer))
951 int start_ofs = lex_ofs (ctx->lexer);
952 struct ctables_var var;
953 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
956 struct ctables_axis *axis = xmalloc (sizeof *axis);
957 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
959 /* XXX should figure out default measures by reading data */
960 axis->scale = (var.is_mrset ? false
961 : lex_match_phrase (ctx->lexer, "[S]") ? true
962 : lex_match_phrase (ctx->lexer, "[C]") ? false
963 : var_get_measure (var.var) == MEASURE_SCALE);
964 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
965 lex_ofs (ctx->lexer) - 1);
970 has_digit (const char *s)
972 return s[strcspn (s, "0123456789")] != '\0';
975 static struct ctables_axis *
976 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
978 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
979 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
982 enum ctables_summary_variant sv = CSV_CELL;
985 int start_ofs = lex_ofs (ctx->lexer);
987 /* Parse function. */
988 enum ctables_summary_function function;
989 if (!parse_ctables_summary_function (ctx->lexer, &function))
992 /* Parse percentile. */
993 double percentile = 0;
994 if (function == CTSF_PTILE)
996 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
998 percentile = lex_number (ctx->lexer);
999 lex_get (ctx->lexer);
1004 if (lex_is_string (ctx->lexer))
1006 label = ss_xstrdup (lex_tokss (ctx->lexer));
1007 lex_get (ctx->lexer);
1010 label = ctables_summary_default_label (function, percentile);
1013 struct fmt_spec format;
1014 const struct fmt_spec *formatp;
1015 if (lex_token (ctx->lexer) == T_ID
1016 && has_digit (lex_tokcstr (ctx->lexer)))
1018 if (!parse_format_specifier (ctx->lexer, &format)
1019 || !fmt_check_output (&format)
1020 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1030 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1031 lex_ofs (ctx->lexer) - 1);
1032 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1034 msg_location_destroy (loc);
1036 lex_match (ctx->lexer, T_COMMA);
1037 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1039 if (!lex_force_match (ctx->lexer, T_LBRACK))
1043 else if (lex_match (ctx->lexer, T_RBRACK))
1045 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1052 ctables_axis_destroy (sub);
1056 static const struct ctables_axis *
1057 find_scale (const struct ctables_axis *axis)
1061 else if (axis->op == CTAO_VAR)
1065 assert (!axis->var.is_mrset);
1073 for (size_t i = 0; i < 2; i++)
1075 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1083 static const struct ctables_axis *
1084 find_categorical_summary_spec (const struct ctables_axis *axis)
1088 else if (axis->op == CTAO_VAR)
1089 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1092 for (size_t i = 0; i < 2; i++)
1094 const struct ctables_axis *sum
1095 = find_categorical_summary_spec (axis->subs[i]);
1103 static struct ctables_axis *
1104 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1106 int start_ofs = lex_ofs (ctx->lexer);
1107 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1111 while (lex_match (ctx->lexer, T_GT))
1113 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1117 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1118 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1120 const struct ctables_axis *outer_scale = find_scale (lhs);
1121 const struct ctables_axis *inner_scale = find_scale (rhs);
1122 if (outer_scale && inner_scale)
1124 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1125 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1126 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1127 ctables_axis_destroy (nest);
1131 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1134 msg_at (SE, nest->loc,
1135 _("Summaries may only be requested for categorical variables "
1136 "at the innermost nesting level."));
1137 msg_at (SN, outer_sum->loc,
1138 _("This outer categorical variable has a summary."));
1139 ctables_axis_destroy (nest);
1149 static struct ctables_axis *
1150 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1152 int start_ofs = lex_ofs (ctx->lexer);
1153 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1157 while (lex_match (ctx->lexer, T_PLUS))
1159 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1163 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1164 ctx->lexer, start_ofs);
1171 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1172 struct ctables *ct, struct ctables_table *t,
1173 enum pivot_axis_type a)
1175 if (lex_token (lexer) == T_BY
1176 || lex_token (lexer) == T_SLASH
1177 || lex_token (lexer) == T_ENDCMD)
1180 struct ctables_axis_parse_ctx ctx = {
1186 t->axes[a] = ctables_axis_parse_stack (&ctx);
1187 return t->axes[a] != NULL;
1191 ctables_chisq_destroy (struct ctables_chisq *chisq)
1197 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1203 ctables_table_destroy (struct ctables_table *t)
1208 for (size_t i = 0; i < t->n_categories; i++)
1209 ctables_categories_unref (t->categories[i]);
1210 free (t->categories);
1212 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1213 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1214 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1218 ctables_chisq_destroy (t->chisq);
1219 ctables_pairwise_destroy (t->pairwise);
1224 ctables_destroy (struct ctables *ct)
1229 pivot_table_look_unref (ct->look);
1233 for (size_t i = 0; i < ct->n_tables; i++)
1234 ctables_table_destroy (ct->tables[i]);
1239 static struct ctables_category
1240 cct_range (double low, double high)
1242 return (struct ctables_category) {
1244 .range = { low, high }
1249 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1250 struct ctables_table *t)
1252 if (!lex_match_id (lexer, "VARIABLES"))
1254 lex_match (lexer, T_EQUALS);
1256 struct variable **vars;
1258 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1261 struct ctables_categories *c = xmalloc (sizeof *c);
1262 *c = (struct ctables_categories) { .n_refs = n_vars };
1263 for (size_t i = 0; i < n_vars; i++)
1265 struct ctables_categories **cp
1266 = &t->categories[var_get_dict_index (vars[i])];
1267 ctables_categories_unref (*cp);
1272 size_t allocated_cats = 0;
1273 if (lex_match (lexer, T_LBRACK))
1277 if (c->n_cats >= allocated_cats)
1278 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1280 struct ctables_category *cat = &c->cats[c->n_cats];
1281 if (lex_match_id (lexer, "OTHERNM"))
1282 cat->type = CCT_OTHERNM;
1283 else if (lex_match_id (lexer, "MISSING"))
1284 cat->type = CCT_MISSING;
1285 else if (lex_match_id (lexer, "SUBTOTAL"))
1286 *cat = (struct ctables_category)
1287 { .type = CCT_SUBTOTAL, .total_label = NULL };
1288 else if (lex_match_id (lexer, "HSUBTOTAL"))
1289 *cat = (struct ctables_category)
1290 { .type = CCT_HSUBTOTAL, .total_label = NULL };
1291 else if (lex_match_id (lexer, "LO"))
1293 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1295 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1298 else if (lex_is_number (lexer))
1300 double number = lex_number (lexer);
1302 if (lex_match_id (lexer, "THRU"))
1304 cat->type = CCT_RANGE;
1305 cat->range[0] = number;
1306 if (lex_match_id (lexer, "HI"))
1307 *cat = cct_range (number, DBL_MAX);
1310 if (!lex_force_num (lexer))
1312 *cat = cct_range (number, lex_number (lexer));
1317 *cat = (struct ctables_category) {
1322 else if (lex_is_string (lexer))
1324 *cat = (struct ctables_category) {
1326 .string = ss_xstrdup (lex_tokss (lexer)),
1332 lex_error (lexer, NULL);
1336 if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1338 if (lex_match (lexer, T_EQUALS))
1340 if (!lex_force_string (lexer))
1343 cat->total_label = ss_xstrdup (lex_tokss (lexer));
1347 cat->total_label = xstrdup (_("Subtotal"));
1351 lex_match (lexer, T_COMMA);
1353 while (!lex_match (lexer, T_RBRACK));
1356 struct ctables_category cat = {
1358 .include_missing = false,
1359 .sort_ascending = true,
1361 bool show_totals = false;
1362 char *total_label = NULL;
1363 bool totals_before = false;
1364 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1366 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1368 lex_match (lexer, T_EQUALS);
1369 if (lex_match_id (lexer, "A"))
1370 cat.sort_ascending = true;
1371 else if (lex_match_id (lexer, "D"))
1372 cat.sort_ascending = false;
1375 lex_error_expecting (lexer, "A", "D");
1379 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1381 lex_match (lexer, T_EQUALS);
1382 if (lex_match_id (lexer, "VALUE"))
1383 cat.type = CCT_VALUE;
1384 else if (lex_match_id (lexer, "LABEL"))
1385 cat.type = CCT_LABEL;
1388 cat.type = CCT_FUNCTION;
1389 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1392 if (lex_match (lexer, T_LPAREN))
1394 cat.sort_var = parse_variable (lexer, dict);
1398 if (cat.sort_function == CTSF_PTILE)
1400 lex_match (lexer, T_COMMA);
1401 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1403 cat.percentile = lex_number (lexer);
1407 if (!lex_force_match (lexer, T_RPAREN))
1410 else if (ctables_function_availability (cat.sort_function)
1413 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1418 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1420 lex_match (lexer, T_EQUALS);
1421 if (lex_match_id (lexer, "INCLUDE"))
1422 cat.include_missing = true;
1423 else if (lex_match_id (lexer, "EXCLUDE"))
1424 cat.include_missing = false;
1427 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1431 else if (lex_match_id (lexer, "TOTAL"))
1433 lex_match (lexer, T_EQUALS);
1434 if (!parse_bool (lexer, &show_totals))
1437 else if (lex_match_id (lexer, "LABEL"))
1439 lex_match (lexer, T_EQUALS);
1440 if (!lex_force_string (lexer))
1443 total_label = ss_xstrdup (lex_tokss (lexer));
1446 else if (lex_match_id (lexer, "POSITION"))
1448 lex_match (lexer, T_EQUALS);
1449 if (lex_match_id (lexer, "BEFORE"))
1450 totals_before = true;
1451 else if (lex_match_id (lexer, "AFTER"))
1452 totals_before = false;
1455 lex_error_expecting (lexer, "BEFORE", "AFTER");
1459 else if (lex_match_id (lexer, "EMPTY"))
1461 lex_match (lexer, T_EQUALS);
1462 if (lex_match_id (lexer, "INCLUDE"))
1463 c->show_empty = true;
1464 else if (lex_match_id (lexer, "EXCLUDE"))
1465 c->show_empty = false;
1468 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1475 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1476 "TOTAL", "LABEL", "POSITION", "EMPTY");
1478 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1485 if (c->n_cats >= allocated_cats)
1486 c->cats = x2nrealloc (c->cats, &allocated_cats,
1488 c->cats[c->n_cats++] = cat;
1493 if (c->n_cats >= allocated_cats)
1494 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1496 struct ctables_category *totals;
1499 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1500 totals = &c->cats[0];
1503 totals = &c->cats[c->n_cats];
1506 *totals = (struct ctables_category) {
1508 .total_label = total_label ? total_label : xstrdup (_("Total")),
1512 struct ctables_category *subtotal = NULL;
1513 for (size_t i = totals_before ? 0 : c->n_cats;
1514 totals_before ? i < c->n_cats : i-- > 0;
1515 totals_before ? i++ : 0)
1517 struct ctables_category *cat = &c->cats[i];
1525 cat->subtotal = subtotal;
1545 ctables_nest_uninit (struct ctables_nest *nest)
1552 ctables_stack_uninit (struct ctables_stack *stack)
1556 for (size_t i = 0; i < stack->n; i++)
1557 ctables_nest_uninit (&stack->nests[i]);
1558 free (stack->nests);
1562 static struct ctables_stack
1563 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1570 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1571 for (size_t i = 0; i < s0.n; i++)
1572 for (size_t j = 0; j < s1.n; j++)
1574 const struct ctables_nest *a = &s0.nests[i];
1575 const struct ctables_nest *b = &s1.nests[j];
1577 size_t allocate = a->n + b->n;
1578 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1579 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1581 for (size_t k = 0; k < a->n; k++)
1582 vars[n++] = a->vars[k];
1583 for (size_t k = 0; k < b->n; k++)
1584 vars[n++] = b->vars[k];
1585 assert (n == allocate);
1587 const struct ctables_nest *summary_src;
1588 if (!a->specs[CSV_CELL].var)
1590 else if (!b->specs[CSV_CELL].var)
1595 struct ctables_nest *new = &stack.nests[stack.n++];
1596 *new = (struct ctables_nest) {
1598 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1599 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1603 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1604 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1606 ctables_stack_uninit (&s0);
1607 ctables_stack_uninit (&s1);
1611 static struct ctables_stack
1612 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1614 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1615 for (size_t i = 0; i < s0.n; i++)
1616 stack.nests[stack.n++] = s0.nests[i];
1617 for (size_t i = 0; i < s1.n; i++)
1618 stack.nests[stack.n++] = s1.nests[i];
1619 assert (stack.n == s0.n + s1.n);
1625 static struct ctables_stack
1626 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1629 return (struct ctables_stack) { .n = 0 };
1634 assert (!a->var.is_mrset);
1636 struct variable **vars = xmalloc (sizeof *vars);
1639 struct ctables_nest *nest = xmalloc (sizeof *nest);
1640 *nest = (struct ctables_nest) {
1643 .scale_idx = a->scale ? 0 : SIZE_MAX,
1645 if (a->specs[CSV_CELL].n || a->scale)
1646 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1648 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1649 nest->specs[sv].var = a->var.var;
1651 return (struct ctables_stack) { .nests = nest, .n = 1 };
1654 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1655 enumerate_fts (axis_type, a->subs[1]));
1658 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1659 enumerate_fts (axis_type, a->subs[1]));
1665 union ctables_summary
1667 /* COUNT, VALIDN, TOTALN. */
1674 /* MINIMUM, MAXIMUM, RANGE. */
1681 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1682 struct moments1 *moments;
1684 /* XXX percentiles, median, mode, multiple response */
1688 ctables_summary_init (union ctables_summary *s,
1689 const struct ctables_summary_spec *ss)
1691 switch (ss->function)
1695 case CTSF_ROWPCT_COUNT:
1696 case CTSF_COLPCT_COUNT:
1697 case CTSF_TABLEPCT_COUNT:
1698 case CTSF_SUBTABLEPCT_COUNT:
1699 case CTSF_LAYERPCT_COUNT:
1700 case CTSF_LAYERROWPCT_COUNT:
1701 case CTSF_LAYERCOLPCT_COUNT:
1702 case CTSF_ROWPCT_VALIDN:
1703 case CTSF_COLPCT_VALIDN:
1704 case CTSF_TABLEPCT_VALIDN:
1705 case CTSF_SUBTABLEPCT_VALIDN:
1706 case CTSF_LAYERPCT_VALIDN:
1707 case CTSF_LAYERROWPCT_VALIDN:
1708 case CTSF_LAYERCOLPCT_VALIDN:
1709 case CTSF_ROWPCT_TOTALN:
1710 case CTSF_COLPCT_TOTALN:
1711 case CTSF_TABLEPCT_TOTALN:
1712 case CTSF_SUBTABLEPCT_TOTALN:
1713 case CTSF_LAYERPCT_TOTALN:
1714 case CTSF_LAYERROWPCT_TOTALN:
1715 case CTSF_LAYERCOLPCT_TOTALN:
1720 s->missing = s->valid = 0;
1726 s->min = s->max = SYSMIS;
1734 case CTSF_ROWPCT_SUM:
1735 case CTSF_COLPCT_SUM:
1736 case CTSF_TABLEPCT_SUM:
1737 case CTSF_SUBTABLEPCT_SUM:
1738 case CTSF_LAYERPCT_SUM:
1739 case CTSF_LAYERROWPCT_SUM:
1740 case CTSF_LAYERCOLPCT_SUM:
1741 s->moments = moments1_create (MOMENT_VARIANCE);
1750 case CTSF_RESPONSES:
1751 case CTSF_ROWPCT_RESPONSES:
1752 case CTSF_COLPCT_RESPONSES:
1753 case CTSF_TABLEPCT_RESPONSES:
1754 case CTSF_SUBTABLEPCT_RESPONSES:
1755 case CTSF_LAYERPCT_RESPONSES:
1756 case CTSF_LAYERROWPCT_RESPONSES:
1757 case CTSF_LAYERCOLPCT_RESPONSES:
1758 case CTSF_ROWPCT_RESPONSES_COUNT:
1759 case CTSF_COLPCT_RESPONSES_COUNT:
1760 case CTSF_TABLEPCT_RESPONSES_COUNT:
1761 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1762 case CTSF_LAYERPCT_RESPONSES_COUNT:
1763 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1764 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1765 case CTSF_ROWPCT_COUNT_RESPONSES:
1766 case CTSF_COLPCT_COUNT_RESPONSES:
1767 case CTSF_TABLEPCT_COUNT_RESPONSES:
1768 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1769 case CTSF_LAYERPCT_COUNT_RESPONSES:
1770 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1771 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1777 ctables_summary_uninit (union ctables_summary *s,
1778 const struct ctables_summary_spec *ss)
1780 switch (ss->function)
1784 case CTSF_ROWPCT_COUNT:
1785 case CTSF_COLPCT_COUNT:
1786 case CTSF_TABLEPCT_COUNT:
1787 case CTSF_SUBTABLEPCT_COUNT:
1788 case CTSF_LAYERPCT_COUNT:
1789 case CTSF_LAYERROWPCT_COUNT:
1790 case CTSF_LAYERCOLPCT_COUNT:
1791 case CTSF_ROWPCT_VALIDN:
1792 case CTSF_COLPCT_VALIDN:
1793 case CTSF_TABLEPCT_VALIDN:
1794 case CTSF_SUBTABLEPCT_VALIDN:
1795 case CTSF_LAYERPCT_VALIDN:
1796 case CTSF_LAYERROWPCT_VALIDN:
1797 case CTSF_LAYERCOLPCT_VALIDN:
1798 case CTSF_ROWPCT_TOTALN:
1799 case CTSF_COLPCT_TOTALN:
1800 case CTSF_TABLEPCT_TOTALN:
1801 case CTSF_SUBTABLEPCT_TOTALN:
1802 case CTSF_LAYERPCT_TOTALN:
1803 case CTSF_LAYERROWPCT_TOTALN:
1804 case CTSF_LAYERCOLPCT_TOTALN:
1821 case CTSF_ROWPCT_SUM:
1822 case CTSF_COLPCT_SUM:
1823 case CTSF_TABLEPCT_SUM:
1824 case CTSF_SUBTABLEPCT_SUM:
1825 case CTSF_LAYERPCT_SUM:
1826 case CTSF_LAYERROWPCT_SUM:
1827 case CTSF_LAYERCOLPCT_SUM:
1828 moments1_destroy (s->moments);
1837 case CTSF_RESPONSES:
1838 case CTSF_ROWPCT_RESPONSES:
1839 case CTSF_COLPCT_RESPONSES:
1840 case CTSF_TABLEPCT_RESPONSES:
1841 case CTSF_SUBTABLEPCT_RESPONSES:
1842 case CTSF_LAYERPCT_RESPONSES:
1843 case CTSF_LAYERROWPCT_RESPONSES:
1844 case CTSF_LAYERCOLPCT_RESPONSES:
1845 case CTSF_ROWPCT_RESPONSES_COUNT:
1846 case CTSF_COLPCT_RESPONSES_COUNT:
1847 case CTSF_TABLEPCT_RESPONSES_COUNT:
1848 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1849 case CTSF_LAYERPCT_RESPONSES_COUNT:
1850 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1851 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1852 case CTSF_ROWPCT_COUNT_RESPONSES:
1853 case CTSF_COLPCT_COUNT_RESPONSES:
1854 case CTSF_TABLEPCT_COUNT_RESPONSES:
1855 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1856 case CTSF_LAYERPCT_COUNT_RESPONSES:
1857 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1858 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1864 ctables_summary_add (union ctables_summary *s,
1865 const struct ctables_summary_spec *ss,
1866 const struct variable *var, const union value *value,
1869 switch (ss->function)
1873 case CTSF_ROWPCT_COUNT:
1874 case CTSF_COLPCT_COUNT:
1875 case CTSF_TABLEPCT_COUNT:
1876 case CTSF_SUBTABLEPCT_COUNT:
1877 case CTSF_LAYERPCT_COUNT:
1878 case CTSF_LAYERROWPCT_COUNT:
1879 case CTSF_LAYERCOLPCT_COUNT:
1880 case CTSF_ROWPCT_VALIDN:
1881 case CTSF_COLPCT_VALIDN:
1882 case CTSF_TABLEPCT_VALIDN:
1883 case CTSF_SUBTABLEPCT_VALIDN:
1884 case CTSF_LAYERPCT_VALIDN:
1885 case CTSF_LAYERROWPCT_VALIDN:
1886 case CTSF_LAYERCOLPCT_VALIDN:
1887 case CTSF_ROWPCT_TOTALN:
1888 case CTSF_COLPCT_TOTALN:
1889 case CTSF_TABLEPCT_TOTALN:
1890 case CTSF_SUBTABLEPCT_TOTALN:
1891 case CTSF_LAYERPCT_TOTALN:
1892 case CTSF_LAYERROWPCT_TOTALN:
1893 case CTSF_LAYERCOLPCT_TOTALN:
1898 if (var_is_value_missing (var, value))
1899 s->missing += weight;
1907 if (!var_is_value_missing (var, value))
1909 assert (!var_is_alpha (var)); /* XXX? */
1910 if (s->min == SYSMIS || value->f < s->min)
1912 if (s->max == SYSMIS || value->f > s->max)
1922 case CTSF_ROWPCT_SUM:
1923 case CTSF_COLPCT_SUM:
1924 case CTSF_TABLEPCT_SUM:
1925 case CTSF_SUBTABLEPCT_SUM:
1926 case CTSF_LAYERPCT_SUM:
1927 case CTSF_LAYERROWPCT_SUM:
1928 case CTSF_LAYERCOLPCT_SUM:
1929 if (!var_is_value_missing (var, value))
1930 moments1_add (s->moments, value->f, weight);
1939 case CTSF_RESPONSES:
1940 case CTSF_ROWPCT_RESPONSES:
1941 case CTSF_COLPCT_RESPONSES:
1942 case CTSF_TABLEPCT_RESPONSES:
1943 case CTSF_SUBTABLEPCT_RESPONSES:
1944 case CTSF_LAYERPCT_RESPONSES:
1945 case CTSF_LAYERROWPCT_RESPONSES:
1946 case CTSF_LAYERCOLPCT_RESPONSES:
1947 case CTSF_ROWPCT_RESPONSES_COUNT:
1948 case CTSF_COLPCT_RESPONSES_COUNT:
1949 case CTSF_TABLEPCT_RESPONSES_COUNT:
1950 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1951 case CTSF_LAYERPCT_RESPONSES_COUNT:
1952 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1953 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1954 case CTSF_ROWPCT_COUNT_RESPONSES:
1955 case CTSF_COLPCT_COUNT_RESPONSES:
1956 case CTSF_TABLEPCT_COUNT_RESPONSES:
1957 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1958 case CTSF_LAYERPCT_COUNT_RESPONSES:
1959 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1960 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1966 ctables_summary_value (const struct ctables_cell *cell,
1967 union ctables_summary *s,
1968 const struct ctables_summary_spec *ss)
1970 switch (ss->function)
1976 case CTSF_SUBTABLEPCT_COUNT:
1977 return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
1979 case CTSF_ROWPCT_COUNT:
1980 return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
1982 case CTSF_COLPCT_COUNT:
1983 return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
1985 case CTSF_TABLEPCT_COUNT:
1986 return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
1988 case CTSF_LAYERPCT_COUNT:
1989 return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
1991 case CTSF_LAYERROWPCT_COUNT:
1992 return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
1994 case CTSF_LAYERCOLPCT_COUNT:
1995 return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
1997 case CTSF_ROWPCT_VALIDN:
1998 case CTSF_COLPCT_VALIDN:
1999 case CTSF_TABLEPCT_VALIDN:
2000 case CTSF_SUBTABLEPCT_VALIDN:
2001 case CTSF_LAYERPCT_VALIDN:
2002 case CTSF_LAYERROWPCT_VALIDN:
2003 case CTSF_LAYERCOLPCT_VALIDN:
2004 case CTSF_ROWPCT_TOTALN:
2005 case CTSF_COLPCT_TOTALN:
2006 case CTSF_TABLEPCT_TOTALN:
2007 case CTSF_SUBTABLEPCT_TOTALN:
2008 case CTSF_LAYERPCT_TOTALN:
2009 case CTSF_LAYERROWPCT_TOTALN:
2010 case CTSF_LAYERCOLPCT_TOTALN:
2015 return s->valid + s->missing;
2028 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2033 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2039 double weight, variance;
2040 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2041 return calc_semean (variance, weight);
2047 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2048 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2053 double weight, mean;
2054 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2055 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2061 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2065 case CTSF_ROWPCT_SUM:
2066 case CTSF_COLPCT_SUM:
2067 case CTSF_TABLEPCT_SUM:
2068 case CTSF_SUBTABLEPCT_SUM:
2069 case CTSF_LAYERPCT_SUM:
2070 case CTSF_LAYERROWPCT_SUM:
2071 case CTSF_LAYERCOLPCT_SUM:
2080 case CTSF_RESPONSES:
2081 case CTSF_ROWPCT_RESPONSES:
2082 case CTSF_COLPCT_RESPONSES:
2083 case CTSF_TABLEPCT_RESPONSES:
2084 case CTSF_SUBTABLEPCT_RESPONSES:
2085 case CTSF_LAYERPCT_RESPONSES:
2086 case CTSF_LAYERROWPCT_RESPONSES:
2087 case CTSF_LAYERCOLPCT_RESPONSES:
2088 case CTSF_ROWPCT_RESPONSES_COUNT:
2089 case CTSF_COLPCT_RESPONSES_COUNT:
2090 case CTSF_TABLEPCT_RESPONSES_COUNT:
2091 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2092 case CTSF_LAYERPCT_RESPONSES_COUNT:
2093 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2094 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2095 case CTSF_ROWPCT_COUNT_RESPONSES:
2096 case CTSF_COLPCT_COUNT_RESPONSES:
2097 case CTSF_TABLEPCT_COUNT_RESPONSES:
2098 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2099 case CTSF_LAYERPCT_COUNT_RESPONSES:
2100 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2101 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2108 struct ctables_cell_sort_aux
2110 const struct ctables_table *t;
2111 enum pivot_axis_type a;
2115 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2117 const struct ctables_cell_sort_aux *aux = aux_;
2118 struct ctables_cell *const *ap = a_;
2119 struct ctables_cell *const *bp = b_;
2120 const struct ctables_cell *a = *ap;
2121 const struct ctables_cell *b = *bp;
2123 size_t a_idx = a->axes[aux->a].nest_idx;
2124 size_t b_idx = b->axes[aux->a].nest_idx;
2126 return a_idx < b_idx ? -1 : 1;
2128 const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2129 for (size_t i = 0; i < nest->n; i++)
2130 if (i != nest->scale_idx)
2132 const struct variable *var = nest->vars[i];
2133 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2134 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2135 if (a_cv->category != b_cv->category)
2136 return a_cv->category > b_cv->category ? 1 : -1;
2138 const union value *a_val = &a_cv->value;
2139 const union value *b_val = &b_cv->value;
2140 switch (a_cv->category->type)
2147 /* Must be equal. */
2154 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2162 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2164 return a_cv->category->sort_ascending ? cmp : -cmp;
2170 const char *a_label = var_lookup_value_label (var, a_val);
2171 const char *b_label = var_lookup_value_label (var, b_val);
2173 ? (b_label ? strcmp (a_label, b_label) : 1)
2174 : (b_label ? -1 : value_compare_3way (
2175 a_val, b_val, var_get_width (var))));
2177 return a_cv->category->sort_ascending ? cmp : -cmp;
2191 For each ctables_table:
2192 For each combination of row vars:
2193 For each combination of column vars:
2194 For each combination of layer vars:
2196 Make a table of row values:
2197 Sort entries by row values
2198 Assign a 0-based index to each actual value
2199 Construct a dimension
2200 Make a table of column values
2201 Make a table of layer values
2203 Fill the table entry using the indexes from before.
2206 static struct ctables_domain *
2207 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2208 enum ctables_domain_type domain)
2211 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2213 size_t idx = cell->axes[a].nest_idx;
2214 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2215 hash = hash_int (idx, hash);
2216 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2218 size_t v_idx = nest->domains[domain][i];
2219 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2220 var_get_width (nest->vars[v_idx]), hash);
2224 struct ctables_domain *d;
2225 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2227 const struct ctables_cell *df = d->example;
2228 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2230 size_t idx = cell->axes[a].nest_idx;
2231 if (idx != df->axes[a].nest_idx)
2234 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2235 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2237 size_t v_idx = nest->domains[domain][i];
2238 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2239 &cell->axes[a].cvs[v_idx].value,
2240 var_get_width (nest->vars[v_idx])))
2249 d = xmalloc (sizeof *d);
2250 *d = (struct ctables_domain) { .example = cell };
2251 hmap_insert (&t->domains[domain], &d->node, hash);
2255 static const struct ctables_category *
2256 ctables_categories_match (const struct ctables_categories *c,
2257 const union value *v, const struct variable *var)
2259 const struct ctables_category *othernm = NULL;
2260 for (size_t i = c->n_cats; i-- > 0; )
2262 const struct ctables_category *cat = &c->cats[i];
2266 if (cat->number == v->f)
2274 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2275 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2280 if (var_is_value_missing (var, v))
2297 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2302 return var_is_value_missing (var, v) ? NULL : othernm;
2305 static const struct ctables_category *
2306 ctables_categories_total (const struct ctables_categories *c)
2308 const struct ctables_category *first = &c->cats[0];
2309 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2310 return (first->type == CCT_TOTAL ? first
2311 : last->type == CCT_TOTAL ? last
2315 static struct ctables_cell *
2316 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2317 size_t ix[PIVOT_N_AXES],
2318 const struct ctables_category *cats[PIVOT_N_AXES][10])
2320 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2323 enum ctables_summary_variant sv = CSV_CELL;
2324 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2326 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2327 hash = hash_int (ix[a], hash);
2328 for (size_t i = 0; i < nest->n; i++)
2329 if (i != nest->scale_idx)
2331 hash = hash_pointer (cats[a][i], hash);
2332 if (cats[a][i]->type != CCT_TOTAL
2333 && cats[a][i]->type != CCT_SUBTOTAL
2334 && cats[a][i]->type != CCT_HSUBTOTAL)
2335 hash = value_hash (case_data (c, nest->vars[i]),
2336 var_get_width (nest->vars[i]), hash);
2342 struct ctables_cell *cell;
2343 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2345 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2347 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2348 if (cell->axes[a].nest_idx != ix[a])
2350 for (size_t i = 0; i < nest->n; i++)
2351 if (i != nest->scale_idx
2352 && (cats[a][i] != cell->axes[a].cvs[i].category
2353 || (cats[a][i]->type != CCT_TOTAL
2354 && cats[a][i]->type != CCT_SUBTOTAL
2355 && cats[a][i]->type != CCT_HSUBTOTAL
2356 && !value_equal (case_data (c, nest->vars[i]),
2357 &cell->axes[a].cvs[i].value,
2358 var_get_width (nest->vars[i])))))
2367 cell = xmalloc (sizeof *cell);
2370 cell->contributes_to_domains = true;
2371 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2373 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2374 cell->axes[a].nest_idx = ix[a];
2375 cell->axes[a].cvs = (nest->n
2376 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2378 for (size_t i = 0; i < nest->n; i++)
2380 const struct ctables_category *cat = cats[a][i];
2382 if (i != nest->scale_idx)
2384 const struct ctables_category *subtotal = cat->subtotal;
2385 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2388 if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2389 cell->contributes_to_domains = false;
2392 cell->axes[a].cvs[i].category = cat;
2393 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2394 var_get_width (nest->vars[i]));
2398 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2399 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2400 for (size_t i = 0; i < specs->n; i++)
2401 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2402 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2403 cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2404 hmap_insert (&t->cells, &cell->node, hash);
2409 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2410 size_t ix[PIVOT_N_AXES],
2411 const struct ctables_category *cats[PIVOT_N_AXES][10],
2414 struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2415 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2417 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2418 for (size_t i = 0; i < specs->n; i++)
2419 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2420 case_data (c, specs->var), weight);
2421 if (cell->contributes_to_domains)
2422 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2423 cell->domains[dt]->valid += weight;
2427 recurse_totals (struct ctables_table *t, const struct ccase *c,
2428 size_t ix[PIVOT_N_AXES],
2429 const struct ctables_category *cats[PIVOT_N_AXES][10],
2431 enum pivot_axis_type start_axis, size_t start_nest)
2433 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2435 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2436 for (size_t i = start_nest; i < nest->n; i++)
2438 if (i == nest->scale_idx)
2441 const struct variable *var = nest->vars[i];
2443 const struct ctables_category *total = ctables_categories_total (
2444 t->categories[var_get_dict_index (var)]);
2447 const struct ctables_category *save = cats[a][i];
2449 ctables_cell_add__ (t, c, ix, cats, weight);
2450 recurse_totals (t, c, ix, cats, weight, a, i + 1);
2459 recurse_subtotals (struct ctables_table *t, const struct ccase *c,
2460 size_t ix[PIVOT_N_AXES],
2461 const struct ctables_category *cats[PIVOT_N_AXES][10],
2463 enum pivot_axis_type start_axis, size_t start_nest)
2465 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2467 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2468 for (size_t i = start_nest; i < nest->n; i++)
2470 if (i == nest->scale_idx)
2473 const struct ctables_category *save = cats[a][i];
2476 cats[a][i] = save->subtotal;
2477 ctables_cell_add__ (t, c, ix, cats, weight);
2478 recurse_subtotals (t, c, ix, cats, weight, a, i + 1);
2487 ctables_cell_insert (struct ctables_table *t,
2488 const struct ccase *c,
2489 size_t ir, size_t ic, size_t il,
2492 size_t ix[PIVOT_N_AXES] = {
2493 [PIVOT_AXIS_ROW] = ir,
2494 [PIVOT_AXIS_COLUMN] = ic,
2495 [PIVOT_AXIS_LAYER] = il,
2498 const struct ctables_category *cats[PIVOT_N_AXES][10];
2499 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2501 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2502 for (size_t i = 0; i < nest->n; i++)
2504 if (i == nest->scale_idx)
2507 const struct variable *var = nest->vars[i];
2508 const union value *value = case_data (c, var);
2510 if (var_is_numeric (var) && value->f == SYSMIS)
2513 cats[a][i] = ctables_categories_match (
2514 t->categories[var_get_dict_index (var)], value, var);
2520 ctables_cell_add__ (t, c, ix, cats, weight);
2522 recurse_totals (t, c, ix, cats, weight, 0, 0);
2523 recurse_subtotals (t, c, ix, cats, weight, 0, 0);
2528 const struct ctables_summary_spec_set *set;
2533 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2535 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2536 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2537 if (as->function != bs->function)
2538 return as->function > bs->function ? 1 : -1;
2539 else if (as->percentile != bs->percentile)
2540 return as->percentile < bs->percentile ? 1 : -1;
2541 return strcmp (as->label, bs->label);
2544 static struct pivot_value *
2545 ctables_category_create_label (const struct ctables_category *cat,
2546 const struct variable *var,
2547 const union value *value)
2549 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2550 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2551 : pivot_value_new_var_value (var, value));
2554 static struct ctables_value *
2555 ctables_value_find__ (struct ctables_table *t, const union value *value,
2556 int width, unsigned int hash)
2558 struct ctables_value *clv;
2559 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2560 hash, &t->clabels_values_map)
2561 if (value_equal (value, &clv->value, width))
2566 static struct ctables_value *
2567 ctables_value_find (struct ctables_table *t,
2568 const union value *value, int width)
2570 return ctables_value_find__ (t, value, width,
2571 value_hash (value, width, 0));
2575 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2577 struct pivot_table *pt = pivot_table_create__ (
2579 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2580 : pivot_value_new_text (N_("Custom Tables"))),
2583 pivot_table_set_caption (
2584 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2586 pivot_table_set_caption (
2587 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2589 bool summary_dimension = (t->summary_axis != t->slabels_axis
2590 || (!t->slabels_visible
2591 && t->summary_specs.n > 1));
2592 if (summary_dimension)
2594 struct pivot_dimension *d = pivot_dimension_create (
2595 pt, t->slabels_axis, N_("Statistics"));
2596 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2597 if (!t->slabels_visible)
2598 d->hide_all_labels = true;
2599 for (size_t i = 0; i < specs->n; i++)
2600 pivot_category_create_leaf (
2601 d->root, pivot_value_new_text (specs->specs[i].label));
2604 bool categories_dimension = t->clabels_example != NULL;
2605 if (categories_dimension)
2607 struct pivot_dimension *d = pivot_dimension_create (
2608 pt, t->label_axis[t->clabels_from_axis],
2609 t->clabels_from_axis == PIVOT_AXIS_ROW
2610 ? N_("Row Categories")
2611 : N_("Column Categories"));
2612 const struct variable *var = t->clabels_example;
2613 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2614 for (size_t i = 0; i < t->n_clabels_values; i++)
2616 const struct ctables_value *value = t->clabels_values[i];
2617 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2618 assert (cat != NULL);
2619 pivot_category_create_leaf (d->root, ctables_category_create_label (
2620 cat, t->clabels_example, &value->value));
2624 pivot_table_set_look (pt, ct->look);
2625 struct pivot_dimension *d[PIVOT_N_AXES];
2626 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2628 static const char *names[] = {
2629 [PIVOT_AXIS_ROW] = N_("Rows"),
2630 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2631 [PIVOT_AXIS_LAYER] = N_("Layers"),
2633 d[a] = (t->axes[a] || a == t->summary_axis
2634 ? pivot_dimension_create (pt, a, names[a])
2639 assert (t->axes[a]);
2641 struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2642 size_t n_sorted = 0;
2644 struct ctables_cell *cell;
2645 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2647 sorted[n_sorted++] = cell;
2648 assert (n_sorted <= t->cells.count);
2650 struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2651 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2653 size_t max_depth = 0;
2654 for (size_t j = 0; j < t->stacks[a].n; j++)
2655 if (t->stacks[a].nests[j].n > max_depth)
2656 max_depth = t->stacks[a].nests[j].n;
2658 /* Pivot categories:
2660 - variable label for nest->vars[0], if vlabel != CTVL_NONE
2661 - category for nest->vars[0], if nest->scale_idx != 0
2662 - variable label for nest->vars[1], if vlabel != CTVL_NONE
2663 - category for nest->vars[1], if nest->scale_idx != 1
2665 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2666 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2667 - summary function, if 'a == t->slabels_axis && a ==
2670 Additional dimensions:
2672 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2674 - If 't->label_axis[b] == a' for some 'b != a', add a category
2678 struct ctables_level
2680 enum ctables_level_type
2682 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2683 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2684 CTL_SUMMARY, /* Summary functions. */
2690 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2691 size_t n_levels = 0;
2693 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2695 for (size_t j = 0; j < n_sorted; j++)
2697 struct ctables_cell *cell = sorted[j];
2698 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2699 const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2701 bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2705 for (size_t k = 0; k < nest->n; k++)
2707 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2708 if (vlabel != CTVL_NONE)
2710 levels[n_levels++] = (struct ctables_level) {
2716 if (nest->scale_idx != k
2717 && (k != nest->n - 1 || t->label_axis[a] == a))
2719 levels[n_levels++] = (struct ctables_level) {
2720 .type = CTL_CATEGORY,
2726 if (!summary_dimension && a == t->slabels_axis)
2728 levels[n_levels++] = (struct ctables_level) {
2729 .type = CTL_SUMMARY,
2730 .var_idx = SIZE_MAX,
2735 size_t n_common = 0;
2738 for (; n_common < n_levels; n_common++)
2740 const struct ctables_level *level = &levels[n_common];
2741 if (level->type == CTL_CATEGORY)
2743 size_t var_idx = level->var_idx;
2744 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
2745 if (prev->axes[a].cvs[var_idx].category != c)
2747 else if (c->type != CCT_SUBTOTAL
2748 && c->type != CCT_HSUBTOTAL
2749 && c->type != CCT_TOTAL
2750 && !value_equal (&prev->axes[a].cvs[var_idx].value,
2751 &cell->axes[a].cvs[var_idx].value,
2752 var_get_type (nest->vars[var_idx])))
2758 for (size_t k = n_common; k < n_levels; k++)
2760 const struct ctables_level *level = &levels[k];
2761 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2762 if (level->type == CTL_SUMMARY)
2764 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2765 for (size_t m = 0; m < specs->n; m++)
2767 int leaf = pivot_category_create_leaf (
2768 parent, pivot_value_new_text (specs->specs[m].label));
2775 const struct variable *var = nest->vars[level->var_idx];
2776 struct pivot_value *label;
2777 if (level->type == CTL_VAR)
2778 label = pivot_value_new_variable (var);
2779 else if (level->type == CTL_CATEGORY)
2781 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2782 label = ctables_category_create_label (cv->category,
2788 if (k == n_levels - 1)
2789 prev_leaf = pivot_category_create_leaf (parent, label);
2791 groups[k] = pivot_category_create_group__ (parent, label);
2795 cell->axes[a].leaf = prev_leaf;
2801 struct ctables_cell *cell;
2802 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2807 const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2808 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2809 for (size_t j = 0; j < specs->n; j++)
2812 size_t n_dindexes = 0;
2814 if (summary_dimension)
2815 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2817 if (categories_dimension)
2819 const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2820 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2821 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2822 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2823 assert (ctv != NULL);
2824 dindexes[n_dindexes++] = ctv->leaf;
2827 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2830 int leaf = cell->axes[a].leaf;
2831 if (a == t->summary_axis && !summary_dimension)
2833 dindexes[n_dindexes++] = leaf;
2836 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2837 struct pivot_value *value = pivot_value_new_number (d);
2838 value->numeric.format = specs->specs[j].format;
2839 pivot_table_put (pt, dindexes, n_dindexes, value);
2843 pivot_table_submit (pt);
2847 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2849 enum pivot_axis_type label_pos = t->label_axis[a];
2853 t->clabels_from_axis = a;
2855 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2856 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2858 const struct ctables_stack *stack = &t->stacks[a];
2862 const struct ctables_nest *n0 = &stack->nests[0];
2864 const struct variable *v0 = n0->vars[n0->n - 1];
2865 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2866 t->clabels_example = v0;
2868 for (size_t i = 0; i < c0->n_cats; i++)
2869 if (c0->cats[i].type == CCT_FUNCTION)
2871 msg (SE, _("%s=%s is not allowed with sorting based "
2872 "on a summary function."),
2873 subcommand_name, pos_name);
2876 if (n0->n - 1 == n0->scale_idx)
2878 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2879 "but %s is a scale variable."),
2880 subcommand_name, pos_name, var_get_name (v0));
2884 for (size_t i = 1; i < stack->n; i++)
2886 const struct ctables_nest *ni = &stack->nests[i];
2888 const struct variable *vi = ni->vars[ni->n - 1];
2889 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2891 if (ni->n - 1 == ni->scale_idx)
2893 msg (SE, _("%s=%s requires the variables to be moved to be "
2894 "categorical, but %s is a scale variable."),
2895 subcommand_name, pos_name, var_get_name (vi));
2898 if (var_get_width (v0) != var_get_width (vi))
2900 msg (SE, _("%s=%s requires the variables to be "
2901 "moved to have the same width, but %s has "
2902 "width %d and %s has width %d."),
2903 subcommand_name, pos_name,
2904 var_get_name (v0), var_get_width (v0),
2905 var_get_name (vi), var_get_width (vi));
2908 if (!val_labs_equal (var_get_value_labels (v0),
2909 var_get_value_labels (vi)))
2911 msg (SE, _("%s=%s requires the variables to be "
2912 "moved to have the same value labels, but %s "
2913 "and %s have different value labels."),
2914 subcommand_name, pos_name,
2915 var_get_name (v0), var_get_name (vi));
2918 if (!ctables_categories_equal (c0, ci))
2920 msg (SE, _("%s=%s requires the variables to be "
2921 "moved to have the same category "
2922 "specifications, but %s and %s have different "
2923 "category specifications."),
2924 subcommand_name, pos_name,
2925 var_get_name (v0), var_get_name (vi));
2934 ctables_prepare_table (struct ctables_table *t)
2936 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2939 t->stacks[a] = enumerate_fts (a, t->axes[a]);
2941 for (size_t j = 0; j < t->stacks[a].n; j++)
2943 struct ctables_nest *nest = &t->stacks[a].nests[j];
2944 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2946 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
2947 nest->n_domains[dt] = 0;
2949 for (size_t k = 0; k < nest->n; k++)
2951 if (k == nest->scale_idx)
2960 if (a != PIVOT_AXIS_LAYER)
2967 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2968 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2969 : a == PIVOT_AXIS_ROW)
2971 if (k == nest->n - 1
2972 || (nest->scale_idx == nest->n - 1
2973 && k == nest->n - 2))
2979 if (a == PIVOT_AXIS_COLUMN)
2984 if (a == PIVOT_AXIS_ROW)
2989 nest->domains[dt][nest->n_domains[dt]++] = k;
2996 struct ctables_nest *nest = xmalloc (sizeof *nest);
2997 *nest = (struct ctables_nest) { .n = 0 };
2998 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3001 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3002 for (size_t i = 0; i < stack->n; i++)
3004 struct ctables_nest *nest = &stack->nests[i];
3005 if (!nest->specs[CSV_CELL].n)
3007 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3008 specs->specs = xmalloc (sizeof *specs->specs);
3011 enum ctables_summary_function function
3012 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3013 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3015 *specs->specs = (struct ctables_summary_spec) {
3016 .function = function,
3017 .format = ctables_summary_default_format (function, &var),
3018 .label = ctables_summary_default_label (function, 0),
3021 specs->var = nest->vars[0];
3023 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3024 &nest->specs[CSV_CELL]);
3026 else if (!nest->specs[CSV_TOTAL].n)
3027 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3028 &nest->specs[CSV_CELL]);
3031 struct ctables_summary_spec_set *merged = &t->summary_specs;
3032 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3034 for (size_t j = 0; j < stack->n; j++)
3036 const struct ctables_nest *nest = &stack->nests[j];
3038 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3039 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3044 struct merge_item min = items[0];
3045 for (size_t j = 1; j < n_left; j++)
3046 if (merge_item_compare_3way (&items[j], &min) < 0)
3049 if (merged->n >= merged->allocated)
3050 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3051 sizeof *merged->specs);
3052 merged->specs[merged->n++] = min.set->specs[min.ofs];
3054 for (size_t j = 0; j < n_left; )
3056 if (merge_item_compare_3way (&items[j], &min) == 0)
3058 struct merge_item *item = &items[j];
3059 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3060 if (++item->ofs >= item->set->n)
3062 items[j] = items[--n_left];
3071 for (size_t j = 0; j < merged->n; j++)
3072 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3074 for (size_t j = 0; j < stack->n; j++)
3076 const struct ctables_nest *nest = &stack->nests[j];
3077 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3079 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3080 for (size_t k = 0; k < specs->n; k++)
3081 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3082 specs->specs[k].axis_idx);
3088 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3089 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3093 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3094 enum pivot_axis_type a)
3096 struct ctables_stack *stack = &t->stacks[a];
3097 for (size_t i = 0; i < stack->n; i++)
3099 const struct ctables_nest *nest = &stack->nests[i];
3100 const struct variable *var = nest->vars[nest->n - 1];
3101 int width = var_get_width (var);
3102 const union value *value = case_data (c, var);
3104 if (var_is_numeric (var) && value->f == SYSMIS)
3107 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3111 unsigned int hash = value_hash (value, width, 0);
3113 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3116 clv = xmalloc (sizeof *clv);
3117 value_clone (&clv->value, value, width);
3118 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3124 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3126 const struct ctables_value *const *ap = a_;
3127 const struct ctables_value *const *bp = b_;
3128 const struct ctables_value *a = *ap;
3129 const struct ctables_value *b = *bp;
3130 const int *width = width_;
3131 return value_compare_3way (&a->value, &b->value, *width);
3135 ctables_sort_clabels_values (struct ctables_table *t)
3137 int width = var_get_width (t->clabels_example);
3139 size_t n = hmap_count (&t->clabels_values_map);
3140 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3142 struct ctables_value *clv;
3144 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3145 t->clabels_values[i++] = clv;
3146 t->n_clabels_values = n;
3149 sort (t->clabels_values, n, sizeof *t->clabels_values,
3150 compare_clabels_values_3way, &width);
3152 for (size_t i = 0; i < n; i++)
3153 t->clabels_values[i]->leaf = i;
3157 ctables_execute (struct dataset *ds, struct ctables *ct)
3159 struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3162 bool warn_on_invalid = true;
3163 double total_weight = 0;
3164 for (struct ccase *c = casereader_read (input); c;
3165 case_unref (c), c = casereader_read (input))
3167 double weight = dict_get_case_weight (dataset_dict (ds), c,
3169 total_weight += weight;
3171 for (size_t i = 0; i < ct->n_tables; i++)
3173 struct ctables_table *t = ct->tables[i];
3175 for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3176 for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3177 for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3178 ctables_cell_insert (t, c, ir, ic, il, weight);
3180 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3181 if (t->label_axis[a] != a)
3182 ctables_insert_clabels_values (t, c, a);
3185 casereader_destroy (input);
3187 for (size_t i = 0; i < ct->n_tables; i++)
3189 struct ctables_table *t = ct->tables[i];
3191 if (t->clabels_example)
3192 ctables_sort_clabels_values (t);
3194 ctables_table_output (ct, ct->tables[i]);
3196 return proc_commit (ds);
3200 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3202 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3203 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3204 enum settings_value_show tvars = settings_get_show_variables ();
3205 for (size_t i = 0; i < n_vars; i++)
3206 vlabels[i] = (enum ctables_vlabel) tvars;
3208 struct ctables *ct = xmalloc (sizeof *ct);
3209 *ct = (struct ctables) {
3210 .look = pivot_table_look_unshare (pivot_table_look_ref (
3211 pivot_table_look_get_default ())),
3213 .hide_threshold = 5,
3215 ct->look->omit_empty = false;
3217 if (!lex_force_match (lexer, T_SLASH))
3220 while (!lex_match_id (lexer, "TABLE"))
3222 if (lex_match_id (lexer, "FORMAT"))
3224 double widths[2] = { SYSMIS, SYSMIS };
3225 double units_per_inch = 72.0;
3227 while (lex_token (lexer) != T_SLASH)
3229 if (lex_match_id (lexer, "MINCOLWIDTH"))
3231 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3234 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3236 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3239 else if (lex_match_id (lexer, "UNITS"))
3241 lex_match (lexer, T_EQUALS);
3242 if (lex_match_id (lexer, "POINTS"))
3243 units_per_inch = 72.0;
3244 else if (lex_match_id (lexer, "INCHES"))
3245 units_per_inch = 1.0;
3246 else if (lex_match_id (lexer, "CM"))
3247 units_per_inch = 2.54;
3250 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3254 else if (lex_match_id (lexer, "EMPTY"))
3259 lex_match (lexer, T_EQUALS);
3260 if (lex_match_id (lexer, "ZERO"))
3262 /* Nothing to do. */
3264 else if (lex_match_id (lexer, "BLANK"))
3265 ct->zero = xstrdup ("");
3266 else if (lex_force_string (lexer))
3268 ct->zero = ss_xstrdup (lex_tokss (lexer));
3274 else if (lex_match_id (lexer, "MISSING"))
3276 lex_match (lexer, T_EQUALS);
3277 if (!lex_force_string (lexer))
3281 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3282 ? ss_xstrdup (lex_tokss (lexer))
3288 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3289 "UNITS", "EMPTY", "MISSING");
3294 if (widths[0] != SYSMIS && widths[1] != SYSMIS
3295 && widths[0] > widths[1])
3297 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3301 for (size_t i = 0; i < 2; i++)
3302 if (widths[i] != SYSMIS)
3304 int *wr = ct->look->width_ranges[TABLE_HORZ];
3305 wr[i] = widths[i] / units_per_inch * 96.0;
3310 else if (lex_match_id (lexer, "VLABELS"))
3312 if (!lex_force_match_id (lexer, "VARIABLES"))
3314 lex_match (lexer, T_EQUALS);
3316 struct variable **vars;
3318 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3322 if (!lex_force_match_id (lexer, "DISPLAY"))
3327 lex_match (lexer, T_EQUALS);
3329 enum ctables_vlabel vlabel;
3330 if (lex_match_id (lexer, "DEFAULT"))
3331 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3332 else if (lex_match_id (lexer, "NAME"))
3334 else if (lex_match_id (lexer, "LABEL"))
3335 vlabel = CTVL_LABEL;
3336 else if (lex_match_id (lexer, "BOTH"))
3338 else if (lex_match_id (lexer, "NONE"))
3342 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3348 for (size_t i = 0; i < n_vars; i++)
3349 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3352 else if (lex_match_id (lexer, "MRSETS"))
3354 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3356 lex_match (lexer, T_EQUALS);
3357 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3360 else if (lex_match_id (lexer, "SMISSING"))
3362 if (lex_match_id (lexer, "VARIABLE"))
3363 ct->smissing_listwise = false;
3364 else if (lex_match_id (lexer, "LISTWISE"))
3365 ct->smissing_listwise = true;
3368 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3373 else if (lex_match_id (lexer, "WEIGHT"))
3375 if (!lex_force_match_id (lexer, "VARIABLE"))
3377 lex_match (lexer, T_EQUALS);
3378 ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3379 if (!ct->base_weight)
3382 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3384 if (!lex_force_match_id (lexer, "COUNT"))
3386 lex_match (lexer, T_EQUALS);
3387 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3389 ct->hide_threshold = lex_integer (lexer);
3394 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3395 "SMISSING", "PCOMPUTE", "PPROPERTIES",
3396 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3400 if (!lex_force_match (lexer, T_SLASH))
3404 size_t allocated_tables = 0;
3407 if (ct->n_tables >= allocated_tables)
3408 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3409 sizeof *ct->tables);
3411 struct ctables_category *cat = xmalloc (sizeof *cat);
3412 *cat = (struct ctables_category) {
3414 .include_missing = false,
3415 .sort_ascending = true,
3418 struct ctables_categories *c = xmalloc (sizeof *c);
3419 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3420 *c = (struct ctables_categories) {
3426 struct ctables_categories **categories = xnmalloc (n_vars,
3427 sizeof *categories);
3428 for (size_t i = 0; i < n_vars; i++)
3431 struct ctables_table *t = xmalloc (sizeof *t);
3432 *t = (struct ctables_table) {
3433 .cells = HMAP_INITIALIZER (t->cells),
3434 .slabels_axis = PIVOT_AXIS_COLUMN,
3435 .slabels_visible = true,
3436 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3438 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3439 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3440 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3442 .clabels_from_axis = PIVOT_AXIS_LAYER,
3443 .categories = categories,
3444 .n_categories = n_vars,
3447 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3448 hmap_init (&t->domains[dt]);
3449 ct->tables[ct->n_tables++] = t;
3451 lex_match (lexer, T_EQUALS);
3452 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3454 if (lex_match (lexer, T_BY))
3456 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3457 ct, t, PIVOT_AXIS_COLUMN))
3460 if (lex_match (lexer, T_BY))
3462 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3463 ct, t, PIVOT_AXIS_LAYER))
3468 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3469 && !t->axes[PIVOT_AXIS_LAYER])
3471 lex_error (lexer, _("At least one variable must be specified."));
3475 const struct ctables_axis *scales[PIVOT_N_AXES];
3476 size_t n_scales = 0;
3477 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3479 scales[a] = find_scale (t->axes[a]);
3485 msg (SE, _("Scale variables may appear only on one axis."));
3486 if (scales[PIVOT_AXIS_ROW])
3487 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3488 _("This scale variable appears on the rows axis."));
3489 if (scales[PIVOT_AXIS_COLUMN])
3490 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3491 _("This scale variable appears on the columns axis."));
3492 if (scales[PIVOT_AXIS_LAYER])
3493 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3494 _("This scale variable appears on the layer axis."));
3498 const struct ctables_axis *summaries[PIVOT_N_AXES];
3499 size_t n_summaries = 0;
3500 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3502 summaries[a] = (scales[a]
3504 : find_categorical_summary_spec (t->axes[a]));
3508 if (n_summaries > 1)
3510 msg (SE, _("Summaries may appear only on one axis."));
3511 if (summaries[PIVOT_AXIS_ROW])
3512 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3513 _("This variable on the rows axis has a summary."));
3514 if (summaries[PIVOT_AXIS_COLUMN])
3515 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3516 _("This variable on the columns axis has a summary."));
3517 if (summaries[PIVOT_AXIS_LAYER])
3518 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3519 _("This variable on the layers axis has a summary."));
3522 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3523 if (n_summaries ? summaries[a] : t->axes[a])
3525 t->summary_axis = a;
3529 if (lex_token (lexer) == T_ENDCMD)
3531 if (!ctables_prepare_table (t))
3535 if (!lex_force_match (lexer, T_SLASH))
3538 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3540 if (lex_match_id (lexer, "SLABELS"))
3542 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3544 if (lex_match_id (lexer, "POSITION"))
3546 lex_match (lexer, T_EQUALS);
3547 if (lex_match_id (lexer, "COLUMN"))
3548 t->slabels_axis = PIVOT_AXIS_COLUMN;
3549 else if (lex_match_id (lexer, "ROW"))
3550 t->slabels_axis = PIVOT_AXIS_ROW;
3551 else if (lex_match_id (lexer, "LAYER"))
3552 t->slabels_axis = PIVOT_AXIS_LAYER;
3555 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3559 else if (lex_match_id (lexer, "VISIBLE"))
3561 lex_match (lexer, T_EQUALS);
3562 if (!parse_bool (lexer, &t->slabels_visible))
3567 lex_error_expecting (lexer, "POSITION", "VISIBLE");
3572 else if (lex_match_id (lexer, "CLABELS"))
3574 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3576 if (lex_match_id (lexer, "AUTO"))
3578 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3579 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3581 else if (lex_match_id (lexer, "ROWLABELS"))
3583 lex_match (lexer, T_EQUALS);
3584 if (lex_match_id (lexer, "OPPOSITE"))
3585 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3586 else if (lex_match_id (lexer, "LAYER"))
3587 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3590 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3594 else if (lex_match_id (lexer, "COLLABELS"))
3596 lex_match (lexer, T_EQUALS);
3597 if (lex_match_id (lexer, "OPPOSITE"))
3598 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3599 else if (lex_match_id (lexer, "LAYER"))
3600 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3603 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3609 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3615 else if (lex_match_id (lexer, "CRITERIA"))
3617 if (!lex_force_match_id (lexer, "CILEVEL"))
3619 lex_match (lexer, T_EQUALS);
3621 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3623 t->cilevel = lex_number (lexer);
3626 else if (lex_match_id (lexer, "CATEGORIES"))
3628 if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3631 else if (lex_match_id (lexer, "TITLES"))
3636 if (lex_match_id (lexer, "CAPTION"))
3637 textp = &t->caption;
3638 else if (lex_match_id (lexer, "CORNER"))
3640 else if (lex_match_id (lexer, "TITLE"))
3644 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3647 lex_match (lexer, T_EQUALS);
3649 struct string s = DS_EMPTY_INITIALIZER;
3650 while (lex_is_string (lexer))
3652 if (!ds_is_empty (&s))
3653 ds_put_byte (&s, ' ');
3654 ds_put_substring (&s, lex_tokss (lexer));
3658 *textp = ds_steal_cstr (&s);
3660 while (lex_token (lexer) != T_SLASH
3661 && lex_token (lexer) != T_ENDCMD);
3663 else if (lex_match_id (lexer, "SIGTEST"))
3667 t->chisq = xmalloc (sizeof *t->chisq);
3668 *t->chisq = (struct ctables_chisq) {
3670 .include_mrsets = true,
3671 .all_visible = true,
3677 if (lex_match_id (lexer, "TYPE"))
3679 lex_match (lexer, T_EQUALS);
3680 if (!lex_force_match_id (lexer, "CHISQUARE"))
3683 else if (lex_match_id (lexer, "ALPHA"))
3685 lex_match (lexer, T_EQUALS);
3686 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3688 t->chisq->alpha = lex_number (lexer);
3691 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3693 lex_match (lexer, T_EQUALS);
3694 if (parse_bool (lexer, &t->chisq->include_mrsets))
3697 else if (lex_match_id (lexer, "CATEGORIES"))
3699 lex_match (lexer, T_EQUALS);
3700 if (lex_match_id (lexer, "ALLVISIBLE"))
3701 t->chisq->all_visible = true;
3702 else if (lex_match_id (lexer, "SUBTOTALS"))
3703 t->chisq->all_visible = false;
3706 lex_error_expecting (lexer,
3707 "ALLVISIBLE", "SUBTOTALS");
3713 lex_error_expecting (lexer, "TYPE", "ALPHA",
3714 "INCLUDEMRSETS", "CATEGORIES");
3718 while (lex_token (lexer) != T_SLASH
3719 && lex_token (lexer) != T_ENDCMD);
3721 else if (lex_match_id (lexer, "COMPARETEST"))
3725 t->pairwise = xmalloc (sizeof *t->pairwise);
3726 *t->pairwise = (struct ctables_pairwise) {
3728 .alpha = { .05, .05 },
3729 .adjust = BONFERRONI,
3730 .include_mrsets = true,
3731 .meansvariance_allcats = true,
3732 .all_visible = true,
3741 if (lex_match_id (lexer, "TYPE"))
3743 lex_match (lexer, T_EQUALS);
3744 if (lex_match_id (lexer, "PROP"))
3745 t->pairwise->type = PROP;
3746 else if (lex_match_id (lexer, "MEAN"))
3747 t->pairwise->type = MEAN;
3750 lex_error_expecting (lexer, "PROP", "MEAN");
3754 else if (lex_match_id (lexer, "ALPHA"))
3756 lex_match (lexer, T_EQUALS);
3758 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3760 double a0 = lex_number (lexer);
3763 lex_match (lexer, T_COMMA);
3764 if (lex_is_number (lexer))
3766 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3768 double a1 = lex_number (lexer);
3771 t->pairwise->alpha[0] = MIN (a0, a1);
3772 t->pairwise->alpha[1] = MAX (a0, a1);
3775 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3777 else if (lex_match_id (lexer, "ADJUST"))
3779 lex_match (lexer, T_EQUALS);
3780 if (lex_match_id (lexer, "BONFERRONI"))
3781 t->pairwise->adjust = BONFERRONI;
3782 else if (lex_match_id (lexer, "BH"))
3783 t->pairwise->adjust = BH;
3784 else if (lex_match_id (lexer, "NONE"))
3785 t->pairwise->adjust = 0;
3788 lex_error_expecting (lexer, "BONFERRONI", "BH",
3793 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3795 lex_match (lexer, T_EQUALS);
3796 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3799 else if (lex_match_id (lexer, "MEANSVARIANCE"))
3801 lex_match (lexer, T_EQUALS);
3802 if (lex_match_id (lexer, "ALLCATS"))
3803 t->pairwise->meansvariance_allcats = true;
3804 else if (lex_match_id (lexer, "TESTEDCATS"))
3805 t->pairwise->meansvariance_allcats = false;
3808 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3812 else if (lex_match_id (lexer, "CATEGORIES"))
3814 lex_match (lexer, T_EQUALS);
3815 if (lex_match_id (lexer, "ALLVISIBLE"))
3816 t->pairwise->all_visible = true;
3817 else if (lex_match_id (lexer, "SUBTOTALS"))
3818 t->pairwise->all_visible = false;
3821 lex_error_expecting (lexer, "ALLVISIBLE",
3826 else if (lex_match_id (lexer, "MERGE"))
3828 lex_match (lexer, T_EQUALS);
3829 if (!parse_bool (lexer, &t->pairwise->merge))
3832 else if (lex_match_id (lexer, "STYLE"))
3834 lex_match (lexer, T_EQUALS);
3835 if (lex_match_id (lexer, "APA"))
3836 t->pairwise->apa_style = true;
3837 else if (lex_match_id (lexer, "SIMPLE"))
3838 t->pairwise->apa_style = false;
3841 lex_error_expecting (lexer, "APA", "SIMPLE");
3845 else if (lex_match_id (lexer, "SHOWSIG"))
3847 lex_match (lexer, T_EQUALS);
3848 if (!parse_bool (lexer, &t->pairwise->show_sig))
3853 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3854 "INCLUDEMRSETS", "MEANSVARIANCE",
3855 "CATEGORIES", "MERGE", "STYLE",
3860 while (lex_token (lexer) != T_SLASH
3861 && lex_token (lexer) != T_ENDCMD);
3865 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3866 "CRITERIA", "CATEGORIES", "TITLES",
3867 "SIGTEST", "COMPARETEST");
3871 if (!lex_match (lexer, T_SLASH))
3875 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3876 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3878 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3882 if (!ctables_prepare_table (t))
3885 while (lex_token (lexer) != T_ENDCMD);
3887 bool ok = ctables_execute (ds, ct);
3888 ctables_destroy (ct);
3889 return ok ? CMD_SUCCESS : CMD_FAILURE;
3892 ctables_destroy (ct);