Parameter estimate matched with appropriate variable during estimation
[pspp] / src / 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 "error.h"
22 #include <stdlib.h>
23 #include "alloc.h"
24 #include "case.h"
25 #include "command.h"
26 #include "dictionary.h"
27 #include "error.h"
28 #include "lexer.h"
29 #include "pool.h"
30 #include "range-prs.h"
31 #include "str.h"
32 #include "var.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 trns_header h;
84     struct dst_var *dst_vars;
85     struct pool *pool;
86   };
87 \f
88 /* Parser. */
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 pool *, struct criteria *);
94 static bool parse_string_criteria (struct pool *, struct criteria *);
95
96 int
97 cmd_count (void)
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 = xmalloc (sizeof *trns);
104   trns->h.proc = count_trns_proc;
105   trns->h.free = count_trns_free;
106   trns->pool = pool_create ();
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 ())
119         goto fail;
120       dv->var = dict_lookup_var (default_dict, tokid);
121       if (dv->var != NULL)
122         {
123           if (dv->var->type == ALPHA)
124             {
125               msg (SE, _("Destination cannot be a string variable."));
126               goto fail;
127             }
128         }
129       else
130         dv->name = pool_strdup (trns->pool, tokid);
131
132       lex_get ();
133       if (!lex_force_match ('='))
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 (default_dict, &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 ('('))
149             goto fail;
150
151           crit->value_cnt = 0;
152           if (crit->vars[0]->type == NUMERIC)
153             ok = parse_numeric_criteria (trns->pool, crit);
154           else
155             ok = parse_string_criteria (trns->pool, crit);
156           if (!ok)
157             goto fail;
158
159           if (token == '/' || token == '.')
160             break;
161
162           crit = crit->next = pool_alloc (trns->pool, sizeof *crit);
163         }
164
165       if (token == '.')
166         break;
167
168       if (!lex_force_match ('/'))
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 (default_dict, dv->name);
180
181         if (dv->var == NULL) 
182           dv->var = dict_create_var_assert (default_dict, dv->name, 0);
183       }
184
185   add_transformation (&trns->h);
186   return CMD_SUCCESS;
187
188 fail:
189   count_trns_free (&trns->h);
190   return CMD_FAILURE;
191 }
192
193 /* Parses a set of numeric criterion values.  Returns success. */
194 static bool
195 parse_numeric_criteria (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 ("SYSMIS"))
207         crit->count_system_missing = true;
208       else if (lex_match_id ("MISSING"))
209         crit->count_user_missing = true;
210       else if (parse_num_range (&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 (',');
227       if (lex_match (')'))
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 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 (crit->vars[i]->width > len)
243       len = crit->vars[i]->width;
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 ())
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_c_str (&tokstr));
259       lex_get ();
260
261       lex_match (',');
262       if (lex_match (')'))
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]->fv);
281       if (x == SYSMIS)
282         counter += crit->count_system_missing;
283       else if (crit->count_user_missing
284                && mv_is_num_user_missing (&crit->vars[i]->miss, 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]->fv), *v,
315                      crit->vars[i]->width))
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 (struct trns_header *trns_, struct ccase *c,
328                  int case_num UNUSED)
329 {
330   struct count_trns *trns = (struct count_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 (crit->vars[0]->type == NUMERIC)
341           counter += count_numeric (crit, c);
342         else
343           counter += count_string (crit, c);
344       case_data_rw (c, dv->var->fv)->f = counter;
345     }
346   return -1;
347 }
348
349 /* Destroys all dynamic data structures associated with TRNS. */
350 static void
351 count_trns_free (struct trns_header *trns_)
352 {
353   struct count_trns *trns = (struct count_trns *) trns_;
354   pool_destroy (trns->pool);
355 }