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;
1692 struct casewriter *writer;
1697 /* XXX percentiles, mode, 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);
1761 struct caseproto *proto = caseproto_create ();
1762 proto = caseproto_add_width (proto, 0);
1763 proto = caseproto_add_width (proto, 0);
1765 struct subcase ordering;
1766 subcase_init (&ordering, 0, 0, SC_ASCEND);
1767 s->writer = sort_create_writer (&ordering, proto);
1768 subcase_uninit (&ordering);
1769 caseproto_unref (proto);
1779 case CTSF_RESPONSES:
1780 case CTSF_ROWPCT_RESPONSES:
1781 case CTSF_COLPCT_RESPONSES:
1782 case CTSF_TABLEPCT_RESPONSES:
1783 case CTSF_SUBTABLEPCT_RESPONSES:
1784 case CTSF_LAYERPCT_RESPONSES:
1785 case CTSF_LAYERROWPCT_RESPONSES:
1786 case CTSF_LAYERCOLPCT_RESPONSES:
1787 case CTSF_ROWPCT_RESPONSES_COUNT:
1788 case CTSF_COLPCT_RESPONSES_COUNT:
1789 case CTSF_TABLEPCT_RESPONSES_COUNT:
1790 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1791 case CTSF_LAYERPCT_RESPONSES_COUNT:
1792 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1793 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1794 case CTSF_ROWPCT_COUNT_RESPONSES:
1795 case CTSF_COLPCT_COUNT_RESPONSES:
1796 case CTSF_TABLEPCT_COUNT_RESPONSES:
1797 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1798 case CTSF_LAYERPCT_COUNT_RESPONSES:
1799 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1800 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1806 ctables_summary_uninit (union ctables_summary *s,
1807 const struct ctables_summary_spec *ss)
1809 switch (ss->function)
1813 case CTSF_ROWPCT_COUNT:
1814 case CTSF_COLPCT_COUNT:
1815 case CTSF_TABLEPCT_COUNT:
1816 case CTSF_SUBTABLEPCT_COUNT:
1817 case CTSF_LAYERPCT_COUNT:
1818 case CTSF_LAYERROWPCT_COUNT:
1819 case CTSF_LAYERCOLPCT_COUNT:
1820 case CTSF_ROWPCT_VALIDN:
1821 case CTSF_COLPCT_VALIDN:
1822 case CTSF_TABLEPCT_VALIDN:
1823 case CTSF_SUBTABLEPCT_VALIDN:
1824 case CTSF_LAYERPCT_VALIDN:
1825 case CTSF_LAYERROWPCT_VALIDN:
1826 case CTSF_LAYERCOLPCT_VALIDN:
1827 case CTSF_ROWPCT_TOTALN:
1828 case CTSF_COLPCT_TOTALN:
1829 case CTSF_TABLEPCT_TOTALN:
1830 case CTSF_SUBTABLEPCT_TOTALN:
1831 case CTSF_LAYERPCT_TOTALN:
1832 case CTSF_LAYERROWPCT_TOTALN:
1833 case CTSF_LAYERCOLPCT_TOTALN:
1851 case CTSF_ROWPCT_SUM:
1852 case CTSF_COLPCT_SUM:
1853 case CTSF_TABLEPCT_SUM:
1854 case CTSF_SUBTABLEPCT_SUM:
1855 case CTSF_LAYERPCT_SUM:
1856 case CTSF_LAYERROWPCT_SUM:
1857 case CTSF_LAYERCOLPCT_SUM:
1858 moments1_destroy (s->moments);
1863 casewriter_destroy (s->writer);
1869 case CTSF_RESPONSES:
1870 case CTSF_ROWPCT_RESPONSES:
1871 case CTSF_COLPCT_RESPONSES:
1872 case CTSF_TABLEPCT_RESPONSES:
1873 case CTSF_SUBTABLEPCT_RESPONSES:
1874 case CTSF_LAYERPCT_RESPONSES:
1875 case CTSF_LAYERROWPCT_RESPONSES:
1876 case CTSF_LAYERCOLPCT_RESPONSES:
1877 case CTSF_ROWPCT_RESPONSES_COUNT:
1878 case CTSF_COLPCT_RESPONSES_COUNT:
1879 case CTSF_TABLEPCT_RESPONSES_COUNT:
1880 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1881 case CTSF_LAYERPCT_RESPONSES_COUNT:
1882 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1883 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1884 case CTSF_ROWPCT_COUNT_RESPONSES:
1885 case CTSF_COLPCT_COUNT_RESPONSES:
1886 case CTSF_TABLEPCT_COUNT_RESPONSES:
1887 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1888 case CTSF_LAYERPCT_COUNT_RESPONSES:
1889 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1890 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1896 ctables_summary_add (union ctables_summary *s,
1897 const struct ctables_summary_spec *ss,
1898 const struct variable *var, const union value *value,
1901 switch (ss->function)
1905 case CTSF_ROWPCT_COUNT:
1906 case CTSF_COLPCT_COUNT:
1907 case CTSF_TABLEPCT_COUNT:
1908 case CTSF_SUBTABLEPCT_COUNT:
1909 case CTSF_LAYERPCT_COUNT:
1910 case CTSF_LAYERROWPCT_COUNT:
1911 case CTSF_LAYERCOLPCT_COUNT:
1912 case CTSF_ROWPCT_VALIDN:
1913 case CTSF_COLPCT_VALIDN:
1914 case CTSF_TABLEPCT_VALIDN:
1915 case CTSF_SUBTABLEPCT_VALIDN:
1916 case CTSF_LAYERPCT_VALIDN:
1917 case CTSF_LAYERROWPCT_VALIDN:
1918 case CTSF_LAYERCOLPCT_VALIDN:
1919 case CTSF_ROWPCT_TOTALN:
1920 case CTSF_COLPCT_TOTALN:
1921 case CTSF_TABLEPCT_TOTALN:
1922 case CTSF_SUBTABLEPCT_TOTALN:
1923 case CTSF_LAYERPCT_TOTALN:
1924 case CTSF_LAYERROWPCT_TOTALN:
1925 case CTSF_LAYERCOLPCT_TOTALN:
1931 if (var_is_value_missing (var, value))
1932 s->missing += weight;
1940 if (!var_is_value_missing (var, value))
1942 assert (!var_is_alpha (var)); /* XXX? */
1943 if (s->min == SYSMIS || value->f < s->min)
1945 if (s->max == SYSMIS || value->f > s->max)
1955 case CTSF_ROWPCT_SUM:
1956 case CTSF_COLPCT_SUM:
1957 case CTSF_TABLEPCT_SUM:
1958 case CTSF_SUBTABLEPCT_SUM:
1959 case CTSF_LAYERPCT_SUM:
1960 case CTSF_LAYERROWPCT_SUM:
1961 case CTSF_LAYERCOLPCT_SUM:
1962 if (!var_is_value_missing (var, value))
1963 moments1_add (s->moments, value->f, weight);
1968 if (var_is_value_missing (var, value))
1970 s->ovalid += weight;
1972 struct ccase *c = case_create (casewriter_get_proto (s->writer));
1973 *case_num_rw_idx (c, 0) = value->f;
1974 *case_num_rw_idx (c, 1) = weight;
1975 casewriter_write (s->writer, c);
1982 case CTSF_RESPONSES:
1983 case CTSF_ROWPCT_RESPONSES:
1984 case CTSF_COLPCT_RESPONSES:
1985 case CTSF_TABLEPCT_RESPONSES:
1986 case CTSF_SUBTABLEPCT_RESPONSES:
1987 case CTSF_LAYERPCT_RESPONSES:
1988 case CTSF_LAYERROWPCT_RESPONSES:
1989 case CTSF_LAYERCOLPCT_RESPONSES:
1990 case CTSF_ROWPCT_RESPONSES_COUNT:
1991 case CTSF_COLPCT_RESPONSES_COUNT:
1992 case CTSF_TABLEPCT_RESPONSES_COUNT:
1993 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1994 case CTSF_LAYERPCT_RESPONSES_COUNT:
1995 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1996 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1997 case CTSF_ROWPCT_COUNT_RESPONSES:
1998 case CTSF_COLPCT_COUNT_RESPONSES:
1999 case CTSF_TABLEPCT_COUNT_RESPONSES:
2000 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2001 case CTSF_LAYERPCT_COUNT_RESPONSES:
2002 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2003 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2009 ctables_summary_value (const struct ctables_cell *cell,
2010 union ctables_summary *s,
2011 const struct ctables_summary_spec *ss)
2013 switch (ss->function)
2019 case CTSF_SUBTABLEPCT_COUNT:
2020 return cell->domains[CTDT_SUBTABLE]->valid ? s->valid / cell->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
2022 case CTSF_ROWPCT_COUNT:
2023 return cell->domains[CTDT_ROW]->valid ? s->valid / cell->domains[CTDT_ROW]->valid * 100 : SYSMIS;
2025 case CTSF_COLPCT_COUNT:
2026 return cell->domains[CTDT_COL]->valid ? s->valid / cell->domains[CTDT_COL]->valid * 100 : SYSMIS;
2028 case CTSF_TABLEPCT_COUNT:
2029 return cell->domains[CTDT_TABLE]->valid ? s->valid / cell->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
2031 case CTSF_LAYERPCT_COUNT:
2032 return cell->domains[CTDT_LAYER]->valid ? s->valid / cell->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
2034 case CTSF_LAYERROWPCT_COUNT:
2035 return cell->domains[CTDT_LAYERROW]->valid ? s->valid / cell->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
2037 case CTSF_LAYERCOLPCT_COUNT:
2038 return cell->domains[CTDT_LAYERCOL]->valid ? s->valid / cell->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
2040 case CTSF_ROWPCT_VALIDN:
2041 case CTSF_COLPCT_VALIDN:
2042 case CTSF_TABLEPCT_VALIDN:
2043 case CTSF_SUBTABLEPCT_VALIDN:
2044 case CTSF_LAYERPCT_VALIDN:
2045 case CTSF_LAYERROWPCT_VALIDN:
2046 case CTSF_LAYERCOLPCT_VALIDN:
2047 case CTSF_ROWPCT_TOTALN:
2048 case CTSF_COLPCT_TOTALN:
2049 case CTSF_TABLEPCT_TOTALN:
2050 case CTSF_SUBTABLEPCT_TOTALN:
2051 case CTSF_LAYERPCT_TOTALN:
2052 case CTSF_LAYERROWPCT_TOTALN:
2053 case CTSF_LAYERCOLPCT_TOTALN:
2061 return s->valid + s->missing;
2074 return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2079 moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2085 double weight, variance;
2086 moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2087 return calc_semean (variance, weight);
2093 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2094 return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2099 double weight, mean;
2100 moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2101 return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2107 moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2111 case CTSF_ROWPCT_SUM:
2112 case CTSF_COLPCT_SUM:
2113 case CTSF_TABLEPCT_SUM:
2114 case CTSF_SUBTABLEPCT_SUM:
2115 case CTSF_LAYERPCT_SUM:
2116 case CTSF_LAYERROWPCT_SUM:
2117 case CTSF_LAYERCOLPCT_SUM:
2123 struct casereader *reader = casewriter_make_reader (s->writer);
2126 struct percentile *median = percentile_create (0.5, s->ovalid);
2127 struct order_stats *os = &median->parent;
2128 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2129 s->ovalue = percentile_calculate (median, PC_HAVERAGE);
2130 statistic_destroy (&median->parent.parent);
2137 struct casereader *reader = casewriter_make_reader (s->writer);
2140 struct mode *mode = mode_create ();
2141 struct order_stats *os = &mode->parent;
2142 order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2143 s->ovalue = mode->mode;
2144 statistic_destroy (&mode->parent.parent);
2151 case CTSF_RESPONSES:
2152 case CTSF_ROWPCT_RESPONSES:
2153 case CTSF_COLPCT_RESPONSES:
2154 case CTSF_TABLEPCT_RESPONSES:
2155 case CTSF_SUBTABLEPCT_RESPONSES:
2156 case CTSF_LAYERPCT_RESPONSES:
2157 case CTSF_LAYERROWPCT_RESPONSES:
2158 case CTSF_LAYERCOLPCT_RESPONSES:
2159 case CTSF_ROWPCT_RESPONSES_COUNT:
2160 case CTSF_COLPCT_RESPONSES_COUNT:
2161 case CTSF_TABLEPCT_RESPONSES_COUNT:
2162 case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2163 case CTSF_LAYERPCT_RESPONSES_COUNT:
2164 case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2165 case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2166 case CTSF_ROWPCT_COUNT_RESPONSES:
2167 case CTSF_COLPCT_COUNT_RESPONSES:
2168 case CTSF_TABLEPCT_COUNT_RESPONSES:
2169 case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2170 case CTSF_LAYERPCT_COUNT_RESPONSES:
2171 case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2172 case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2179 struct ctables_cell_sort_aux
2181 const struct ctables_table *t;
2182 enum pivot_axis_type a;
2186 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2188 const struct ctables_cell_sort_aux *aux = aux_;
2189 struct ctables_cell *const *ap = a_;
2190 struct ctables_cell *const *bp = b_;
2191 const struct ctables_cell *a = *ap;
2192 const struct ctables_cell *b = *bp;
2194 size_t a_idx = a->axes[aux->a].nest_idx;
2195 size_t b_idx = b->axes[aux->a].nest_idx;
2197 return a_idx < b_idx ? -1 : 1;
2199 const struct ctables_nest *nest = &aux->t->stacks[aux->a].nests[a_idx];
2200 for (size_t i = 0; i < nest->n; i++)
2201 if (i != nest->scale_idx)
2203 const struct variable *var = nest->vars[i];
2204 const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2205 const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2206 if (a_cv->category != b_cv->category)
2207 return a_cv->category > b_cv->category ? 1 : -1;
2209 const union value *a_val = &a_cv->value;
2210 const union value *b_val = &b_cv->value;
2211 switch (a_cv->category->type)
2218 /* Must be equal. */
2225 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2233 int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2235 return a_cv->category->sort_ascending ? cmp : -cmp;
2241 const char *a_label = var_lookup_value_label (var, a_val);
2242 const char *b_label = var_lookup_value_label (var, b_val);
2244 ? (b_label ? strcmp (a_label, b_label) : 1)
2245 : (b_label ? -1 : value_compare_3way (
2246 a_val, b_val, var_get_width (var))));
2248 return a_cv->category->sort_ascending ? cmp : -cmp;
2262 For each ctables_table:
2263 For each combination of row vars:
2264 For each combination of column vars:
2265 For each combination of layer vars:
2267 Make a table of row values:
2268 Sort entries by row values
2269 Assign a 0-based index to each actual value
2270 Construct a dimension
2271 Make a table of column values
2272 Make a table of layer values
2274 Fill the table entry using the indexes from before.
2277 static struct ctables_domain *
2278 ctables_domain_insert (struct ctables_table *t, struct ctables_cell *cell,
2279 enum ctables_domain_type domain)
2282 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2284 size_t idx = cell->axes[a].nest_idx;
2285 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2286 hash = hash_int (idx, hash);
2287 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2289 size_t v_idx = nest->domains[domain][i];
2290 hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2291 var_get_width (nest->vars[v_idx]), hash);
2295 struct ctables_domain *d;
2296 HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
2298 const struct ctables_cell *df = d->example;
2299 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2301 size_t idx = cell->axes[a].nest_idx;
2302 if (idx != df->axes[a].nest_idx)
2305 const struct ctables_nest *nest = &t->stacks[a].nests[idx];
2306 for (size_t i = 0; i < nest->n_domains[domain]; i++)
2308 size_t v_idx = nest->domains[domain][i];
2309 if (!value_equal (&df->axes[a].cvs[v_idx].value,
2310 &cell->axes[a].cvs[v_idx].value,
2311 var_get_width (nest->vars[v_idx])))
2320 d = xmalloc (sizeof *d);
2321 *d = (struct ctables_domain) { .example = cell };
2322 hmap_insert (&t->domains[domain], &d->node, hash);
2326 static const struct ctables_category *
2327 ctables_categories_match (const struct ctables_categories *c,
2328 const union value *v, const struct variable *var)
2330 const struct ctables_category *othernm = NULL;
2331 for (size_t i = c->n_cats; i-- > 0; )
2333 const struct ctables_category *cat = &c->cats[i];
2337 if (cat->number == v->f)
2345 if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2346 && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2351 if (var_is_value_missing (var, v))
2368 return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2373 return var_is_value_missing (var, v) ? NULL : othernm;
2376 static const struct ctables_category *
2377 ctables_categories_total (const struct ctables_categories *c)
2379 const struct ctables_category *first = &c->cats[0];
2380 const struct ctables_category *last = &c->cats[c->n_cats - 1];
2381 return (first->type == CCT_TOTAL ? first
2382 : last->type == CCT_TOTAL ? last
2386 static struct ctables_cell *
2387 ctables_cell_insert__ (struct ctables_table *t, const struct ccase *c,
2388 size_t ix[PIVOT_N_AXES],
2389 const struct ctables_category *cats[PIVOT_N_AXES][10])
2391 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2394 enum ctables_summary_variant sv = CSV_CELL;
2395 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2397 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2398 hash = hash_int (ix[a], hash);
2399 for (size_t i = 0; i < nest->n; i++)
2400 if (i != nest->scale_idx)
2402 hash = hash_pointer (cats[a][i], hash);
2403 if (cats[a][i]->type != CCT_TOTAL
2404 && cats[a][i]->type != CCT_SUBTOTAL
2405 && cats[a][i]->type != CCT_HSUBTOTAL)
2406 hash = value_hash (case_data (c, nest->vars[i]),
2407 var_get_width (nest->vars[i]), hash);
2413 struct ctables_cell *cell;
2414 HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &t->cells)
2416 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2418 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2419 if (cell->axes[a].nest_idx != ix[a])
2421 for (size_t i = 0; i < nest->n; i++)
2422 if (i != nest->scale_idx
2423 && (cats[a][i] != cell->axes[a].cvs[i].category
2424 || (cats[a][i]->type != CCT_TOTAL
2425 && cats[a][i]->type != CCT_SUBTOTAL
2426 && cats[a][i]->type != CCT_HSUBTOTAL
2427 && !value_equal (case_data (c, nest->vars[i]),
2428 &cell->axes[a].cvs[i].value,
2429 var_get_width (nest->vars[i])))))
2438 cell = xmalloc (sizeof *cell);
2441 cell->contributes_to_domains = true;
2442 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2444 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2445 cell->axes[a].nest_idx = ix[a];
2446 cell->axes[a].cvs = (nest->n
2447 ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2449 for (size_t i = 0; i < nest->n; i++)
2451 const struct ctables_category *cat = cats[a][i];
2453 if (i != nest->scale_idx)
2455 const struct ctables_category *subtotal = cat->subtotal;
2456 if (subtotal && subtotal->type == CCT_HSUBTOTAL)
2459 if (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL)
2460 cell->contributes_to_domains = false;
2463 cell->axes[a].cvs[i].category = cat;
2464 value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2465 var_get_width (nest->vars[i]));
2469 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2470 cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2471 for (size_t i = 0; i < specs->n; i++)
2472 ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2473 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2474 cell->domains[dt] = ctables_domain_insert (t, cell, dt);
2475 hmap_insert (&t->cells, &cell->node, hash);
2480 ctables_cell_add__ (struct ctables_table *t, const struct ccase *c,
2481 size_t ix[PIVOT_N_AXES],
2482 const struct ctables_category *cats[PIVOT_N_AXES][10],
2485 struct ctables_cell *cell = ctables_cell_insert__ (t, c, ix, cats);
2486 const struct ctables_nest *ss = &t->stacks[t->summary_axis].nests[ix[t->summary_axis]];
2488 const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2489 for (size_t i = 0; i < specs->n; i++)
2490 ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2491 case_data (c, specs->var), weight);
2492 if (cell->contributes_to_domains)
2493 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2494 cell->domains[dt]->valid += weight;
2498 recurse_totals (struct ctables_table *t, const struct ccase *c,
2499 size_t ix[PIVOT_N_AXES],
2500 const struct ctables_category *cats[PIVOT_N_AXES][10],
2502 enum pivot_axis_type start_axis, size_t start_nest)
2504 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2506 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2507 for (size_t i = start_nest; i < nest->n; i++)
2509 if (i == nest->scale_idx)
2512 const struct variable *var = nest->vars[i];
2514 const struct ctables_category *total = ctables_categories_total (
2515 t->categories[var_get_dict_index (var)]);
2518 const struct ctables_category *save = cats[a][i];
2520 ctables_cell_add__ (t, c, ix, cats, weight);
2521 recurse_totals (t, c, ix, cats, weight, a, i + 1);
2530 recurse_subtotals (struct ctables_table *t, const struct ccase *c,
2531 size_t ix[PIVOT_N_AXES],
2532 const struct ctables_category *cats[PIVOT_N_AXES][10],
2534 enum pivot_axis_type start_axis, size_t start_nest)
2536 for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2538 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2539 for (size_t i = start_nest; i < nest->n; i++)
2541 if (i == nest->scale_idx)
2544 const struct ctables_category *save = cats[a][i];
2547 cats[a][i] = save->subtotal;
2548 ctables_cell_add__ (t, c, ix, cats, weight);
2549 recurse_subtotals (t, c, ix, cats, weight, a, i + 1);
2558 ctables_cell_insert (struct ctables_table *t,
2559 const struct ccase *c,
2560 size_t ir, size_t ic, size_t il,
2563 size_t ix[PIVOT_N_AXES] = {
2564 [PIVOT_AXIS_ROW] = ir,
2565 [PIVOT_AXIS_COLUMN] = ic,
2566 [PIVOT_AXIS_LAYER] = il,
2569 const struct ctables_category *cats[PIVOT_N_AXES][10];
2570 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2572 const struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
2573 for (size_t i = 0; i < nest->n; i++)
2575 if (i == nest->scale_idx)
2578 const struct variable *var = nest->vars[i];
2579 const union value *value = case_data (c, var);
2581 if (var_is_numeric (var) && value->f == SYSMIS)
2584 cats[a][i] = ctables_categories_match (
2585 t->categories[var_get_dict_index (var)], value, var);
2591 ctables_cell_add__ (t, c, ix, cats, weight);
2593 recurse_totals (t, c, ix, cats, weight, 0, 0);
2594 recurse_subtotals (t, c, ix, cats, weight, 0, 0);
2599 const struct ctables_summary_spec_set *set;
2604 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
2606 const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
2607 const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
2608 if (as->function != bs->function)
2609 return as->function > bs->function ? 1 : -1;
2610 else if (as->percentile != bs->percentile)
2611 return as->percentile < bs->percentile ? 1 : -1;
2612 return strcmp (as->label, bs->label);
2615 static struct pivot_value *
2616 ctables_category_create_label (const struct ctables_category *cat,
2617 const struct variable *var,
2618 const union value *value)
2620 return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL || cat->type == CCT_HSUBTOTAL
2621 ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
2622 : pivot_value_new_var_value (var, value));
2625 static struct ctables_value *
2626 ctables_value_find__ (struct ctables_table *t, const union value *value,
2627 int width, unsigned int hash)
2629 struct ctables_value *clv;
2630 HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
2631 hash, &t->clabels_values_map)
2632 if (value_equal (value, &clv->value, width))
2637 static struct ctables_value *
2638 ctables_value_find (struct ctables_table *t,
2639 const union value *value, int width)
2641 return ctables_value_find__ (t, value, width,
2642 value_hash (value, width, 0));
2646 ctables_table_output (struct ctables *ct, struct ctables_table *t)
2648 struct pivot_table *pt = pivot_table_create__ (
2650 ? pivot_value_new_user_text (t->title, SIZE_MAX)
2651 : pivot_value_new_text (N_("Custom Tables"))),
2654 pivot_table_set_caption (
2655 pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2657 pivot_table_set_caption (
2658 pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2660 bool summary_dimension = (t->summary_axis != t->slabels_axis
2661 || (!t->slabels_visible
2662 && t->summary_specs.n > 1));
2663 if (summary_dimension)
2665 struct pivot_dimension *d = pivot_dimension_create (
2666 pt, t->slabels_axis, N_("Statistics"));
2667 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2668 if (!t->slabels_visible)
2669 d->hide_all_labels = true;
2670 for (size_t i = 0; i < specs->n; i++)
2671 pivot_category_create_leaf (
2672 d->root, pivot_value_new_text (specs->specs[i].label));
2675 bool categories_dimension = t->clabels_example != NULL;
2676 if (categories_dimension)
2678 struct pivot_dimension *d = pivot_dimension_create (
2679 pt, t->label_axis[t->clabels_from_axis],
2680 t->clabels_from_axis == PIVOT_AXIS_ROW
2681 ? N_("Row Categories")
2682 : N_("Column Categories"));
2683 const struct variable *var = t->clabels_example;
2684 const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
2685 for (size_t i = 0; i < t->n_clabels_values; i++)
2687 const struct ctables_value *value = t->clabels_values[i];
2688 const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
2689 assert (cat != NULL);
2690 pivot_category_create_leaf (d->root, ctables_category_create_label (
2691 cat, t->clabels_example, &value->value));
2695 pivot_table_set_look (pt, ct->look);
2696 struct pivot_dimension *d[PIVOT_N_AXES];
2697 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2699 static const char *names[] = {
2700 [PIVOT_AXIS_ROW] = N_("Rows"),
2701 [PIVOT_AXIS_COLUMN] = N_("Columns"),
2702 [PIVOT_AXIS_LAYER] = N_("Layers"),
2704 d[a] = (t->axes[a] || a == t->summary_axis
2705 ? pivot_dimension_create (pt, a, names[a])
2710 assert (t->axes[a]);
2712 struct ctables_cell **sorted = xnmalloc (t->cells.count, sizeof *sorted);
2713 size_t n_sorted = 0;
2715 struct ctables_cell *cell;
2716 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2718 sorted[n_sorted++] = cell;
2719 assert (n_sorted <= t->cells.count);
2721 struct ctables_cell_sort_aux aux = { .t = t, .a = a };
2722 sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
2724 size_t max_depth = 0;
2725 for (size_t j = 0; j < t->stacks[a].n; j++)
2726 if (t->stacks[a].nests[j].n > max_depth)
2727 max_depth = t->stacks[a].nests[j].n;
2729 /* Pivot categories:
2731 - variable label for nest->vars[0], if vlabel != CTVL_NONE
2732 - category for nest->vars[0], if nest->scale_idx != 0
2733 - variable label for nest->vars[1], if vlabel != CTVL_NONE
2734 - category for nest->vars[1], if nest->scale_idx != 1
2736 - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
2737 - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
2738 - summary function, if 'a == t->slabels_axis && a ==
2741 Additional dimensions:
2743 - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
2745 - If 't->label_axis[b] == a' for some 'b != a', add a category
2749 struct ctables_level
2751 enum ctables_level_type
2753 CTL_VAR, /* Variable label for nest->vars[var_idx]. */
2754 CTL_CATEGORY, /* Category for nest->vars[var_idx]. */
2755 CTL_SUMMARY, /* Summary functions. */
2761 struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
2762 size_t n_levels = 0;
2764 struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
2766 for (size_t j = 0; j < n_sorted; j++)
2768 struct ctables_cell *cell = sorted[j];
2769 struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
2770 const struct ctables_nest *nest = &t->stacks[a].nests[cell->axes[a].nest_idx];
2772 bool new_subtable = !prev || prev->axes[a].nest_idx != cell->axes[a].nest_idx;
2776 for (size_t k = 0; k < nest->n; k++)
2778 enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
2779 if (vlabel != CTVL_NONE)
2781 levels[n_levels++] = (struct ctables_level) {
2787 if (nest->scale_idx != k
2788 && (k != nest->n - 1 || t->label_axis[a] == a))
2790 levels[n_levels++] = (struct ctables_level) {
2791 .type = CTL_CATEGORY,
2797 if (!summary_dimension && a == t->slabels_axis)
2799 levels[n_levels++] = (struct ctables_level) {
2800 .type = CTL_SUMMARY,
2801 .var_idx = SIZE_MAX,
2806 size_t n_common = 0;
2809 for (; n_common < n_levels; n_common++)
2811 const struct ctables_level *level = &levels[n_common];
2812 if (level->type == CTL_CATEGORY)
2814 size_t var_idx = level->var_idx;
2815 const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
2816 if (prev->axes[a].cvs[var_idx].category != c)
2818 else if (c->type != CCT_SUBTOTAL
2819 && c->type != CCT_HSUBTOTAL
2820 && c->type != CCT_TOTAL
2821 && !value_equal (&prev->axes[a].cvs[var_idx].value,
2822 &cell->axes[a].cvs[var_idx].value,
2823 var_get_type (nest->vars[var_idx])))
2829 for (size_t k = n_common; k < n_levels; k++)
2831 const struct ctables_level *level = &levels[k];
2832 struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
2833 if (level->type == CTL_SUMMARY)
2835 const struct ctables_summary_spec_set *specs = &t->summary_specs;
2836 for (size_t m = 0; m < specs->n; m++)
2838 int leaf = pivot_category_create_leaf (
2839 parent, pivot_value_new_text (specs->specs[m].label));
2846 const struct variable *var = nest->vars[level->var_idx];
2847 struct pivot_value *label;
2848 if (level->type == CTL_VAR)
2849 label = pivot_value_new_variable (var);
2850 else if (level->type == CTL_CATEGORY)
2852 const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
2853 label = ctables_category_create_label (cv->category,
2859 if (k == n_levels - 1)
2860 prev_leaf = pivot_category_create_leaf (parent, label);
2862 groups[k] = pivot_category_create_group__ (parent, label);
2866 cell->axes[a].leaf = prev_leaf;
2872 struct ctables_cell *cell;
2873 HMAP_FOR_EACH (cell, struct ctables_cell, node, &t->cells)
2878 const struct ctables_nest *specs_nest = &t->stacks[t->summary_axis].nests[cell->axes[t->summary_axis].nest_idx];
2879 const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
2880 for (size_t j = 0; j < specs->n; j++)
2883 size_t n_dindexes = 0;
2885 if (summary_dimension)
2886 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
2888 if (categories_dimension)
2890 const struct ctables_nest *clabels_nest = &t->stacks[t->clabels_from_axis].nests[cell->axes[t->clabels_from_axis].nest_idx];
2891 const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
2892 const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
2893 const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
2894 assert (ctv != NULL);
2895 dindexes[n_dindexes++] = ctv->leaf;
2898 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2901 int leaf = cell->axes[a].leaf;
2902 if (a == t->summary_axis && !summary_dimension)
2904 dindexes[n_dindexes++] = leaf;
2907 double d = ctables_summary_value (cell, &cell->summaries[j], &specs->specs[j]);
2908 struct pivot_value *value = pivot_value_new_number (d);
2909 value->numeric.format = specs->specs[j].format;
2910 pivot_table_put (pt, dindexes, n_dindexes, value);
2914 pivot_table_submit (pt);
2918 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
2920 enum pivot_axis_type label_pos = t->label_axis[a];
2924 t->clabels_from_axis = a;
2926 const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
2927 const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
2929 const struct ctables_stack *stack = &t->stacks[a];
2933 const struct ctables_nest *n0 = &stack->nests[0];
2935 const struct variable *v0 = n0->vars[n0->n - 1];
2936 struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
2937 t->clabels_example = v0;
2939 for (size_t i = 0; i < c0->n_cats; i++)
2940 if (c0->cats[i].type == CCT_FUNCTION)
2942 msg (SE, _("%s=%s is not allowed with sorting based "
2943 "on a summary function."),
2944 subcommand_name, pos_name);
2947 if (n0->n - 1 == n0->scale_idx)
2949 msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
2950 "but %s is a scale variable."),
2951 subcommand_name, pos_name, var_get_name (v0));
2955 for (size_t i = 1; i < stack->n; i++)
2957 const struct ctables_nest *ni = &stack->nests[i];
2959 const struct variable *vi = ni->vars[ni->n - 1];
2960 struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
2962 if (ni->n - 1 == ni->scale_idx)
2964 msg (SE, _("%s=%s requires the variables to be moved to be "
2965 "categorical, but %s is a scale variable."),
2966 subcommand_name, pos_name, var_get_name (vi));
2969 if (var_get_width (v0) != var_get_width (vi))
2971 msg (SE, _("%s=%s requires the variables to be "
2972 "moved to have the same width, but %s has "
2973 "width %d and %s has width %d."),
2974 subcommand_name, pos_name,
2975 var_get_name (v0), var_get_width (v0),
2976 var_get_name (vi), var_get_width (vi));
2979 if (!val_labs_equal (var_get_value_labels (v0),
2980 var_get_value_labels (vi)))
2982 msg (SE, _("%s=%s requires the variables to be "
2983 "moved to have the same value labels, but %s "
2984 "and %s have different value labels."),
2985 subcommand_name, pos_name,
2986 var_get_name (v0), var_get_name (vi));
2989 if (!ctables_categories_equal (c0, ci))
2991 msg (SE, _("%s=%s requires the variables to be "
2992 "moved to have the same category "
2993 "specifications, but %s and %s have different "
2994 "category specifications."),
2995 subcommand_name, pos_name,
2996 var_get_name (v0), var_get_name (vi));
3005 ctables_prepare_table (struct ctables_table *t)
3007 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3010 t->stacks[a] = enumerate_fts (a, t->axes[a]);
3012 for (size_t j = 0; j < t->stacks[a].n; j++)
3014 struct ctables_nest *nest = &t->stacks[a].nests[j];
3015 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3017 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3018 nest->n_domains[dt] = 0;
3020 for (size_t k = 0; k < nest->n; k++)
3022 if (k == nest->scale_idx)
3031 if (a != PIVOT_AXIS_LAYER)
3038 if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3039 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3040 : a == PIVOT_AXIS_ROW)
3042 if (k == nest->n - 1
3043 || (nest->scale_idx == nest->n - 1
3044 && k == nest->n - 2))
3050 if (a == PIVOT_AXIS_COLUMN)
3055 if (a == PIVOT_AXIS_ROW)
3060 nest->domains[dt][nest->n_domains[dt]++] = k;
3067 struct ctables_nest *nest = xmalloc (sizeof *nest);
3068 *nest = (struct ctables_nest) { .n = 0 };
3069 t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3072 struct ctables_stack *stack = &t->stacks[t->summary_axis];
3073 for (size_t i = 0; i < stack->n; i++)
3075 struct ctables_nest *nest = &stack->nests[i];
3076 if (!nest->specs[CSV_CELL].n)
3078 struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3079 specs->specs = xmalloc (sizeof *specs->specs);
3082 enum ctables_summary_function function
3083 = specs->var ? CTSF_MEAN : CTSF_COUNT;
3084 struct ctables_var var = { .is_mrset = false, .var = specs->var };
3086 *specs->specs = (struct ctables_summary_spec) {
3087 .function = function,
3088 .format = ctables_summary_default_format (function, &var),
3089 .label = ctables_summary_default_label (function, 0),
3092 specs->var = nest->vars[0];
3094 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3095 &nest->specs[CSV_CELL]);
3097 else if (!nest->specs[CSV_TOTAL].n)
3098 ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3099 &nest->specs[CSV_CELL]);
3102 struct ctables_summary_spec_set *merged = &t->summary_specs;
3103 struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3105 for (size_t j = 0; j < stack->n; j++)
3107 const struct ctables_nest *nest = &stack->nests[j];
3109 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3110 items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3115 struct merge_item min = items[0];
3116 for (size_t j = 1; j < n_left; j++)
3117 if (merge_item_compare_3way (&items[j], &min) < 0)
3120 if (merged->n >= merged->allocated)
3121 merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3122 sizeof *merged->specs);
3123 merged->specs[merged->n++] = min.set->specs[min.ofs];
3125 for (size_t j = 0; j < n_left; )
3127 if (merge_item_compare_3way (&items[j], &min) == 0)
3129 struct merge_item *item = &items[j];
3130 item->set->specs[item->ofs].axis_idx = merged->n - 1;
3131 if (++item->ofs >= item->set->n)
3133 items[j] = items[--n_left];
3142 for (size_t j = 0; j < merged->n; j++)
3143 printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3145 for (size_t j = 0; j < stack->n; j++)
3147 const struct ctables_nest *nest = &stack->nests[j];
3148 for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3150 const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3151 for (size_t k = 0; k < specs->n; k++)
3152 printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3153 specs->specs[k].axis_idx);
3159 return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3160 && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3164 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3165 enum pivot_axis_type a)
3167 struct ctables_stack *stack = &t->stacks[a];
3168 for (size_t i = 0; i < stack->n; i++)
3170 const struct ctables_nest *nest = &stack->nests[i];
3171 const struct variable *var = nest->vars[nest->n - 1];
3172 int width = var_get_width (var);
3173 const union value *value = case_data (c, var);
3175 if (var_is_numeric (var) && value->f == SYSMIS)
3178 if (!ctables_categories_match (t->categories [var_get_dict_index (var)],
3182 unsigned int hash = value_hash (value, width, 0);
3184 struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3187 clv = xmalloc (sizeof *clv);
3188 value_clone (&clv->value, value, width);
3189 hmap_insert (&t->clabels_values_map, &clv->node, hash);
3195 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3197 const struct ctables_value *const *ap = a_;
3198 const struct ctables_value *const *bp = b_;
3199 const struct ctables_value *a = *ap;
3200 const struct ctables_value *b = *bp;
3201 const int *width = width_;
3202 return value_compare_3way (&a->value, &b->value, *width);
3206 ctables_sort_clabels_values (struct ctables_table *t)
3208 int width = var_get_width (t->clabels_example);
3210 size_t n = hmap_count (&t->clabels_values_map);
3211 t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
3213 struct ctables_value *clv;
3215 HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
3216 t->clabels_values[i++] = clv;
3217 t->n_clabels_values = n;
3220 sort (t->clabels_values, n, sizeof *t->clabels_values,
3221 compare_clabels_values_3way, &width);
3223 for (size_t i = 0; i < n; i++)
3224 t->clabels_values[i]->leaf = i;
3228 ctables_execute (struct dataset *ds, struct ctables *ct)
3230 struct casereader *input = casereader_create_filter_weight (proc_open (ds),
3233 bool warn_on_invalid = true;
3234 double total_weight = 0;
3235 for (struct ccase *c = casereader_read (input); c;
3236 case_unref (c), c = casereader_read (input))
3238 double weight = dict_get_case_weight (dataset_dict (ds), c,
3240 total_weight += weight;
3242 for (size_t i = 0; i < ct->n_tables; i++)
3244 struct ctables_table *t = ct->tables[i];
3246 for (size_t ir = 0; ir < t->stacks[PIVOT_AXIS_ROW].n; ir++)
3247 for (size_t ic = 0; ic < t->stacks[PIVOT_AXIS_COLUMN].n; ic++)
3248 for (size_t il = 0; il < t->stacks[PIVOT_AXIS_LAYER].n; il++)
3249 ctables_cell_insert (t, c, ir, ic, il, weight);
3251 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3252 if (t->label_axis[a] != a)
3253 ctables_insert_clabels_values (t, c, a);
3256 casereader_destroy (input);
3258 for (size_t i = 0; i < ct->n_tables; i++)
3260 struct ctables_table *t = ct->tables[i];
3262 if (t->clabels_example)
3263 ctables_sort_clabels_values (t);
3265 ctables_table_output (ct, ct->tables[i]);
3267 return proc_commit (ds);
3271 cmd_ctables (struct lexer *lexer, struct dataset *ds)
3273 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3274 enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
3275 enum settings_value_show tvars = settings_get_show_variables ();
3276 for (size_t i = 0; i < n_vars; i++)
3277 vlabels[i] = (enum ctables_vlabel) tvars;
3279 struct ctables *ct = xmalloc (sizeof *ct);
3280 *ct = (struct ctables) {
3281 .look = pivot_table_look_unshare (pivot_table_look_ref (
3282 pivot_table_look_get_default ())),
3284 .hide_threshold = 5,
3286 ct->look->omit_empty = false;
3288 if (!lex_force_match (lexer, T_SLASH))
3291 while (!lex_match_id (lexer, "TABLE"))
3293 if (lex_match_id (lexer, "FORMAT"))
3295 double widths[2] = { SYSMIS, SYSMIS };
3296 double units_per_inch = 72.0;
3298 while (lex_token (lexer) != T_SLASH)
3300 if (lex_match_id (lexer, "MINCOLWIDTH"))
3302 if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
3305 else if (lex_match_id (lexer, "MAXCOLWIDTH"))
3307 if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
3310 else if (lex_match_id (lexer, "UNITS"))
3312 lex_match (lexer, T_EQUALS);
3313 if (lex_match_id (lexer, "POINTS"))
3314 units_per_inch = 72.0;
3315 else if (lex_match_id (lexer, "INCHES"))
3316 units_per_inch = 1.0;
3317 else if (lex_match_id (lexer, "CM"))
3318 units_per_inch = 2.54;
3321 lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
3325 else if (lex_match_id (lexer, "EMPTY"))
3330 lex_match (lexer, T_EQUALS);
3331 if (lex_match_id (lexer, "ZERO"))
3333 /* Nothing to do. */
3335 else if (lex_match_id (lexer, "BLANK"))
3336 ct->zero = xstrdup ("");
3337 else if (lex_force_string (lexer))
3339 ct->zero = ss_xstrdup (lex_tokss (lexer));
3345 else if (lex_match_id (lexer, "MISSING"))
3347 lex_match (lexer, T_EQUALS);
3348 if (!lex_force_string (lexer))
3352 ct->missing = (strcmp (lex_tokcstr (lexer), ".")
3353 ? ss_xstrdup (lex_tokss (lexer))
3359 lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
3360 "UNITS", "EMPTY", "MISSING");
3365 if (widths[0] != SYSMIS && widths[1] != SYSMIS
3366 && widths[0] > widths[1])
3368 msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
3372 for (size_t i = 0; i < 2; i++)
3373 if (widths[i] != SYSMIS)
3375 int *wr = ct->look->width_ranges[TABLE_HORZ];
3376 wr[i] = widths[i] / units_per_inch * 96.0;
3381 else if (lex_match_id (lexer, "VLABELS"))
3383 if (!lex_force_match_id (lexer, "VARIABLES"))
3385 lex_match (lexer, T_EQUALS);
3387 struct variable **vars;
3389 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
3393 if (!lex_force_match_id (lexer, "DISPLAY"))
3398 lex_match (lexer, T_EQUALS);
3400 enum ctables_vlabel vlabel;
3401 if (lex_match_id (lexer, "DEFAULT"))
3402 vlabel = (enum ctables_vlabel) settings_get_show_variables ();
3403 else if (lex_match_id (lexer, "NAME"))
3405 else if (lex_match_id (lexer, "LABEL"))
3406 vlabel = CTVL_LABEL;
3407 else if (lex_match_id (lexer, "BOTH"))
3409 else if (lex_match_id (lexer, "NONE"))
3413 lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
3419 for (size_t i = 0; i < n_vars; i++)
3420 ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
3423 else if (lex_match_id (lexer, "MRSETS"))
3425 if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
3427 lex_match (lexer, T_EQUALS);
3428 if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
3431 else if (lex_match_id (lexer, "SMISSING"))
3433 if (lex_match_id (lexer, "VARIABLE"))
3434 ct->smissing_listwise = false;
3435 else if (lex_match_id (lexer, "LISTWISE"))
3436 ct->smissing_listwise = true;
3439 lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
3444 else if (lex_match_id (lexer, "WEIGHT"))
3446 if (!lex_force_match_id (lexer, "VARIABLE"))
3448 lex_match (lexer, T_EQUALS);
3449 ct->base_weight = parse_variable (lexer, dataset_dict (ds));
3450 if (!ct->base_weight)
3453 else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
3455 if (!lex_force_match_id (lexer, "COUNT"))
3457 lex_match (lexer, T_EQUALS);
3458 if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
3460 ct->hide_threshold = lex_integer (lexer);
3465 lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
3466 "SMISSING", "PCOMPUTE", "PPROPERTIES",
3467 "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
3471 if (!lex_force_match (lexer, T_SLASH))
3475 size_t allocated_tables = 0;
3478 if (ct->n_tables >= allocated_tables)
3479 ct->tables = x2nrealloc (ct->tables, &allocated_tables,
3480 sizeof *ct->tables);
3482 struct ctables_category *cat = xmalloc (sizeof *cat);
3483 *cat = (struct ctables_category) {
3485 .include_missing = false,
3486 .sort_ascending = true,
3489 struct ctables_categories *c = xmalloc (sizeof *c);
3490 size_t n_vars = dict_get_n_vars (dataset_dict (ds));
3491 *c = (struct ctables_categories) {
3497 struct ctables_categories **categories = xnmalloc (n_vars,
3498 sizeof *categories);
3499 for (size_t i = 0; i < n_vars; i++)
3502 struct ctables_table *t = xmalloc (sizeof *t);
3503 *t = (struct ctables_table) {
3504 .cells = HMAP_INITIALIZER (t->cells),
3505 .slabels_axis = PIVOT_AXIS_COLUMN,
3506 .slabels_visible = true,
3507 .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
3509 [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
3510 [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
3511 [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
3513 .clabels_from_axis = PIVOT_AXIS_LAYER,
3514 .categories = categories,
3515 .n_categories = n_vars,
3518 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3519 hmap_init (&t->domains[dt]);
3520 ct->tables[ct->n_tables++] = t;
3522 lex_match (lexer, T_EQUALS);
3523 if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
3525 if (lex_match (lexer, T_BY))
3527 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3528 ct, t, PIVOT_AXIS_COLUMN))
3531 if (lex_match (lexer, T_BY))
3533 if (!ctables_axis_parse (lexer, dataset_dict (ds),
3534 ct, t, PIVOT_AXIS_LAYER))
3539 if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
3540 && !t->axes[PIVOT_AXIS_LAYER])
3542 lex_error (lexer, _("At least one variable must be specified."));
3546 const struct ctables_axis *scales[PIVOT_N_AXES];
3547 size_t n_scales = 0;
3548 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3550 scales[a] = find_scale (t->axes[a]);
3556 msg (SE, _("Scale variables may appear only on one axis."));
3557 if (scales[PIVOT_AXIS_ROW])
3558 msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
3559 _("This scale variable appears on the rows axis."));
3560 if (scales[PIVOT_AXIS_COLUMN])
3561 msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
3562 _("This scale variable appears on the columns axis."));
3563 if (scales[PIVOT_AXIS_LAYER])
3564 msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
3565 _("This scale variable appears on the layer axis."));
3569 const struct ctables_axis *summaries[PIVOT_N_AXES];
3570 size_t n_summaries = 0;
3571 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3573 summaries[a] = (scales[a]
3575 : find_categorical_summary_spec (t->axes[a]));
3579 if (n_summaries > 1)
3581 msg (SE, _("Summaries may appear only on one axis."));
3582 if (summaries[PIVOT_AXIS_ROW])
3583 msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
3584 _("This variable on the rows axis has a summary."));
3585 if (summaries[PIVOT_AXIS_COLUMN])
3586 msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
3587 _("This variable on the columns axis has a summary."));
3588 if (summaries[PIVOT_AXIS_LAYER])
3589 msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
3590 _("This variable on the layers axis has a summary."));
3593 for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3594 if (n_summaries ? summaries[a] : t->axes[a])
3596 t->summary_axis = a;
3600 if (lex_token (lexer) == T_ENDCMD)
3602 if (!ctables_prepare_table (t))
3606 if (!lex_force_match (lexer, T_SLASH))
3609 while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
3611 if (lex_match_id (lexer, "SLABELS"))
3613 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3615 if (lex_match_id (lexer, "POSITION"))
3617 lex_match (lexer, T_EQUALS);
3618 if (lex_match_id (lexer, "COLUMN"))
3619 t->slabels_axis = PIVOT_AXIS_COLUMN;
3620 else if (lex_match_id (lexer, "ROW"))
3621 t->slabels_axis = PIVOT_AXIS_ROW;
3622 else if (lex_match_id (lexer, "LAYER"))
3623 t->slabels_axis = PIVOT_AXIS_LAYER;
3626 lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
3630 else if (lex_match_id (lexer, "VISIBLE"))
3632 lex_match (lexer, T_EQUALS);
3633 if (!parse_bool (lexer, &t->slabels_visible))
3638 lex_error_expecting (lexer, "POSITION", "VISIBLE");
3643 else if (lex_match_id (lexer, "CLABELS"))
3645 while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
3647 if (lex_match_id (lexer, "AUTO"))
3649 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
3650 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
3652 else if (lex_match_id (lexer, "ROWLABELS"))
3654 lex_match (lexer, T_EQUALS);
3655 if (lex_match_id (lexer, "OPPOSITE"))
3656 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
3657 else if (lex_match_id (lexer, "LAYER"))
3658 t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
3661 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3665 else if (lex_match_id (lexer, "COLLABELS"))
3667 lex_match (lexer, T_EQUALS);
3668 if (lex_match_id (lexer, "OPPOSITE"))
3669 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
3670 else if (lex_match_id (lexer, "LAYER"))
3671 t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
3674 lex_error_expecting (lexer, "OPPOSITE", "LAYER");
3680 lex_error_expecting (lexer, "AUTO", "ROWLABELS",
3686 else if (lex_match_id (lexer, "CRITERIA"))
3688 if (!lex_force_match_id (lexer, "CILEVEL"))
3690 lex_match (lexer, T_EQUALS);
3692 if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
3694 t->cilevel = lex_number (lexer);
3697 else if (lex_match_id (lexer, "CATEGORIES"))
3699 if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
3702 else if (lex_match_id (lexer, "TITLES"))
3707 if (lex_match_id (lexer, "CAPTION"))
3708 textp = &t->caption;
3709 else if (lex_match_id (lexer, "CORNER"))
3711 else if (lex_match_id (lexer, "TITLE"))
3715 lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
3718 lex_match (lexer, T_EQUALS);
3720 struct string s = DS_EMPTY_INITIALIZER;
3721 while (lex_is_string (lexer))
3723 if (!ds_is_empty (&s))
3724 ds_put_byte (&s, ' ');
3725 ds_put_substring (&s, lex_tokss (lexer));
3729 *textp = ds_steal_cstr (&s);
3731 while (lex_token (lexer) != T_SLASH
3732 && lex_token (lexer) != T_ENDCMD);
3734 else if (lex_match_id (lexer, "SIGTEST"))
3738 t->chisq = xmalloc (sizeof *t->chisq);
3739 *t->chisq = (struct ctables_chisq) {
3741 .include_mrsets = true,
3742 .all_visible = true,
3748 if (lex_match_id (lexer, "TYPE"))
3750 lex_match (lexer, T_EQUALS);
3751 if (!lex_force_match_id (lexer, "CHISQUARE"))
3754 else if (lex_match_id (lexer, "ALPHA"))
3756 lex_match (lexer, T_EQUALS);
3757 if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
3759 t->chisq->alpha = lex_number (lexer);
3762 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3764 lex_match (lexer, T_EQUALS);
3765 if (parse_bool (lexer, &t->chisq->include_mrsets))
3768 else if (lex_match_id (lexer, "CATEGORIES"))
3770 lex_match (lexer, T_EQUALS);
3771 if (lex_match_id (lexer, "ALLVISIBLE"))
3772 t->chisq->all_visible = true;
3773 else if (lex_match_id (lexer, "SUBTOTALS"))
3774 t->chisq->all_visible = false;
3777 lex_error_expecting (lexer,
3778 "ALLVISIBLE", "SUBTOTALS");
3784 lex_error_expecting (lexer, "TYPE", "ALPHA",
3785 "INCLUDEMRSETS", "CATEGORIES");
3789 while (lex_token (lexer) != T_SLASH
3790 && lex_token (lexer) != T_ENDCMD);
3792 else if (lex_match_id (lexer, "COMPARETEST"))
3796 t->pairwise = xmalloc (sizeof *t->pairwise);
3797 *t->pairwise = (struct ctables_pairwise) {
3799 .alpha = { .05, .05 },
3800 .adjust = BONFERRONI,
3801 .include_mrsets = true,
3802 .meansvariance_allcats = true,
3803 .all_visible = true,
3812 if (lex_match_id (lexer, "TYPE"))
3814 lex_match (lexer, T_EQUALS);
3815 if (lex_match_id (lexer, "PROP"))
3816 t->pairwise->type = PROP;
3817 else if (lex_match_id (lexer, "MEAN"))
3818 t->pairwise->type = MEAN;
3821 lex_error_expecting (lexer, "PROP", "MEAN");
3825 else if (lex_match_id (lexer, "ALPHA"))
3827 lex_match (lexer, T_EQUALS);
3829 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3831 double a0 = lex_number (lexer);
3834 lex_match (lexer, T_COMMA);
3835 if (lex_is_number (lexer))
3837 if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
3839 double a1 = lex_number (lexer);
3842 t->pairwise->alpha[0] = MIN (a0, a1);
3843 t->pairwise->alpha[1] = MAX (a0, a1);
3846 t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
3848 else if (lex_match_id (lexer, "ADJUST"))
3850 lex_match (lexer, T_EQUALS);
3851 if (lex_match_id (lexer, "BONFERRONI"))
3852 t->pairwise->adjust = BONFERRONI;
3853 else if (lex_match_id (lexer, "BH"))
3854 t->pairwise->adjust = BH;
3855 else if (lex_match_id (lexer, "NONE"))
3856 t->pairwise->adjust = 0;
3859 lex_error_expecting (lexer, "BONFERRONI", "BH",
3864 else if (lex_match_id (lexer, "INCLUDEMRSETS"))
3866 lex_match (lexer, T_EQUALS);
3867 if (!parse_bool (lexer, &t->pairwise->include_mrsets))
3870 else if (lex_match_id (lexer, "MEANSVARIANCE"))
3872 lex_match (lexer, T_EQUALS);
3873 if (lex_match_id (lexer, "ALLCATS"))
3874 t->pairwise->meansvariance_allcats = true;
3875 else if (lex_match_id (lexer, "TESTEDCATS"))
3876 t->pairwise->meansvariance_allcats = false;
3879 lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
3883 else if (lex_match_id (lexer, "CATEGORIES"))
3885 lex_match (lexer, T_EQUALS);
3886 if (lex_match_id (lexer, "ALLVISIBLE"))
3887 t->pairwise->all_visible = true;
3888 else if (lex_match_id (lexer, "SUBTOTALS"))
3889 t->pairwise->all_visible = false;
3892 lex_error_expecting (lexer, "ALLVISIBLE",
3897 else if (lex_match_id (lexer, "MERGE"))
3899 lex_match (lexer, T_EQUALS);
3900 if (!parse_bool (lexer, &t->pairwise->merge))
3903 else if (lex_match_id (lexer, "STYLE"))
3905 lex_match (lexer, T_EQUALS);
3906 if (lex_match_id (lexer, "APA"))
3907 t->pairwise->apa_style = true;
3908 else if (lex_match_id (lexer, "SIMPLE"))
3909 t->pairwise->apa_style = false;
3912 lex_error_expecting (lexer, "APA", "SIMPLE");
3916 else if (lex_match_id (lexer, "SHOWSIG"))
3918 lex_match (lexer, T_EQUALS);
3919 if (!parse_bool (lexer, &t->pairwise->show_sig))
3924 lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
3925 "INCLUDEMRSETS", "MEANSVARIANCE",
3926 "CATEGORIES", "MERGE", "STYLE",
3931 while (lex_token (lexer) != T_SLASH
3932 && lex_token (lexer) != T_ENDCMD);
3936 lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3937 "CRITERIA", "CATEGORIES", "TITLES",
3938 "SIGTEST", "COMPARETEST");
3942 if (!lex_match (lexer, T_SLASH))
3946 if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
3947 && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
3949 msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3953 if (!ctables_prepare_table (t))
3956 while (lex_token (lexer) != T_ENDCMD);
3958 bool ok = ctables_execute (ds, ct);
3959 ctables_destroy (ct);
3960 return ok ? CMD_SUCCESS : CMD_FAILURE;
3963 ctables_destroy (ct);