1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2009, 2010, 2012, 2013, 2014 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/>. */
22 #include "data/case.h"
23 #include "data/casereader.h"
24 #include "data/dataset.h"
25 #include "data/dictionary.h"
26 #include "data/transformations.h"
27 #include "data/variable.h"
28 #include "language/command.h"
29 #include "language/lexer/lexer.h"
30 #include "language/lexer/variable-parser.h"
31 #include "libpspp/array.h"
32 #include "libpspp/compiler.h"
33 #include "libpspp/hash-functions.h"
34 #include "libpspp/hmap.h"
35 #include "libpspp/i18n.h"
36 #include "libpspp/message.h"
37 #include "libpspp/pool.h"
38 #include "libpspp/str.h"
40 #include "gl/xalloc.h"
41 #include "gl/c-xvasprintf.h"
42 #include "gl/mbiter.h"
43 #include "gl/size_max.h"
46 #define _(msgid) gettext (msgid)
48 /* FIXME: Implement PRINT subcommand. */
50 /* Explains how to recode one value. */
53 struct hmap_node hmap_node; /* Element in "struct arc_spec" hash table. */
54 union value from; /* Original value. */
55 int width; /* Width of the original value */
56 bool missing; /* Is 'from' missing in its source varible? */
57 char *value_label; /* Value label in source variable, if any. */
59 double to; /* Recoded value. */
62 /* Explains how to recode an AUTORECODE variable. */
65 int width; /* Variable width. */
66 int src_idx; /* Case index of source variable. */
67 struct variable *dst; /* Target variable. */
68 struct missing_values mv; /* Missing values of source variable. */
69 char *label; /* Variable label of source variable. */
70 struct rec_items *items;
73 /* Descending or ascending sort order. */
82 struct hmap ht; /* Hash table of "struct arc_item"s. */
87 /* AUTORECODE data. */
90 struct arc_spec *specs;
96 static trns_proc_func autorecode_trns_proc;
97 static trns_free_func autorecode_trns_free;
99 static int compare_arc_items (const void *, const void *, const void *aux);
100 static void arc_free (struct autorecode_pgm *);
101 static struct arc_item *find_arc_item (
102 const struct rec_items *, const union value *, int width,
105 /* Returns WIDTH with any trailing spaces in VALUE trimmed off (except that a
106 minimum width of 1 is always returned because otherwise the width would
107 indicate a numeric type). */
109 value_trim_spaces (const union value *value, int width)
111 while (width > 1 && value->s[width - 1] == ' ')
116 /* Performs the AUTORECODE procedure. */
118 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
120 struct dictionary *dict = dataset_dict (ds);
122 const struct variable **src_vars = NULL;
125 char **dst_names = NULL;
128 enum arc_direction direction = ASCENDING;
130 /* Create procedure. */
131 struct autorecode_pgm *arc = xzalloc (sizeof *arc);
132 arc->blank_valid = true;
134 /* Parse variable lists. */
135 lex_match_id (lexer, "VARIABLES");
136 lex_match (lexer, T_EQUALS);
137 if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
138 PV_NO_DUPLICATE | PV_NO_SCRATCH))
140 lex_match (lexer, T_SLASH);
141 if (!lex_force_match_id (lexer, "INTO"))
143 lex_match (lexer, T_EQUALS);
144 if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
147 if (n_dsts != n_srcs)
149 msg (SE, _("Source variable count (%zu) does not match "
150 "target variable count (%zu)."),
155 for (size_t i = 0; i < n_dsts; i++)
157 const char *name = dst_names[i];
159 if (dict_lookup_var (dict, name) != NULL)
161 msg (SE, _("Target variable %s duplicates existing variable %s."),
169 while (lex_match (lexer, T_SLASH))
171 if (lex_match_id (lexer, "DESCENDING"))
172 direction = DESCENDING;
173 else if (lex_match_id (lexer, "PRINT"))
175 /* Not yet implemented. */
177 else if (lex_match_id (lexer, "GROUP"))
179 else if (lex_match_id (lexer, "BLANK"))
181 lex_match (lexer, T_EQUALS);
182 if (lex_match_id (lexer, "VALID"))
184 arc->blank_valid = true;
186 else if (lex_match_id (lexer, "MISSING"))
188 arc->blank_valid = false;
192 lex_error_expecting (lexer, "VALID", "MISSING");
198 lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
203 if (lex_token (lexer) != T_ENDCMD)
205 lex_error (lexer, _("expecting end of command"));
209 /* If GROUP is specified, verify that the variables are all string or all
213 enum val_type type = var_get_type (src_vars[0]);
214 for (size_t i = 1; i < n_dsts; i++)
216 if (var_get_type (src_vars[i]) != type)
218 size_t string_idx = type == VAL_STRING ? 0 : i;
219 size_t numeric_idx = type == VAL_STRING ? i : 0;
220 lex_error (lexer, _("With GROUP, variables may not mix string "
221 "variables (such as %s) and numeric "
222 "variables (such as %s)."),
223 var_get_name (src_vars[string_idx]),
224 var_get_name (src_vars[numeric_idx]));
230 /* Allocate all the specs and the rec_items that they point to.
232 If GROUP is specified, there is only a single global rec_items, with the
233 maximum width 'width', and all of the specs point to it; otherwise each
234 spec has its own rec_items. */
235 arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
236 arc->n_specs = n_dsts;
237 for (size_t i = 0; i < n_dsts; i++)
239 struct arc_spec *spec = &arc->specs[i];
241 spec->width = var_get_width (src_vars[i]);
242 spec->src_idx = var_get_case_index (src_vars[i]);
244 const char *label = var_get_label (src_vars[i]);
245 spec->label = label ? xstrdup (label) : NULL;
248 spec->items = arc->specs[0].items;
251 spec->items = xzalloc (sizeof (*spec->items));
252 hmap_init (&spec->items->ht);
256 /* Initialize specs[*]->mv to the user-missing values for each
260 /* Use the first source variable that has any user-missing values. */
262 for (size_t i = 0; i < n_dsts; i++)
263 if (var_has_missing_values (src_vars[i]))
269 for (size_t i = 0; i < n_dsts; i++)
270 mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[mv_idx]));
274 /* Each variable uses its own user-missing values. */
275 for (size_t i = 0; i < n_dsts; i++)
276 mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[i]));
279 /* Execute procedure. */
280 struct casereader *input = proc_open (ds);
282 for (; (c = casereader_read (input)) != NULL; case_unref (c))
283 for (size_t i = 0; i < arc->n_specs; i++)
285 struct arc_spec *spec = &arc->specs[i];
286 const union value *value = case_data_idx (c, spec->src_idx);
287 if (spec->width == 0 && value->f == SYSMIS)
289 /* AUTORECODE never changes the system-missing value.
290 (Leaving it out of the translation table has this
291 effect automatically because values not found in the
292 translation table get translated to system-missing.) */
296 int width = value_trim_spaces (value, spec->width);
297 if (width == 1 && value->s[0] == ' ' && !arc->blank_valid)
300 size_t hash = value_hash (value, width, 0);
301 if (find_arc_item (spec->items, value, width, hash))
304 struct string value_label = DS_EMPTY_INITIALIZER;
305 var_append_value_name__ (src_vars[i], value,
306 SETTINGS_VALUE_SHOW_LABEL, &value_label);
308 struct arc_item *item = xmalloc (sizeof *item);
310 value_clone (&item->from, value, width);
311 item->missing = mv_is_value_missing_varwidth (&spec->mv, value, spec->width,
313 item->value_label = ds_steal_cstr (&value_label);
314 hmap_insert (&spec->items->ht, &item->hmap_node, hash);
316 ds_destroy (&value_label);
318 bool ok = casereader_destroy (input);
319 ok = proc_commit (ds) && ok;
321 /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
323 dict = dataset_dict (ds);
325 /* Create transformation. */
326 for (size_t i = 0; i < arc->n_specs; i++)
328 struct arc_spec *spec = &arc->specs[i];
330 /* Create destination variable. */
331 spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
332 var_set_label (spec->dst, spec->label);
334 /* Set print format. */
335 size_t n_items = hmap_count (&spec->items->ht);
336 char *longest_value = xasprintf ("%zu", n_items);
337 struct fmt_spec format = { .type = FMT_F, .w = strlen (longest_value) };
338 var_set_both_formats (spec->dst, &format);
339 free (longest_value);
341 /* Create array of pointers to items. */
342 struct arc_item **items = xmalloc (n_items * sizeof *items);
343 struct arc_item *item;
345 HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
347 assert (j == n_items);
349 /* Sort array by value. */
350 sort (items, n_items, sizeof *items, compare_arc_items, &direction);
352 /* Assign recoded values in sorted order. */
353 for (j = 0; j < n_items; j++)
354 items[j]->to = j + 1;
356 /* Assign user-missing values.
358 User-missing values in the source variable(s) must be marked
359 as user-missing values in the destination variable. There
360 might be an arbitrary number of missing values, since the
361 source variable might have a range. Our sort function always
362 puts missing values together at the top of the range, so that
363 means that we can use a missing value range to cover all of
364 the user-missing values in any case (but we avoid it unless
365 necessary because user-missing value ranges are an obscure
367 size_t n_missing = n_items;
368 for (size_t k = 0; k < n_items; k++)
369 if (!items[n_items - k - 1]->missing)
376 size_t lo = n_items - (n_missing - 1);
379 struct missing_values mv;
382 mv_add_range (&mv, lo, hi);
383 else if (n_missing > 0)
384 for (size_t k = 0; k < n_missing; k++)
385 mv_add_num (&mv, lo + k);
386 var_set_missing_values (spec->dst, &mv);
390 /* Add value labels to the destination variable. */
391 for (j = 0; j < n_items; j++)
393 const char *value_label = items[j]->value_label;
394 if (value_label && value_label[0])
396 union value to_val = { .f = items[j]->to };
397 var_add_value_label (spec->dst, &to_val, value_label);
404 add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
406 for (size_t i = 0; i < n_dsts; i++)
411 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
414 for (size_t i = 0; i < n_dsts; i++)
419 return CMD_CASCADING_FAILURE;
423 arc_free (struct autorecode_pgm *arc)
427 for (size_t i = 0; i < arc->n_specs; i++)
429 struct arc_spec *spec = &arc->specs[i];
430 struct arc_item *item, *next;
432 HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
435 value_destroy (&item->from, item->width);
436 free (item->value_label);
437 hmap_delete (&spec->items->ht, &item->hmap_node);
441 mv_destroy (&spec->mv);
445 (arc->n_specs == 1 || arc->specs[0].items == arc->specs[1].items
448 for (size_t i = 0; i < n_rec_items; i++)
450 struct arc_spec *spec = &arc->specs[i];
451 hmap_destroy (&spec->items->ht);
460 static struct arc_item *
461 find_arc_item (const struct rec_items *items,
462 const union value *value, int width,
465 struct arc_item *item;
467 HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, &items->ht)
468 if (item->width == width && value_equal (value, &item->from, width))
474 compare_arc_items (const void *a_, const void *b_, const void *direction_)
476 const struct arc_item *const *ap = a_;
477 const struct arc_item *const *bp = b_;
478 const struct arc_item *a = *ap;
479 const struct arc_item *b = *bp;
481 /* User-missing values always sort to the highest target values
482 (regardless of sort direction). */
483 if (a->missing != b->missing)
484 return a->missing < b->missing ? -1 : 1;
486 /* Otherwise, compare the data. */
491 cmp = value_compare_3way (&a->from, &b->from, aw);
495 cmp = buf_compare_rpad (CHAR_CAST_BUG (const char *, a->from.s), aw,
496 CHAR_CAST_BUG (const char *, b->from.s), bw);
499 /* Then apply sort direction. */
500 const enum arc_direction *directionp = direction_;
501 enum arc_direction direction = *directionp;
502 return direction == ASCENDING ? cmp : -cmp;
506 autorecode_trns_proc (void *arc_, struct ccase **c,
507 casenumber case_idx UNUSED)
509 struct autorecode_pgm *arc = arc_;
511 *c = case_unshare (*c);
512 for (size_t i = 0; i < arc->n_specs; i++)
514 const struct arc_spec *spec = &arc->specs[i];
515 const union value *value = case_data_idx (*c, spec->src_idx);
516 int width = value_trim_spaces (value, spec->width);
517 size_t hash = value_hash (value, width, 0);
518 const struct arc_item *item = find_arc_item (spec->items, value, width,
520 case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
523 return TRNS_CONTINUE;
527 autorecode_trns_free (void *arc_)
529 struct autorecode_pgm *arc = arc_;