Add the /BLANK subcommand to AUTORECODE
[pspp] / src / language / stats / autorecode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010 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 <stdlib.h>
20
21 #include "data/case.h"
22 #include "data/casereader.h"
23 #include "data/dataset.h"
24 #include "data/dictionary.h"
25 #include "data/transformations.h"
26 #include "data/variable.h"
27 #include "language/command.h"
28 #include "language/lexer/lexer.h"
29 #include "language/lexer/variable-parser.h"
30 #include "libpspp/array.h"
31 #include "libpspp/compiler.h"
32 #include "libpspp/hash-functions.h"
33 #include "libpspp/hmap.h"
34 #include "libpspp/i18n.h"
35 #include "libpspp/message.h"
36 #include "libpspp/pool.h"
37 #include "libpspp/str.h"
38
39 #include "gl/xalloc.h"
40 #include "gl/vasnprintf.h"
41 #include "gl/mbiter.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* FIXME: Implement PRINT subcommand. */
47
48 /* Explains how to recode one value. */
49 struct arc_item
50   {
51     struct hmap_node hmap_node; /* Element in "struct arc_spec" hash table. */
52     union value from;           /* Original value. */
53     int width;                  /* Width of the original value */
54
55     double to;                  /* Recoded value. */
56   };
57
58 /* Explains how to recode an AUTORECODE variable. */
59 struct arc_spec
60   {
61     const struct variable *src; /* Source variable. */
62     struct variable *dst;       /* Target variable. */
63     struct hmap *items;         /* Hash table of "struct arc_item"s. */
64   };
65
66 /* Descending or ascending sort order. */
67 enum arc_direction
68   {
69     ASCENDING,
70     DESCENDING
71   };
72
73 /* AUTORECODE data. */
74 struct autorecode_pgm
75 {
76   struct arc_spec *specs;
77   size_t n_specs;
78
79   /* Hash table of "struct arc_item"s. */
80   struct hmap *global_items;
81
82   bool blank_valid;
83   const struct dictionary *dict;
84 };
85
86 static trns_proc_func autorecode_trns_proc;
87 static trns_free_func autorecode_trns_free;
88
89 static int compare_arc_items (const void *, const void *, const void *aux);
90 static void arc_free (struct autorecode_pgm *);
91 static struct arc_item *find_arc_item (const struct arc_spec *, const union value *,
92                                        size_t hash);
93
94 static bool
95 value_is_blank (const union value *val, int width, const struct dictionary *dict)
96 {
97   mbi_iterator_t iter;
98   const char *str = CHAR_CAST_BUG (const char*, value_str (val, width));
99   char *text = recode_string (UTF8, dict_get_encoding (dict), str, width);
100
101   for (mbi_init (iter, text, width); mbi_avail (iter); mbi_advance (iter))
102     {
103       mbchar_t c = mbi_cur (iter);
104
105       if ( ! mb_isblank (c))
106         {
107           free (text);
108           return false;
109         }
110     }
111
112   free (text);
113   return true;
114 }
115
116 /* Performs the AUTORECODE procedure. */
117 int
118 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
119 {
120   struct autorecode_pgm *arc = NULL;
121
122   struct dictionary *dict = dataset_dict (ds);
123   const struct variable **src_vars = NULL;
124   char **dst_names = NULL;
125   size_t n_srcs = 0;
126   size_t n_dsts = 0;
127
128   enum arc_direction direction = ASCENDING;
129   bool print = true;
130
131   struct casereader *input;
132   struct ccase *c;
133
134   size_t i;
135   bool ok;
136
137   /* Create procedure. */
138   arc = xzalloc (sizeof *arc);
139   arc->blank_valid = true;
140   arc->dict = dataset_dict (ds);
141
142   /* Parse variable lists. */
143   lex_match_id (lexer, "VARIABLES");
144   lex_match (lexer, T_EQUALS);
145   if (!parse_variables_const (lexer, arc->dict, &src_vars, &n_srcs,
146                               PV_NO_DUPLICATE))
147     goto error;
148   if (!lex_force_match_id (lexer, "INTO"))
149     goto error;
150   lex_match (lexer, T_EQUALS);
151   if (!parse_DATA_LIST_vars (lexer, arc->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 (i = 0; i < n_dsts; i++)
163     {
164       const char *name = dst_names[i];
165
166       if (dict_lookup_var (arc->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   while (lex_match (lexer, T_SLASH))
176     {
177       if (lex_match_id (lexer, "DESCENDING"))
178         direction = DESCENDING;
179       else if (lex_match_id (lexer, "PRINT"))
180         print = true;
181       else if (lex_match_id (lexer, "GROUP"))
182         {
183           arc->global_items = xmalloc (sizeof (*arc->global_items));
184           hmap_init (arc->global_items);
185         }
186       else if (lex_match_id (lexer, "BLANK"))
187         {
188           lex_match (lexer, T_EQUALS);
189           if (lex_match_id (lexer, "VALID"))
190             {
191               arc->blank_valid = true;
192             }
193           else if (lex_match_id (lexer, "MISSING"))
194             {
195               arc->blank_valid = false;
196             }
197           else
198             goto error;
199         }
200       else
201         goto error;
202     }
203
204   if (lex_token (lexer) != T_ENDCMD)
205     {
206       lex_error (lexer, _("expecting end of command"));
207       goto error;
208     }
209
210   arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
211   arc->n_specs = n_dsts;
212
213
214   for (i = 0; i < n_dsts; i++)
215     {
216       struct arc_spec *spec = &arc->specs[i];
217
218       spec->src = src_vars[i];
219       if (arc->global_items)
220         {
221           spec->items = arc->global_items;
222         }
223       else
224         {
225           spec->items = xmalloc (sizeof (*spec->items));
226           hmap_init (spec->items);
227         }
228     }
229
230
231   /* Execute procedure. */
232   input = proc_open (ds);
233   for (; (c = casereader_read (input)) != NULL; case_unref (c))
234     for (i = 0; i < arc->n_specs; i++)
235       {
236         struct arc_spec *spec = &arc->specs[i];
237         int width = var_get_width (spec->src);
238         const union value *value = case_data (c, spec->src);
239         size_t hash = value_hash (value, width, 0);
240         struct arc_item *item;
241
242         item = find_arc_item (spec, value, hash);
243         if ( (item == NULL)
244              &&  
245              ( arc->blank_valid || var_is_numeric (spec->src) || ! value_is_blank (value, width, arc->dict))
246              )
247           {
248             item = xmalloc (sizeof *item);
249             item->width = width;
250             value_clone (&item->from, value, width);
251             hmap_insert (spec->items, &item->hmap_node, hash);
252           }
253       }
254   ok = casereader_destroy (input);
255   ok = proc_commit (ds) && ok;
256
257   /* Create transformation. */
258   for (i = 0; i < arc->n_specs; i++)
259     {
260       struct arc_spec *spec = &arc->specs[i];
261       struct arc_item **items;
262       struct arc_item *item;
263       size_t n_items;
264       size_t j;
265
266       /* Create destination variable. */
267       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
268
269       /* Create array of pointers to items. */
270       n_items = hmap_count (spec->items);
271       items = xmalloc (n_items * sizeof *items);
272       j = 0;
273       HMAP_FOR_EACH (item, struct arc_item, hmap_node, spec->items)
274         items[j++] = item;
275
276       assert (j == n_items);
277
278       /* Sort array by value. */
279       sort (items, n_items, sizeof *items, compare_arc_items, NULL);
280
281       /* Assign recoded values in sorted order. */
282       for (j = 0; j < n_items; j++)
283         {
284           const union value *from = &items[j]->from;
285           size_t len;
286           char *recoded_value  = NULL;
287           char *c;
288           const int src_width = items[j]->width;
289           union value to_val;
290           value_init (&to_val, 0);
291
292           items[j]->to = direction == ASCENDING ? j + 1 : n_items - j;
293           
294           to_val.f = items[j]->to;
295
296           /* Add value labels to the destination variable which indicate
297              the source value from whence the new value comes. */
298           if (src_width > 0)
299             {
300               const char *str = CHAR_CAST_BUG (const char*, value_str (from, src_width));
301
302               recoded_value = recode_string (UTF8, dict_get_encoding (arc->dict), str, src_width);
303             }
304           else
305             recoded_value = asnprintf (NULL, &len, "%g", from->f);
306           
307           /* Remove trailing whitespace */
308           for (c = recoded_value; *c != '\0'; c++)
309             if ( *c == ' ')
310               {
311                 *c = '\0';
312                 break;
313               }
314
315           var_add_value_label (spec->dst, &to_val, recoded_value);
316           value_destroy (&to_val, 0);
317           free (recoded_value);
318         }
319
320       /* Free array. */
321       free (items);
322     }
323   add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
324
325   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
326
327 error:
328   for (i = 0; i < n_dsts; i++)
329     free (dst_names[i]);
330   free (dst_names);
331   free (src_vars);
332   arc_free (arc);
333   return CMD_CASCADING_FAILURE;
334 }
335
336 static void
337 arc_free (struct autorecode_pgm *arc)
338 {
339   if (arc != NULL)
340     {
341       size_t i;
342
343       for (i = 0; i < arc->n_specs; i++)
344         {
345           struct arc_spec *spec = &arc->specs[i];
346           struct arc_item *item, *next;
347
348           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
349                               spec->items)
350             {
351               value_destroy (&item->from, item->width);
352               hmap_delete (spec->items, &item->hmap_node);
353               free (item);
354             }
355         }
356
357       if (arc->global_items)
358         {
359           free (arc->global_items);
360         }
361       else
362         {
363           for (i = 0; i < arc->n_specs; i++)
364             {
365               struct arc_spec *spec = &arc->specs[i];
366               if (spec->items)
367                 {
368                   hmap_destroy (spec->items);
369                   free (spec->items);
370                 }
371             }
372         }
373
374       free (arc->specs);
375       free (arc);
376     }
377 }
378
379 static struct arc_item *
380 find_arc_item (const struct arc_spec *spec, const union value *value,
381                size_t hash)
382 {
383   struct arc_item *item;
384
385   HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, spec->items)
386     if (value_equal (value, &item->from, var_get_width (spec->src)))
387       return item;
388   return NULL;
389 }
390
391 static int
392 compare_arc_items (const void *a_, const void *b_, const void *aux UNUSED)
393 {
394   const struct arc_item *const *a = a_;
395   const struct arc_item *const *b = b_;
396   int width_a = (*a)->width;
397   int width_b = (*b)->width;
398
399   if ( width_a == width_b)
400     return value_compare_3way (&(*a)->from, &(*b)->from, width_a);
401
402   if ( width_a == 0 && width_b != 0)
403     return -1;
404
405   if ( width_b == 0 && width_a != 0)
406     return +1;
407
408   return buf_compare_rpad (CHAR_CAST_BUG (const char *, value_str (&(*a)->from, width_a)), width_a,
409                            CHAR_CAST_BUG (const char *, value_str (&(*b)->from, width_b)), width_b);
410 }
411
412 static int
413 autorecode_trns_proc (void *arc_, struct ccase **c,
414                       casenumber case_idx UNUSED)
415 {
416   struct autorecode_pgm *arc = arc_;
417   size_t i;
418
419   *c = case_unshare (*c);
420   for (i = 0; i < arc->n_specs; i++)
421     {
422       const struct arc_spec *spec = &arc->specs[i];
423       int width = var_get_width (spec->src);
424       const union value *value = case_data (*c, spec->src);
425       const struct arc_item *item = find_arc_item (spec, value, value_hash (value, width, 0));
426
427       case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
428     }
429
430   return TRNS_CONTINUE;
431 }
432
433 static bool
434 autorecode_trns_free (void *arc_)
435 {
436   struct autorecode_pgm *arc = arc_;
437
438   arc_free (arc);
439   return true;
440 }