03de84e28592b3d5422df5192518d27b3e01d498
[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/dictionary.h"
24 #include "data/procedure.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/i18n.h"
32 #include "libpspp/compiler.h"
33 #include "libpspp/hash-functions.h"
34 #include "libpspp/hmap.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
42 #include "gettext.h"
43 #define _(msgid) gettext (msgid)
44
45 /* FIXME: Implement PRINT subcommand. */
46
47 /* Explains how to recode one value. */
48 struct arc_item
49   {
50     struct hmap_node hmap_node; /* Element in "struct arc_spec" hash table. */
51     union value from;           /* Original value. */
52     double to;                  /* Recoded value. */
53   };
54
55 /* Explains how to recode an AUTORECODE variable. */
56 struct arc_spec
57   {
58     const struct variable *src; /* Source variable. */
59     struct variable *dst;       /* Target variable. */
60     struct hmap items;          /* Hash table of "struct arc_item"s. */
61   };
62
63 /* Descending or ascending sort order. */
64 enum arc_direction
65   {
66     ASCENDING,
67     DESCENDING
68   };
69
70 /* AUTORECODE data. */
71 struct autorecode_pgm
72   {
73     struct arc_spec *specs;
74     size_t n_specs;
75   };
76
77 static trns_proc_func autorecode_trns_proc;
78 static trns_free_func autorecode_trns_free;
79
80 static int compare_arc_items (const void *, const void *, const void *width);
81 static void arc_free (struct autorecode_pgm *);
82 static struct arc_item *find_arc_item (struct arc_spec *, const union value *,
83                                        size_t hash);
84
85 /* Performs the AUTORECODE procedure. */
86 int
87 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
88 {
89   struct autorecode_pgm *arc = NULL;
90   struct dictionary *dict = dataset_dict (ds);
91
92   const struct variable **src_vars = NULL;
93   char **dst_names = NULL;
94   size_t n_srcs = 0;
95   size_t n_dsts = 0;
96
97   enum arc_direction direction;
98   bool print;
99
100   struct casereader *input;
101   struct ccase *c;
102
103   size_t i;
104   bool ok;
105
106   /* Parse variable lists. */
107   lex_match_id (lexer, "VARIABLES");
108   lex_match (lexer, '=');
109   if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
110                               PV_NO_DUPLICATE))
111     goto error;
112   if (!lex_force_match_id (lexer, "INTO"))
113     goto error;
114   lex_match (lexer, '=');
115   if (!parse_DATA_LIST_vars (lexer, &dst_names, &n_dsts, PV_NO_DUPLICATE))
116     goto error;
117   if (n_dsts != n_srcs)
118     {
119       msg (SE, _("Source variable count (%zu) does not match "
120                  "target variable count (%zu)."),
121            n_srcs, n_dsts);
122
123       goto error;
124     }
125   for (i = 0; i < n_dsts; i++)
126     {
127       const char *name = dst_names[i];
128
129       if (dict_lookup_var (dict, name) != NULL)
130         {
131           msg (SE, _("Target variable %s duplicates existing variable %s."),
132                name, name);
133           goto error;
134         }
135     }
136
137   /* Parse options. */
138   direction = ASCENDING;
139   print = false;
140   while (lex_match (lexer, '/'))
141     if (lex_match_id (lexer, "DESCENDING"))
142       direction = DESCENDING;
143     else if (lex_match_id (lexer, "PRINT"))
144       print = true;
145   if (lex_token (lexer) != '.')
146     {
147       lex_error (lexer, _("expecting end of command"));
148       goto error;
149     }
150
151   /* Create procedure. */
152   arc = xmalloc (sizeof *arc);
153   arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
154   arc->n_specs = n_dsts;
155   for (i = 0; i < n_dsts; i++)
156     {
157       struct arc_spec *spec = &arc->specs[i];
158
159       spec->src = src_vars[i];
160       hmap_init (&spec->items);
161     }
162
163   /* Execute procedure. */
164   input = proc_open (ds);
165   for (; (c = casereader_read (input)) != NULL; case_unref (c))
166     for (i = 0; i < arc->n_specs; i++)
167       {
168         struct arc_spec *spec = &arc->specs[i];
169         int width = var_get_width (spec->src);
170         const union value *value = case_data (c, spec->src);
171         size_t hash = value_hash (value, width, 0);
172         struct arc_item *item;
173
174         item = find_arc_item (spec, value, hash);
175         if (item == NULL)
176           {
177             item = xmalloc (sizeof *item);
178             value_clone (&item->from, value, width);
179             hmap_insert (&spec->items, &item->hmap_node, hash);
180           }
181       }
182   ok = casereader_destroy (input);
183   ok = proc_commit (ds) && ok;
184
185   /* Create transformation. */
186   for (i = 0; i < arc->n_specs; i++)
187     {
188       struct arc_spec *spec = &arc->specs[i];
189       struct arc_item **items;
190       struct arc_item *item;
191       size_t n_items;
192       int src_width;
193       size_t j;
194
195       /* Create destination variable. */
196       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
197
198       /* Create array of pointers to items. */
199       n_items = hmap_count (&spec->items);
200       items = xmalloc (n_items * sizeof *items);
201       j = 0;
202       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items)
203         items[j++] = item;
204       assert (j == n_items);
205
206       /* Sort array by value. */
207       src_width = var_get_width (spec->src);
208       sort (items, n_items, sizeof *items, compare_arc_items, &src_width);
209
210       /* Assign recoded values in sorted order. */
211       for (j = 0; j < n_items; j++)
212         {
213           const union value *from = &items[j]->from;
214           size_t len;
215           char *recoded_value  = NULL;
216           char *c;
217
218           union value to_val;
219           value_init (&to_val, 0);
220
221           items[j]->to = direction == ASCENDING ? j + 1 : n_items - j;
222           
223           to_val.f = items[j]->to;
224
225           /* Add value labels to the destination variable which indicate
226              the source value from whence the new value comes. */
227
228           if (src_width > 0)
229             recoded_value = 
230               recode_string (UTF8, dict_get_encoding (dict), (char *) value_str (from, src_width), src_width);
231           else
232             recoded_value = asnprintf (NULL, &len, "%g", from->f);
233           
234           /* Remove trailing whitespace */
235           for (c = recoded_value; *c != '\0'; c++)
236             if ( *c == ' ')
237               {
238                 *c = '\0';
239                 break;
240               }
241
242           var_add_value_label (spec->dst, &to_val, recoded_value);
243           value_destroy (&to_val, 0);
244           free (recoded_value);
245         }
246
247       /* Free array. */
248       free (items);
249     }
250   add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
251
252   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
253
254 error:
255   for (i = 0; i < n_dsts; i++)
256     free (dst_names[i]);
257   free (dst_names);
258   free (src_vars);
259   arc_free (arc);
260   return CMD_CASCADING_FAILURE;
261 }
262
263 static void
264 arc_free (struct autorecode_pgm *arc)
265 {
266   if (arc != NULL)
267     {
268       size_t i;
269
270       for (i = 0; i < arc->n_specs; i++)
271         {
272           struct arc_spec *spec = &arc->specs[i];
273           int width = var_get_width (spec->src);
274           struct arc_item *item, *next;
275
276           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
277                               &spec->items)
278             {
279               value_destroy (&item->from, width);
280               hmap_delete (&spec->items, &item->hmap_node);
281               free (item);
282             }
283           hmap_destroy (&spec->items);
284         }
285       free (arc->specs);
286       free (arc);
287     }
288 }
289
290 static struct arc_item *
291 find_arc_item (struct arc_spec *spec, const union value *value,
292                size_t hash)
293 {
294   struct arc_item *item;
295
296   HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash,
297                            &spec->items)
298     if (value_equal (value, &item->from, var_get_width (spec->src)))
299       return item;
300   return NULL;
301 }
302
303 static int
304 compare_arc_items (const void *a_, const void *b_, const void *width_)
305 {
306   const struct arc_item *const *a = a_;
307   const struct arc_item *const *b = b_;
308   const int *width = width_;
309
310   return value_compare_3way (&(*a)->from, &(*b)->from, *width);
311 }
312
313 static int
314 autorecode_trns_proc (void *arc_, struct ccase **c,
315                       casenumber case_idx UNUSED)
316 {
317   struct autorecode_pgm *arc = arc_;
318   size_t i;
319
320   *c = case_unshare (*c);
321   for (i = 0; i < arc->n_specs; i++)
322     {
323       struct arc_spec *spec = &arc->specs[i];
324       int width = var_get_width (spec->src);
325       const union value *value = case_data (*c, spec->src);
326       struct arc_item *item;
327
328       item = find_arc_item (spec, value, value_hash (value, width, 0));
329       case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
330     }
331
332   return TRNS_CONTINUE;
333 }
334
335 static bool
336 autorecode_trns_free (void *arc_)
337 {
338   struct autorecode_pgm *arc = arc_;
339
340   arc_free (arc);
341   return true;
342 }