oneway: Fix descriptives for multiple variables
[pspp] / src / math / categoricals.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 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 <stdio.h>
20
21 #include "categoricals.h"
22
23 #include <gl/xalloc.h>
24 #include <data/variable.h>
25 #include <data/case.h>
26 #include <data/value.h>
27 #include <libpspp/hmap.h>
28 #include <libpspp/pool.h>
29
30 #include <libpspp/str.h>
31
32 struct value_node
33 {
34   struct hmap_node node;      /* Node in hash map. */
35   union value value;          /* The value being labeled. */
36   double cc;                  /* The total of the weights of cases with this value */
37
38   void *user_data;            /* A pointer to data which the caller can store stuff */
39
40   int subscript;              /* A zero based integer, unique within the variable.
41                                  Can be used as an index into an array */
42 };
43
44
45 struct var_params
46 {
47   /* A map indexed by a union values */
48   struct hmap map;
49
50   const struct variable *var;
51
52   int base_subscript;
53
54   /* The number of distinct values of this variable */
55   int n_cats;
56
57   /* A map of values indexed by subscript */
58   const struct value_node **reverse_value_map;
59
60   /* Total of the weights of this variable */
61   double cc; 
62 };
63
64
65 struct categoricals
66 {
67   /* The weight variable */
68   const struct variable *wv;
69
70
71   /* An array of var_params */
72   struct var_params *vp;
73
74   /* The size of VP. (ie, the number of variables involved.) */
75   size_t n_vp;
76
77   /* The number of categorical variables which contain entries.
78      In the absence of missing values, this will be equal to N_VP */
79   size_t n_vars;
80
81   /* A map to enable the lookup of variables indexed by subscript */
82   int *reverse_variable_map;
83
84   size_t n_cats_total;
85
86   struct pool *pool;
87
88   /* Missing values to be excluded */
89   enum mv_class exclude;
90
91
92
93   /* Function to be called on each update */
94   update_func *update;
95
96
97   /* Function specified by the caller to create user_data */
98   user_data_create_func *user_data_create;
99
100
101   /* Auxilliary data to be passed to update and user_data_create_func*/
102   void *aux1;
103   void *aux2;
104 };
105
106
107 void
108 categoricals_destroy ( struct categoricals *cat)
109 {
110   int i;
111   if (cat != NULL)
112     {
113       for (i = 0 ; i < cat->n_vp; ++i)
114         hmap_destroy (&cat->vp[i].map);
115       
116       pool_destroy (cat->pool);
117       free (cat);
118     }
119 }
120
121
122 #if 0
123 void
124 categoricals_dump (const struct categoricals *cat)
125 {
126   int v;
127
128   for (v = 0 ; v < cat->n_vp; ++v)
129     {
130       const struct var_params *vp = &cat->vp[v];
131       const struct hmap *m = &vp->map;
132       struct hmap_node *node ;
133       int x;
134      
135       printf ("\n%s (%d)  CC=%g n_cats=%d:\n", 
136               var_get_name (vp->var), vp->base_subscript, vp->cc, vp->n_cats);
137
138       printf ("Reverse map\n");
139       for (x = 0 ; x < vp->n_cats; ++x)
140         {
141           struct string s;
142           const struct value_node *vn = vp->reverse_value_map[x];
143           ds_init_empty (&s);
144           var_append_value_name (vp->var, &vn->value, &s);
145           printf ("Value for %d is %s\n", x, ds_cstr(&s));
146           ds_destroy (&s);
147         }
148
149       printf ("\nForward map\n");
150       for (node = hmap_first (m); node; node = hmap_next (m, node))
151         {
152           struct string s;
153           const struct value_node *vn = HMAP_DATA (node, struct value_node, node);
154           ds_init_empty (&s);
155           var_append_value_name (vp->var, &vn->value, &s);
156           printf ("Value: %s; Index %d; CC %g\n",
157                   ds_cstr (&s),
158                   vn->subscript, vn->cc);
159           ds_destroy (&s);
160         }
161     }
162
163   assert (cat->n_vars <= cat->n_vp);
164
165   printf ("\n");
166   printf ("Number of categorical variables: %d\n", cat->n_vp);
167   printf ("Number of non-empty categorical variables: %d\n", cat->n_vars);
168   printf ("Total number of categories: %d\n", cat->n_cats_total);
169
170   printf ("\nReverse variable map:\n");
171
172   for (v = 0 ; v < cat->n_cats_total; ++v)
173     printf ("%d ", cat->reverse_variable_map[v]);
174   printf ("\n");
175 }
176 #endif
177
178
179
180 static struct value_node *
181 lookup_value (const struct hmap *map, const struct variable *var, const union value *val)
182 {
183   struct value_node *foo;
184   unsigned int width = var_get_width (var);
185   size_t hash = value_hash (val, width, 0);
186
187   HMAP_FOR_EACH_WITH_HASH (foo, struct value_node, node, hash, map)
188     {
189       if (value_equal (val, &foo->value, width))
190         break;
191
192       fprintf (stderr, "Warning: Hash table collision\n");
193     }
194
195   return foo;
196 }
197
198
199 struct categoricals *
200 categoricals_create (const struct variable *const *v, size_t n_vars,
201                      const struct variable *wv, enum mv_class exclude,
202                      user_data_create_func *udf,
203                      update_func *update, void *aux1, void *aux2
204                      )
205 {
206   size_t i;
207   struct categoricals *cat = xmalloc (sizeof *cat);
208   
209   cat->n_vp = n_vars;
210   cat->wv = wv;
211   cat->n_cats_total = 0;
212   cat->n_vars = 0;
213   cat->reverse_variable_map = NULL;
214   cat->pool = pool_create ();
215   cat->exclude = exclude;
216   cat->update = update;
217   cat->user_data_create = udf;
218
219   cat->aux1 = aux1;
220   cat->aux2 = aux2;
221
222
223   cat->vp = pool_calloc (cat->pool, cat->n_vp, sizeof *cat->vp);
224
225   for (i = 0 ; i < cat->n_vp; ++i)
226     {
227       hmap_init (&cat->vp[i].map);
228       cat->vp[i].var = v[i];
229     }
230
231   return cat;
232 }
233
234
235
236 void
237 categoricals_update (struct categoricals *cat, const struct ccase *c)
238 {
239   size_t i;
240   
241   const double weight = cat->wv ? case_data (c, cat->wv)->f : 1.0;
242
243   assert (NULL == cat->reverse_variable_map);
244
245   for (i = 0 ; i < cat->n_vp; ++i)
246     {
247       const struct variable *var = cat->vp[i].var;
248       unsigned int width = var_get_width (var);
249       const union value *val = case_data (c, var);
250       size_t hash;
251       struct value_node *node ;
252
253       if ( var_is_value_missing (var, val, cat->exclude))
254         continue;
255
256       hash = value_hash (val, width, 0);
257       node = lookup_value (&cat->vp[i].map, var, val);
258
259       if ( NULL == node)
260         {
261           node = pool_malloc (cat->pool, sizeof *node);
262
263           value_init (&node->value, width);
264           value_copy (&node->value, val, width);
265           node->cc = 0.0;
266
267           hmap_insert (&cat->vp[i].map, &node->node,  hash);
268           cat->n_cats_total++;
269           
270           if ( 0 == cat->vp[i].n_cats)
271             cat->n_vars++;
272
273           node->subscript = cat->vp[i].n_cats++ ;
274
275           if (cat->user_data_create)
276             node->user_data = cat->user_data_create (cat->aux1, cat->aux2);
277         }
278
279       node->cc += weight;
280       cat->vp[i].cc += weight;
281
282       if (cat->update)
283         cat->update (node->user_data, cat->wv, var, c, cat->aux1, cat->aux2);
284     }
285 }
286
287 /* Return the number of categories (distinct values) for variable N */
288 size_t
289 categoricals_n_count (const struct categoricals *cat, size_t n)
290 {
291   return hmap_count (&cat->vp[n].map);
292 }
293
294
295 /* Return the total number of categories */
296 size_t
297 categoricals_total (const struct categoricals *cat)
298 {
299   return cat->n_cats_total;
300 }
301
302
303 /* This function must be called *before* any call to categoricals_get_*_by subscript an
304  *after* all calls to categoricals_update */
305 void
306 categoricals_done (struct categoricals *cat)
307 {
308   /* Implementation Note: Whilst this function is O(n) in cat->n_cats_total, in most
309      uses it will be more efficient that using a tree based structure, since it
310      is called only once, and means that subsequent lookups will be O(1).
311
312      1 call of O(n) + 10^9 calls of O(1) is better than 10^9 calls of O(log n).
313   */
314   int v;
315   int idx = 0;
316   cat->reverse_variable_map = pool_calloc (cat->pool,
317                                            cat->n_cats_total,
318                                            sizeof *cat->reverse_variable_map);
319   
320   for (v = 0 ; v < cat->n_vp; ++v)
321     {
322       int i;
323       struct var_params *vp = &cat->vp[v];
324       int n_cats_total = categoricals_n_count (cat, v);
325       struct hmap_node *node ;
326
327       vp->reverse_value_map = pool_calloc (cat->pool, n_cats_total, sizeof *vp->reverse_value_map);
328
329       vp->base_subscript = idx;
330
331       for (node = hmap_first (&vp->map); node; node = hmap_next (&vp->map, node))
332         {
333           const struct value_node *vn = HMAP_DATA (node, struct value_node, node);
334           vp->reverse_value_map[vn->subscript] = vn;
335         }
336
337       /* Populate the reverse variable map.
338        */
339       for (i = 0; i < vp->n_cats; ++i)
340         cat->reverse_variable_map[idx++] = v;
341     }
342
343   assert (cat->n_vars <= cat->n_vp);
344 }
345
346
347 static int
348 reverse_variable_lookup (const struct categoricals *cat, int subscript)
349 {
350   assert (cat->reverse_variable_map);
351   assert (subscript >= 0);
352   assert (subscript < cat->n_cats_total);
353
354   return cat->reverse_variable_map[subscript];
355 }
356
357
358 /* Return the categorical variable corresponding to SUBSCRIPT */
359 const struct variable *
360 categoricals_get_variable_by_subscript (const struct categoricals *cat, int subscript)
361 {
362   int index = reverse_variable_lookup (cat, subscript);
363
364   return cat->vp[index].var;
365 }
366
367 /* Return the value corresponding to SUBSCRIPT */
368 const union value *
369 categoricals_get_value_by_subscript (const struct categoricals *cat, int subscript)
370 {
371   int vindex = reverse_variable_lookup (cat, subscript);
372   const struct var_params *vp = &cat->vp[vindex];
373   const struct value_node *vn = vp->reverse_value_map [subscript - vp->base_subscript];
374
375   return &vn->value;
376 }
377
378
379 double
380 categoricals_get_weight_by_subscript (const struct categoricals *cat, int subscript)
381 {
382   int vindex = reverse_variable_lookup (cat, subscript);
383   const struct var_params *vp = &cat->vp[vindex];
384
385   return vp->cc;
386 }
387
388 double
389 categoricals_get_sum_by_subscript (const struct categoricals *cat, int subscript)
390 {
391   int vindex = reverse_variable_lookup (cat, subscript);
392   const struct var_params *vp = &cat->vp[vindex];
393
394   const struct value_node *vn = vp->reverse_value_map [subscript - vp->base_subscript];
395   return vn->cc;
396 }
397
398
399 /* Returns unity if the value in case C at SUBSCRIPT is equal to the category
400    for that subscript */
401 double
402 categoricals_get_binary_by_subscript (const struct categoricals *cat, int subscript,
403                                       const struct ccase *c)
404 {
405   const struct variable *var = categoricals_get_variable_by_subscript (cat, subscript);
406   int width = var_get_width (var);
407
408   const union value *val = case_data (c, var);
409
410   return value_equal (val, categoricals_get_value_by_subscript (cat, subscript), width);
411 }
412
413
414 size_t
415 categoricals_get_n_variables (const struct categoricals *cat)
416 {
417   return cat->n_vars;
418 }
419
420
421
422 void *
423 categoricals_get_user_data_by_subscript (const struct categoricals *cat, int subscript)
424 {
425   int vindex = reverse_variable_lookup (cat, subscript);
426   const struct var_params *vp = &cat->vp[vindex];
427
428   const struct value_node *vn = vp->reverse_value_map [subscript - vp->base_subscript];
429   return vn->user_data;
430 }