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