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