80854d3100661cb81715adfa402f915288b5a13e
[pspp-builds.git] / src / language / xforms / count.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
22 #include <stdlib.h>
23
24 #include <data/case.h>
25 #include <data/dictionary.h>
26 #include <data/procedure.h>
27 #include <data/transformations.h>
28 #include <data/variable.h>
29 #include <language/command.h>
30 #include <language/lexer/lexer.h>
31 #include <language/lexer/range-parser.h>
32 #include <language/lexer/variable-parser.h>
33 #include <libpspp/alloc.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/message.h>
36 #include <libpspp/message.h>
37 #include <libpspp/pool.h>
38 #include <libpspp/str.h>
39
40 #include "gettext.h"
41 #define _(msgid) gettext (msgid)
42
43 /* Value or range? */
44 enum value_type
45   {
46     CNT_SINGLE,                 /* Single value. */
47     CNT_RANGE                   /* a <= x <= b. */
48   };
49
50 /* Numeric count criteria. */
51 struct num_value
52   {
53     enum value_type type;       /* How to interpret a, b. */
54     double a, b;                /* Values to count. */
55   };
56
57 struct criteria
58   {
59     struct criteria *next;
60
61     /* Variables to count. */
62     struct variable **vars;
63     size_t var_cnt;
64
65     /* Count special values?. */
66     bool count_system_missing;  /* Count system missing? */
67     bool count_user_missing;    /* Count user missing? */
68
69     /* Criterion values. */    
70     size_t value_cnt;
71     union
72       {
73         struct num_value *num;
74         char **str;
75       }
76     values;
77   };
78
79 struct dst_var
80   {
81     struct dst_var *next;
82     struct variable *var;       /* Destination variable. */
83     char *name;                 /* Name of dest var. */
84     struct criteria *crit;      /* The criteria specifications. */
85   };
86
87 struct count_trns
88   {
89     struct dst_var *dst_vars;
90     struct pool *pool;
91   };
92
93 static trns_proc_func count_trns_proc;
94 static trns_free_func count_trns_free;
95
96 static bool parse_numeric_criteria (struct lexer *, struct pool *, struct criteria *);
97 static bool parse_string_criteria (struct lexer *, struct pool *, struct criteria *);
98 \f
99 int
100 cmd_count (struct lexer *lexer, struct dataset *ds)
101 {
102   struct dst_var *dv;           /* Destination var being parsed. */
103   struct count_trns *trns;      /* Transformation. */
104
105   /* Parses each slash-delimited specification. */
106   trns = pool_create_container (struct count_trns, pool);
107   trns->dst_vars = dv = pool_alloc (trns->pool, sizeof *dv);
108   for (;;)
109     {
110       struct criteria *crit;
111
112       /* Initialize this struct dst_var to ensure proper cleanup. */
113       dv->next = NULL;
114       dv->var = NULL;
115       dv->crit = NULL;
116
117       /* Get destination variable, or at least its name. */
118       if (!lex_force_id (lexer))
119         goto fail;
120       dv->var = dict_lookup_var (dataset_dict (ds), lex_tokid (lexer));
121       if (dv->var != NULL)
122         {
123           if (var_is_alpha (dv->var))
124             {
125               msg (SE, _("Destination cannot be a string variable."));
126               goto fail;
127             }
128         }
129       else
130         dv->name = pool_strdup (trns->pool, lex_tokid (lexer));
131
132       lex_get (lexer);
133       if (!lex_force_match (lexer, '='))
134         goto fail;
135
136       crit = dv->crit = pool_alloc (trns->pool, sizeof *crit);
137       for (;;)
138         {
139           bool ok;
140           
141           crit->next = NULL;
142           crit->vars = NULL;
143           if (!parse_variables (lexer, dataset_dict (ds), &crit->vars, &crit->var_cnt,
144                                 PV_DUPLICATE | PV_SAME_TYPE))
145             goto fail;
146           pool_register (trns->pool, free, crit->vars);
147
148           if (!lex_force_match (lexer, '('))
149             goto fail;
150
151           crit->value_cnt = 0;
152           if (var_is_numeric (crit->vars[0]))
153             ok = parse_numeric_criteria (lexer, trns->pool, crit);
154           else
155             ok = parse_string_criteria (lexer, trns->pool, crit);
156           if (!ok)
157             goto fail;
158
159           if (lex_token (lexer) == '/' || lex_token (lexer) == '.')
160             break;
161
162           crit = crit->next = pool_alloc (trns->pool, sizeof *crit);
163         }
164
165       if (lex_token (lexer) == '.')
166         break;
167
168       if (!lex_force_match (lexer, '/'))
169         goto fail;
170       dv = dv->next = pool_alloc (trns->pool, sizeof *dv);
171     }
172
173   /* Create all the nonexistent destination variables. */
174   for (dv = trns->dst_vars; dv; dv = dv->next)
175     if (dv->var == NULL)
176       {
177         /* It's valid, though motivationally questionable, to count to
178            the same dest var more than once. */
179         dv->var = dict_lookup_var (dataset_dict (ds), dv->name);
180
181         if (dv->var == NULL) 
182           dv->var = dict_create_var_assert (dataset_dict (ds), dv->name, 0);
183       }
184
185   add_transformation (ds, count_trns_proc, count_trns_free, trns);
186   return CMD_SUCCESS;
187
188 fail:
189   count_trns_free (trns);
190   return CMD_FAILURE;
191 }
192
193 /* Parses a set of numeric criterion values.  Returns success. */
194 static bool
195 parse_numeric_criteria (struct lexer *lexer, struct pool *pool, struct criteria *crit)
196 {
197   size_t allocated = 0;
198
199   crit->values.num = NULL;
200   crit->count_system_missing = false;
201   crit->count_user_missing = false;
202   for (;;)
203     {
204       double low, high;
205       
206       if (lex_match_id (lexer, "SYSMIS"))
207         crit->count_system_missing = true;
208       else if (lex_match_id (lexer, "MISSING"))
209         crit->count_user_missing = true;
210       else if (parse_num_range (lexer, &low, &high, NULL)) 
211         {
212           struct num_value *cur;
213
214           if (crit->value_cnt >= allocated)
215             crit->values.num = pool_2nrealloc (pool, crit->values.num,
216                                                &allocated,
217                                                sizeof *crit->values.num);
218           cur = &crit->values.num[crit->value_cnt++];
219           cur->type = low == high ? CNT_SINGLE : CNT_RANGE;
220           cur->a = low;
221           cur->b = high;
222         }
223       else
224         return false;
225
226       lex_match (lexer, ',');
227       if (lex_match (lexer, ')'))
228         break;
229     }
230   return true;
231 }
232
233 /* Parses a set of string criteria values.  Returns success. */
234 static bool
235 parse_string_criteria (struct lexer *lexer, struct pool *pool, struct criteria *crit)
236 {
237   int len = 0;
238   size_t allocated = 0;
239   size_t i;
240
241   for (i = 0; i < crit->var_cnt; i++)
242     if (var_get_width (crit->vars[i]) > len)
243       len = var_get_width (crit->vars[i]);
244
245   crit->values.str = NULL;
246   for (;;)
247     {
248       char **cur;
249       if (crit->value_cnt >= allocated)
250         crit->values.str = pool_2nrealloc (pool, crit->values.str,
251                                            &allocated,
252                                            sizeof *crit->values.str);
253
254       if (!lex_force_string (lexer))
255         return false;
256       cur = &crit->values.str[crit->value_cnt++];
257       *cur = pool_alloc (pool, len + 1);
258       str_copy_rpad (*cur, len + 1, ds_cstr (lex_tokstr (lexer)));
259       lex_get (lexer);
260
261       lex_match (lexer, ',');
262       if (lex_match (lexer, ')'))
263         break;
264     }
265
266   return true;
267 }
268 \f
269 /* Transformation. */
270
271 /* Counts the number of values in case C matching CRIT. */
272 static inline int
273 count_numeric (struct criteria *crit, struct ccase *c)
274 {
275   int counter = 0;
276   size_t i;
277
278   for (i = 0; i < crit->var_cnt; i++)
279     {
280       double x = case_num (c, crit->vars[i]);
281       if (x == SYSMIS)
282         counter += crit->count_system_missing;
283       else if (crit->count_user_missing
284                && var_is_num_user_missing (crit->vars[i], x))
285         counter++;
286       else 
287         {
288           struct num_value *v;
289           
290           for (v = crit->values.num; v < crit->values.num + crit->value_cnt;
291                v++) 
292             if (v->type == CNT_SINGLE ? x == v->a : x >= v->a && x <= v->b) 
293               {
294                 counter++;
295                 break;
296               } 
297         }
298     }
299   
300   return counter;
301 }
302
303 /* Counts the number of values in case C matching CRIT. */
304 static inline int
305 count_string (struct criteria *crit, struct ccase *c)
306 {
307   int counter = 0;
308   size_t i;
309
310   for (i = 0; i < crit->var_cnt; i++)
311     {
312       char **v;
313       for (v = crit->values.str; v < crit->values.str + crit->value_cnt; v++)
314         if (!memcmp (case_str (c, crit->vars[i]), *v,
315                      var_get_width (crit->vars[i])))
316           {
317             counter++;
318             break;
319           }
320     }
321
322   return counter;
323 }
324
325 /* Performs the COUNT transformation T on case C. */
326 static int
327 count_trns_proc (void *trns_, struct ccase *c,
328                  casenumber case_num UNUSED)
329 {
330   struct count_trns *trns = trns_;
331   struct dst_var *dv;
332
333   for (dv = trns->dst_vars; dv; dv = dv->next)
334     {
335       struct criteria *crit;
336       int counter;
337
338       counter = 0;
339       for (crit = dv->crit; crit; crit = crit->next)
340         if (var_is_numeric (crit->vars[0]))
341           counter += count_numeric (crit, c);
342         else
343           counter += count_string (crit, c);
344       case_data_rw (c, dv->var)->f = counter;
345     }
346   return TRNS_CONTINUE;
347 }
348
349 /* Destroys all dynamic data structures associated with TRNS. */
350 static bool
351 count_trns_free (void *trns_)
352 {
353   struct count_trns *trns = (struct count_trns *) trns_;
354   pool_destroy (trns->pool);
355   return true;
356 }