1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2021 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "data/casereader.h"
22 #include "data/casewriter.h"
23 #include "data/dataset.h"
24 #include "data/dictionary.h"
25 #include "data/mrset.h"
26 #include "data/subcase.h"
27 #include "data/value-labels.h"
28 #include "language/command.h"
29 #include "language/lexer/format-parser.h"
30 #include "language/lexer/lexer.h"
31 #include "language/lexer/variable-parser.h"
32 #include "libpspp/array.h"
33 #include "libpspp/assertion.h"
34 #include "libpspp/hash-functions.h"
35 #include "libpspp/hmap.h"
36 #include "libpspp/message.h"
37 #include "libpspp/string-array.h"
38 #include "math/mode.h"
39 #include "math/moments.h"
40 #include "math/percentiles.h"
41 #include "math/sort.h"
42 #include "output/pivot-table.h"
44 #include "gl/minmax.h"
45 #include "gl/xalloc.h"
48 #define _(msgid) gettext (msgid)
49 #define N_(msgid) (msgid)
53 CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
54 CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
55 CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
56 CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
60 - unweighted summaries (U*)
61 - lower confidence limits (*.LCL)
62 - upper confidence limits (*.UCL)
63 - standard error (*.SE)
66 /* All variables. */ \
67 S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL) \
68 S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
69 S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
70 S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
71 S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
72 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
73 S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
74 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
75 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
76 S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
77 S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
78 S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
79 S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
80 S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
81 S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
82 S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
83 S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
84 S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
85 S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
86 S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
87 S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
88 S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
89 S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
91 /* Scale variables, totals, and subtotals. */ \
92 S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE) \
93 S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE) \
94 S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE) \
95 S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE) \
96 S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE) \
97 S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE) \
98 S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE) \
99 S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE) \
100 S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
101 S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
102 S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE) \
103 S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE) \
104 S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
105 S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE) \
106 S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
107 S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
108 S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
109 S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
110 S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
111 S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
112 S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
113 S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
114 S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
116 /* Multiple response sets. */ \
117 S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
118 S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
119 S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
120 S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
121 S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122 S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123 S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124 S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125 S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
126 S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
127 S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
128 S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129 S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130 S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131 S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132 S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
133 S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
134 S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
135 S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136 S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137 S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138 S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
140 enum ctables_summary_function
142 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
148 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
149 N_CTSF_FUNCTIONS = SUMMARIES
153 enum ctables_domain_type
155 /* Within a section, where stacked variables divide one section from
157 CTDT_TABLE, /* All layers of a whole section. */
158 CTDT_LAYER, /* One layer within a section. */
159 CTDT_LAYERROW, /* Row in one layer within a section. */
160 CTDT_LAYERCOL, /* Column in one layer within a section. */
162 /* Within a subtable, where a subtable pairs an innermost row variable with
163 an innermost column variable within a single layer. */
164 CTDT_SUBTABLE, /* Whole subtable. */
165 CTDT_ROW, /* Row within a subtable. */
166 CTDT_COL, /* Column within a subtable. */
170 struct ctables_domain
172 struct hmap_node node;
174 const struct ctables_cell *example;
180 enum ctables_summary_variant
189 /* In struct ctables's 'cells' hmap. Indexed by all the values in all the
190 axes (except the scalar variable, if any). */
191 struct hmap_node node;
193 /* The domains that contain this cell. */
194 bool contributes_to_domains;
195 struct ctables_domain *domains[N_CTDTS];
198 enum ctables_summary_variant sv;
203 struct ctables_cell_value
205 const struct ctables_category *category;
213 union ctables_summary *summaries;
218 struct pivot_table_look *look;
220 /* If this is NULL, zeros are displayed using the normal print format.
221 Otherwise, this string is displayed. */
224 /* If this is NULL, missing values are displayed using the normal print
225 format. Otherwise, this string is displayed. */
228 /* Indexed by variable dictionary index. */
229 enum ctables_vlabel *vlabels;
231 bool mrsets_count_duplicates; /* MRSETS. */
232 bool smissing_listwise; /* SMISSING. */
233 struct variable *base_weight; /* WEIGHT. */
234 int hide_threshold; /* HIDESMALLCOUNTS. */
236 struct ctables_table **tables;
240 struct ctables_postcompute
242 struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
243 const char *name; /* Name, without leading &. */
245 struct ctables_postcompute_expr *expr;
248 bool hide_source_cats;
251 struct ctables_postcompute_expr
253 enum ctables_postcompute_op
261 /* XXX SUBTOTAL and HSUBTOTAL */
274 /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
279 XXX what about string ranges? */
282 /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
283 struct ctables_postcompute_expr *subs[2];
287 struct ctables_summary_spec_set
289 struct ctables_summary_spec *specs;
293 struct variable *var;
296 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
297 const struct ctables_summary_spec_set *);
298 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
300 /* A nested sequence of variables, e.g. a > b > c. */
303 struct variable **vars;
306 size_t *domains[N_CTDTS];
307 size_t n_domains[N_CTDTS];
309 struct ctables_summary_spec_set specs[N_CSVS];
312 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
315 struct ctables_nest *nests;
321 struct hmap_node node;
328 struct ctables_axis *axes[PIVOT_N_AXES];
329 struct ctables_stack stacks[PIVOT_N_AXES];
330 enum pivot_axis_type summary_axis;
331 struct ctables_summary_spec_set summary_specs;
333 struct hmap domains[N_CTDTS];
335 const struct variable *clabels_example;
336 struct hmap clabels_values_map;
337 struct ctables_value **clabels_values;
338 size_t n_clabels_values;
340 enum pivot_axis_type slabels_axis;
341 bool slabels_visible;
343 /* The innermost category labels for axis 'a' appear on axis label_axis[a].
345 Most commonly, label_axis[a] == a, and in particular we always have
346 label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
348 If ROWLABELS or COLLABELS is specified, then one of
349 label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
350 opposite axis or PIVOT_AXIS_LAYER. Only one of them will differ.
352 enum pivot_axis_type label_axis[PIVOT_N_AXES];
353 enum pivot_axis_type clabels_from_axis;
355 /* Indexed by variable dictionary index. */
356 struct ctables_categories **categories;
365 struct ctables_chisq *chisq;
366 struct ctables_pairwise *pairwise;
374 struct variable *var;
375 const struct mrset *mrset;
379 static const struct fmt_spec *
380 ctables_var_get_print_format (const struct ctables_var *var)
382 return (var->is_mrset
383 ? var_get_print_format (var->mrset->vars[0])
384 : var_get_print_format (var->var));
388 ctables_var_name (const struct ctables_var *var)
390 return var->is_mrset ? var->mrset->name : var_get_name (var->var);
393 struct ctables_categories
396 struct ctables_category *cats;
401 struct ctables_category
403 enum ctables_category_type
421 struct ctables_category *subtotal;
425 double number; /* CCT_NUMBER. */
426 char *string; /* CCT_STRING. */
427 double range[2]; /* CCT_RANGE. */
428 char *total_label; /* CCT_SUBTOTAL, CCT_HSUBTOTAL, CCT_TOTAL. */
430 /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
433 bool include_missing;
437 enum ctables_summary_function sort_function;
438 struct variable *sort_var;
445 ctables_category_uninit (struct ctables_category *cat)
465 free (cat->total_label);
476 ctables_category_equal (const struct ctables_category *a,
477 const struct ctables_category *b)
479 if (a->type != b->type)
485 return a->number == b->number;
488 return strcmp (a->string, b->string);
491 return a->range[0] == b->range[0] && a->range[1] == b->range[1];
500 return !strcmp (a->total_label, b->total_label);
505 return (a->include_missing == b->include_missing
506 && a->sort_ascending == b->sort_ascending
507 && a->sort_function == b->sort_function
508 && a->sort_var == b->sort_var
509 && a->percentile == b->percentile);
516 ctables_categories_unref (struct ctables_categories *c)
521 assert (c->n_refs > 0);
525 for (size_t i = 0; i < c->n_cats; i++)
526 ctables_category_uninit (&c->cats[i]);
532 ctables_categories_equal (const struct ctables_categories *a,
533 const struct ctables_categories *b)
535 if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
538 for (size_t i = 0; i < a->n_cats; i++)
539 if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
545 /* Chi-square test (SIGTEST). */
553 /* Pairwise comparison test (COMPARETEST). */
554 struct ctables_pairwise
556 enum { PROP, MEAN } type;
559 bool meansvariance_allcats;
561 enum { BONFERRONI = 1, BH } adjust;
585 struct ctables_var var;
587 struct ctables_summary_spec_set specs[N_CSVS];
591 struct ctables_axis *subs[2];
594 struct msg_location *loc;
597 static void ctables_axis_destroy (struct ctables_axis *);
606 enum ctables_function_availability
608 CTFA_ALL, /* Any variables. */
609 CTFA_SCALE, /* Only scale variables, totals, and subtotals. */
610 CTFA_MRSETS, /* Only multiple-response sets */
613 struct ctables_summary_spec
615 enum ctables_summary_function function;
616 double percentile; /* CTSF_PTILE only. */
618 struct fmt_spec format; /* XXX extra CTABLES formats */
623 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
624 const struct ctables_summary_spec *src)
627 dst->label = xstrdup (src->label);
631 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
638 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
639 const struct ctables_summary_spec_set *src)
641 struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
642 for (size_t i = 0; i < src->n; i++)
643 ctables_summary_spec_clone (&specs[i], &src->specs[i]);
645 *dst = (struct ctables_summary_spec_set) {
654 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
656 for (size_t i = 0; i < set->n; i++)
657 ctables_summary_spec_uninit (&set->specs[i]);
662 parse_col_width (struct lexer *lexer, const char *name, double *width)
664 lex_match (lexer, T_EQUALS);
665 if (lex_match_id (lexer, "DEFAULT"))
667 else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
669 *width = lex_number (lexer);
679 parse_bool (struct lexer *lexer, bool *b)
681 if (lex_match_id (lexer, "NO"))
683 else if (lex_match_id (lexer, "YES"))
687 lex_error_expecting (lexer, "YES", "NO");
693 static enum ctables_function_availability
694 ctables_function_availability (enum ctables_summary_function f)
696 static enum ctables_function_availability availability[] = {
697 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
702 return availability[f];
706 parse_ctables_summary_function (struct lexer *lexer,
707 enum ctables_summary_function *f)
711 enum ctables_summary_function function;
712 struct substring name;
714 static struct pair names[] = {
715 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
716 { ENUM, SS_LITERAL_INITIALIZER (NAME) },
719 /* The .COUNT suffix may be omitted. */
720 S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
721 S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
722 S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
723 S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
724 S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
725 S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
726 S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
730 if (!lex_force_id (lexer))
733 for (size_t i = 0; i < sizeof names / sizeof *names; i++)
734 if (ss_equals_case (names[i].name, lex_tokss (lexer)))
736 *f = names[i].function;
741 lex_error (lexer, _("Expecting summary function name."));
746 ctables_axis_destroy (struct ctables_axis *axis)
754 for (size_t i = 0; i < N_CSVS; i++)
755 ctables_summary_spec_set_uninit (&axis->specs[i]);
760 ctables_axis_destroy (axis->subs[0]);
761 ctables_axis_destroy (axis->subs[1]);
764 msg_location_destroy (axis->loc);
768 static struct ctables_axis *
769 ctables_axis_new_nonterminal (enum ctables_axis_op op,
770 struct ctables_axis *sub0,
771 struct ctables_axis *sub1,
772 struct lexer *lexer, int start_ofs)
774 struct ctables_axis *axis = xmalloc (sizeof *axis);
775 *axis = (struct ctables_axis) {
777 .subs = { sub0, sub1 },
778 .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
783 struct ctables_axis_parse_ctx
786 struct dictionary *dict;
788 struct ctables_table *t;
791 static struct fmt_spec
792 ctables_summary_default_format (enum ctables_summary_function function,
793 const struct ctables_var *var)
795 static const enum ctables_format default_formats[] = {
796 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
800 switch (default_formats[function])
803 return (struct fmt_spec) { .type = FMT_F, .w = 40 };
806 return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
809 return *ctables_var_get_print_format (var);
817 ctables_summary_default_label (enum ctables_summary_function function,
820 static const char *default_labels[] = {
821 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
826 return (function == CTSF_PTILE
827 ? xasprintf (_("Percentile %.2f"), percentile)
828 : xstrdup (gettext (default_labels[function])));
832 ctables_summary_function_name (enum ctables_summary_function function)
834 static const char *names[] = {
835 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
839 return names[function];
843 add_summary_spec (struct ctables_axis *axis,
844 enum ctables_summary_function function, double percentile,
845 const char *label, const struct fmt_spec *format,
846 const struct msg_location *loc, enum ctables_summary_variant sv)
848 if (axis->op == CTAO_VAR)
850 const char *function_name = ctables_summary_function_name (function);
851 const char *var_name = ctables_var_name (&axis->var);
852 switch (ctables_function_availability (function))
855 if (!axis->var.is_mrset)
857 msg_at (SE, loc, _("Summary function %s applies only to multiple "
858 "response sets."), function_name);
859 msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
869 _("Summary function %s applies only to scale variables."),
871 msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
881 struct ctables_summary_spec_set *set = &axis->specs[sv];
882 if (set->n >= set->allocated)
883 set->specs = x2nrealloc (set->specs, &set->allocated,
886 struct ctables_summary_spec *dst = &set->specs[set->n++];
887 *dst = (struct ctables_summary_spec) {
888 .function = function,
889 .percentile = percentile,
890 .label = xstrdup (label),
891 .format = (format ? *format
892 : ctables_summary_default_format (function, &axis->var)),
898 for (size_t i = 0; i < 2; i++)
899 if (!add_summary_spec (axis->subs[i], function, percentile, label,
906 static struct ctables_axis *ctables_axis_parse_stack (
907 struct ctables_axis_parse_ctx *);
910 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
911 struct ctables_var *var)
913 if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
915 *var = (struct ctables_var) {
917 .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
921 lex_error (lexer, _("'%s' does not name a multiple-response set "
922 "in the active file dictionary."),
923 lex_tokcstr (lexer));
931 *var = (struct ctables_var) {
933 .var = parse_variable (lexer, dict),
935 return var->var != NULL;
939 static struct ctables_axis *
940 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
942 if (lex_match (ctx->lexer, T_LPAREN))
944 struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
945 if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
947 ctables_axis_destroy (sub);
953 if (!lex_force_id (ctx->lexer))
956 int start_ofs = lex_ofs (ctx->lexer);
957 struct ctables_var var;
958 if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
961 struct ctables_axis *axis = xmalloc (sizeof *axis);
962 *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
964 /* XXX should figure out default measures by reading data */
965 axis->scale = (var.is_mrset ? false
966 : lex_match_phrase (ctx->lexer, "[S]") ? true
967 : lex_match_phrase (ctx->lexer, "[C]") ? false
968 : var_get_measure (var.var) == MEASURE_SCALE);
969 axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
970 lex_ofs (ctx->lexer) - 1);
975 has_digit (const char *s)
977 return s[strcspn (s, "0123456789")] != '\0';
980 static struct ctables_axis *
981 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
983 struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
984 if (!sub || !lex_match (ctx->lexer, T_LBRACK))
987 enum ctables_summary_variant sv = CSV_CELL;
990 int start_ofs = lex_ofs (ctx->lexer);
992 /* Parse function. */
993 enum ctables_summary_function function;
994 if (!parse_ctables_summary_function (ctx->lexer, &function))
997 /* Parse percentile. */
998 double percentile = 0;
999 if (function == CTSF_PTILE)
1001 if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1003 percentile = lex_number (ctx->lexer);
1004 lex_get (ctx->lexer);
1009 if (lex_is_string (ctx->lexer))
1011 label = ss_xstrdup (lex_tokss (ctx->lexer));
1012 lex_get (ctx->lexer);
1015 label = ctables_summary_default_label (function, percentile);
1018 struct fmt_spec format;
1019 const struct fmt_spec *formatp;
1020 if (lex_token (ctx->lexer) == T_ID
1021 && has_digit (lex_tokcstr (ctx->lexer)))
1023 if (!parse_format_specifier (ctx->lexer, &format)
1024 || !fmt_check_output (&format)
1025 || !fmt_check_type_compat (&format, VAL_NUMERIC))
1035 struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1036 lex_ofs (ctx->lexer) - 1);
1037 add_summary_spec (sub, function, percentile, label, formatp, loc, sv);
1039 msg_location_destroy (loc);
1041 lex_match (ctx->lexer, T_COMMA);
1042 if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1044 if (!lex_force_match (ctx->lexer, T_LBRACK))
1048 else if (lex_match (ctx->lexer, T_RBRACK))
1050 if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1057 ctables_axis_destroy (sub);
1061 static const struct ctables_axis *
1062 find_scale (const struct ctables_axis *axis)
1066 else if (axis->op == CTAO_VAR)
1070 assert (!axis->var.is_mrset);
1078 for (size_t i = 0; i < 2; i++)
1080 const struct ctables_axis *scale = find_scale (axis->subs[i]);
1088 static const struct ctables_axis *
1089 find_categorical_summary_spec (const struct ctables_axis *axis)
1093 else if (axis->op == CTAO_VAR)
1094 return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1097 for (size_t i = 0; i < 2; i++)
1099 const struct ctables_axis *sum
1100 = find_categorical_summary_spec (axis->subs[i]);
1108 static struct ctables_axis *
1109 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1111 int start_ofs = lex_ofs (ctx->lexer);
1112 struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1116 while (lex_match (ctx->lexer, T_GT))
1118 struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1122 struct ctables_axis *nest = ctables_axis_new_nonterminal (
1123 CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1125 const struct ctables_axis *outer_scale = find_scale (lhs);
1126 const struct ctables_axis *inner_scale = find_scale (rhs);
1127 if (outer_scale && inner_scale)
1129 msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1130 msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1131 msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1132 ctables_axis_destroy (nest);
1136 const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1139 msg_at (SE, nest->loc,
1140 _("Summaries may only be requested for categorical variables "
1141 "at the innermost nesting level."));
1142 msg_at (SN, outer_sum->loc,
1143 _("This outer categorical variable has a summary."));
1144 ctables_axis_destroy (nest);
1154 static struct ctables_axis *
1155 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1157 int start_ofs = lex_ofs (ctx->lexer);
1158 struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1162 while (lex_match (ctx->lexer, T_PLUS))
1164 struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1168 lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1169 ctx->lexer, start_ofs);
1176 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1177 struct ctables *ct, struct ctables_table *t,
1178 enum pivot_axis_type a)
1180 if (lex_token (lexer) == T_BY
1181 || lex_token (lexer) == T_SLASH
1182 || lex_token (lexer) == T_ENDCMD)
1185 struct ctables_axis_parse_ctx ctx = {
1191 t->axes[a] = ctables_axis_parse_stack (&ctx);
1192 return t->axes[a] != NULL;
1196 ctables_chisq_destroy (struct ctables_chisq *chisq)
1202 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1208 ctables_table_destroy (struct ctables_table *t)
1213 for (size_t i = 0; i < t->n_categories; i++)
1214 ctables_categories_unref (t->categories[i]);
1215 free (t->categories);
1217 ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1218 ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1219 ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1223 ctables_chisq_destroy (t->chisq);
1224 ctables_pairwise_destroy (t->pairwise);
1229 ctables_destroy (struct ctables *ct)
1234 pivot_table_look_unref (ct->look);
1238 for (size_t i = 0; i < ct->n_tables; i++)
1239 ctables_table_destroy (ct->tables[i]);
1244 static struct ctables_category
1245 cct_range (double low, double high)
1247 return (struct ctables_category) {
1249 .range = { low, high }
1254 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1255 struct ctables_table *t)
1257 if (!lex_match_id (lexer, "VARIABLES"))
1259 lex_match (lexer, T_EQUALS);
1261 struct variable **vars;
1263 if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1266 struct ctables_categories *c = xmalloc (sizeof *c);
1267 *c = (struct ctables_categories) { .n_refs = n_vars };
1268 for (size_t i = 0; i < n_vars; i++)
1270 struct ctables_categories **cp
1271 = &t->categories[var_get_dict_index (vars[i])];
1272 ctables_categories_unref (*cp);
1277 size_t allocated_cats = 0;
1278 if (lex_match (lexer, T_LBRACK))
1282 if (c->n_cats >= allocated_cats)
1283 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1285 struct ctables_category *cat = &c->cats[c->n_cats];
1286 if (lex_match_id (lexer, "OTHERNM"))
1287 cat->type = CCT_OTHERNM;
1288 else if (lex_match_id (lexer, "MISSING"))
1289 cat->type = CCT_MISSING;
1290 else if (lex_match_id (lexer, "SUBTOTAL"))
1291 *cat = (struct ctables_category)
1292 { .type = CCT_SUBTOTAL, .total_label = NULL };
1293 else if (lex_match_id (lexer, "HSUBTOTAL"))
1294 *cat = (struct ctables_category)
1295 { .type = CCT_HSUBTOTAL, .total_label = NULL };
1296 else if (lex_match_id (lexer, "LO"))
1298 if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1300 *cat = cct_range (-DBL_MAX, lex_number (lexer));
1303 else if (lex_is_number (lexer))
1305 double number = lex_number (lexer);
1307 if (lex_match_id (lexer, "THRU"))
1309 cat->type = CCT_RANGE;
1310 cat->range[0] = number;
1311 if (lex_match_id (lexer, "HI"))
1312 *cat = cct_range (number, DBL_MAX);
1315 if (!lex_force_num (lexer))
1317 *cat = cct_range (number, lex_number (lexer));
1322 *cat = (struct ctables_category) {
1327 else if (lex_is_string (lexer))
1329 *cat = (struct ctables_category) {
1331 .string = ss_xstrdup (lex_tokss (lexer)),
1337 lex_error (lexer, NULL);
1341 if (cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
1343 if (lex_match (lexer, T_EQUALS))
1345 if (!lex_force_string (lexer))
1348 cat->total_label = ss_xstrdup (lex_tokss (lexer));
1352 cat->total_label = xstrdup (_("Subtotal"));
1356 lex_match (lexer, T_COMMA);
1358 while (!lex_match (lexer, T_RBRACK));
1361 struct ctables_category cat = {
1363 .include_missing = false,
1364 .sort_ascending = true,
1366 bool show_totals = false;
1367 char *total_label = NULL;
1368 bool totals_before = false;
1369 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1371 if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1373 lex_match (lexer, T_EQUALS);
1374 if (lex_match_id (lexer, "A"))
1375 cat.sort_ascending = true;
1376 else if (lex_match_id (lexer, "D"))
1377 cat.sort_ascending = false;
1380 lex_error_expecting (lexer, "A", "D");
1384 else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1386 lex_match (lexer, T_EQUALS);
1387 if (lex_match_id (lexer, "VALUE"))
1388 cat.type = CCT_VALUE;
1389 else if (lex_match_id (lexer, "LABEL"))
1390 cat.type = CCT_LABEL;
1393 cat.type = CCT_FUNCTION;
1394 if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1397 if (lex_match (lexer, T_LPAREN))
1399 cat.sort_var = parse_variable (lexer, dict);
1403 if (cat.sort_function == CTSF_PTILE)
1405 lex_match (lexer, T_COMMA);
1406 if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1408 cat.percentile = lex_number (lexer);
1412 if (!lex_force_match (lexer, T_RPAREN))
1415 else if (ctables_function_availability (cat.sort_function)
1418 bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1423 else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1425 lex_match (lexer, T_EQUALS);
1426 if (lex_match_id (lexer, "INCLUDE"))
1427 cat.include_missing = true;
1428 else if (lex_match_id (lexer, "EXCLUDE"))
1429 cat.include_missing = false;
1432 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1436 else if (lex_match_id (lexer, "TOTAL"))
1438 lex_match (lexer, T_EQUALS);
1439 if (!parse_bool (lexer, &show_totals))
1442 else if (lex_match_id (lexer, "LABEL"))
1444 lex_match (lexer, T_EQUALS);
1445 if (!lex_force_string (lexer))
1448 total_label = ss_xstrdup (lex_tokss (lexer));
1451 else if (lex_match_id (lexer, "POSITION"))
1453 lex_match (lexer, T_EQUALS);
1454 if (lex_match_id (lexer, "BEFORE"))
1455 totals_before = true;
1456 else if (lex_match_id (lexer, "AFTER"))
1457 totals_before = false;
1460 lex_error_expecting (lexer, "BEFORE", "AFTER");
1464 else if (lex_match_id (lexer, "EMPTY"))
1466 lex_match (lexer, T_EQUALS);
1467 if (lex_match_id (lexer, "INCLUDE"))
1468 c->show_empty = true;
1469 else if (lex_match_id (lexer, "EXCLUDE"))
1470 c->show_empty = false;
1473 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1480 lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1481 "TOTAL", "LABEL", "POSITION", "EMPTY");
1483 lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1490 if (c->n_cats >= allocated_cats)
1491 c->cats = x2nrealloc (c->cats, &allocated_cats,
1493 c->cats[c->n_cats++] = cat;
1498 if (c->n_cats >= allocated_cats)
1499 c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1501 struct ctables_category *totals;
1504 insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1505 totals = &c->cats[0];
1508 totals = &c->cats[c->n_cats];
1511 *totals = (struct ctables_category) {
1513 .total_label = total_label ? total_label : xstrdup (_("Total")),
1517 struct ctables_category *subtotal = NULL;
1518 for (size_t i = totals_before ? 0 : c->n_cats;
1519 totals_before ? i < c->n_cats : i-- > 0;
1520 totals_before ? i++ : 0)
1522 struct ctables_category *cat = &c->cats[i];
1530 cat->subtotal = subtotal;
1550 ctables_nest_uninit (struct ctables_nest *nest)
1557 ctables_stack_uninit (struct ctables_stack *stack)
1561 for (size_t i = 0; i < stack->n; i++)
1562 ctables_nest_uninit (&stack->nests[i]);
1563 free (stack->nests);
1567 static struct ctables_stack
1568 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1575 struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1576 for (size_t i = 0; i < s0.n; i++)
1577 for (size_t j = 0; j < s1.n; j++)
1579 const struct ctables_nest *a = &s0.nests[i];
1580 const struct ctables_nest *b = &s1.nests[j];
1582 size_t allocate = a->n + b->n;
1583 struct variable **vars = xnmalloc (allocate, sizeof *vars);
1584 enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1586 for (size_t k = 0; k < a->n; k++)
1587 vars[n++] = a->vars[k];
1588 for (size_t k = 0; k < b->n; k++)
1589 vars[n++] = b->vars[k];
1590 assert (n == allocate);
1592 const struct ctables_nest *summary_src;
1593 if (!a->specs[CSV_CELL].var)
1595 else if (!b->specs[CSV_CELL].var)
1600 struct ctables_nest *new = &stack.nests[stack.n++];
1601 *new = (struct ctables_nest) {
1603 .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1604 : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1608 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1609 ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1611 ctables_stack_uninit (&s0);
1612 ctables_stack_uninit (&s1);
1616 static struct ctables_stack
1617 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1619 struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1620 for (size_t i = 0; i < s0.n; i++)
1621 stack.nests[stack.n++] = s0.nests[i];
1622 for (size_t i = 0; i < s1.n; i++)
1623 stack.nests[stack.n++] = s1.nests[i];
1624 assert (stack.n == s0.n + s1.n);
1630 static struct ctables_stack
1631 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1634 return (struct ctables_stack) { .n = 0 };
1639 assert (!a->var.is_mrset);
1641 struct variable **vars = xmalloc (sizeof *vars);
1644 struct ctables_nest *nest = xmalloc (sizeof *nest);
1645 *nest = (struct ctables_nest) {
1648 .scale_idx = a->scale ? 0 : SIZE_MAX,
1650 if (a->specs[CSV_CELL].n || a->scale)
1651 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1653 ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
1654 nest->specs[sv].var = a->var.var;
1656 return (struct ctables_stack) { .nests = nest, .n = 1 };
1659 return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1660 enumerate_fts (axis_type, a->subs[1]));
1663 return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1664 enumerate_fts (axis_type, a->subs[1]));
1670 union ctables_summary
1672 /* COUNT, VALIDN, TOTALN. */
1679 /* MINIMUM, MAXIMUM, RANGE. */
1686 /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1687 struct moments1 *moments;
1689 /* MEDIAN, MODE, PTILE. */
1692 struct casewriter *writer;
1697 /* XXX multiple response */
1701 ctables_summary_init (union ctables_summary *s,
1702 const struct ctables_summary_spec *ss)
1704 switch (ss->function)
1708 case CTSF_ROWPCT_COUNT:
1709 case CTSF_COLPCT_COUNT:
1710 case CTSF_TABLEPCT_COUNT:
1711 case CTSF_SUBTABLEPCT_COUNT:
1712 case CTSF_LAYERPCT_COUNT:
1713 case CTSF_LAYERROWPCT_COUNT:
1714 case CTSF_LAYERCOLPCT_COUNT:
1715 case CTSF_ROWPCT_VALIDN:
1716 case CTSF_COLPCT_VALIDN:
1717 case CTSF_TABLEPCT_VALIDN:
1718 case CTSF_SUBTABLEPCT_VALIDN:
1719 case CTSF_LAYERPCT_VALIDN:
1720 case CTSF_LAYERROWPCT_VALIDN:
1721 case CTSF_LAYERCOLPCT_VALIDN:
1722 case CTSF_ROWPCT_TOTALN:
1723 case CTSF_COLPCT_TOTALN:
1724 case CTSF_TABLEPCT_TOTALN:
1725 case CTSF_SUBTABLEPCT_TOTALN:
1726 case CTSF_LAYERPCT_TOTALN:
1727 case CTSF_LAYERROWPCT_TOTALN:
1728 case CTSF_LAYERCOLPCT_TOTALN:
1734 s->missing = s->valid = 0;
1740 s->min = s->max = SYSMIS;
1748 case CTSF_ROWPCT_SUM:
1749 case CTSF_COLPCT_SUM:
1750 case CTSF_TABLEPCT_SUM:
1751 case CTSF_SUBTABLEPCT_SUM:
1752 case CTSF_LAYERPCT_SUM:
1753 case CTSF_LAYERROWPCT_SUM:
1754 case CTSF_LAYERCOLPCT_SUM:
1755 s->moments = moments1_create (MOMENT_VARIANCE);
1762 struct caseproto *proto = caseproto_create ();
1763 proto = caseproto_add_width (proto, 0);
1764 proto = caseproto_add_width (proto, 0);
1766 struct subcase ordering;
1767 subcase_init (&ordering, 0, 0, SC_ASCEND);
1768 s->writer = sort_create_writer (&ordering, proto);
1769 subcase_uninit (&ordering);
1770 caseproto_unref (proto);
1777 case CTSF_RESPONSES:
1778 case CTSF_ROWPCT_RESPONSES:
1779 case CTSF_COLPCT_RESPONSES:
1780 case CTSF_TABLEPCT_RESPONSES:
1781 case CTSF_SUBTABLEPCT_RESPONSES:
1782 case CTSF_LAYERPCT_RESPONSES:
1783 case CTSF_LAYERROWPCT_RESPONSES:
1784 case CTSF_LAYERCOLPCT_RESPONSES:
1785 case CTSF_ROWPCT_RESPONSES_COUNT:
1786 case CTSF_COLPCT_RESPONSES_COUNT:
1787 case CTSF_TABLEPCT_RESPONSES_COUNT:
1788 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1789 case CTSF_LAYERPCT_RESPONSES_COUNT:
1790 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1791 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1792 case CTSF_ROWPCT_COUNT_RESPONSES:
1793 case CTSF_COLPCT_COUNT_RESPONSES:
1794 case CTSF_TABLEPCT_COUNT_RESPONSES:
1795 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1796 case CTSF_LAYERPCT_COUNT_RESPONSES:
1797 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1798 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1804 ctables_summary_uninit (union ctables_summary *s,
1805 const struct ctables_summary_spec *ss)
1807 switch (ss->function)
1811 case CTSF_ROWPCT_COUNT:
1812 case CTSF_COLPCT_COUNT:
1813 case CTSF_TABLEPCT_COUNT:
1814 case CTSF_SUBTABLEPCT_COUNT:
1815 case CTSF_LAYERPCT_COUNT:
1816 case CTSF_LAYERROWPCT_COUNT:
1817 case CTSF_LAYERCOLPCT_COUNT:
1818 case CTSF_ROWPCT_VALIDN:
1819 case CTSF_COLPCT_VALIDN:
1820 case CTSF_TABLEPCT_VALIDN:
1821 case CTSF_SUBTABLEPCT_VALIDN:
1822 case CTSF_LAYERPCT_VALIDN:
1823 case CTSF_LAYERROWPCT_VALIDN:
1824 case CTSF_LAYERCOLPCT_VALIDN:
1825 case CTSF_ROWPCT_TOTALN:
1826 case CTSF_COLPCT_TOTALN:
1827 case CTSF_TABLEPCT_TOTALN:
1828 case CTSF_SUBTABLEPCT_TOTALN:
1829 case CTSF_LAYERPCT_TOTALN:
1830 case CTSF_LAYERROWPCT_TOTALN:
1831 case CTSF_LAYERCOLPCT_TOTALN:
1849 case CTSF_ROWPCT_SUM:
1850 case CTSF_COLPCT_SUM:
1851 case CTSF_TABLEPCT_SUM:
1852 case CTSF_SUBTABLEPCT_SUM:
1853 case CTSF_LAYERPCT_SUM:
1854 case CTSF_LAYERROWPCT_SUM:
1855 case CTSF_LAYERCOLPCT_SUM:
1856 moments1_destroy (s->moments);
1862 casewriter_destroy (s->writer);
1865 case CTSF_RESPONSES:
1866 case CTSF_ROWPCT_RESPONSES:
1867 case CTSF_COLPCT_RESPONSES:
1868 case CTSF_TABLEPCT_RESPONSES:
1869 case CTSF_SUBTABLEPCT_RESPONSES:
1870 case CTSF_LAYERPCT_RESPONSES:
1871 case CTSF_LAYERROWPCT_RESPONSES:
1872 case CTSF_LAYERCOLPCT_RESPONSES:
1873 case CTSF_ROWPCT_RESPONSES_COUNT:
1874 case CTSF_COLPCT_RESPONSES_COUNT:
1875 case CTSF_TABLEPCT_RESPONSES_COUNT:
1876 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1877 case CTSF_LAYERPCT_RESPONSES_COUNT:
1878 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1879 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1880 case CTSF_ROWPCT_COUNT_RESPONSES:
1881 case CTSF_COLPCT_COUNT_RESPONSES:
1882 case CTSF_TABLEPCT_COUNT_RESPONSES:
1883 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1884 case CTSF_LAYERPCT_COUNT_RESPONSES:
1885 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1886 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1892 ctables_summary_add (union ctables_summary *s,
1893 const struct ctables_summary_spec *ss,
1894 const struct variable *var, const union value *value,
1897 switch (ss->function)
1901 case CTSF_ROWPCT_COUNT:
1902 case CTSF_COLPCT_COUNT:
1903 case CTSF_TABLEPCT_COUNT:
1904 case CTSF_SUBTABLEPCT_COUNT:
1905 case CTSF_LAYERPCT_COUNT:
1906 case CTSF_LAYERROWPCT_COUNT:
1907 case CTSF_LAYERCOLPCT_COUNT:
1908 case CTSF_ROWPCT_VALIDN:
1909 case CTSF_COLPCT_VALIDN:
1910 case CTSF_TABLEPCT_VALIDN:
1911 case CTSF_SUBTABLEPCT_VALIDN:
1912 case CTSF_LAYERPCT_VALIDN:
1913 case CTSF_LAYERROWPCT_VALIDN:
1914 case CTSF_LAYERCOLPCT_VALIDN:
1915 case CTSF_ROWPCT_TOTALN:
1916 case CTSF_COLPCT_TOTALN:
1917 case CTSF_TABLEPCT_TOTALN:
1918 case CTSF_SUBTABLEPCT_TOTALN:
1919 case CTSF_LAYERPCT_TOTALN:
1920 case CTSF_LAYERROWPCT_TOTALN:
1921 case CTSF_LAYERCOLPCT_TOTALN:
1927 if (var_is_value_missing (var, value))
1928 s->missing += weight;
1936 if (!var_is_value_missing (var, value))
1938 assert (!var_is_alpha (var)); /* XXX? */
1939 if (s->min == SYSMIS || value->f < s->min)
1941 if (s->max == SYSMIS || value->f > s->max)
1951 case CTSF_ROWPCT_SUM:
1952 case CTSF_COLPCT_SUM:
1953 case CTSF_TABLEPCT_SUM:
1954 case CTSF_SUBTABLEPCT_SUM:
1955 case CTSF_LAYERPCT_SUM:
1956 case CTSF_LAYERROWPCT_SUM:
1957 case CTSF_LAYERCOLPCT_SUM:
1958 if (!var_is_value_missing (var, value))
1959 moments1_add (s->moments, value->f, weight);
1965 if (var_is_value_missing (var, value))
1967 s->ovalid += weight;
1969 struct ccase *c = case_create (casewriter_get_proto (s->writer));
1970 *case_num_rw_idx (c, 0) = value->f;
1971 *case_num_rw_idx (c, 1) = weight;
1972 casewriter_write (s->writer, c);
1976 case CTSF_RESPONSES:
1977 case CTSF_ROWPCT_RESPONSES:
1978 case CTSF_COLPCT_RESPONSES:
1979 case CTSF_TABLEPCT_RESPONSES:
1980 case CTSF_SUBTABLEPCT_RESPONSES:
1981 case CTSF_LAYERPCT_RESPONSES:
1982 case CTSF_LAYERROWPCT_RESPONSES:
1983 case CTSF_LAYERCOLPCT_RESPONSES:
1984 case CTSF_ROWPCT_RESPONSES_COUNT:
1985 case CTSF_COLPCT_RESPONSES_COUNT:
1986 case CTSF_TABLEPCT_RESPONSES_COUNT:
1987 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1988 case CTSF_LAYERPCT_RESPONSES_COUNT:
1989 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1990 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1991 case CTSF_ROWPCT_COUNT_RESPONSES:
1992 case CTSF_COLPCT_COUNT_RESPONSES:
1993 case CTSF_TABLEPCT_COUNT_RESPONSES:
1994 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1995 case CTSF_LAYERPCT_COUNT_RESPONSES:
1996 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1997 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2003 ctables_summary_value (const struct ctables_cell *cell,
2004 union ctables_summary *s,
2005 const struct ctables_summary_spec *ss)
2007 switch (ss->function)
2013 case CTSF_SUBTABLEPCT_COUNT:
2014 return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
2016 case CTSF_ROWPCT_COUNT:
2017 return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
2019 case CTSF_COLPCT_COUNT:
2020 return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
2022 case CTSF_TABLEPCT_COUNT:
2023 return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
2025 case CTSF_LAYERPCT_COUNT:
2026 return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
2028 case CTSF_LAYERROWPCT_COUNT:
2029 return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
2031 case CTSF_LAYERCOLPCT_COUNT:
2032 return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
2034 case CTSF_ROWPCT_VALIDN:
2035 case CTSF_COLPCT_VALIDN:
2036 case CTSF_TABLEPCT_VALIDN:
2037 case CTSF_SUBTABLEPCT_VALIDN:
2038 case CTSF_LAYERPCT_VALIDN:
2039 case CTSF_LAYERROWPCT_VALIDN:
2040 case CTSF_LAYERCOLPCT_VALIDN:
2041 case CTSF_ROWPCT_TOTALN:
2042 case CTSF_COLPCT_TOTALN:
2043 case CTSF_TABLEPCT_TOTALN:
2044 case CTSF_SUBTABLEPCT_TOTALN:
2045 case CTSF_LAYERPCT_TOTALN:
2046 case CTSF_LAYERROWPCT_TOTALN:
2047 case CTSF_LAYERCOLPCT_TOTALN:
2055 return s->valid + s->missing;
2068 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2073 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2079 double weight, variance;
2080 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2081 return calc_semean (variance, weight);
2087 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2088 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2093 double weight, mean;
2094 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2095 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2101 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2105 case CTSF_ROWPCT_SUM:
2106 case CTSF_COLPCT_SUM:
2107 case CTSF_TABLEPCT_SUM:
2108 case CTSF_SUBTABLEPCT_SUM:
2109 case CTSF_LAYERPCT_SUM:
2110 case CTSF_LAYERROWPCT_SUM:
2111 case CTSF_LAYERCOLPCT_SUM:
2118 struct casereader *reader = casewriter_make_reader (s->writer);
2121 struct percentile *ptile = percentile_create (
2122 ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2123 struct order_stats *os = &ptile->parent;
2124 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2125 s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2126 statistic_destroy (&ptile->parent.parent);
2133 struct casereader *reader = casewriter_make_reader (s->writer);
2136 struct mode *mode = mode_create ();
2137 struct order_stats *os = &mode->parent;
2138 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2139 s->ovalue = mode->mode;
2140 statistic_destroy (&mode->parent.parent);
2144 case CTSF_RESPONSES:
2145 case CTSF_ROWPCT_RESPONSES:
2146 case CTSF_COLPCT_RESPONSES:
2147 case CTSF_TABLEPCT_RESPONSES:
2148 case CTSF_SUBTABLEPCT_RESPONSES:
2149 case CTSF_LAYERPCT_RESPONSES:
2150 case CTSF_LAYERROWPCT_RESPONSES:
2151 case CTSF_LAYERCOLPCT_RESPONSES:
2152 case CTSF_ROWPCT_RESPONSES_COUNT:
2153 case CTSF_COLPCT_RESPONSES_COUNT:
2154 case CTSF_TABLEPCT_RESPONSES_COUNT:
2155 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2156 case CTSF_LAYERPCT_RESPONSES_COUNT:
2157 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2158 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2159 case CTSF_ROWPCT_COUNT_RESPONSES:
2160 case CTSF_COLPCT_COUNT_RESPONSES:
2161 case CTSF_TABLEPCT_COUNT_RESPONSES:
2162 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2163 case CTSF_LAYERPCT_COUNT_RESPONSES:
2164 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2165 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2172 struct ctables_cell_sort_aux
2174 const struct ctables_table *t;
2175 enum pivot_axis_type a;
2179 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2181 const struct ctables_cell_sort_aux *aux = aux_;
2182 struct ctables_cell *const *ap = a_;
2183 struct ctables_cell *const *bp = b_;
2184 const struct ctables_cell *a = *ap;
2185 const struct ctables_cell *b = *bp;
2187 size_t a_idx = a->axes[aux->a].nest_idx;
2188 size_t b_idx = b->axes[aux->a].nest_idx;
2190 return a_idx < b_idx ? -1 : 1;
2192 const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2193 for (size_t i = 0; i < nest->n; i++)
2194 if (i != nest->scale_idx)
2196 const struct variable *var = nest->vars[i];
2197 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2198 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2199 if (a_cv->category != b_cv->category)
2200 return a_cv->category > b_cv->category ? 1 : -1;
2202 const union value *a_val = &a_cv->value;
2203 const union value *b_val = &b_cv->value;
2204 switch (a_cv->category->type)
2211 /* Must be equal. */
2218 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2226 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2228 return a_cv->category->sort_ascending ? cmp : -cmp;
2234 const char *a_label = var_lookup_value_label (var, a_val);
2235 const char *b_label = var_lookup_value_label (var, b_val);
2237 ? (b_label ? strcmp (a_label, b_label) : 1)
2238 : (b_label ? -1 : value_compare_3way (
2239 a_val, b_val, var_get_width (var))));
2241 return a_cv->category->sort_ascending ? cmp : -cmp;
2255 For each ctables_table:
2256 For each combination of row vars:
2257 For each combination of column vars:
2258 For each combination of layer vars:
2260 Make a table of row values:
2261 Sort entries by row values
2262 Assign a 0-based index to each actual value
2263 Construct a dimension
2264 Make a table of column values
2265 Make a table of layer values
2267 Fill the table entry using the indexes from before.
2270 static struct ctables_domain *
2271 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2272 enum ctables_domain_type domain)
2275 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2277 size_t idx = cell->axes[a].nest_idx;
2278 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2279 hash = hash_int (idx, hash);
2280 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2282 size_t v_idx = nest->domains[domain][i];
2283 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2284 var_get_width (nest->vars[v_idx]), hash);
2288 struct ctables_domain *d;
2289 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2291 const struct ctables_cell *df = d->example;
2292 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2294 size_t idx = cell->axes[a].nest_idx;
2295 if (idx != df->axes[a].nest_idx)
2298 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2299 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2301 size_t v_idx = nest->domains[domain][i];
2302 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2303 &cell->axes[a].cvs[v_idx].value,
2304 var_get_width (nest->vars[v_idx])))
2313 d = xmalloc (sizeof *d);
2314 *d = (struct ctables_domain) { .example = cell };
2315 hmap_insert (&t->domains[domain], &d->node, hash);
2319 static const struct ctables_category *
2320 ctables_categories_match (const struct ctables_categories *c,
2321 const union value *v, const struct variable *var)
2323 const struct ctables_category *othernm = NULL;
2324 for (size_t i = c->n_cats; i-- > 0; )
2326 const struct ctables_category *cat = &c->cats[i];
2330 if (cat->number == v->f)
2338 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2339 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2344 if (var_is_value_missing (var, v))
2361 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2366 return var_is_value_missing (var, v) ? NULL : othernm;
2369 static const struct ctables_category *
2370 ctables_categories_total (const struct ctables_categories *c)
2372 const struct ctables_category *first = &c->cats[0];
2373 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2374 return (first->type == CCT_TOTAL ? first
2375 : last->type == CCT_TOTAL ? last
2379 static struct ctables_cell *
2380 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2381 size_t ix[PIVOT_N_AXES],
2382 const struct ctables_category *cats[PIVOT_N_AXES][10])
2384 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2387 enum ctables_summary_variant sv = CSV_CELL;
2388 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2390 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2391 hash = hash_int (ix[a], hash);
2392 for (size_t i = 0; i < nest->n; i++)
2393 if (i != nest->scale_idx)
2395 hash = hash_pointer (cats[a][i], hash);
2396 if (cats[a][i]->type != CCT_TOTAL
2397 && cats[a][i]->type != CCT_SUBTOTAL
2398 && cats[a][i]->type != CCT_HSUBTOTAL)
2399 hash = value_hash (case_data (c, nest->vars[i]),
2400 var_get_width (nest->vars[i]), hash);
2406 struct ctables_cell *cell;
2407 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2409 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2411 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2412 if (cell->axes[a].nest_idx != ix[a])
2414 for (size_t i = 0; i < nest->n; i++)
2415 if (i != nest->scale_idx
2416 && (cats[a][i] != cell->axes[a].cvs[i].category
2417 || (cats[a][i]->type != CCT_TOTAL
2418 && cats[a][i]->type != CCT_SUBTOTAL
2419 && cats[a][i]->type != CCT_HSUBTOTAL
2420 && !value_equal (case_data (c, nest->vars[i]),
2421 &cell->axes[a].cvs[i].value,
2422 var_get_width (nest->vars[i])))))
2431 cell = xmalloc (sizeof *cell);
2434 cell->contributes_to_domains = true;
2435 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2437 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2438 cell->axes[a].nest_idx = ix[a];
2439 cell->axes[a].cvs = (nest->n
2440 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2442 for (size_t i = 0; i < nest->n; i++)
2444 const struct ctables_category *cat = cats[a][i];
2446 if (i != nest->scale_idx)
2448 const struct ctables_category *subtotal = cat->subtotal;
2449 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2452 if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2453 cell->contributes_to_domains = false;
2456 cell->axes[a].cvs[i].category = cat;
2457 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2458 var_get_width (nest->vars[i]));
2462 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2463 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2464 for (size_t i = 0; i < specs->n; i++)
2465 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2466 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2467 cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2468 hmap_insert (&t->cells, &cell->node, hash);
2473 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2474 size_t ix[PIVOT_N_AXES],
2475 const struct ctables_category *cats[PIVOT_N_AXES][10],
2478 struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2479 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2481 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2482 for (size_t i = 0; i < specs->n; i++)
2483 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2484 case_data (c, specs->var), weight);
2485 if (cell->contributes_to_domains)
2486 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2487 cell->domains[dt]->valid += weight;
2491 recurse_totals (struct ctables_table *t, const struct ccase *c,
2492 size_t ix[PIVOT_N_AXES],
2493 const struct ctables_category *cats[PIVOT_N_AXES][10],
2495 enum pivot_axis_type start_axis, size_t start_nest)
2497 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2499 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2500 for (size_t i = start_nest; i < nest->n; i++)
2502 if (i == nest->scale_idx)
2505 const struct variable *var = nest->vars[i];
2507 const struct ctables_category *total = ctables_categories_total (
2508 t->categories[var_get_dict_index (var)]);
2511 const struct ctables_category *save = cats[a][i];
2513 ctables_cell_add__ (t, c, ix, cats, weight);
2514 recurse_totals (t, c, ix, cats, weight, a, i + 1);
2523 recurse_subtotals (struct ctables_table *t, const struct ccase *c,
2524 size_t ix[PIVOT_N_AXES],
2525 const struct ctables_category *cats[PIVOT_N_AXES][10],
2527 enum pivot_axis_type start_axis, size_t start_nest)
2529 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2531 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2532 for (size_t i = start_nest; i < nest->n; i++)
2534 if (i == nest->scale_idx)
2537 const struct ctables_category *save = cats[a][i];
2540 cats[a][i] = save->subtotal;
2541 ctables_cell_add__ (t, c, ix, cats, weight);
2542 recurse_subtotals (t, c, ix, cats, weight, a, i + 1);
2551 ctables_cell_insert (struct ctables_table *t,
2552 const struct ccase *c,
2553 size_t ir, size_t ic, size_t il,
2556 size_t ix[PIVOT_N_AXES] = {
2557 [PIVOT_AXIS_ROW] = ir,
2558 [PIVOT_AXIS_COLUMN] = ic,
2559 [PIVOT_AXIS_LAYER] = il,
2562 const struct ctables_category *cats[PIVOT_N_AXES][10];
2563 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2565 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2566 for (size_t i = 0; i < nest->n; i++)
2568 if (i == nest->scale_idx)
2571 const struct variable *var = nest->vars[i];
2572 const union value *value = case_data (c, var);
2574 if (var_is_numeric (var) && value->f == SYSMIS)
2577 cats[a][i] = ctables_categories_match (
2578 t->categories[var_get_dict_index (var)], value, var);
2584 ctables_cell_add__ (t, c, ix, cats, weight);
2586 recurse_totals (t, c, ix, cats, weight, 0, 0);
2587 recurse_subtotals (t, c, ix, cats, weight, 0, 0);
2592 const struct ctables_summary_spec_set *set;
2597 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2599 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2600 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2601 if (as->function != bs->function)
2602 return as->function > bs->function ? 1 : -1;
2603 else if (as->percentile != bs->percentile)
2604 return as->percentile < bs->percentile ? 1 : -1;
2605 return strcmp (as->label, bs->label);
2608 static struct pivot_value *
2609 ctables_category_create_label (const struct ctables_category *cat,
2610 const struct variable *var,
2611 const union value *value)
2613 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2614 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2615 : pivot_value_new_var_value (var, value));
2618 static struct ctables_value *
2619 ctables_value_find__ (struct ctables_table *t, const union value *value,
2620 int width, unsigned int hash)
2622 struct ctables_value *clv;
2623 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2624 hash, &t->clabels_values_map)
2625 if (value_equal (value, &clv->value, width))
2630 static struct ctables_value *
2631 ctables_value_find (struct ctables_table *t,
2632 const union value *value, int width)
2634 return ctables_value_find__ (t, value, width,
2635 value_hash (value, width, 0));
2639 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2641 struct pivot_table *pt = pivot_table_create__ (
2643 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2644 : pivot_value_new_text (N_("Custom Tables"))),
2647 pivot_table_set_caption (
2648 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2650 pivot_table_set_caption (
2651 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2653 bool summary_dimension = (t->summary_axis != t->slabels_axis
2654 || (!t->slabels_visible
2655 && t->summary_specs.n > 1));
2656 if (summary_dimension)
2658 struct pivot_dimension *d = pivot_dimension_create (
2659 pt, t->slabels_axis, N_("Statistics"));
2660 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2661 if (!t->slabels_visible)
2662 d->hide_all_labels = true;
2663 for (size_t i = 0; i < specs->n; i++)
2664 pivot_category_create_leaf (
2665 d->root, pivot_value_new_text (specs->specs[i].label));
2668 bool categories_dimension = t->clabels_example != NULL;
2669 if (categories_dimension)
2671 struct pivot_dimension *d = pivot_dimension_create (
2672 pt, t->label_axis[t->clabels_from_axis],
2673 t->clabels_from_axis == PIVOT_AXIS_ROW
2674 ? N_("Row Categories")
2675 : N_("Column Categories"));
2676 const struct variable *var = t->clabels_example;
2677 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2678 for (size_t i = 0; i < t->n_clabels_values; i++)
2680 const struct ctables_value *value = t->clabels_values[i];
2681 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2682 assert (cat != NULL);
2683 pivot_category_create_leaf (d->root, ctables_category_create_label (
2684 cat, t->clabels_example, &value->value));
2688 pivot_table_set_look (pt, ct->look);
2689 struct pivot_dimension *d[PIVOT_N_AXES];
2690 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2692 static const char *names[] = {
2693 [PIVOT_AXIS_ROW] = N_("Rows"),
2694 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2695 [PIVOT_AXIS_LAYER] = N_("Layers"),
2697 d[a] = (t->axes[a] || a == t->summary_axis
2698 ? pivot_dimension_create (pt, a, names[a])
2703 assert (t->axes[a]);
2705 struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2706 size_t n_sorted = 0;
2708 struct ctables_cell *cell;
2709 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2711 sorted[n_sorted++] = cell;
2712 assert (n_sorted <= t->cells.count);
2714 struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2715 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2717 size_t max_depth = 0;
2718 for (size_t j = 0; j < t->stacks[a].n; j++)
2719 if (t->stacks[a].nests[j].n > max_depth)
2720 max_depth = t->stacks[a].nests[j].n;
2722 /* Pivot categories:
2724 - variable label for nest->vars[0], if vlabel != CTVL_NONE
2725 - category for nest->vars[0], if nest->scale_idx != 0
2726 - variable label for nest->vars[1], if vlabel != CTVL_NONE
2727 - category for nest->vars[1], if nest->scale_idx != 1
2729 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2730 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2731 - summary function, if 'a == t->slabels_axis && a ==
2734 Additional dimensions:
2736 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2738 - If 't->label_axis[b] == a' for some 'b != a', add a category
2742 struct ctables_level
2744 enum ctables_level_type
2746 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2747 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2748 CTL_SUMMARY, /* Summary functions. */
2754 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2755 size_t n_levels = 0;
2757 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2759 for (size_t j = 0; j < n_sorted; j++)
2761 struct ctables_cell *cell = sorted[j];
2762 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2763 const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2765 bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2769 for (size_t k = 0; k < nest->n; k++)
2771 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2772 if (vlabel != CTVL_NONE)
2774 levels[n_levels++] = (struct ctables_level) {
2780 if (nest->scale_idx != k
2781 && (k != nest->n - 1 || t->label_axis[a] == a))
2783 levels[n_levels++] = (struct ctables_level) {
2784 .type = CTL_CATEGORY,
2790 if (!summary_dimension && a == t->slabels_axis)
2792 levels[n_levels++] = (struct ctables_level) {
2793 .type = CTL_SUMMARY,
2794 .var_idx = SIZE_MAX,
2799 size_t n_common = 0;
2802 for (; n_common < n_levels; n_common++)
2804 const struct ctables_level *level = &levels[n_common];
2805 if (level->type == CTL_CATEGORY)
2807 size_t var_idx = level->var_idx;
2808 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
2809 if (prev->axes[a].cvs[var_idx].category != c)
2811 else if (c->type != CCT_SUBTOTAL
2812 && c->type != CCT_HSUBTOTAL
2813 && c->type != CCT_TOTAL
2814 && !value_equal (&prev->axes[a].cvs[var_idx].value,
2815 &cell->axes[a].cvs[var_idx].value,
2816 var_get_type (nest->vars[var_idx])))
2822 for (size_t k = n_common; k < n_levels; k++)
2824 const struct ctables_level *level = &levels[k];
2825 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2826 if (level->type == CTL_SUMMARY)
2828 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2829 for (size_t m = 0; m < specs->n; m++)
2831 int leaf = pivot_category_create_leaf (
2832 parent, pivot_value_new_text (specs->specs[m].label));
2839 const struct variable *var = nest->vars[level->var_idx];
2840 struct pivot_value *label;
2841 if (level->type == CTL_VAR)
2842 label = pivot_value_new_variable (var);
2843 else if (level->type == CTL_CATEGORY)
2845 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2846 label = ctables_category_create_label (cv->category,
2852 if (k == n_levels - 1)
2853 prev_leaf = pivot_category_create_leaf (parent, label);
2855 groups[k] = pivot_category_create_group__ (parent, label);
2859 cell->axes[a].leaf = prev_leaf;
2865 struct ctables_cell *cell;
2866 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2871 const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2872 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2873 for (size_t j = 0; j < specs->n; j++)
2876 size_t n_dindexes = 0;
2878 if (summary_dimension)
2879 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2881 if (categories_dimension)
2883 const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2884 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2885 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2886 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2887 assert (ctv != NULL);
2888 dindexes[n_dindexes++] = ctv->leaf;
2891 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2894 int leaf = cell->axes[a].leaf;
2895 if (a == t->summary_axis && !summary_dimension)
2897 dindexes[n_dindexes++] = leaf;
2900 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2901 struct pivot_value *value = pivot_value_new_number (d);
2902 value->numeric.format = specs->specs[j].format;
2903 pivot_table_put (pt, dindexes, n_dindexes, value);
2907 pivot_table_submit (pt);
2911 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2913 enum pivot_axis_type label_pos = t->label_axis[a];
2917 t->clabels_from_axis = a;
2919 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2920 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2922 const struct ctables_stack *stack = &t->stacks[a];
2926 const struct ctables_nest *n0 = &stack->nests[0];
2928 const struct variable *v0 = n0->vars[n0->n - 1];
2929 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2930 t->clabels_example = v0;
2932 for (size_t i = 0; i < c0->n_cats; i++)
2933 if (c0->cats[i].type == CCT_FUNCTION)
2935 msg (SE, _("%s=%s is not allowed with sorting based "
2936 "on a summary function."),
2937 subcommand_name, pos_name);
2940 if (n0->n - 1 == n0->scale_idx)
2942 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2943 "but %s is a scale variable."),
2944 subcommand_name, pos_name, var_get_name (v0));
2948 for (size_t i = 1; i < stack->n; i++)
2950 const struct ctables_nest *ni = &stack->nests[i];
2952 const struct variable *vi = ni->vars[ni->n - 1];
2953 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2955 if (ni->n - 1 == ni->scale_idx)
2957 msg (SE, _("%s=%s requires the variables to be moved to be "
2958 "categorical, but %s is a scale variable."),
2959 subcommand_name, pos_name, var_get_name (vi));
2962 if (var_get_width (v0) != var_get_width (vi))
2964 msg (SE, _("%s=%s requires the variables to be "
2965 "moved to have the same width, but %s has "
2966 "width %d and %s has width %d."),
2967 subcommand_name, pos_name,
2968 var_get_name (v0), var_get_width (v0),
2969 var_get_name (vi), var_get_width (vi));
2972 if (!val_labs_equal (var_get_value_labels (v0),
2973 var_get_value_labels (vi)))
2975 msg (SE, _("%s=%s requires the variables to be "
2976 "moved to have the same value labels, but %s "
2977 "and %s have different value labels."),
2978 subcommand_name, pos_name,
2979 var_get_name (v0), var_get_name (vi));
2982 if (!ctables_categories_equal (c0, ci))
2984 msg (SE, _("%s=%s requires the variables to be "
2985 "moved to have the same category "
2986 "specifications, but %s and %s have different "
2987 "category specifications."),
2988 subcommand_name, pos_name,
2989 var_get_name (v0), var_get_name (vi));
2998 ctables_prepare_table (struct ctables_table *t)
3000 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3003 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3005 for (size_t j = 0; j < t->stacks[a].n; j++)
3007 struct ctables_nest *nest = &t->stacks[a].nests[j];
3008 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3010 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3011 nest->n_domains[dt] = 0;
3013 for (size_t k = 0; k < nest->n; k++)
3015 if (k == nest->scale_idx)
3024 if (a != PIVOT_AXIS_LAYER)
3031 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3032 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3033 : a == PIVOT_AXIS_ROW)
3035 if (k == nest->n - 1
3036 || (nest->scale_idx == nest->n - 1
3037 && k == nest->n - 2))
3043 if (a == PIVOT_AXIS_COLUMN)
3048 if (a == PIVOT_AXIS_ROW)
3053 nest->domains[dt][nest->n_domains[dt]++] = k;
3060 struct ctables_nest *nest = xmalloc (sizeof *nest);
3061 *nest = (struct ctables_nest) { .n = 0 };
3062 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3065 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3066 for (size_t i = 0; i < stack->n; i++)
3068 struct ctables_nest *nest = &stack->nests[i];
3069 if (!nest->specs[CSV_CELL].n)
3071 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3072 specs->specs = xmalloc (sizeof *specs->specs);
3075 enum ctables_summary_function function
3076 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3077 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3079 *specs->specs = (struct ctables_summary_spec) {
3080 .function = function,
3081 .format = ctables_summary_default_format (function, &var),
3082 .label = ctables_summary_default_label (function, 0),
3085 specs->var = nest->vars[0];
3087 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3088 &nest->specs[CSV_CELL]);
3090 else if (!nest->specs[CSV_TOTAL].n)
3091 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3092 &nest->specs[CSV_CELL]);
3095 struct ctables_summary_spec_set *merged = &t->summary_specs;
3096 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3098 for (size_t j = 0; j < stack->n; j++)
3100 const struct ctables_nest *nest = &stack->nests[j];
3102 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3103 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3108 struct merge_item min = items[0];
3109 for (size_t j = 1; j < n_left; j++)
3110 if (merge_item_compare_3way (&items[j], &min) < 0)
3113 if (merged->n >= merged->allocated)
3114 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3115 sizeof *merged->specs);
3116 merged->specs[merged->n++] = min.set->specs[min.ofs];
3118 for (size_t j = 0; j < n_left; )
3120 if (merge_item_compare_3way (&items[j], &min) == 0)
3122 struct merge_item *item = &items[j];
3123 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3124 if (++item->ofs >= item->set->n)
3126 items[j] = items[--n_left];
3135 for (size_t j = 0; j < merged->n; j++)
3136 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3138 for (size_t j = 0; j < stack->n; j++)
3140 const struct ctables_nest *nest = &stack->nests[j];
3141 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3143 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3144 for (size_t k = 0; k < specs->n; k++)
3145 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3146 specs->specs[k].axis_idx);
3152 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3153 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3157 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3158 enum pivot_axis_type a)
3160 struct ctables_stack *stack = &t->stacks[a];
3161 for (size_t i = 0; i < stack->n; i++)
3163 const struct ctables_nest *nest = &stack->nests[i];
3164 const struct variable *var = nest->vars[nest->n - 1];
3165 int width = var_get_width (var);
3166 const union value *value = case_data (c, var);
3168 if (var_is_numeric (var) && value->f == SYSMIS)
3171 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3175 unsigned int hash = value_hash (value, width, 0);
3177 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3180 clv = xmalloc (sizeof *clv);
3181 value_clone (&clv->value, value, width);
3182 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3188 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3190 const struct ctables_value *const *ap = a_;
3191 const struct ctables_value *const *bp = b_;
3192 const struct ctables_value *a = *ap;
3193 const struct ctables_value *b = *bp;
3194 const int *width = width_;
3195 return value_compare_3way (&a->value, &b->value, *width);
3199 ctables_sort_clabels_values (struct ctables_table *t)
3201 int width = var_get_width (t->clabels_example);
3203 size_t n = hmap_count (&t->clabels_values_map);
3204 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3206 struct ctables_value *clv;
3208 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3209 t->clabels_values[i++] = clv;
3210 t->n_clabels_values = n;
3213 sort (t->clabels_values, n, sizeof *t->clabels_values,
3214 compare_clabels_values_3way, &width);
3216 for (size_t i = 0; i < n; i++)
3217 t->clabels_values[i]->leaf = i;
3221 ctables_execute (struct dataset *ds, struct ctables *ct)
3223 struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3226 bool warn_on_invalid = true;
3227 double total_weight = 0;
3228 for (struct ccase *c = casereader_read (input); c;
3229 case_unref (c), c = casereader_read (input))
3231 double weight = dict_get_case_weight (dataset_dict (ds), c,
3233 total_weight += weight;
3235 for (size_t i = 0; i < ct->n_tables; i++)
3237 struct ctables_table *t = ct->tables[i];
3239 for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3240 for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3241 for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3242 ctables_cell_insert (t, c, ir, ic, il, weight);
3244 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3245 if (t->label_axis[a] != a)
3246 ctables_insert_clabels_values (t, c, a);
3249 casereader_destroy (input);
3251 for (size_t i = 0; i < ct->n_tables; i++)
3253 struct ctables_table *t = ct->tables[i];
3255 if (t->clabels_example)
3256 ctables_sort_clabels_values (t);
3258 ctables_table_output (ct, ct->tables[i]);
3260 return proc_commit (ds);
3264 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3266 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3267 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3268 enum settings_value_show tvars = settings_get_show_variables ();
3269 for (size_t i = 0; i < n_vars; i++)
3270 vlabels[i] = (enum ctables_vlabel) tvars;
3272 struct ctables *ct = xmalloc (sizeof *ct);
3273 *ct = (struct ctables) {
3274 .look = pivot_table_look_unshare (pivot_table_look_ref (
3275 pivot_table_look_get_default ())),
3277 .hide_threshold = 5,
3279 ct->look->omit_empty = false;
3281 if (!lex_force_match (lexer, T_SLASH))
3284 while (!lex_match_id (lexer, "TABLE"))
3286 if (lex_match_id (lexer, "FORMAT"))
3288 double widths[2] = { SYSMIS, SYSMIS };
3289 double units_per_inch = 72.0;
3291 while (lex_token (lexer) != T_SLASH)
3293 if (lex_match_id (lexer, "MINCOLWIDTH"))
3295 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3298 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3300 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3303 else if (lex_match_id (lexer, "UNITS"))
3305 lex_match (lexer, T_EQUALS);
3306 if (lex_match_id (lexer, "POINTS"))
3307 units_per_inch = 72.0;
3308 else if (lex_match_id (lexer, "INCHES"))
3309 units_per_inch = 1.0;
3310 else if (lex_match_id (lexer, "CM"))
3311 units_per_inch = 2.54;
3314 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3318 else if (lex_match_id (lexer, "EMPTY"))
3323 lex_match (lexer, T_EQUALS);
3324 if (lex_match_id (lexer, "ZERO"))
3326 /* Nothing to do. */
3328 else if (lex_match_id (lexer, "BLANK"))
3329 ct->zero = xstrdup ("");
3330 else if (lex_force_string (lexer))
3332 ct->zero = ss_xstrdup (lex_tokss (lexer));
3338 else if (lex_match_id (lexer, "MISSING"))
3340 lex_match (lexer, T_EQUALS);
3341 if (!lex_force_string (lexer))
3345 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3346 ? ss_xstrdup (lex_tokss (lexer))
3352 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3353 "UNITS", "EMPTY", "MISSING");
3358 if (widths[0] != SYSMIS && widths[1] != SYSMIS
3359 && widths[0] > widths[1])
3361 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3365 for (size_t i = 0; i < 2; i++)
3366 if (widths[i] != SYSMIS)
3368 int *wr = ct->look->width_ranges[TABLE_HORZ];
3369 wr[i] = widths[i] / units_per_inch * 96.0;
3374 else if (lex_match_id (lexer, "VLABELS"))
3376 if (!lex_force_match_id (lexer, "VARIABLES"))
3378 lex_match (lexer, T_EQUALS);
3380 struct variable **vars;
3382 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3386 if (!lex_force_match_id (lexer, "DISPLAY"))
3391 lex_match (lexer, T_EQUALS);
3393 enum ctables_vlabel vlabel;
3394 if (lex_match_id (lexer, "DEFAULT"))
3395 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3396 else if (lex_match_id (lexer, "NAME"))
3398 else if (lex_match_id (lexer, "LABEL"))
3399 vlabel = CTVL_LABEL;
3400 else if (lex_match_id (lexer, "BOTH"))
3402 else if (lex_match_id (lexer, "NONE"))
3406 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3412 for (size_t i = 0; i < n_vars; i++)
3413 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3416 else if (lex_match_id (lexer, "MRSETS"))
3418 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3420 lex_match (lexer, T_EQUALS);
3421 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3424 else if (lex_match_id (lexer, "SMISSING"))
3426 if (lex_match_id (lexer, "VARIABLE"))
3427 ct->smissing_listwise = false;
3428 else if (lex_match_id (lexer, "LISTWISE"))
3429 ct->smissing_listwise = true;
3432 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3437 else if (lex_match_id (lexer, "WEIGHT"))
3439 if (!lex_force_match_id (lexer, "VARIABLE"))
3441 lex_match (lexer, T_EQUALS);
3442 ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3443 if (!ct->base_weight)
3446 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3448 if (!lex_force_match_id (lexer, "COUNT"))
3450 lex_match (lexer, T_EQUALS);
3451 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3453 ct->hide_threshold = lex_integer (lexer);
3458 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3459 "SMISSING", "PCOMPUTE", "PPROPERTIES",
3460 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3464 if (!lex_force_match (lexer, T_SLASH))
3468 size_t allocated_tables = 0;
3471 if (ct->n_tables >= allocated_tables)
3472 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3473 sizeof *ct->tables);
3475 struct ctables_category *cat = xmalloc (sizeof *cat);
3476 *cat = (struct ctables_category) {
3478 .include_missing = false,
3479 .sort_ascending = true,
3482 struct ctables_categories *c = xmalloc (sizeof *c);
3483 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3484 *c = (struct ctables_categories) {
3490 struct ctables_categories **categories = xnmalloc (n_vars,
3491 sizeof *categories);
3492 for (size_t i = 0; i < n_vars; i++)
3495 struct ctables_table *t = xmalloc (sizeof *t);
3496 *t = (struct ctables_table) {
3497 .cells = HMAP_INITIALIZER (t->cells),
3498 .slabels_axis = PIVOT_AXIS_COLUMN,
3499 .slabels_visible = true,
3500 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3502 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3503 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3504 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3506 .clabels_from_axis = PIVOT_AXIS_LAYER,
3507 .categories = categories,
3508 .n_categories = n_vars,
3511 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3512 hmap_init (&t->domains[dt]);
3513 ct->tables[ct->n_tables++] = t;
3515 lex_match (lexer, T_EQUALS);
3516 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3518 if (lex_match (lexer, T_BY))
3520 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3521 ct, t, PIVOT_AXIS_COLUMN))
3524 if (lex_match (lexer, T_BY))
3526 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3527 ct, t, PIVOT_AXIS_LAYER))
3532 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3533 && !t->axes[PIVOT_AXIS_LAYER])
3535 lex_error (lexer, _("At least one variable must be specified."));
3539 const struct ctables_axis *scales[PIVOT_N_AXES];
3540 size_t n_scales = 0;
3541 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3543 scales[a] = find_scale (t->axes[a]);
3549 msg (SE, _("Scale variables may appear only on one axis."));
3550 if (scales[PIVOT_AXIS_ROW])
3551 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3552 _("This scale variable appears on the rows axis."));
3553 if (scales[PIVOT_AXIS_COLUMN])
3554 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3555 _("This scale variable appears on the columns axis."));
3556 if (scales[PIVOT_AXIS_LAYER])
3557 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3558 _("This scale variable appears on the layer axis."));
3562 const struct ctables_axis *summaries[PIVOT_N_AXES];
3563 size_t n_summaries = 0;
3564 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3566 summaries[a] = (scales[a]
3568 : find_categorical_summary_spec (t->axes[a]));
3572 if (n_summaries > 1)
3574 msg (SE, _("Summaries may appear only on one axis."));
3575 if (summaries[PIVOT_AXIS_ROW])
3576 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3577 _("This variable on the rows axis has a summary."));
3578 if (summaries[PIVOT_AXIS_COLUMN])
3579 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3580 _("This variable on the columns axis has a summary."));
3581 if (summaries[PIVOT_AXIS_LAYER])
3582 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3583 _("This variable on the layers axis has a summary."));
3586 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3587 if (n_summaries ? summaries[a] : t->axes[a])
3589 t->summary_axis = a;
3593 if (lex_token (lexer) == T_ENDCMD)
3595 if (!ctables_prepare_table (t))
3599 if (!lex_force_match (lexer, T_SLASH))
3602 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3604 if (lex_match_id (lexer, "SLABELS"))
3606 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3608 if (lex_match_id (lexer, "POSITION"))
3610 lex_match (lexer, T_EQUALS);
3611 if (lex_match_id (lexer, "COLUMN"))
3612 t->slabels_axis = PIVOT_AXIS_COLUMN;
3613 else if (lex_match_id (lexer, "ROW"))
3614 t->slabels_axis = PIVOT_AXIS_ROW;
3615 else if (lex_match_id (lexer, "LAYER"))
3616 t->slabels_axis = PIVOT_AXIS_LAYER;
3619 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3623 else if (lex_match_id (lexer, "VISIBLE"))
3625 lex_match (lexer, T_EQUALS);
3626 if (!parse_bool (lexer, &t->slabels_visible))
3631 lex_error_expecting (lexer, "POSITION", "VISIBLE");
3636 else if (lex_match_id (lexer, "CLABELS"))
3638 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3640 if (lex_match_id (lexer, "AUTO"))
3642 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3643 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3645 else if (lex_match_id (lexer, "ROWLABELS"))
3647 lex_match (lexer, T_EQUALS);
3648 if (lex_match_id (lexer, "OPPOSITE"))
3649 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3650 else if (lex_match_id (lexer, "LAYER"))
3651 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3654 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3658 else if (lex_match_id (lexer, "COLLABELS"))
3660 lex_match (lexer, T_EQUALS);
3661 if (lex_match_id (lexer, "OPPOSITE"))
3662 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3663 else if (lex_match_id (lexer, "LAYER"))
3664 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3667 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3673 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3679 else if (lex_match_id (lexer, "CRITERIA"))
3681 if (!lex_force_match_id (lexer, "CILEVEL"))
3683 lex_match (lexer, T_EQUALS);
3685 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3687 t->cilevel = lex_number (lexer);
3690 else if (lex_match_id (lexer, "CATEGORIES"))
3692 if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3695 else if (lex_match_id (lexer, "TITLES"))
3700 if (lex_match_id (lexer, "CAPTION"))
3701 textp = &t->caption;
3702 else if (lex_match_id (lexer, "CORNER"))
3704 else if (lex_match_id (lexer, "TITLE"))
3708 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3711 lex_match (lexer, T_EQUALS);
3713 struct string s = DS_EMPTY_INITIALIZER;
3714 while (lex_is_string (lexer))
3716 if (!ds_is_empty (&s))
3717 ds_put_byte (&s, ' ');
3718 ds_put_substring (&s, lex_tokss (lexer));
3722 *textp = ds_steal_cstr (&s);
3724 while (lex_token (lexer) != T_SLASH
3725 && lex_token (lexer) != T_ENDCMD);
3727 else if (lex_match_id (lexer, "SIGTEST"))
3731 t->chisq = xmalloc (sizeof *t->chisq);
3732 *t->chisq = (struct ctables_chisq) {
3734 .include_mrsets = true,
3735 .all_visible = true,
3741 if (lex_match_id (lexer, "TYPE"))
3743 lex_match (lexer, T_EQUALS);
3744 if (!lex_force_match_id (lexer, "CHISQUARE"))
3747 else if (lex_match_id (lexer, "ALPHA"))
3749 lex_match (lexer, T_EQUALS);
3750 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3752 t->chisq->alpha = lex_number (lexer);
3755 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3757 lex_match (lexer, T_EQUALS);
3758 if (parse_bool (lexer, &t->chisq->include_mrsets))
3761 else if (lex_match_id (lexer, "CATEGORIES"))
3763 lex_match (lexer, T_EQUALS);
3764 if (lex_match_id (lexer, "ALLVISIBLE"))
3765 t->chisq->all_visible = true;
3766 else if (lex_match_id (lexer, "SUBTOTALS"))
3767 t->chisq->all_visible = false;
3770 lex_error_expecting (lexer,
3771 "ALLVISIBLE", "SUBTOTALS");
3777 lex_error_expecting (lexer, "TYPE", "ALPHA",
3778 "INCLUDEMRSETS", "CATEGORIES");
3782 while (lex_token (lexer) != T_SLASH
3783 && lex_token (lexer) != T_ENDCMD);
3785 else if (lex_match_id (lexer, "COMPARETEST"))
3789 t->pairwise = xmalloc (sizeof *t->pairwise);
3790 *t->pairwise = (struct ctables_pairwise) {
3792 .alpha = { .05, .05 },
3793 .adjust = BONFERRONI,
3794 .include_mrsets = true,
3795 .meansvariance_allcats = true,
3796 .all_visible = true,
3805 if (lex_match_id (lexer, "TYPE"))
3807 lex_match (lexer, T_EQUALS);
3808 if (lex_match_id (lexer, "PROP"))
3809 t->pairwise->type = PROP;
3810 else if (lex_match_id (lexer, "MEAN"))
3811 t->pairwise->type = MEAN;
3814 lex_error_expecting (lexer, "PROP", "MEAN");
3818 else if (lex_match_id (lexer, "ALPHA"))
3820 lex_match (lexer, T_EQUALS);
3822 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3824 double a0 = lex_number (lexer);
3827 lex_match (lexer, T_COMMA);
3828 if (lex_is_number (lexer))
3830 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3832 double a1 = lex_number (lexer);
3835 t->pairwise->alpha[0] = MIN (a0, a1);
3836 t->pairwise->alpha[1] = MAX (a0, a1);
3839 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3841 else if (lex_match_id (lexer, "ADJUST"))
3843 lex_match (lexer, T_EQUALS);
3844 if (lex_match_id (lexer, "BONFERRONI"))
3845 t->pairwise->adjust = BONFERRONI;
3846 else if (lex_match_id (lexer, "BH"))
3847 t->pairwise->adjust = BH;
3848 else if (lex_match_id (lexer, "NONE"))
3849 t->pairwise->adjust = 0;
3852 lex_error_expecting (lexer, "BONFERRONI", "BH",
3857 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3859 lex_match (lexer, T_EQUALS);
3860 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3863 else if (lex_match_id (lexer, "MEANSVARIANCE"))
3865 lex_match (lexer, T_EQUALS);
3866 if (lex_match_id (lexer, "ALLCATS"))
3867 t->pairwise->meansvariance_allcats = true;
3868 else if (lex_match_id (lexer, "TESTEDCATS"))
3869 t->pairwise->meansvariance_allcats = false;
3872 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3876 else if (lex_match_id (lexer, "CATEGORIES"))
3878 lex_match (lexer, T_EQUALS);
3879 if (lex_match_id (lexer, "ALLVISIBLE"))
3880 t->pairwise->all_visible = true;
3881 else if (lex_match_id (lexer, "SUBTOTALS"))
3882 t->pairwise->all_visible = false;
3885 lex_error_expecting (lexer, "ALLVISIBLE",
3890 else if (lex_match_id (lexer, "MERGE"))
3892 lex_match (lexer, T_EQUALS);
3893 if (!parse_bool (lexer, &t->pairwise->merge))
3896 else if (lex_match_id (lexer, "STYLE"))
3898 lex_match (lexer, T_EQUALS);
3899 if (lex_match_id (lexer, "APA"))
3900 t->pairwise->apa_style = true;
3901 else if (lex_match_id (lexer, "SIMPLE"))
3902 t->pairwise->apa_style = false;
3905 lex_error_expecting (lexer, "APA", "SIMPLE");
3909 else if (lex_match_id (lexer, "SHOWSIG"))
3911 lex_match (lexer, T_EQUALS);
3912 if (!parse_bool (lexer, &t->pairwise->show_sig))
3917 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3918 "INCLUDEMRSETS", "MEANSVARIANCE",
3919 "CATEGORIES", "MERGE", "STYLE",
3924 while (lex_token (lexer) != T_SLASH
3925 && lex_token (lexer) != T_ENDCMD);
3929 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3930 "CRITERIA", "CATEGORIES", "TITLES",
3931 "SIGTEST", "COMPARETEST");
3935 if (!lex_match (lexer, T_SLASH))
3939 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3940 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3942 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3946 if (!ctables_prepare_table (t))
3949 while (lex_token (lexer) != T_ENDCMD);
3951 bool ok = ctables_execute (ds, ct);
3952 ctables_destroy (ct);
3953 return ok ? CMD_SUCCESS : CMD_FAILURE;
3956 ctables_destroy (ct);