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