d5a3ea970e9f5e6b4fb2cb6684705eacaa25bafe
[pspp] / src / language / stats / autorecode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2012, 2013, 2014 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include <float.h>
20 #include <stdlib.h>
21
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"
39
40 #include "gl/xalloc.h"
41 #include "gl/c-xvasprintf.h"
42 #include "gl/mbiter.h"
43 #include "gl/size_max.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 /* FIXME: Implement PRINT subcommand. */
49
50 /* Explains how to recode one value. */
51 struct arc_item
52   {
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. */
58
59     double to;                  /* Recoded value. */
60   };
61
62 /* Explains how to recode an AUTORECODE variable. */
63 struct arc_spec
64   {
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;
71   };
72
73 /* Descending or ascending sort order. */
74 enum arc_direction
75   {
76     ASCENDING,
77     DESCENDING
78   };
79
80 struct rec_items
81 {
82   struct hmap ht;         /* Hash table of "struct arc_item"s. */
83 };
84
85
86
87 /* AUTORECODE data. */
88 struct autorecode_pgm
89 {
90   struct arc_spec *specs;
91   size_t n_specs;
92
93   bool blank_valid;
94 };
95
96 static trns_proc_func autorecode_trns_proc;
97 static trns_free_func autorecode_trns_free;
98
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,
103   size_t hash);
104
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). */
108 static int
109 value_trim_spaces (const union value *value, int width)
110 {
111   while (width > 1 && value->s[width - 1] == ' ')
112     width--;
113   return width;
114 }
115
116 /* Performs the AUTORECODE procedure. */
117 int
118 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
119 {
120   struct dictionary *dict = dataset_dict (ds);
121
122   const struct variable **src_vars = NULL;
123   size_t n_srcs = 0;
124
125   char **dst_names = NULL;
126   size_t n_dsts = 0;
127
128   enum arc_direction direction = ASCENDING;
129
130   /* Create procedure. */
131   struct autorecode_pgm *arc = xzalloc (sizeof *arc);
132   arc->blank_valid = true;
133
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))
139     goto error;
140   lex_match (lexer, T_SLASH);
141   if (!lex_force_match_id (lexer, "INTO"))
142     goto error;
143   lex_match (lexer, T_EQUALS);
144   if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
145                              PV_NO_DUPLICATE))
146     goto error;
147   if (n_dsts != n_srcs)
148     {
149       msg (SE, _("Source variable count (%zu) does not match "
150                  "target variable count (%zu)."),
151            n_srcs, n_dsts);
152
153       goto error;
154     }
155   for (size_t i = 0; i < n_dsts; i++)
156     {
157       const char *name = dst_names[i];
158
159       if (dict_lookup_var (dict, name) != NULL)
160         {
161           msg (SE, _("Target variable %s duplicates existing variable %s."),
162                name, name);
163           goto error;
164         }
165     }
166
167   /* Parse options. */
168   bool group = false;
169   while (lex_match (lexer, T_SLASH))
170     {
171       if (lex_match_id (lexer, "DESCENDING"))
172         direction = DESCENDING;
173       else if (lex_match_id (lexer, "PRINT"))
174         {
175           /* Not yet implemented. */
176         }
177       else if (lex_match_id (lexer, "GROUP"))
178         group = true;
179       else if (lex_match_id (lexer, "BLANK"))
180         {
181           lex_match (lexer, T_EQUALS);
182           if (lex_match_id (lexer, "VALID"))
183             {
184               arc->blank_valid = true;
185             }
186           else if (lex_match_id (lexer, "MISSING"))
187             {
188               arc->blank_valid = false;
189             }
190           else
191             {
192               lex_error_expecting (lexer, "VALID", "MISSING");
193               goto error;
194             }
195         }
196       else
197         {
198           lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
199           goto error;
200         }
201     }
202
203   if (lex_token (lexer) != T_ENDCMD)
204     {
205       lex_error (lexer, _("expecting end of command"));
206       goto error;
207     }
208
209   /* If GROUP is specified, verify that the variables are all string or all
210      numeric.  */
211   if (group)
212     {
213       enum val_type type = var_get_type (src_vars[0]);
214       for (size_t i = 1; i < n_dsts; i++)
215         {
216           if (var_get_type (src_vars[i]) != type)
217             {
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]));
225               goto error;
226             }
227         }
228     }
229
230   /* Allocate all the specs and the rec_items that they point to.
231
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++)
238     {
239       struct arc_spec *spec = &arc->specs[i];
240
241       spec->width = var_get_width (src_vars[i]);
242       spec->src_idx = var_get_case_index (src_vars[i]);
243
244       const char *label = var_get_label (src_vars[i]);
245       spec->label = label ? xstrdup (label) : NULL;
246
247       if (group && i > 0)
248         spec->items = arc->specs[0].items;
249       else
250         {
251           spec->items = xzalloc (sizeof (*spec->items));
252           hmap_init (&spec->items->ht);
253         }
254     }
255
256   /* Initialize specs[*]->mv to the user-missing values for each
257      source variable. */
258   if (group)
259     {
260       /* Use the first source variable that has any user-missing values. */
261       size_t mv_idx = 0;
262       for (size_t i = 0; i < n_dsts; i++)
263         if (var_has_missing_values (src_vars[i]))
264           {
265             mv_idx = i;
266             break;
267           }
268
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]));
271     }
272   else
273     {
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]));
277     }
278
279   /* Execute procedure. */
280   struct casereader *input = proc_open (ds);
281   struct ccase *c;
282   for (; (c = casereader_read (input)) != NULL; case_unref (c))
283     for (size_t i = 0; i < arc->n_specs; i++)
284       {
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)
288           {
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.) */
293             continue;
294           }
295
296         int width = value_trim_spaces (value, spec->width);
297         if (width == 1 && value->s[0] == ' ' && !arc->blank_valid)
298           continue;
299
300         size_t hash = value_hash (value, width, 0);
301         if (find_arc_item (spec->items, value, width, hash))
302           continue;
303
304         struct string value_label = DS_EMPTY_INITIALIZER;
305         var_append_value_name__ (src_vars[i], value,
306                                  SETTINGS_VALUE_SHOW_LABEL, &value_label);
307
308         struct arc_item *item = xmalloc (sizeof *item);
309         item->width = width;
310         value_clone (&item->from, value, width);
311         item->missing = mv_is_value_missing_varwidth (&spec->mv, value, spec->width,
312                                                       MV_ANY);
313         item->value_label = ds_steal_cstr (&value_label);
314         hmap_insert (&spec->items->ht, &item->hmap_node, hash);
315
316         ds_destroy (&value_label);
317       }
318   bool ok = casereader_destroy (input);
319   ok = proc_commit (ds) && ok;
320
321   /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
322      use). */
323   dict = dataset_dict (ds);
324
325   /* Create transformation. */
326   for (size_t i = 0; i < arc->n_specs; i++)
327     {
328       struct arc_spec *spec = &arc->specs[i];
329
330       /* Create destination variable. */
331       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
332       var_set_label (spec->dst, spec->label);
333
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);
340
341       /* Create array of pointers to items. */
342       struct arc_item **items = xmalloc (n_items * sizeof *items);
343       struct arc_item *item;
344       size_t j = 0;
345       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
346         items[j++] = item;
347       assert (j == n_items);
348
349       /* Sort array by value. */
350       sort (items, n_items, sizeof *items, compare_arc_items, &direction);
351
352       /* Assign recoded values in sorted order. */
353       for (j = 0; j < n_items; j++)
354         items[j]->to = j + 1;
355
356       /* Assign user-missing values.
357
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
366          feature). */
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)
370           {
371             n_missing = k;
372             break;
373           }
374       if (n_missing > 0)
375         {
376           size_t lo = n_items - (n_missing - 1);
377           size_t hi = n_items;
378
379           struct missing_values mv;
380           mv_init (&mv, 0);
381           if (n_missing > 3)
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);
387           mv_destroy (&mv);
388         }
389
390       /* Add value labels to the destination variable. */
391       for (j = 0; j < n_items; j++)
392         {
393           const char *value_label = items[j]->value_label;
394           if (value_label && value_label[0])
395             {
396               union value to_val = { .f = items[j]->to };
397               var_add_value_label (spec->dst, &to_val, value_label);
398             }
399         }
400
401       /* Free array. */
402       free (items);
403     }
404   add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
405
406   for (size_t i = 0; i < n_dsts; i++)
407     free (dst_names[i]);
408   free (dst_names);
409   free (src_vars);
410
411   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
412
413 error:
414   for (size_t i = 0; i < n_dsts; i++)
415     free (dst_names[i]);
416   free (dst_names);
417   free (src_vars);
418   arc_free (arc);
419   return CMD_CASCADING_FAILURE;
420 }
421
422 static void
423 arc_free (struct autorecode_pgm *arc)
424 {
425   if (arc != NULL)
426     {
427       for (size_t i = 0; i < arc->n_specs; i++)
428         {
429           struct arc_spec *spec = &arc->specs[i];
430           struct arc_item *item, *next;
431
432           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
433                               &spec->items->ht)
434             {
435               value_destroy (&item->from, item->width);
436               free (item->value_label);
437               hmap_delete (&spec->items->ht, &item->hmap_node);
438               free (item);
439             }
440           free (spec->label);
441           mv_destroy (&spec->mv);
442         }
443
444       size_t n_rec_items =
445         (arc->n_specs == 1 || arc->specs[0].items == arc->specs[1].items
446          ? 1
447          : arc->n_specs);
448       for (size_t i = 0; i < n_rec_items; i++)
449         {
450           struct arc_spec *spec = &arc->specs[i];
451           hmap_destroy (&spec->items->ht);
452           free (spec->items);
453         }
454
455       free (arc->specs);
456       free (arc);
457     }
458 }
459
460 static struct arc_item *
461 find_arc_item (const struct rec_items *items,
462                const union value *value, int width,
463                size_t hash)
464 {
465   struct arc_item *item;
466
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))
469       return item;
470   return NULL;
471 }
472
473 static int
474 compare_arc_items (const void *a_, const void *b_, const void *direction_)
475 {
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;
480
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;
485
486   /* Otherwise, compare the data. */
487   int aw = a->width;
488   int bw = b->width;
489   int cmp;
490   if (aw == bw)
491     cmp = value_compare_3way (&a->from, &b->from, aw);
492   else
493     {
494       assert (aw && bw);
495       cmp = buf_compare_rpad (CHAR_CAST_BUG (const char *, a->from.s), aw,
496                               CHAR_CAST_BUG (const char *, b->from.s), bw);
497     }
498
499   /* Then apply sort direction. */
500   const enum arc_direction *directionp = direction_;
501   enum arc_direction direction = *directionp;
502   return direction == ASCENDING ? cmp : -cmp;
503 }
504
505 static int
506 autorecode_trns_proc (void *arc_, struct ccase **c,
507                       casenumber case_idx UNUSED)
508 {
509   struct autorecode_pgm *arc = arc_;
510
511   *c = case_unshare (*c);
512   for (size_t i = 0; i < arc->n_specs; i++)
513     {
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,
519                                                    hash);
520       case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
521     }
522
523   return TRNS_CONTINUE;
524 }
525
526 static bool
527 autorecode_trns_free (void *arc_)
528 {
529   struct autorecode_pgm *arc = arc_;
530
531   arc_free (arc);
532   return true;
533 }