6481a263268f84fc43fe8cb000e23230a51038b5
[pspp] / src / language / stats / autorecode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2012, 2013, 2014
3    2021,  Free Software Foundation, Inc.
4
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.
9
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.
14
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/>. */
17
18 #include <config.h>
19
20 #include <float.h>
21 #include <stdlib.h>
22
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"
41
42 #include "gl/xalloc.h"
43 #include "gl/c-xvasprintf.h"
44 #include "gl/mbiter.h"
45 #include "gl/size_max.h"
46
47 #include "gettext.h"
48 #define _(msgid) gettext (msgid)
49 #define N_(msgid) (msgid)
50
51 /* Explains how to recode one value. */
52 struct arc_item
53   {
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. */
59
60     double to;                  /* Recoded value. */
61   };
62
63 /* Explains how to recode an AUTORECODE variable. */
64 struct arc_spec
65   {
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;
74   };
75
76 /* Descending or ascending sort order. */
77 enum arc_direction
78   {
79     ASCENDING,
80     DESCENDING
81   };
82
83 struct rec_items
84 {
85   struct hmap ht;         /* Hash table of "struct arc_item"s. */
86 };
87
88
89
90 /* AUTORECODE data. */
91 struct autorecode_pgm
92 {
93   struct arc_spec *specs;
94   size_t n_specs;
95
96   bool blank_valid;
97 };
98
99 static trns_proc_func autorecode_trns_proc;
100 static trns_free_func autorecode_trns_free;
101
102 static int compare_arc_items (const void *, const void *, const void *aux);
103 static void arc_free (struct autorecode_pgm *);
104 static struct arc_item *find_arc_item (
105   const struct rec_items *, const union value *, int width,
106   size_t hash);
107
108 /* Returns WIDTH with any trailing spaces in VALUE trimmed off (except that a
109    minimum width of 1 is always returned because otherwise the width would
110    indicate a numeric type). */
111 static int
112 value_trim_spaces (const union value *value, int width)
113 {
114   while (width > 1 && value->s[width - 1] == ' ')
115     width--;
116   return width;
117 }
118
119 /* Performs the AUTORECODE procedure. */
120 int
121 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
122 {
123   struct dictionary *dict = dataset_dict (ds);
124
125   const struct variable **src_vars = NULL;
126   size_t n_srcs = 0;
127
128   char **dst_names = NULL;
129   size_t n_dsts = 0;
130
131   enum arc_direction direction = ASCENDING;
132   bool print = false;
133
134   /* Create procedure. */
135   struct autorecode_pgm *arc = xzalloc (sizeof *arc);
136   arc->blank_valid = true;
137
138   /* Parse variable lists. */
139   lex_match_id (lexer, "VARIABLES");
140   lex_match (lexer, T_EQUALS);
141   if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
142                               PV_NO_DUPLICATE | PV_NO_SCRATCH))
143     goto error;
144   lex_match (lexer, T_SLASH);
145   if (!lex_force_match_id (lexer, "INTO"))
146     goto error;
147   lex_match (lexer, T_EQUALS);
148   if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
149                              PV_NO_DUPLICATE))
150     goto error;
151   if (n_dsts != n_srcs)
152     {
153       msg (SE, _("Source variable count (%zu) does not match "
154                  "target variable count (%zu)."),
155            n_srcs, n_dsts);
156
157       goto error;
158     }
159   for (size_t i = 0; i < n_dsts; i++)
160     {
161       const char *name = dst_names[i];
162
163       if (dict_lookup_var (dict, name) != NULL)
164         {
165           msg (SE, _("Target variable %s duplicates existing variable %s."),
166                name, name);
167           goto error;
168         }
169     }
170
171   /* Parse options. */
172   bool group = false;
173   while (lex_match (lexer, T_SLASH))
174     {
175       if (lex_match_id (lexer, "DESCENDING"))
176         direction = DESCENDING;
177       else if (lex_match_id (lexer, "PRINT"))
178         print = true;
179       else if (lex_match_id (lexer, "GROUP"))
180         group = true;
181       else if (lex_match_id (lexer, "BLANK"))
182         {
183           lex_match (lexer, T_EQUALS);
184           if (lex_match_id (lexer, "VALID"))
185             {
186               arc->blank_valid = true;
187             }
188           else if (lex_match_id (lexer, "MISSING"))
189             {
190               arc->blank_valid = false;
191             }
192           else
193             {
194               lex_error_expecting (lexer, "VALID", "MISSING");
195               goto error;
196             }
197         }
198       else
199         {
200           lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
201           goto error;
202         }
203     }
204
205   if (lex_token (lexer) != T_ENDCMD)
206     {
207       lex_error (lexer, _("expecting end of command"));
208       goto error;
209     }
210
211   /* If GROUP is specified, verify that the variables are all string or all
212      numeric.  */
213   if (group)
214     {
215       enum val_type type = var_get_type (src_vars[0]);
216       for (size_t i = 1; i < n_dsts; i++)
217         {
218           if (var_get_type (src_vars[i]) != type)
219             {
220               size_t string_idx = type == VAL_STRING ? 0 : i;
221               size_t numeric_idx = type == VAL_STRING ? i : 0;
222               lex_error (lexer, _("With GROUP, variables may not mix string "
223                                   "variables (such as %s) and numeric "
224                                   "variables (such as %s)."),
225                          var_get_name (src_vars[string_idx]),
226                          var_get_name (src_vars[numeric_idx]));
227               goto error;
228             }
229         }
230     }
231
232   /* Allocate all the specs and the rec_items that they point to.
233
234      If GROUP is specified, there is only a single global rec_items, with the
235      maximum width 'width', and all of the specs point to it; otherwise each
236      spec has its own rec_items. */
237   arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
238   arc->n_specs = n_dsts;
239   for (size_t i = 0; i < n_dsts; i++)
240     {
241       struct arc_spec *spec = &arc->specs[i];
242
243       spec->width = var_get_width (src_vars[i]);
244       spec->src_idx = var_get_case_index (src_vars[i]);
245       spec->src_name = xstrdup (var_get_name (src_vars[i]));
246       spec->format = *var_get_print_format (src_vars[i]);
247
248       const char *label = var_get_label (src_vars[i]);
249       spec->label = xstrdup_if_nonnull (label);
250
251       if (group && i > 0)
252         spec->items = arc->specs[0].items;
253       else
254         {
255           spec->items = xzalloc (sizeof (*spec->items));
256           hmap_init (&spec->items->ht);
257         }
258     }
259
260   /* Initialize specs[*]->mv to the user-missing values for each
261      source variable. */
262   if (group)
263     {
264       /* Use the first source variable that has any user-missing values. */
265       size_t mv_idx = 0;
266       for (size_t i = 0; i < n_dsts; i++)
267         if (var_has_missing_values (src_vars[i]))
268           {
269             mv_idx = i;
270             break;
271           }
272
273       for (size_t i = 0; i < n_dsts; i++)
274         mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[mv_idx]));
275     }
276   else
277     {
278       /* Each variable uses its own user-missing values. */
279       for (size_t i = 0; i < n_dsts; i++)
280         mv_copy (&arc->specs[i].mv, var_get_missing_values (src_vars[i]));
281     }
282
283   /* Execute procedure. */
284   struct casereader *input = proc_open (ds);
285   struct ccase *c;
286   for (; (c = casereader_read (input)) != NULL; case_unref (c))
287     for (size_t i = 0; i < arc->n_specs; i++)
288       {
289         struct arc_spec *spec = &arc->specs[i];
290         const union value *value = case_data_idx (c, spec->src_idx);
291         if (spec->width == 0 && value->f == SYSMIS)
292           {
293             /* AUTORECODE never changes the system-missing value.
294                (Leaving it out of the translation table has this
295                effect automatically because values not found in the
296                translation table get translated to system-missing.) */
297             continue;
298           }
299
300         int width = value_trim_spaces (value, spec->width);
301         if (width == 1 && value->s[0] == ' ' && !arc->blank_valid)
302           continue;
303
304         size_t hash = value_hash (value, width, 0);
305         if (find_arc_item (spec->items, value, width, hash))
306           continue;
307
308         struct string value_label = DS_EMPTY_INITIALIZER;
309         var_append_value_name__ (src_vars[i], value,
310                                  SETTINGS_VALUE_SHOW_LABEL, &value_label);
311
312         struct arc_item *item = xmalloc (sizeof *item);
313         item->width = width;
314         value_clone (&item->from, value, width);
315         item->missing = mv_is_value_missing_varwidth (&spec->mv, value, spec->width,
316                                                       MV_ANY);
317         item->value_label = ds_steal_cstr (&value_label);
318         hmap_insert (&spec->items->ht, &item->hmap_node, hash);
319
320         ds_destroy (&value_label);
321       }
322   bool ok = casereader_destroy (input);
323   ok = proc_commit (ds) && ok;
324
325   /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
326      use). */
327   dict = dataset_dict (ds);
328
329   /* Create transformation. */
330   for (size_t i = 0; i < arc->n_specs; i++)
331     {
332       struct arc_spec *spec = &arc->specs[i];
333
334       /* Create destination variable. */
335       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
336       var_set_label (spec->dst, spec->label);
337
338       /* Set print format. */
339       size_t n_items = hmap_count (&spec->items->ht);
340       char *longest_value = xasprintf ("%zu", n_items);
341       struct fmt_spec format = { .type = FMT_F, .w = strlen (longest_value) };
342       var_set_both_formats (spec->dst, &format);
343       free (longest_value);
344
345       /* Create array of pointers to items. */
346       struct arc_item **items = xmalloc (n_items * sizeof *items);
347       struct arc_item *item;
348       size_t j = 0;
349       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
350         items[j++] = item;
351       assert (j == n_items);
352
353       /* Sort array by value. */
354       sort (items, n_items, sizeof *items, compare_arc_items, &direction);
355
356       /* Assign recoded values in sorted order. */
357       for (j = 0; j < n_items; j++)
358         items[j]->to = j + 1;
359
360       if (print && (!group || i == 0))
361         {
362           struct pivot_value *title
363             = (group
364                ? pivot_value_new_text (N_("Recoding grouped variables."))
365                : spec->label && spec->label[0]
366                ? pivot_value_new_text_format (N_("Recoding %s into %s (%s)."),
367                                               spec->src_name,
368                                               var_get_name (spec->dst),
369                                               spec->label)
370                : pivot_value_new_text_format (N_("Recoding %s into %s."),
371                                               spec->src_name,
372                                               var_get_name (spec->dst)));
373           struct pivot_table *table = pivot_table_create__ (title, "Recoding");
374
375           pivot_dimension_create (
376             table, PIVOT_AXIS_COLUMN, N_("Attributes"),
377             N_("New Value"), N_("Value Label"));
378
379           struct pivot_dimension *old_values = pivot_dimension_create (
380             table, PIVOT_AXIS_ROW, N_("Old Value"));
381           old_values->root->show_label = true;
382
383           for (size_t k = 0; k < n_items; k++)
384             {
385               const struct arc_item *item = items[k];
386               int old_value_idx = pivot_category_create_leaf (
387                 old_values->root, pivot_value_new_value (
388                   &item->from, item->width,
389                   (item->width
390                    ? &(struct fmt_spec) { .type = FMT_F, .w = item->width }
391                    : &spec->format),
392                   dict_get_encoding (dict)));
393               pivot_table_put2 (table, 0, old_value_idx,
394                                 pivot_value_new_integer (item->to));
395
396               const char *value_label = item->value_label;
397               if (value_label && value_label[0])
398                 pivot_table_put2 (table, 1, old_value_idx,
399                                   pivot_value_new_user_text (value_label, -1));
400             }
401
402           pivot_table_submit (table);
403         }
404
405       /* Assign user-missing values.
406
407          User-missing values in the source variable(s) must be marked
408          as user-missing values in the destination variable.  There
409          might be an arbitrary number of missing values, since the
410          source variable might have a range.  Our sort function always
411          puts missing values together at the top of the range, so that
412          means that we can use a missing value range to cover all of
413          the user-missing values in any case (but we avoid it unless
414          necessary because user-missing value ranges are an obscure
415          feature). */
416       size_t n_missing = n_items;
417       for (size_t k = 0; k < n_items; k++)
418         if (!items[n_items - k - 1]->missing)
419           {
420             n_missing = k;
421             break;
422           }
423       if (n_missing > 0)
424         {
425           size_t lo = n_items - (n_missing - 1);
426           size_t hi = n_items;
427
428           struct missing_values mv;
429           mv_init (&mv, 0);
430           if (n_missing > 3)
431             mv_add_range (&mv, lo, hi);
432           else
433             for (size_t k = 0; k < n_missing; k++)
434               mv_add_num (&mv, lo + k);
435           var_set_missing_values (spec->dst, &mv);
436           mv_destroy (&mv);
437         }
438
439       /* Add value labels to the destination variable. */
440       for (j = 0; j < n_items; j++)
441         {
442           const char *value_label = items[j]->value_label;
443           if (value_label && value_label[0])
444             {
445               union value to_val = { .f = items[j]->to };
446               var_add_value_label (spec->dst, &to_val, value_label);
447             }
448         }
449
450       /* Free array. */
451       free (items);
452     }
453   add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
454
455   for (size_t i = 0; i < n_dsts; i++)
456     free (dst_names[i]);
457   free (dst_names);
458   free (src_vars);
459
460   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
461
462 error:
463   for (size_t i = 0; i < n_dsts; i++)
464     free (dst_names[i]);
465   free (dst_names);
466   free (src_vars);
467   arc_free (arc);
468   return CMD_CASCADING_FAILURE;
469 }
470
471 static void
472 arc_free (struct autorecode_pgm *arc)
473 {
474   if (arc != NULL)
475     {
476       for (size_t i = 0; i < arc->n_specs; i++)
477         {
478           struct arc_spec *spec = &arc->specs[i];
479           struct arc_item *item, *next;
480
481           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
482                               &spec->items->ht)
483             {
484               value_destroy (&item->from, item->width);
485               free (item->value_label);
486               hmap_delete (&spec->items->ht, &item->hmap_node);
487               free (item);
488             }
489           free (spec->label);
490           free (spec->src_name);
491           mv_destroy (&spec->mv);
492         }
493
494       size_t n_rec_items =
495         (arc->n_specs >= 2 && arc->specs[0].items == arc->specs[1].items
496          ? 1
497          : arc->n_specs);
498
499       for (size_t i = 0; i < n_rec_items; i++)
500         {
501           struct arc_spec *spec = &arc->specs[i];
502           hmap_destroy (&spec->items->ht);
503           free (spec->items);
504         }
505
506       free (arc->specs);
507       free (arc);
508     }
509 }
510
511 static struct arc_item *
512 find_arc_item (const struct rec_items *items,
513                const union value *value, int width,
514                size_t hash)
515 {
516   struct arc_item *item;
517
518   HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, &items->ht)
519     if (item->width == width && value_equal (value, &item->from, width))
520       return item;
521   return NULL;
522 }
523
524 static int
525 compare_arc_items (const void *a_, const void *b_, const void *direction_)
526 {
527   const struct arc_item *const *ap = a_;
528   const struct arc_item *const *bp = b_;
529   const struct arc_item *a = *ap;
530   const struct arc_item *b = *bp;
531
532   /* User-missing values always sort to the highest target values
533      (regardless of sort direction). */
534   if (a->missing != b->missing)
535     return a->missing < b->missing ? -1 : 1;
536
537   /* Otherwise, compare the data. */
538   int aw = a->width;
539   int bw = b->width;
540   int cmp;
541   if (aw == bw)
542     cmp = value_compare_3way (&a->from, &b->from, aw);
543   else
544     {
545       assert (aw && bw);
546       cmp = buf_compare_rpad (CHAR_CAST_BUG (const char *, a->from.s), aw,
547                               CHAR_CAST_BUG (const char *, b->from.s), bw);
548     }
549
550   /* Then apply sort direction. */
551   const enum arc_direction *directionp = direction_;
552   enum arc_direction direction = *directionp;
553   return direction == ASCENDING ? cmp : -cmp;
554 }
555
556 static int
557 autorecode_trns_proc (void *arc_, struct ccase **c,
558                       casenumber case_idx UNUSED)
559 {
560   struct autorecode_pgm *arc = arc_;
561
562   *c = case_unshare (*c);
563   for (size_t i = 0; i < arc->n_specs; i++)
564     {
565       const struct arc_spec *spec = &arc->specs[i];
566       const union value *value = case_data_idx (*c, spec->src_idx);
567       int width = value_trim_spaces (value, spec->width);
568       size_t hash = value_hash (value, width, 0);
569       const struct arc_item *item = find_arc_item (spec->items, value, width,
570                                                    hash);
571       *case_num_rw (*c, spec->dst) = item ? item->to : SYSMIS;
572     }
573
574   return TRNS_CONTINUE;
575 }
576
577 static bool
578 autorecode_trns_free (void *arc_)
579 {
580   struct autorecode_pgm *arc = arc_;
581
582   arc_free (arc);
583   return true;
584 }