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