893880a61b5f8476ebe270bb25ca3476cd0e4c1a
[pspp-builds.git] / src / language / stats / autorecode.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    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, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19 #include <config.h>
20 #include <stdlib.h>
21
22 #include <data/case.h>
23 #include <data/casereader.h>
24 #include <data/dictionary.h>
25 #include <data/procedure.h>
26 #include <data/transformations.h>
27 #include <data/variable.h>
28 #include <language/command.h>
29 #include <language/lexer/lexer.h>
30 #include <language/lexer/variable-parser.h>
31 #include <libpspp/alloc.h>
32 #include <libpspp/compiler.h>
33 #include <libpspp/hash.h>
34 #include <libpspp/message.h>
35 #include <libpspp/message.h>
36 #include <libpspp/pool.h>
37 #include <libpspp/str.h>
38
39 #include "gettext.h"
40 #define _(msgid) gettext (msgid)
41
42 /* FIXME: Implement PRINT subcommand. */
43
44 /* An AUTORECODE variable's original value. */
45 union arc_value
46   {
47     double f;                   /* Numeric. */
48     char *c;                    /* Short or long string. */
49   };
50
51 /* Explains how to recode one value.  `from' must be first element.  */
52 struct arc_item
53   {
54     union arc_value from;       /* Original value. */
55     double to;                  /* Recoded value. */
56   };
57
58 /* Explains how to recode an AUTORECODE variable. */
59 struct arc_spec
60   {
61     const struct variable *src; /* Source variable. */
62     struct variable *dest;      /* Target variable. */
63     struct hsh_table *items;    /* Hash table of `freq's. */
64   };
65
66 /* AUTORECODE transformation. */
67 struct autorecode_trns
68   {
69     struct pool *pool;          /* Contains AUTORECODE specs. */
70     struct arc_spec *specs;     /* AUTORECODE specifications. */
71     size_t spec_cnt;            /* Number of specifications. */
72   };
73
74 /* Descending or ascending sort order. */
75 enum direction
76   {
77     ASCENDING,
78     DESCENDING
79   };
80
81 /* AUTORECODE data. */
82 struct autorecode_pgm
83   {
84     const struct variable **src_vars;    /* Source variables. */
85     char **dst_names;              /* Target variable names. */
86     struct variable **dst_vars;    /* Target variables. */
87     struct hsh_table **src_values; /* `union arc_value's of source vars. */
88     size_t var_cnt;                /* Number of variables. */
89     struct pool *src_values_pool;  /* Pool used by src_values. */
90     enum direction direction;      /* Sort order. */
91     int print;                     /* Print mapping table if nonzero. */
92   };
93
94 static trns_proc_func autorecode_trns_proc;
95 static trns_free_func autorecode_trns_free;
96 static hsh_compare_func compare_alpha_value, compare_numeric_value;
97 static hsh_hash_func hash_alpha_value, hash_numeric_value;
98
99 static void recode (struct dataset *, const struct autorecode_pgm *);
100 static void arc_free (struct autorecode_pgm *);
101
102 /* Performs the AUTORECODE procedure. */
103 int
104 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
105 {
106   struct autorecode_pgm arc;
107   struct casereader *input;
108   struct ccase c;
109   size_t dst_cnt;
110   size_t i;
111   bool ok;
112
113   arc.src_vars = NULL;
114   arc.dst_names = NULL;
115   arc.dst_vars = NULL;
116   arc.src_values = NULL;
117   arc.var_cnt = 0;
118   arc.src_values_pool = NULL;
119   arc.direction = ASCENDING;
120   arc.print = 0;
121   dst_cnt = 0;
122
123   lex_match_id (lexer, "VARIABLES");
124   lex_match (lexer, '=');
125   if (!parse_variables_const (lexer, dataset_dict (ds), &arc.src_vars,
126                               &arc.var_cnt,
127                         PV_NO_DUPLICATE))
128     goto lossage;
129   if (!lex_force_match_id (lexer, "INTO"))
130     goto lossage;
131   lex_match (lexer, '=');
132   if (!parse_DATA_LIST_vars (lexer, &arc.dst_names, &dst_cnt, PV_NONE))
133     goto lossage;
134   if (dst_cnt != arc.var_cnt)
135     {
136       size_t i;
137
138       msg (SE, _("Source variable count (%u) does not match "
139                  "target variable count (%u)."),
140            (unsigned) arc.var_cnt, (unsigned) dst_cnt);
141
142       for (i = 0; i < dst_cnt; i++)
143         free (arc.dst_names[i]);
144       free (arc.dst_names);
145       arc.dst_names = NULL;
146
147       goto lossage;
148     }
149   while (lex_match (lexer, '/'))
150     if (lex_match_id (lexer, "DESCENDING"))
151       arc.direction = DESCENDING;
152     else if (lex_match_id (lexer, "PRINT"))
153       arc.print = 1;
154   if (lex_token (lexer) != '.')
155     {
156       lex_error (lexer, _("expecting end of command"));
157       goto lossage;
158     }
159
160   for (i = 0; i < arc.var_cnt; i++)
161     {
162       int j;
163
164       if (dict_lookup_var (dataset_dict (ds), arc.dst_names[i]) != NULL)
165         {
166           msg (SE, _("Target variable %s duplicates existing variable %s."),
167                arc.dst_names[i], arc.dst_names[i]);
168           goto lossage;
169         }
170       for (j = 0; j < i; j++)
171         if (!strcasecmp (arc.dst_names[i], arc.dst_names[j]))
172           {
173             msg (SE, _("Duplicate variable name %s among target variables."),
174                  arc.dst_names[i]);
175             goto lossage;
176           }
177     }
178
179   arc.src_values_pool = pool_create ();
180   arc.dst_vars = xnmalloc (arc.var_cnt, sizeof *arc.dst_vars);
181   arc.src_values = xnmalloc (arc.var_cnt, sizeof *arc.src_values);
182   for (i = 0; i < dst_cnt; i++)
183     {
184         /* FIXME: consolodate this hsh_create */
185     if (var_is_alpha (arc.src_vars[i]))
186       arc.src_values[i] = hsh_create (10, compare_alpha_value,
187                                       hash_alpha_value, NULL, arc.src_vars[i]);
188     else
189       arc.src_values[i] = hsh_create (10, compare_numeric_value,
190                                       hash_numeric_value, NULL, NULL);
191    }
192
193   input = proc_open (ds);
194   for (; casereader_read (input, &c); case_destroy (&c))
195     for (i = 0; i < arc.var_cnt; i++)
196       {
197         union arc_value v, *vp, **vpp;
198
199         if (var_is_numeric (arc.src_vars[i]))
200           v.f = case_num (&c, arc.src_vars[i]);
201         else
202           v.c = (char *) case_str (&c, arc.src_vars[i]);
203
204         vpp = (union arc_value **) hsh_probe (arc.src_values[i], &v);
205         if (*vpp == NULL)
206           {
207             vp = pool_alloc (arc.src_values_pool, sizeof *vp);
208             if (var_is_numeric (arc.src_vars[i]))
209               vp->f = v.f;
210             else
211               vp->c = pool_clone (arc.src_values_pool,
212                                   v.c, var_get_width (arc.src_vars[i]));
213             *vpp = vp;
214           }
215       }
216   ok = casereader_destroy (input);
217   ok = proc_commit (ds) && ok;
218
219   for (i = 0; i < arc.var_cnt; i++)
220     arc.dst_vars[i] = dict_create_var_assert (dataset_dict (ds),
221                                               arc.dst_names[i], 0);
222
223   recode (ds, &arc);
224   arc_free (&arc);
225   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
226
227 lossage:
228   arc_free (&arc);
229   return CMD_CASCADING_FAILURE;
230 }
231
232 static void
233 arc_free (struct autorecode_pgm *arc)
234 {
235   free (arc->src_vars);
236   if (arc->dst_names != NULL)
237     {
238       size_t i;
239
240       for (i = 0; i < arc->var_cnt; i++)
241         free (arc->dst_names[i]);
242       free (arc->dst_names);
243     }
244   free (arc->dst_vars);
245   if (arc->src_values != NULL)
246     {
247       size_t i;
248
249       for (i = 0; i < arc->var_cnt; i++)
250         hsh_destroy (arc->src_values[i]);
251       free (arc->src_values);
252     }
253   pool_destroy (arc->src_values_pool);
254 }
255
256 \f
257 /* AUTORECODE transformation. */
258
259 static void
260 recode (struct dataset *ds, const struct autorecode_pgm *arc)
261 {
262   struct autorecode_trns *trns;
263   size_t i;
264
265   trns = pool_create_container (struct autorecode_trns, pool);
266   trns->specs = pool_nalloc (trns->pool, arc->var_cnt, sizeof *trns->specs);
267   trns->spec_cnt = arc->var_cnt;
268   for (i = 0; i < arc->var_cnt; i++)
269     {
270       struct arc_spec *spec = &trns->specs[i];
271       void *const *p = hsh_sort (arc->src_values[i]);
272       int count = hsh_count (arc->src_values[i]);
273       int j;
274
275       spec->src = arc->src_vars[i];
276       spec->dest = arc->dst_vars[i];
277
278       if (var_is_alpha (arc->src_vars[i]))
279         spec->items = hsh_create (2 * count, compare_alpha_value,
280                                   hash_alpha_value, NULL, arc->src_vars[i]);
281       else
282         spec->items = hsh_create (2 * count, compare_numeric_value,
283                                   hash_numeric_value, NULL, NULL);
284
285       for (j = 0; *p; p++, j++)
286         {
287           struct arc_item *item = pool_alloc (trns->pool, sizeof *item);
288           union arc_value *vp = *p;
289
290           if (var_is_numeric (arc->src_vars[i]))
291             item->from.f = vp->f;
292           else
293             item->from.c = pool_clone (trns->pool, vp->c,
294                                        var_get_width (arc->src_vars[i]));
295           item->to = arc->direction == ASCENDING ? j + 1 : count - j;
296           hsh_force_insert (spec->items, item);
297         }
298     }
299   add_transformation (ds,
300                       autorecode_trns_proc, autorecode_trns_free, trns);
301 }
302
303 /* Executes an AUTORECODE transformation. */
304 static int
305 autorecode_trns_proc (void *trns_, struct ccase *c, casenumber case_idx UNUSED)
306 {
307   struct autorecode_trns *trns = trns_;
308   size_t i;
309
310   for (i = 0; i < trns->spec_cnt; i++)
311     {
312       struct arc_spec *spec = &trns->specs[i];
313       struct arc_item *item;
314       union arc_value v;
315
316       if (var_is_numeric (spec->src))
317         v.f = case_num (c, spec->src);
318       else
319         v.c = (char *) case_str (c, spec->src);
320       item = hsh_force_find (spec->items, &v);
321
322       case_data_rw (c, spec->dest)->f = item->to;
323     }
324   return TRNS_CONTINUE;
325 }
326
327 /* Frees an AUTORECODE transformation. */
328 static bool
329 autorecode_trns_free (void *trns_)
330 {
331   struct autorecode_trns *trns = trns_;
332   size_t i;
333
334   for (i = 0; i < trns->spec_cnt; i++)
335     hsh_destroy (trns->specs[i].items);
336   pool_destroy (trns->pool);
337   return true;
338 }
339 \f
340 /* AUTORECODE procedure. */
341
342 static int
343 compare_alpha_value (const void *a_, const void *b_, const void *v_)
344 {
345   const union arc_value *a = a_;
346   const union arc_value *b = b_;
347   const struct variable *v = v_;
348
349   return memcmp (a->c, b->c, var_get_width (v));
350 }
351
352 static unsigned
353 hash_alpha_value (const void *a_, const void *v_)
354 {
355   const union arc_value *a = a_;
356   const struct variable *v = v_;
357
358   return hsh_hash_bytes (a->c, var_get_width (v));
359 }
360
361 static int
362 compare_numeric_value (const void *a_, const void *b_, const void *aux UNUSED)
363 {
364   const union arc_value *a = a_;
365   const union arc_value *b = b_;
366
367   return a->f < b->f ? -1 : a->f > b->f;
368 }
369
370 static unsigned
371 hash_numeric_value (const void *a_, const void *aux UNUSED)
372 {
373   const union arc_value *a = a_;
374
375   return hsh_hash_double (a->f);
376 }