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