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