048db1191cbecffe1a8dd055e126c9ceb1e71192
[pspp-builds.git] / src / language / stats / autorecode.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include <stdlib.h>
22
23 #include <data/case.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     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     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 bool autorecode_proc_func (const struct ccase *, void *, const struct dataset *);
97 static hsh_compare_func compare_alpha_value, compare_numeric_value;
98 static hsh_hash_func hash_alpha_value, hash_numeric_value;
99
100 static void recode (struct dataset *, const struct autorecode_pgm *);
101 static void arc_free (struct autorecode_pgm *);
102
103 /* Performs the AUTORECODE procedure. */
104 int
105 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
106 {
107   struct autorecode_pgm arc;
108   size_t dst_cnt;
109   size_t i;
110   bool ok;
111
112   arc.src_vars = NULL;
113   arc.dst_names = NULL;
114   arc.dst_vars = NULL;
115   arc.src_values = NULL;
116   arc.var_cnt = 0;
117   arc.src_values_pool = NULL;
118   arc.direction = ASCENDING;
119   arc.print = 0;
120   dst_cnt = 0;
121
122   lex_match_id (lexer, "VARIABLES");
123   lex_match (lexer, '=');
124   if (!parse_variables (lexer, dataset_dict (ds), &arc.src_vars, &arc.var_cnt,
125                         PV_NO_DUPLICATE))
126     goto lossage;
127   if (!lex_force_match_id (lexer, "INTO"))
128     goto lossage;
129   lex_match (lexer, '=');
130   if (!parse_DATA_LIST_vars (lexer, &arc.dst_names, &dst_cnt, PV_NONE))
131     goto lossage;
132   if (dst_cnt != arc.var_cnt)
133     {
134       size_t i;
135
136       msg (SE, _("Source variable count (%u) does not match "
137                  "target variable count (%u)."),
138            (unsigned) arc.var_cnt, (unsigned) dst_cnt);
139
140       for (i = 0; i < dst_cnt; i++)
141         free (arc.dst_names[i]);
142       free (arc.dst_names);
143       arc.dst_names = NULL;
144
145       goto lossage;
146     }
147   while (lex_match (lexer, '/'))
148     if (lex_match_id (lexer, "DESCENDING"))
149       arc.direction = DESCENDING;
150     else if (lex_match_id (lexer, "PRINT"))
151       arc.print = 1;
152   if (lex_token (lexer) != '.')
153     {
154       lex_error (lexer, _("expecting end of command"));
155       goto lossage;
156     }
157
158   for (i = 0; i < arc.var_cnt; i++)
159     {
160       int j;
161
162       if (dict_lookup_var (dataset_dict (ds), arc.dst_names[i]) != NULL)
163         {
164           msg (SE, _("Target variable %s duplicates existing variable %s."),
165                arc.dst_names[i], arc.dst_names[i]);
166           goto lossage;
167         }
168       for (j = 0; j < i; j++)
169         if (!strcasecmp (arc.dst_names[i], arc.dst_names[j]))
170           {
171             msg (SE, _("Duplicate variable name %s among target variables."),
172                  arc.dst_names[i]);
173             goto lossage;
174           }
175     }
176
177   arc.src_values_pool = pool_create ();
178   arc.dst_vars = xnmalloc (arc.var_cnt, sizeof *arc.dst_vars);
179   arc.src_values = xnmalloc (arc.var_cnt, sizeof *arc.src_values);
180   for (i = 0; i < dst_cnt; i++)
181     if (var_is_alpha (arc.src_vars[i]))
182       arc.src_values[i] = hsh_create (10, compare_alpha_value,
183                                       hash_alpha_value, NULL, arc.src_vars[i]);
184     else
185       arc.src_values[i] = hsh_create (10, compare_numeric_value,
186                                       hash_numeric_value, NULL, NULL);
187
188   ok = procedure (ds, autorecode_proc_func, &arc);
189
190   for (i = 0; i < arc.var_cnt; i++)
191     arc.dst_vars[i] = dict_create_var_assert (dataset_dict (ds),
192                                               arc.dst_names[i], 0);
193
194   recode (ds, &arc);
195   arc_free (&arc);
196   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
197
198 lossage:
199   arc_free (&arc);
200   return CMD_CASCADING_FAILURE;
201 }
202
203 static void
204 arc_free (struct autorecode_pgm *arc) 
205 {
206   free (arc->src_vars);
207   if (arc->dst_names != NULL) 
208     {
209       size_t i;
210       
211       for (i = 0; i < arc->var_cnt; i++)
212         free (arc->dst_names[i]);
213       free (arc->dst_names);
214     }
215   free (arc->dst_vars);
216   if (arc->src_values != NULL) 
217     {
218       size_t i;
219
220       for (i = 0; i < arc->var_cnt; i++)
221         hsh_destroy (arc->src_values[i]);
222       free (arc->src_values);
223     }
224   pool_destroy (arc->src_values_pool);
225 }
226
227 \f
228 /* AUTORECODE transformation. */
229
230 static void
231 recode (struct dataset *ds, const struct autorecode_pgm *arc)
232 {
233   struct autorecode_trns *trns;
234   size_t i;
235
236   trns = pool_create_container (struct autorecode_trns, pool);
237   trns->specs = pool_nalloc (trns->pool, arc->var_cnt, sizeof *trns->specs);
238   trns->spec_cnt = arc->var_cnt;
239   for (i = 0; i < arc->var_cnt; i++)
240     {
241       struct arc_spec *spec = &trns->specs[i];
242       void *const *p = hsh_sort (arc->src_values[i]);
243       int count = hsh_count (arc->src_values[i]);
244       int j;
245
246       spec->src = arc->src_vars[i];
247       spec->dest = arc->dst_vars[i];
248
249       if (var_is_alpha (arc->src_vars[i]))
250         spec->items = hsh_create (2 * count, compare_alpha_value,
251                                   hash_alpha_value, NULL, arc->src_vars[i]);
252       else
253         spec->items = hsh_create (2 * count, compare_numeric_value,
254                                   hash_numeric_value, NULL, NULL);
255
256       for (j = 0; *p; p++, j++)
257         {
258           struct arc_item *item = pool_alloc (trns->pool, sizeof *item);
259           union arc_value *vp = *p;
260           
261           if (var_is_numeric (arc->src_vars[i]))
262             item->from.f = vp->f;
263           else
264             item->from.c = pool_clone (trns->pool, vp->c,
265                                        var_get_width (arc->src_vars[i]));
266           item->to = arc->direction == ASCENDING ? j + 1 : count - j;
267           hsh_force_insert (spec->items, item);
268         }
269     }
270   add_transformation (ds, 
271                       autorecode_trns_proc, autorecode_trns_free, trns);
272 }
273
274 /* Executes an AUTORECODE transformation. */
275 static int
276 autorecode_trns_proc (void *trns_, struct ccase *c, casenumber case_idx UNUSED)
277 {
278   struct autorecode_trns *trns = trns_;
279   size_t i;
280
281   for (i = 0; i < trns->spec_cnt; i++)
282     {
283       struct arc_spec *spec = &trns->specs[i];
284       struct arc_item *item;
285       union arc_value v;
286
287       if (var_is_numeric (spec->src))
288         v.f = case_num (c, spec->src);
289       else
290         v.c = (char *) case_str (c, spec->src);
291       item = hsh_force_find (spec->items, &v);
292
293       case_data_rw (c, spec->dest)->f = item->to;
294     }
295   return TRNS_CONTINUE;
296 }
297
298 /* Frees an AUTORECODE transformation. */
299 static bool
300 autorecode_trns_free (void *trns_)
301 {
302   struct autorecode_trns *trns = trns_;
303   size_t i;
304
305   for (i = 0; i < trns->spec_cnt; i++)
306     hsh_destroy (trns->specs[i].items);
307   pool_destroy (trns->pool);
308   return true;
309 }
310 \f
311 /* AUTORECODE procedure. */
312
313 static int
314 compare_alpha_value (const void *a_, const void *b_, const void *v_)
315 {
316   const union arc_value *a = a_;
317   const union arc_value *b = b_;
318   const struct variable *v = v_;
319
320   return memcmp (a->c, b->c, var_get_width (v));
321 }
322
323 static unsigned
324 hash_alpha_value (const void *a_, const void *v_)
325 {
326   const union arc_value *a = a_;
327   const struct variable *v = v_;
328   
329   return hsh_hash_bytes (a->c, var_get_width (v));
330 }
331
332 static int
333 compare_numeric_value (const void *a_, const void *b_, const void *aux UNUSED)
334 {
335   const union arc_value *a = a_;
336   const union arc_value *b = b_;
337
338   return a->f < b->f ? -1 : a->f > b->f;
339 }
340
341 static unsigned
342 hash_numeric_value (const void *a_, const void *aux UNUSED)
343 {
344   const union arc_value *a = a_;
345
346   return hsh_hash_double (a->f);
347 }
348
349 static bool
350 autorecode_proc_func (const struct ccase *c, void *arc_, const struct dataset *ds UNUSED)
351 {
352   struct autorecode_pgm *arc = arc_;
353   size_t i;
354
355   for (i = 0; i < arc->var_cnt; i++)
356     {
357       union arc_value v, *vp, **vpp;
358
359       if (var_is_numeric (arc->src_vars[i]))
360         v.f = case_num (c, arc->src_vars[i]);
361       else
362         v.c = (char *) case_str (c, arc->src_vars[i]);
363
364       vpp = (union arc_value **) hsh_probe (arc->src_values[i], &v);
365       if (*vpp == NULL)
366         {
367           vp = pool_alloc (arc->src_values_pool, sizeof *vp);
368           if (var_is_numeric (arc->src_vars[i]))
369             vp->f = v.f;
370           else
371             vp->c = pool_clone (arc->src_values_pool,
372                                 v.c, var_get_width (arc->src_vars[i]));
373           *vpp = vp;
374         }
375     }
376   return true;
377 }