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