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