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