Merge 'psppsheet' into 'master'.
[pspp] / src / language / stats / autorecode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2012, 2013 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/c-xvasprintf.h"
41 #include "gl/mbiter.h"
42
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 /* FIXME: Implement PRINT subcommand. */
48
49 /* Explains how to recode one value. */
50 struct arc_item
51   {
52     struct hmap_node hmap_node; /* Element in "struct arc_spec" hash table. */
53     union value from;           /* Original value. */
54     int width;                  /* Width of the original value */
55
56     double to;                  /* Recoded value. */
57   };
58
59 /* Explains how to recode an AUTORECODE variable. */
60 struct arc_spec
61   {
62     int width;                  /* Variable width. */
63     int src_idx;                /* Case index of source variable. */
64     struct variable *dst;       /* Target variable. */
65     struct rec_items *items;
66   };
67
68 /* Descending or ascending sort order. */
69 enum arc_direction
70   {
71     ASCENDING,
72     DESCENDING
73   };
74
75 struct rec_items
76 {
77   struct hmap ht;         /* Hash table of "struct arc_item"s. */
78   int refcnt;
79 };
80
81
82
83 /* AUTORECODE data. */
84 struct autorecode_pgm
85 {
86   struct arc_spec *specs;
87   size_t n_specs;
88
89   /* Hash table of "struct arc_item"s. */
90   struct rec_items *global_items;
91
92   bool blank_valid;
93 };
94
95 static trns_proc_func autorecode_trns_proc;
96 static trns_free_func autorecode_trns_free;
97
98 static int compare_arc_items (const void *, const void *, const void *aux);
99 static void arc_free (struct autorecode_pgm *);
100 static struct arc_item *find_arc_item (const struct arc_spec *, const union value *,
101                                        size_t hash);
102
103 static bool
104 value_is_blank (const union value *val, int width, const struct dictionary *dict)
105 {
106   mbi_iterator_t iter;
107   const char *str = CHAR_CAST_BUG (const char*, value_str (val, width));
108   char *text = recode_string (UTF8, dict_get_encoding (dict), str, width);
109
110   for (mbi_init (iter, text, width); mbi_avail (iter); mbi_advance (iter))
111     {
112       mbchar_t c = mbi_cur (iter);
113
114       if ( ! mb_isblank (c))
115         {
116           free (text);
117           return false;
118         }
119     }
120
121   free (text);
122   return true;
123 }
124
125 /* Performs the AUTORECODE procedure. */
126 int
127 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
128 {
129   struct autorecode_pgm *arc = NULL;
130
131   struct dictionary *dict = dataset_dict (ds);
132   const struct variable **src_vars = NULL;
133   char **dst_names = NULL;
134   size_t n_srcs = 0;
135   size_t n_dsts = 0;
136
137   enum arc_direction direction = ASCENDING;
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
149   /* Parse variable lists. */
150   lex_match_id (lexer, "VARIABLES");
151   lex_match (lexer, T_EQUALS);
152   if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
153                               PV_NO_DUPLICATE | PV_NO_SCRATCH))
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, 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 (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->width = var_get_width (src_vars[i]);
229       spec->src_idx = var_get_case_index (src_vars[i]);
230
231       if (arc->global_items)
232         {
233           arc->global_items->refcnt++;
234           spec->items = arc->global_items;
235         }
236       else
237         {
238           spec->items = xzalloc (sizeof (*spec->items));
239           spec->items->refcnt = 1;
240           hmap_init (&spec->items->ht);
241         }
242     }
243
244
245   /* Execute procedure. */
246   input = proc_open (ds);
247   for (; (c = casereader_read (input)) != NULL; case_unref (c))
248     for (i = 0; i < arc->n_specs; i++)
249       {
250         struct arc_spec *spec = &arc->specs[i];
251         int width = spec->width;
252         const union value *value = case_data_idx (c, spec->src_idx);
253         size_t hash = value_hash (value, width, 0);
254         struct arc_item *item;
255
256         item = find_arc_item (spec, value, hash);
257         if ( (item == NULL)
258              &&  
259              ( arc->blank_valid
260                || val_type_from_width (spec->width) == VAL_NUMERIC
261                || ! value_is_blank (value, width, dict))
262              )
263           {
264             item = xmalloc (sizeof *item);
265             item->width = width;
266             value_clone (&item->from, value, width);
267             hmap_insert (&spec->items->ht, &item->hmap_node, hash);
268           }
269       }
270   ok = casereader_destroy (input);
271   ok = proc_commit (ds) && ok;
272
273   /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
274      use). */
275   dict = dataset_dict (ds);
276
277   /* Create transformation. */
278   for (i = 0; i < arc->n_specs; i++)
279     {
280       struct arc_spec *spec = &arc->specs[i];
281       struct arc_item **items;
282       struct arc_item *item;
283       size_t n_items;
284       size_t j;
285
286       /* Create destination variable. */
287       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
288
289       /* Create array of pointers to items. */
290       n_items = hmap_count (&spec->items->ht);
291       items = xmalloc (n_items * sizeof *items);
292       j = 0;
293       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
294         items[j++] = item;
295
296       assert (j == n_items);
297
298       /* Sort array by value. */
299       sort (items, n_items, sizeof *items, compare_arc_items, NULL);
300
301       /* Assign recoded values in sorted order. */
302       for (j = 0; j < n_items; j++)
303         {
304           const union value *from = &items[j]->from;
305           char *recoded_value  = NULL;
306           const int src_width = items[j]->width;
307           union value to_val;
308           size_t len;
309
310           value_init (&to_val, 0);
311
312           items[j]->to = direction == ASCENDING ? j + 1 : n_items - j;
313           
314           to_val.f = items[j]->to;
315
316           /* Add value labels to the destination variable which indicate
317              the source value from whence the new value comes. */
318           if (src_width > 0)
319             {
320               const char *str = CHAR_CAST_BUG (const char*, value_str (from, src_width));
321
322               recoded_value = recode_string (UTF8, dict_get_encoding (dict),
323                                              str, src_width);
324             }
325           else
326             recoded_value = c_xasprintf ("%g", from->f);
327           
328           /* Remove trailing whitespace */
329           len = strlen (recoded_value);
330           while (len > 0 && recoded_value[len - 1] == ' ')
331             recoded_value[--len] = '\0';
332
333           var_add_value_label (spec->dst, &to_val, recoded_value);
334           value_destroy (&to_val, 0);
335           free (recoded_value);
336         }
337
338       /* Free array. */
339       free (items);
340     }
341   add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
342
343   for (i = 0; i < n_dsts; i++)
344     free (dst_names[i]);
345   free (dst_names);
346   free (src_vars);
347
348   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
349
350 error:
351   for (i = 0; i < n_dsts; i++)
352     free (dst_names[i]);
353   free (dst_names);
354   free (src_vars);
355   arc_free (arc);
356   return CMD_CASCADING_FAILURE;
357 }
358
359 static void
360 arc_free (struct autorecode_pgm *arc)
361 {
362   if (arc != NULL)
363     {
364       size_t i;
365
366       for (i = 0; i < arc->n_specs; i++)
367         {
368           struct arc_spec *spec = &arc->specs[i];
369           struct arc_item *item, *next;
370
371           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
372                               &spec->items->ht)
373             {
374               value_destroy (&item->from, item->width);
375               hmap_delete (&spec->items->ht, &item->hmap_node);
376               free (item);
377             }
378         }
379
380       for (i = 0; i < arc->n_specs; i++)
381         {
382           struct arc_spec *spec = &arc->specs[i];
383           
384           if (--spec->items->refcnt == 0)
385             {
386               hmap_destroy (&spec->items->ht);
387               free (spec->items);
388             }
389         }
390
391       if (arc->global_items && --arc->global_items->refcnt == 0)
392         {
393           hmap_destroy (&arc->global_items->ht);
394           free (arc->global_items);
395         }
396       
397       free (arc->specs);
398       free (arc);
399     }
400 }
401
402 static struct arc_item *
403 find_arc_item (const struct arc_spec *spec, const union value *value,
404                size_t hash)
405 {
406   struct arc_item *item;
407
408   HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, &spec->items->ht)
409     if (value_equal (value, &item->from, spec->width))
410       return item;
411   return NULL;
412 }
413
414 static int
415 compare_arc_items (const void *a_, const void *b_, const void *aux UNUSED)
416 {
417   const struct arc_item *const *a = a_;
418   const struct arc_item *const *b = b_;
419   int width_a = (*a)->width;
420   int width_b = (*b)->width;
421
422   if ( width_a == width_b)
423     return value_compare_3way (&(*a)->from, &(*b)->from, width_a);
424
425   if ( width_a == 0 && width_b != 0)
426     return -1;
427
428   if ( width_b == 0 && width_a != 0)
429     return +1;
430
431   return buf_compare_rpad (CHAR_CAST_BUG (const char *, value_str (&(*a)->from, width_a)), width_a,
432                            CHAR_CAST_BUG (const char *, value_str (&(*b)->from, width_b)), width_b);
433 }
434
435 static int
436 autorecode_trns_proc (void *arc_, struct ccase **c,
437                       casenumber case_idx UNUSED)
438 {
439   struct autorecode_pgm *arc = arc_;
440   size_t i;
441
442   *c = case_unshare (*c);
443   for (i = 0; i < arc->n_specs; i++)
444     {
445       const struct arc_spec *spec = &arc->specs[i];
446       const union value *value = case_data_idx (*c, spec->src_idx);
447       unsigned int hash = value_hash (value, spec->width, 0);
448       const struct arc_item *item = find_arc_item (spec, value, hash);
449
450       case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
451     }
452
453   return TRNS_CONTINUE;
454 }
455
456 static bool
457 autorecode_trns_free (void *arc_)
458 {
459   struct autorecode_pgm *arc = arc_;
460
461   arc_free (arc);
462   return true;
463 }