560f9f99ddd15bbbd908cd9fd90a0959eee84ff6
[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 <libpspp/alloc.h>
31 #include <libpspp/compiler.h>
32 #include <libpspp/hash.h>
33 #include <libpspp/message.h>
34 #include <libpspp/message.h>
35 #include <libpspp/pool.h>
36 #include <libpspp/str.h>
37
38 #include "gettext.h"
39 #define _(msgid) gettext (msgid)
40
41 /* FIXME: Implement PRINT subcommand. */
42
43 /* An AUTORECODE variable's original value. */
44 union arc_value 
45   {
46     double f;                   /* Numeric. */
47     char *c;                    /* Short or long string. */
48   };
49
50 /* Explains how to recode one value.  `from' must be first element.  */
51 struct arc_item
52   {
53     union arc_value from;       /* Original value. */
54     double to;                  /* Recoded value. */
55   };
56
57 /* Explains how to recode an AUTORECODE variable. */
58 struct arc_spec
59   {
60     struct variable *src;       /* Source variable. */
61     struct variable *dest;      /* Target variable. */
62     struct hsh_table *items;    /* Hash table of `freq's. */
63   };
64
65 /* AUTORECODE transformation. */
66 struct autorecode_trns
67   {
68     struct pool *pool;          /* Contains AUTORECODE specs. */
69     struct arc_spec *specs;     /* AUTORECODE specifications. */
70     size_t spec_cnt;            /* Number of specifications. */
71   };
72
73 /* Descending or ascending sort order. */
74 enum direction 
75   {
76     ASCENDING,
77     DESCENDING
78   };
79
80 /* AUTORECODE data. */
81 struct autorecode_pgm 
82   {
83     struct variable **src_vars;    /* Source variables. */
84     char **dst_names;              /* Target variable names. */
85     struct variable **dst_vars;    /* Target variables. */
86     struct hsh_table **src_values; /* `union arc_value's of source vars. */
87     size_t var_cnt;                /* Number of variables. */
88     struct pool *src_values_pool;  /* Pool used by src_values. */
89     enum direction direction;      /* Sort order. */
90     int print;                     /* Print mapping table if nonzero. */
91   };
92
93 static trns_proc_func autorecode_trns_proc;
94 static trns_free_func autorecode_trns_free;
95 static bool autorecode_proc_func (const struct ccase *, void *);
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 (const struct autorecode_pgm *);
100 static void arc_free (struct autorecode_pgm *);
101
102 /* Performs the AUTORECODE procedure. */
103 int
104 cmd_autorecode (void)
105 {
106   struct autorecode_pgm arc;
107   size_t dst_cnt;
108   size_t i;
109   bool ok;
110
111   arc.src_vars = NULL;
112   arc.dst_names = NULL;
113   arc.dst_vars = NULL;
114   arc.src_values = NULL;
115   arc.var_cnt = 0;
116   arc.src_values_pool = NULL;
117   arc.direction = ASCENDING;
118   arc.print = 0;
119   dst_cnt = 0;
120
121   lex_match_id ("VARIABLES");
122   lex_match ('=');
123   if (!parse_variables (default_dict, &arc.src_vars, &arc.var_cnt,
124                         PV_NO_DUPLICATE))
125     goto lossage;
126   if (!lex_force_match_id ("INTO"))
127     goto lossage;
128   lex_match ('=');
129   if (!parse_DATA_LIST_vars (&arc.dst_names, &dst_cnt, PV_NONE))
130     goto lossage;
131   if (dst_cnt != arc.var_cnt)
132     {
133       size_t i;
134
135       msg (SE, _("Source variable count (%u) does not match "
136                  "target variable count (%u)."),
137            (unsigned) arc.var_cnt, (unsigned) dst_cnt);
138
139       for (i = 0; i < dst_cnt; i++)
140         free (arc.dst_names[i]);
141       free (arc.dst_names);
142       arc.dst_names = NULL;
143
144       goto lossage;
145     }
146   while (lex_match ('/'))
147     if (lex_match_id ("DESCENDING"))
148       arc.direction = DESCENDING;
149     else if (lex_match_id ("PRINT"))
150       arc.print = 1;
151   if (token != '.')
152     {
153       lex_error (_("expecting end of command"));
154       goto lossage;
155     }
156
157   for (i = 0; i < arc.var_cnt; i++)
158     {
159       int j;
160
161       if (dict_lookup_var (default_dict, arc.dst_names[i]) != NULL)
162         {
163           msg (SE, _("Target variable %s duplicates existing variable %s."),
164                arc.dst_names[i], arc.dst_names[i]);
165           goto lossage;
166         }
167       for (j = 0; j < i; j++)
168         if (!strcasecmp (arc.dst_names[i], arc.dst_names[j]))
169           {
170             msg (SE, _("Duplicate variable name %s among target variables."),
171                  arc.dst_names[i]);
172             goto lossage;
173           }
174     }
175
176   arc.src_values_pool = pool_create ();
177   arc.dst_vars = xnmalloc (arc.var_cnt, sizeof *arc.dst_vars);
178   arc.src_values = xnmalloc (arc.var_cnt, sizeof *arc.src_values);
179   for (i = 0; i < dst_cnt; i++)
180     if (arc.src_vars[i]->type == ALPHA)
181       arc.src_values[i] = hsh_create (10, compare_alpha_value,
182                                       hash_alpha_value, NULL, arc.src_vars[i]);
183     else
184       arc.src_values[i] = hsh_create (10, compare_numeric_value,
185                                       hash_numeric_value, NULL, NULL);
186
187   ok = procedure (autorecode_proc_func, &arc);
188
189   for (i = 0; i < arc.var_cnt; i++)
190     arc.dst_vars[i] = dict_create_var_assert (default_dict,
191                                               arc.dst_names[i], 0);
192
193   recode (&arc);
194   arc_free (&arc);
195   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
196
197 lossage:
198   arc_free (&arc);
199   return CMD_CASCADING_FAILURE;
200 }
201
202 static void
203 arc_free (struct autorecode_pgm *arc) 
204 {
205   free (arc->src_vars);
206   if (arc->dst_names != NULL) 
207     {
208       size_t i;
209       
210       for (i = 0; i < arc->var_cnt; i++)
211         free (arc->dst_names[i]);
212       free (arc->dst_names);
213     }
214   free (arc->dst_vars);
215   if (arc->src_values != NULL) 
216     {
217       size_t i;
218
219       for (i = 0; i < arc->var_cnt; i++)
220         hsh_destroy (arc->src_values[i]);
221       free (arc->src_values);
222     }
223   pool_destroy (arc->src_values_pool);
224 }
225
226 \f
227 /* AUTORECODE transformation. */
228
229 static void
230 recode (const struct autorecode_pgm *arc)
231 {
232   struct autorecode_trns *trns;
233   size_t i;
234
235   trns = pool_create_container (struct autorecode_trns, pool);
236   trns->specs = pool_nalloc (trns->pool, arc->var_cnt, sizeof *trns->specs);
237   trns->spec_cnt = arc->var_cnt;
238   for (i = 0; i < arc->var_cnt; i++)
239     {
240       struct arc_spec *spec = &trns->specs[i];
241       void *const *p = hsh_sort (arc->src_values[i]);
242       int count = hsh_count (arc->src_values[i]);
243       int j;
244
245       spec->src = arc->src_vars[i];
246       spec->dest = arc->dst_vars[i];
247
248       if (arc->src_vars[i]->type == ALPHA)
249         spec->items = hsh_create (2 * count, compare_alpha_value,
250                                   hash_alpha_value, NULL, arc->src_vars[i]);
251       else
252         spec->items = hsh_create (2 * count, compare_numeric_value,
253                                   hash_numeric_value, NULL, NULL);
254
255       for (j = 0; *p; p++, j++)
256         {
257           struct arc_item *item = pool_alloc (trns->pool, sizeof *item);
258           union arc_value *vp = *p;
259           
260           if (arc->src_vars[i]->type == NUMERIC)
261             item->from.f = vp->f;
262           else
263             item->from.c = pool_clone (trns->pool, vp->c,
264                                        arc->src_vars[i]->width);
265           item->to = arc->direction == ASCENDING ? j + 1 : count - j;
266           hsh_force_insert (spec->items, item);
267         }
268     }
269   add_transformation (autorecode_trns_proc, autorecode_trns_free, trns);
270 }
271
272 /* Executes an AUTORECODE transformation. */
273 static int
274 autorecode_trns_proc (void *trns_, struct ccase *c, int case_idx UNUSED)
275 {
276   struct autorecode_trns *trns = trns_;
277   size_t i;
278
279   for (i = 0; i < trns->spec_cnt; i++)
280     {
281       struct arc_spec *spec = &trns->specs[i];
282       struct arc_item *item;
283       union arc_value v;
284
285       if (spec->src->type == NUMERIC)
286         v.f = case_num (c, spec->src->fv);
287       else
288         v.c = (char *) case_str (c, spec->src->fv);
289       item = hsh_force_find (spec->items, &v);
290
291       case_data_rw (c, spec->dest->fv)->f = item->to;
292     }
293   return TRNS_CONTINUE;
294 }
295
296 /* Frees an AUTORECODE transformation. */
297 static bool
298 autorecode_trns_free (void *trns_)
299 {
300   struct autorecode_trns *trns = trns_;
301   size_t i;
302
303   for (i = 0; i < trns->spec_cnt; i++)
304     hsh_destroy (trns->specs[i].items);
305   pool_destroy (trns->pool);
306   return true;
307 }
308 \f
309 /* AUTORECODE procedure. */
310
311 static int
312 compare_alpha_value (const void *a_, const void *b_, void *v_)
313 {
314   const union arc_value *a = a_;
315   const union arc_value *b = b_;
316   const struct variable *v = v_;
317
318   return memcmp (a->c, b->c, v->width);
319 }
320
321 static unsigned
322 hash_alpha_value (const void *a_, void *v_)
323 {
324   const union arc_value *a = a_;
325   const struct variable *v = v_;
326   
327   return hsh_hash_bytes (a->c, v->width);
328 }
329
330 static int
331 compare_numeric_value (const void *a_, const void *b_, void *foo UNUSED)
332 {
333   const union arc_value *a = a_;
334   const union arc_value *b = b_;
335
336   return a->f < b->f ? -1 : a->f > b->f;
337 }
338
339 static unsigned
340 hash_numeric_value (const void *a_, void *foo UNUSED)
341 {
342   const union arc_value *a = a_;
343
344   return hsh_hash_double (a->f);
345 }
346
347 static bool
348 autorecode_proc_func (const struct ccase *c, void *arc_)
349 {
350   struct autorecode_pgm *arc = arc_;
351   size_t i;
352
353   for (i = 0; i < arc->var_cnt; i++)
354     {
355       union arc_value v, *vp, **vpp;
356
357       if (arc->src_vars[i]->type == NUMERIC)
358         v.f = case_num (c, arc->src_vars[i]->fv);
359       else
360         v.c = (char *) case_str (c, arc->src_vars[i]->fv);
361
362       vpp = (union arc_value **) hsh_probe (arc->src_values[i], &v);
363       if (*vpp == NULL)
364         {
365           vp = pool_alloc (arc->src_values_pool, sizeof *vp);
366           if (arc->src_vars[i]->type == NUMERIC)
367             vp->f = v.f;
368           else
369             vp->c = pool_clone (arc->src_values_pool,
370                                 v.c, arc->src_vars[i]->width);
371           *vpp = vp;
372         }
373     }
374   return true;
375 }