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? */
58 double to; /* Recoded value. */
61 /* Explains how to recode an AUTORECODE variable. */
64 int width; /* Variable width. */
65 int src_idx; /* Case index of source variable. */
66 struct variable *dst; /* Target variable. */
67 struct missing_values mv; /* Missing values of source variable. */
68 struct rec_items *items;
71 /* Descending or ascending sort order. */
80 struct hmap ht; /* Hash table of "struct arc_item"s. */
85 /* AUTORECODE data. */
88 struct arc_spec *specs;
94 static trns_proc_func autorecode_trns_proc;
95 static trns_free_func autorecode_trns_free;
97 static int compare_arc_items (const void *, const void *, const void *aux);
98 static void arc_free (struct autorecode_pgm *);
99 static struct arc_item *find_arc_item (
100 const struct rec_items *, const union value *, int width,
103 /* Returns WIDTH with any trailing spaces in VALUE trimmed off (except that a
104 minimum width of 1 is always returned because otherwise the width would
105 indicate a numeric type). */
107 value_trim_spaces (const union value *value, int width)
109 while (width > 1 && value->s[width - 1] == ' ')
114 /* Performs the AUTORECODE procedure. */
116 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
118 struct dictionary *dict = dataset_dict (ds);
120 const struct variable **src_vars = NULL;
123 char **dst_names = NULL;
126 enum arc_direction direction = ASCENDING;
128 /* Create procedure. */
129 struct autorecode_pgm *arc = xzalloc (sizeof *arc);
130 arc->blank_valid = true;
132 /* Parse variable lists. */
133 lex_match_id (lexer, "VARIABLES");
134 lex_match (lexer, T_EQUALS);
135 if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
136 PV_NO_DUPLICATE | PV_NO_SCRATCH))
138 lex_match (lexer, T_SLASH);
139 if (!lex_force_match_id (lexer, "INTO"))
141 lex_match (lexer, T_EQUALS);
142 if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
145 if (n_dsts != n_srcs)
147 msg (SE, _("Source variable count (%zu) does not match "
148 "target variable count (%zu)."),
153 for (size_t i = 0; i < n_dsts; i++)
155 const char *name = dst_names[i];
157 if (dict_lookup_var (dict, name) != NULL)
159 msg (SE, _("Target variable %s duplicates existing variable %s."),
167 while (lex_match (lexer, T_SLASH))
169 if (lex_match_id (lexer, "DESCENDING"))
170 direction = DESCENDING;
171 else if (lex_match_id (lexer, "PRINT"))
173 /* Not yet implemented. */
175 else if (lex_match_id (lexer, "GROUP"))
177 else if (lex_match_id (lexer, "BLANK"))
179 lex_match (lexer, T_EQUALS);
180 if (lex_match_id (lexer, "VALID"))
182 arc->blank_valid = true;
184 else if (lex_match_id (lexer, "MISSING"))
186 arc->blank_valid = false;
190 lex_error_expecting (lexer, "VALID", "MISSING");
196 lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
201 if (lex_token (lexer) != T_ENDCMD)
203 lex_error (lexer, _("expecting end of command"));
207 /* If GROUP is specified, verify that the variables are all string or all
211 enum val_type type = var_get_type (src_vars[0]);
212 for (size_t i = 1; i < n_dsts; i++)
214 if (var_get_type (src_vars[i]) != type)
216 size_t string_idx = type == VAL_STRING ? 0 : i;
217 size_t numeric_idx = type == VAL_STRING ? i : 0;
218 lex_error (lexer, _("With GROUP, variables may not mix string "
219 "variables (such as %s) and numeric "
220 "variables (such as %s)."),
221 var_get_name (src_vars[string_idx]),
222 var_get_name (src_vars[numeric_idx]));
228 /* Allocate all the specs and the rec_items that they point to.
230 If GROUP is specified, there is only a single global rec_items, with the
231 maximum width 'width', and all of the specs point to it; otherwise each
232 spec has its own rec_items. */
233 arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
234 arc->n_specs = n_dsts;
235 for (size_t i = 0; i < n_dsts; i++)
237 struct arc_spec *spec = &arc->specs[i];
239 spec->width = var_get_width (src_vars[i]);
240 spec->src_idx = var_get_case_index (src_vars[i]);
243 spec->items = arc->specs[0].items;
246 spec->items = xzalloc (sizeof (*spec->items));
247 hmap_init (&spec->items->ht);
251 /* Initialize specs[*]->mv to the user-missing values for each
255 /* Use the first source variable that has any user-missing values. */
257 for (size_t i = 0; i < n_dsts; i++)
258 if (var_has_missing_values (src_vars[i]))
264 for (size_t i = 0; i < n_dsts; i++)
265 mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[mv_idx]));
269 /* Each variable uses its own user-missing values. */
270 for (size_t i = 0; i < n_dsts; i++)
271 mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[i]));
274 /* Execute procedure. */
275 struct casereader *input = proc_open (ds);
277 for (; (c = casereader_read (input)) != NULL; case_unref (c))
278 for (size_t i = 0; i < arc->n_specs; i++)
280 struct arc_spec *spec = &arc->specs[i];
281 const union value *value = case_data_idx (c, spec->src_idx);
282 if (spec->width == 0 && value->f == SYSMIS)
284 /* AUTORECODE never changes the system-missing value.
285 (Leaving it out of the translation table has this
286 effect automatically because values not found in the
287 translation table get translated to system-missing.) */
291 int width = value_trim_spaces (value, spec->width);
292 if (width == 1 && value->s[0] == ' ' && !arc->blank_valid)
295 size_t hash = value_hash (value, width, 0);
296 if (find_arc_item (spec->items, value, width, hash))
299 struct arc_item *item = xmalloc (sizeof *item);
301 value_clone (&item->from, value, width);
302 item->missing = mv_is_value_missing_varwidth (&spec->mv, value, spec->width,
304 hmap_insert (&spec->items->ht, &item->hmap_node, hash);
306 bool ok = casereader_destroy (input);
307 ok = proc_commit (ds) && ok;
309 /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
311 dict = dataset_dict (ds);
313 /* Create transformation. */
314 for (size_t i = 0; i < arc->n_specs; i++)
316 struct arc_spec *spec = &arc->specs[i];
317 struct arc_item **items;
318 struct arc_item *item;
322 /* Create destination variable. */
323 spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
325 /* Create array of pointers to items. */
326 n_items = hmap_count (&spec->items->ht);
327 items = xmalloc (n_items * sizeof *items);
329 HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
332 assert (j == n_items);
334 /* Sort array by value. */
335 sort (items, n_items, sizeof *items, compare_arc_items, &direction);
337 /* Assign recoded values in sorted order. */
338 for (j = 0; j < n_items; j++)
339 items[j]->to = j + 1;
341 /* Assign user-missing values.
343 User-missing values in the source variable(s) must be marked
344 as user-missing values in the destination variable. There
345 might be an arbitrary number of missing values, since the
346 source variable might have a range. Our sort function always
347 puts missing values together at the top of the range, so that
348 means that we can use a missing value range to cover all of
349 the user-missing values in any case (but we avoid it unless
350 necessary because user-missing value ranges are an obscure
352 size_t n_missing = n_items;
353 for (size_t k = 0; k < n_items; k++)
354 if (!items[n_items - k - 1]->missing)
361 size_t lo = n_items - (n_missing - 1);
364 struct missing_values mv;
367 mv_add_range (&mv, lo, hi);
368 else if (n_missing > 0)
369 for (size_t k = 0; k < n_missing; k++)
370 mv_add_num (&mv, lo + k);
371 var_set_missing_values (spec->dst, &mv);
375 /* Add value labels to the destination variable which indicate
376 the source value from whence the new value comes. */
377 for (j = 0; j < n_items; j++)
379 const union value *from = &items[j]->from;
380 const int src_width = items[j]->width;
384 const char *str = CHAR_CAST_BUG (const char *, from->s);
386 recoded_value = recode_string (UTF8, dict_get_encoding (dict),
390 recoded_value = c_xasprintf ("%.*g", DBL_DIG + 1, from->f);
392 /* Remove trailing whitespace. */
393 size_t len = strlen (recoded_value);
394 while (len > 0 && recoded_value[len - 1] == ' ')
395 recoded_value[--len] = '\0';
397 /* Add value label, if it would be nonempty. */
400 union value to_val = { .f = items[j]->to };
401 var_add_value_label (spec->dst, &to_val, recoded_value);
403 free (recoded_value);
409 add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
411 for (size_t i = 0; i < n_dsts; i++)
416 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
419 for (size_t i = 0; i < n_dsts; i++)
424 return CMD_CASCADING_FAILURE;
428 arc_free (struct autorecode_pgm *arc)
432 for (size_t i = 0; i < arc->n_specs; i++)
434 struct arc_spec *spec = &arc->specs[i];
435 struct arc_item *item, *next;
437 HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
440 value_destroy (&item->from, item->width);
441 hmap_delete (&spec->items->ht, &item->hmap_node);
444 mv_destroy (&spec->mv);
448 (arc->n_specs == 1 || arc->specs[0].items == arc->specs[1].items
451 for (size_t i = 0; i < n_rec_items; i++)
453 struct arc_spec *spec = &arc->specs[i];
454 hmap_destroy (&spec->items->ht);
463 static struct arc_item *
464 find_arc_item (const struct rec_items *items,
465 const union value *value, int width,
468 struct arc_item *item;
470 HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, &items->ht)
471 if (item->width == width && value_equal (value, &item->from, width))
477 compare_arc_items (const void *a_, const void *b_, const void *direction_)
479 const struct arc_item *const *ap = a_;
480 const struct arc_item *const *bp = b_;
481 const struct arc_item *a = *ap;
482 const struct arc_item *b = *bp;
484 /* User-missing values always sort to the highest target values
485 (regardless of sort direction). */
486 if (a->missing != b->missing)
487 return a->missing < b->missing ? -1 : 1;
489 /* Otherwise, compare the data. */
494 cmp = value_compare_3way (&a->from, &b->from, aw);
498 cmp = buf_compare_rpad (CHAR_CAST_BUG (const char *, a->from.s), aw,
499 CHAR_CAST_BUG (const char *, b->from.s), bw);
502 /* Then apply sort direction. */
503 const enum arc_direction *directionp = direction_;
504 enum arc_direction direction = *directionp;
505 return direction == ASCENDING ? cmp : -cmp;
509 autorecode_trns_proc (void *arc_, struct ccase **c,
510 casenumber case_idx UNUSED)
512 struct autorecode_pgm *arc = arc_;
514 *c = case_unshare (*c);
515 for (size_t i = 0; i < arc->n_specs; i++)
517 const struct arc_spec *spec = &arc->specs[i];
518 const union value *value = case_data_idx (*c, spec->src_idx);
519 int width = value_trim_spaces (value, spec->width);
520 size_t hash = value_hash (value, width, 0);
521 const struct arc_item *item = find_arc_item (spec->items, value, width,
523 case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
526 return TRNS_CONTINUE;
530 autorecode_trns_free (void *arc_)
532 struct autorecode_pgm *arc = arc_;