1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2009, 2010, 2012, 2013, 2014
3 2021, Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "data/case.h"
24 #include "data/casereader.h"
25 #include "data/dataset.h"
26 #include "data/dictionary.h"
27 #include "data/transformations.h"
28 #include "data/variable.h"
29 #include "language/command.h"
30 #include "language/lexer/lexer.h"
31 #include "language/lexer/variable-parser.h"
32 #include "libpspp/array.h"
33 #include "libpspp/compiler.h"
34 #include "libpspp/hash-functions.h"
35 #include "libpspp/hmap.h"
36 #include "libpspp/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/pool.h"
39 #include "libpspp/str.h"
40 #include "output/pivot-table.h"
42 #include "gl/xalloc.h"
43 #include "gl/c-xvasprintf.h"
44 #include "gl/mbiter.h"
45 #include "gl/size_max.h"
48 #define _(msgid) gettext (msgid)
49 #define N_(msgid) (msgid)
51 /* Explains how to recode one value. */
54 struct hmap_node hmap_node; /* Element in "struct arc_spec" hash table. */
55 union value from; /* Original value. */
56 int width; /* Width of the original value */
57 bool missing; /* Is 'from' missing in its source varible? */
58 char *value_label; /* Value label in source variable, if any. */
60 double to; /* Recoded value. */
63 /* Explains how to recode an AUTORECODE variable. */
66 int width; /* Variable width. */
67 int src_idx; /* Case index of source variable. */
68 char *src_name; /* Name of source variable. */
69 struct fmt_spec format; /* Print format in source variable. */
70 struct variable *dst; /* Target variable. */
71 struct missing_values mv; /* Missing values of source variable. */
72 char *label; /* Variable label of source variable. */
73 struct rec_items *items;
76 /* Descending or ascending sort order. */
85 struct hmap ht; /* Hash table of "struct arc_item"s. */
90 /* AUTORECODE data. */
93 struct arc_spec *specs;
99 static const struct trns_class autorecode_trns_class;
101 static int compare_arc_items (const void *, const void *, const void *aux);
102 static void arc_free (struct autorecode_pgm *);
103 static struct arc_item *find_arc_item (
104 const struct rec_items *, const union value *, int width,
107 /* Returns WIDTH with any trailing spaces in VALUE trimmed off (except that a
108 minimum width of 1 is always returned because otherwise the width would
109 indicate a numeric type). */
111 value_trim_spaces (const union value *value, int width)
113 while (width > 1 && value->s[width - 1] == ' ')
118 /* Performs the AUTORECODE procedure. */
120 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
122 struct dictionary *dict = dataset_dict (ds);
124 const struct variable **src_vars = NULL;
127 char **dst_names = NULL;
130 enum arc_direction direction = ASCENDING;
133 /* Create procedure. */
134 struct autorecode_pgm *arc = XZALLOC (struct autorecode_pgm);
135 arc->blank_valid = true;
137 /* Parse variable lists. */
138 lex_match_id (lexer, "VARIABLES");
139 lex_match (lexer, T_EQUALS);
140 if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
141 PV_NO_DUPLICATE | PV_NO_SCRATCH))
143 lex_match (lexer, T_SLASH);
144 if (!lex_force_match_id (lexer, "INTO"))
146 lex_match (lexer, T_EQUALS);
147 if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
150 if (n_dsts != n_srcs)
152 msg (SE, _("Source variable count (%zu) does not match "
153 "target variable count (%zu)."),
158 for (size_t i = 0; i < n_dsts; i++)
160 const char *name = dst_names[i];
162 if (dict_lookup_var (dict, name) != NULL)
164 msg (SE, _("Target variable %s duplicates existing variable %s."),
172 while (lex_match (lexer, T_SLASH))
174 if (lex_match_id (lexer, "DESCENDING"))
175 direction = DESCENDING;
176 else if (lex_match_id (lexer, "PRINT"))
178 else if (lex_match_id (lexer, "GROUP"))
180 else if (lex_match_id (lexer, "BLANK"))
182 lex_match (lexer, T_EQUALS);
183 if (lex_match_id (lexer, "VALID"))
185 arc->blank_valid = true;
187 else if (lex_match_id (lexer, "MISSING"))
189 arc->blank_valid = false;
193 lex_error_expecting (lexer, "VALID", "MISSING");
199 lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
204 if (lex_token (lexer) != T_ENDCMD)
206 lex_error (lexer, _("expecting end of command"));
210 /* If GROUP is specified, verify that the variables are all string or all
214 enum val_type type = var_get_type (src_vars[0]);
215 for (size_t i = 1; i < n_dsts; i++)
217 if (var_get_type (src_vars[i]) != type)
219 size_t string_idx = type == VAL_STRING ? 0 : i;
220 size_t numeric_idx = type == VAL_STRING ? i : 0;
221 lex_error (lexer, _("With GROUP, variables may not mix string "
222 "variables (such as %s) and numeric "
223 "variables (such as %s)."),
224 var_get_name (src_vars[string_idx]),
225 var_get_name (src_vars[numeric_idx]));
231 /* Allocate all the specs and the rec_items that they point to.
233 If GROUP is specified, there is only a single global rec_items, with the
234 maximum width 'width', and all of the specs point to it; otherwise each
235 spec has its own rec_items. */
236 arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
237 arc->n_specs = n_dsts;
238 for (size_t i = 0; i < n_dsts; i++)
240 struct arc_spec *spec = &arc->specs[i];
242 spec->width = var_get_width (src_vars[i]);
243 spec->src_idx = var_get_case_index (src_vars[i]);
244 spec->src_name = xstrdup (var_get_name (src_vars[i]));
245 spec->format = *var_get_print_format (src_vars[i]);
247 const char *label = var_get_label (src_vars[i]);
248 spec->label = xstrdup_if_nonnull (label);
251 spec->items = arc->specs[0].items;
254 spec->items = xzalloc (sizeof (*spec->items));
255 hmap_init (&spec->items->ht);
259 /* Initialize specs[*]->mv to the user-missing values for each
263 /* Use the first source variable that has any user-missing values. */
265 for (size_t i = 0; i < n_dsts; i++)
266 if (var_has_missing_values (src_vars[i]))
272 for (size_t i = 0; i < n_dsts; i++)
273 mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[mv_idx]));
277 /* Each variable uses its own user-missing values. */
278 for (size_t i = 0; i < n_dsts; i++)
279 mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[i]));
282 /* Execute procedure. */
283 struct casereader *input = proc_open (ds);
285 for (; (c = casereader_read (input)) != NULL; case_unref (c))
286 for (size_t i = 0; i < arc->n_specs; i++)
288 struct arc_spec *spec = &arc->specs[i];
289 const union value *value = case_data_idx (c, spec->src_idx);
290 if (spec->width == 0 && value->f == SYSMIS)
292 /* AUTORECODE never changes the system-missing value.
293 (Leaving it out of the translation table has this
294 effect automatically because values not found in the
295 translation table get translated to system-missing.) */
299 int width = value_trim_spaces (value, spec->width);
300 if (width == 1 && value->s[0] == ' ' && !arc->blank_valid)
303 size_t hash = value_hash (value, width, 0);
304 if (find_arc_item (spec->items, value, width, hash))
307 struct string value_label = DS_EMPTY_INITIALIZER;
308 var_append_value_name__ (src_vars[i], value,
309 SETTINGS_VALUE_SHOW_LABEL, &value_label);
311 struct arc_item *item = xmalloc (sizeof *item);
313 value_clone (&item->from, value, width);
314 item->missing = mv_is_value_missing_varwidth (&spec->mv, value,
316 item->value_label = ds_steal_cstr (&value_label);
317 hmap_insert (&spec->items->ht, &item->hmap_node, hash);
319 ds_destroy (&value_label);
321 bool ok = casereader_destroy (input);
322 ok = proc_commit (ds) && ok;
324 /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
326 dict = dataset_dict (ds);
328 /* Create transformation. */
329 for (size_t i = 0; i < arc->n_specs; i++)
331 struct arc_spec *spec = &arc->specs[i];
333 /* Create destination variable. */
334 spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
335 var_set_label (spec->dst, spec->label);
337 /* Set print format. */
338 size_t n_items = hmap_count (&spec->items->ht);
339 char *longest_value = xasprintf ("%zu", n_items);
340 struct fmt_spec format = { .type = FMT_F, .w = strlen (longest_value) };
341 var_set_both_formats (spec->dst, &format);
342 free (longest_value);
344 /* Create array of pointers to items. */
345 struct arc_item **items = xmalloc (n_items * sizeof *items);
346 struct arc_item *item;
348 HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
350 assert (j == n_items);
352 /* Sort array by value. */
353 sort (items, n_items, sizeof *items, compare_arc_items, &direction);
355 /* Assign recoded values in sorted order. */
356 for (j = 0; j < n_items; j++)
357 items[j]->to = j + 1;
359 if (print && (!group || i == 0))
361 struct pivot_value *title
363 ? pivot_value_new_text (N_("Recoding grouped variables."))
364 : spec->label && spec->label[0]
365 ? pivot_value_new_text_format (N_("Recoding %s into %s (%s)."),
367 var_get_name (spec->dst),
369 : pivot_value_new_text_format (N_("Recoding %s into %s."),
371 var_get_name (spec->dst)));
372 struct pivot_table *table = pivot_table_create__ (title, "Recoding");
374 pivot_dimension_create (
375 table, PIVOT_AXIS_COLUMN, N_("Attributes"),
376 N_("New Value"), N_("Value Label"));
378 struct pivot_dimension *old_values = pivot_dimension_create (
379 table, PIVOT_AXIS_ROW, N_("Old Value"));
380 old_values->root->show_label = true;
382 for (size_t k = 0; k < n_items; k++)
384 const struct arc_item *item = items[k];
385 int old_value_idx = pivot_category_create_leaf (
386 old_values->root, pivot_value_new_value (
387 &item->from, item->width,
389 ? &(struct fmt_spec) { .type = FMT_F, .w = item->width }
391 dict_get_encoding (dict)));
392 pivot_table_put2 (table, 0, old_value_idx,
393 pivot_value_new_integer (item->to));
395 const char *value_label = item->value_label;
396 if (value_label && value_label[0])
397 pivot_table_put2 (table, 1, old_value_idx,
398 pivot_value_new_user_text (value_label, -1));
401 pivot_table_submit (table);
404 /* Assign user-missing values.
406 User-missing values in the source variable(s) must be marked
407 as user-missing values in the destination variable. There
408 might be an arbitrary number of missing values, since the
409 source variable might have a range. Our sort function always
410 puts missing values together at the top of the range, so that
411 means that we can use a missing value range to cover all of
412 the user-missing values in any case (but we avoid it unless
413 necessary because user-missing value ranges are an obscure
415 size_t n_missing = n_items;
416 for (size_t k = 0; k < n_items; k++)
417 if (!items[n_items - k - 1]->missing)
424 size_t lo = n_items - (n_missing - 1);
427 struct missing_values mv;
430 mv_add_range (&mv, lo, hi);
432 for (size_t k = 0; k < n_missing; k++)
433 mv_add_num (&mv, lo + k);
434 var_set_missing_values (spec->dst, &mv);
438 /* Add value labels to the destination variable. */
439 for (j = 0; j < n_items; j++)
441 const char *value_label = items[j]->value_label;
442 if (value_label && value_label[0])
444 union value to_val = { .f = items[j]->to };
445 var_add_value_label (spec->dst, &to_val, value_label);
452 add_transformation (ds, &autorecode_trns_class, arc);
454 for (size_t i = 0; i < n_dsts; i++)
459 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
462 for (size_t i = 0; i < n_dsts; i++)
467 return CMD_CASCADING_FAILURE;
471 arc_free (struct autorecode_pgm *arc)
475 for (size_t i = 0; i < arc->n_specs; i++)
477 struct arc_spec *spec = &arc->specs[i];
478 struct arc_item *item, *next;
480 HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
483 value_destroy (&item->from, item->width);
484 free (item->value_label);
485 hmap_delete (&spec->items->ht, &item->hmap_node);
489 free (spec->src_name);
490 mv_destroy (&spec->mv);
494 (arc->n_specs >= 2 && arc->specs[0].items == arc->specs[1].items
498 for (size_t i = 0; i < n_rec_items; i++)
500 struct arc_spec *spec = &arc->specs[i];
501 hmap_destroy (&spec->items->ht);
510 static struct arc_item *
511 find_arc_item (const struct rec_items *items,
512 const union value *value, int width,
515 struct arc_item *item;
517 HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, &items->ht)
518 if (item->width == width && value_equal (value, &item->from, width))
524 compare_arc_items (const void *a_, const void *b_, const void *direction_)
526 const struct arc_item *const *ap = a_;
527 const struct arc_item *const *bp = b_;
528 const struct arc_item *a = *ap;
529 const struct arc_item *b = *bp;
531 /* User-missing values always sort to the highest target values
532 (regardless of sort direction). */
533 if (a->missing != b->missing)
534 return a->missing < b->missing ? -1 : 1;
536 /* Otherwise, compare the data. */
541 cmp = value_compare_3way (&a->from, &b->from, aw);
545 cmp = buf_compare_rpad (CHAR_CAST_BUG (const char *, a->from.s), aw,
546 CHAR_CAST_BUG (const char *, b->from.s), bw);
549 /* Then apply sort direction. */
550 const enum arc_direction *directionp = direction_;
551 enum arc_direction direction = *directionp;
552 return direction == ASCENDING ? cmp : -cmp;
555 static enum trns_result
556 autorecode_trns_proc (void *arc_, struct ccase **c,
557 casenumber case_idx UNUSED)
559 struct autorecode_pgm *arc = arc_;
561 *c = case_unshare (*c);
562 for (size_t i = 0; i < arc->n_specs; i++)
564 const struct arc_spec *spec = &arc->specs[i];
565 const union value *value = case_data_idx (*c, spec->src_idx);
566 int width = value_trim_spaces (value, spec->width);
567 size_t hash = value_hash (value, width, 0);
568 const struct arc_item *item = find_arc_item (spec->items, value, width,
570 *case_num_rw (*c, spec->dst) = item ? item->to : SYSMIS;
573 return TRNS_CONTINUE;
577 autorecode_trns_free (void *arc_)
579 struct autorecode_pgm *arc = arc_;
585 static const struct trns_class autorecode_trns_class = {
586 .name = "AUTORECODE",
587 .execute = autorecode_trns_proc,
588 .destroy = autorecode_trns_free,