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