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