Change how checking for missing values works.
[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 const struct trns_class autorecode_trns_class;
100
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,
105   size_t hash);
106
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). */
110 static int
111 value_trim_spaces (const union value *value, int width)
112 {
113   while (width > 1 && value->s[width - 1] == ' ')
114     width--;
115   return width;
116 }
117
118 /* Performs the AUTORECODE procedure. */
119 int
120 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
121 {
122   struct dictionary *dict = dataset_dict (ds);
123
124   const struct variable **src_vars = NULL;
125   size_t n_srcs = 0;
126
127   char **dst_names = NULL;
128   size_t n_dsts = 0;
129
130   enum arc_direction direction = ASCENDING;
131   bool print = false;
132
133   /* Create procedure. */
134   struct autorecode_pgm *arc = XZALLOC (struct autorecode_pgm);
135   arc->blank_valid = true;
136
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))
142     goto error;
143   lex_match (lexer, T_SLASH);
144   if (!lex_force_match_id (lexer, "INTO"))
145     goto error;
146   lex_match (lexer, T_EQUALS);
147   if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
148                              PV_NO_DUPLICATE))
149     goto error;
150   if (n_dsts != n_srcs)
151     {
152       msg (SE, _("Source variable count (%zu) does not match "
153                  "target variable count (%zu)."),
154            n_srcs, n_dsts);
155
156       goto error;
157     }
158   for (size_t i = 0; i < n_dsts; i++)
159     {
160       const char *name = dst_names[i];
161
162       if (dict_lookup_var (dict, name) != NULL)
163         {
164           msg (SE, _("Target variable %s duplicates existing variable %s."),
165                name, name);
166           goto error;
167         }
168     }
169
170   /* Parse options. */
171   bool group = false;
172   while (lex_match (lexer, T_SLASH))
173     {
174       if (lex_match_id (lexer, "DESCENDING"))
175         direction = DESCENDING;
176       else if (lex_match_id (lexer, "PRINT"))
177         print = true;
178       else if (lex_match_id (lexer, "GROUP"))
179         group = true;
180       else if (lex_match_id (lexer, "BLANK"))
181         {
182           lex_match (lexer, T_EQUALS);
183           if (lex_match_id (lexer, "VALID"))
184             {
185               arc->blank_valid = true;
186             }
187           else if (lex_match_id (lexer, "MISSING"))
188             {
189               arc->blank_valid = false;
190             }
191           else
192             {
193               lex_error_expecting (lexer, "VALID", "MISSING");
194               goto error;
195             }
196         }
197       else
198         {
199           lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
200           goto error;
201         }
202     }
203
204   if (lex_token (lexer) != T_ENDCMD)
205     {
206       lex_error (lexer, _("expecting end of command"));
207       goto error;
208     }
209
210   /* If GROUP is specified, verify that the variables are all string or all
211      numeric.  */
212   if (group)
213     {
214       enum val_type type = var_get_type (src_vars[0]);
215       for (size_t i = 1; i < n_dsts; i++)
216         {
217           if (var_get_type (src_vars[i]) != type)
218             {
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]));
226               goto error;
227             }
228         }
229     }
230
231   /* Allocate all the specs and the rec_items that they point to.
232
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++)
239     {
240       struct arc_spec *spec = &arc->specs[i];
241
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]);
246
247       const char *label = var_get_label (src_vars[i]);
248       spec->label = xstrdup_if_nonnull (label);
249
250       if (group && i > 0)
251         spec->items = arc->specs[0].items;
252       else
253         {
254           spec->items = xzalloc (sizeof (*spec->items));
255           hmap_init (&spec->items->ht);
256         }
257     }
258
259   /* Initialize specs[*]->mv to the user-missing values for each
260      source variable. */
261   if (group)
262     {
263       /* Use the first source variable that has any user-missing values. */
264       size_t mv_idx = 0;
265       for (size_t i = 0; i < n_dsts; i++)
266         if (var_has_missing_values (src_vars[i]))
267           {
268             mv_idx = i;
269             break;
270           }
271
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]));
274     }
275   else
276     {
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]));
280     }
281
282   /* Execute procedure. */
283   struct casereader *input = proc_open (ds);
284   struct ccase *c;
285   for (; (c = casereader_read (input)) != NULL; case_unref (c))
286     for (size_t i = 0; i < arc->n_specs; i++)
287       {
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)
291           {
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.) */
296             continue;
297           }
298
299         int width = value_trim_spaces (value, spec->width);
300         if (width == 1 && value->s[0] == ' ' && !arc->blank_valid)
301           continue;
302
303         size_t hash = value_hash (value, width, 0);
304         if (find_arc_item (spec->items, value, width, hash))
305           continue;
306
307         struct string value_label = DS_EMPTY_INITIALIZER;
308         var_append_value_name__ (src_vars[i], value,
309                                  SETTINGS_VALUE_SHOW_LABEL, &value_label);
310
311         struct arc_item *item = xmalloc (sizeof *item);
312         item->width = width;
313         value_clone (&item->from, value, width);
314         item->missing = mv_is_value_missing_varwidth (&spec->mv, value,
315                                                       spec->width);
316         item->value_label = ds_steal_cstr (&value_label);
317         hmap_insert (&spec->items->ht, &item->hmap_node, hash);
318
319         ds_destroy (&value_label);
320       }
321   bool ok = casereader_destroy (input);
322   ok = proc_commit (ds) && ok;
323
324   /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
325      use). */
326   dict = dataset_dict (ds);
327
328   /* Create transformation. */
329   for (size_t i = 0; i < arc->n_specs; i++)
330     {
331       struct arc_spec *spec = &arc->specs[i];
332
333       /* Create destination variable. */
334       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
335       var_set_label (spec->dst, spec->label);
336
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);
343
344       /* Create array of pointers to items. */
345       struct arc_item **items = xmalloc (n_items * sizeof *items);
346       struct arc_item *item;
347       size_t j = 0;
348       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
349         items[j++] = item;
350       assert (j == n_items);
351
352       /* Sort array by value. */
353       sort (items, n_items, sizeof *items, compare_arc_items, &direction);
354
355       /* Assign recoded values in sorted order. */
356       for (j = 0; j < n_items; j++)
357         items[j]->to = j + 1;
358
359       if (print && (!group || i == 0))
360         {
361           struct pivot_value *title
362             = (group
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)."),
366                                               spec->src_name,
367                                               var_get_name (spec->dst),
368                                               spec->label)
369                : pivot_value_new_text_format (N_("Recoding %s into %s."),
370                                               spec->src_name,
371                                               var_get_name (spec->dst)));
372           struct pivot_table *table = pivot_table_create__ (title, "Recoding");
373
374           pivot_dimension_create (
375             table, PIVOT_AXIS_COLUMN, N_("Attributes"),
376             N_("New Value"), N_("Value Label"));
377
378           struct pivot_dimension *old_values = pivot_dimension_create (
379             table, PIVOT_AXIS_ROW, N_("Old Value"));
380           old_values->root->show_label = true;
381
382           for (size_t k = 0; k < n_items; k++)
383             {
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,
388                   (item->width
389                    ? &(struct fmt_spec) { .type = FMT_F, .w = item->width }
390                    : &spec->format),
391                   dict_get_encoding (dict)));
392               pivot_table_put2 (table, 0, old_value_idx,
393                                 pivot_value_new_integer (item->to));
394
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));
399             }
400
401           pivot_table_submit (table);
402         }
403
404       /* Assign user-missing values.
405
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
414          feature). */
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)
418           {
419             n_missing = k;
420             break;
421           }
422       if (n_missing > 0)
423         {
424           size_t lo = n_items - (n_missing - 1);
425           size_t hi = n_items;
426
427           struct missing_values mv;
428           mv_init (&mv, 0);
429           if (n_missing > 3)
430             mv_add_range (&mv, lo, hi);
431           else
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);
435           mv_destroy (&mv);
436         }
437
438       /* Add value labels to the destination variable. */
439       for (j = 0; j < n_items; j++)
440         {
441           const char *value_label = items[j]->value_label;
442           if (value_label && value_label[0])
443             {
444               union value to_val = { .f = items[j]->to };
445               var_add_value_label (spec->dst, &to_val, value_label);
446             }
447         }
448
449       /* Free array. */
450       free (items);
451     }
452   add_transformation (ds, &autorecode_trns_class, arc);
453
454   for (size_t i = 0; i < n_dsts; i++)
455     free (dst_names[i]);
456   free (dst_names);
457   free (src_vars);
458
459   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
460
461 error:
462   for (size_t i = 0; i < n_dsts; i++)
463     free (dst_names[i]);
464   free (dst_names);
465   free (src_vars);
466   arc_free (arc);
467   return CMD_CASCADING_FAILURE;
468 }
469
470 static void
471 arc_free (struct autorecode_pgm *arc)
472 {
473   if (arc != NULL)
474     {
475       for (size_t i = 0; i < arc->n_specs; i++)
476         {
477           struct arc_spec *spec = &arc->specs[i];
478           struct arc_item *item, *next;
479
480           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
481                               &spec->items->ht)
482             {
483               value_destroy (&item->from, item->width);
484               free (item->value_label);
485               hmap_delete (&spec->items->ht, &item->hmap_node);
486               free (item);
487             }
488           free (spec->label);
489           free (spec->src_name);
490           mv_destroy (&spec->mv);
491         }
492
493       size_t n_rec_items =
494         (arc->n_specs >= 2 && arc->specs[0].items == arc->specs[1].items
495          ? 1
496          : arc->n_specs);
497
498       for (size_t i = 0; i < n_rec_items; i++)
499         {
500           struct arc_spec *spec = &arc->specs[i];
501           hmap_destroy (&spec->items->ht);
502           free (spec->items);
503         }
504
505       free (arc->specs);
506       free (arc);
507     }
508 }
509
510 static struct arc_item *
511 find_arc_item (const struct rec_items *items,
512                const union value *value, int width,
513                size_t hash)
514 {
515   struct arc_item *item;
516
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))
519       return item;
520   return NULL;
521 }
522
523 static int
524 compare_arc_items (const void *a_, const void *b_, const void *direction_)
525 {
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;
530
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;
535
536   /* Otherwise, compare the data. */
537   int aw = a->width;
538   int bw = b->width;
539   int cmp;
540   if (aw == bw)
541     cmp = value_compare_3way (&a->from, &b->from, aw);
542   else
543     {
544       assert (aw && bw);
545       cmp = buf_compare_rpad (CHAR_CAST_BUG (const char *, a->from.s), aw,
546                               CHAR_CAST_BUG (const char *, b->from.s), bw);
547     }
548
549   /* Then apply sort direction. */
550   const enum arc_direction *directionp = direction_;
551   enum arc_direction direction = *directionp;
552   return direction == ASCENDING ? cmp : -cmp;
553 }
554
555 static enum trns_result
556 autorecode_trns_proc (void *arc_, struct ccase **c,
557                       casenumber case_idx UNUSED)
558 {
559   struct autorecode_pgm *arc = arc_;
560
561   *c = case_unshare (*c);
562   for (size_t i = 0; i < arc->n_specs; i++)
563     {
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,
569                                                    hash);
570       *case_num_rw (*c, spec->dst) = item ? item->to : SYSMIS;
571     }
572
573   return TRNS_CONTINUE;
574 }
575
576 static bool
577 autorecode_trns_free (void *arc_)
578 {
579   struct autorecode_pgm *arc = arc_;
580
581   arc_free (arc);
582   return true;
583 }
584
585 static const struct trns_class autorecode_trns_class = {
586   .name = "AUTORECODE",
587   .execute = autorecode_trns_proc,
588   .destroy = autorecode_trns_free,
589 };