ef9c528994428775614adedc1e59ab0949fb1ebc
[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   /* Auxilliary data to be passed to update */
97   void *update_aux;
98
99   /* Function specified by the caller to create user_data */
100   user_data_create_func *user_data_create;
101 };
102
103
104 void
105 categoricals_destroy ( struct categoricals *cat)
106 {
107   int i;
108   if (cat != NULL)
109     {
110       for (i = 0 ; i < cat->n_vp; ++i)
111         hmap_destroy (&cat->vp[i].map);
112       
113       pool_destroy (cat->pool);
114       free (cat);
115     }
116 }
117
118
119 #if 0
120 void
121 categoricals_dump (const struct categoricals *cat)
122 {
123   int v;
124
125   for (v = 0 ; v < cat->n_vp; ++v)
126     {
127       const struct var_params *vp = &cat->vp[v];
128       const struct hmap *m = &vp->map;
129       struct hmap_node *node ;
130       int x;
131      
132       printf ("\n%s (%d)  CC=%g n_cats=%d:\n", 
133               var_get_name (vp->var), vp->base_subscript, vp->cc, vp->n_cats);
134
135       printf ("Reverse map\n");
136       for (x = 0 ; x < vp->n_cats; ++x)
137         {
138           struct string s;
139           const struct value_node *vn = vp->reverse_value_map[x];
140           ds_init_empty (&s);
141           var_append_value_name (vp->var, &vn->value, &s);
142           printf ("Value for %d is %s\n", x, ds_cstr(&s));
143           ds_destroy (&s);
144         }
145
146       printf ("\nForward map\n");
147       for (node = hmap_first (m); node; node = hmap_next (m, node))
148         {
149           struct string s;
150           const struct value_node *vn = HMAP_DATA (node, struct value_node, node);
151           ds_init_empty (&s);
152           var_append_value_name (vp->var, &vn->value, &s);
153           printf ("Value: %s; Index %d; CC %g\n",
154                   ds_cstr (&s),
155                   vn->subscript, vn->cc);
156           ds_destroy (&s);
157         }
158     }
159
160   assert (cat->n_vars <= cat->n_vp);
161
162   printf ("\n");
163   printf ("Number of categorical variables: %d\n", cat->n_vp);
164   printf ("Number of non-empty categorical variables: %d\n", cat->n_vars);
165   printf ("Total number of categories: %d\n", cat->n_cats_total);
166
167   printf ("\nReverse variable map:\n");
168
169   for (v = 0 ; v < cat->n_cats_total; ++v)
170     printf ("%d ", cat->reverse_variable_map[v]);
171   printf ("\n");
172 }
173 #endif
174
175
176
177 static struct value_node *
178 lookup_value (const struct hmap *map, const struct variable *var, const union value *val)
179 {
180   struct value_node *foo;
181   unsigned int width = var_get_width (var);
182   size_t hash = value_hash (val, width, 0);
183
184   HMAP_FOR_EACH_WITH_HASH (foo, struct value_node, node, hash, map)
185     {
186       if (value_equal (val, &foo->value, width))
187         break;
188
189       fprintf (stderr, "Warning: Hash table collision\n");
190     }
191
192   return foo;
193 }
194
195
196 struct categoricals *
197 categoricals_create (const struct variable *const *v, size_t n_vars,
198                      const struct variable *wv, enum mv_class exclude,
199                      user_data_create_func *udf,
200                      update_func *update, void *aux
201                      )
202 {
203   size_t i;
204   struct categoricals *cat = xmalloc (sizeof *cat);
205   
206   cat->n_vp = n_vars;
207   cat->wv = wv;
208   cat->n_cats_total = 0;
209   cat->n_vars = 0;
210   cat->reverse_variable_map = NULL;
211   cat->pool = pool_create ();
212   cat->exclude = exclude;
213   cat->update = update;
214   cat->update_aux = aux;
215   cat->user_data_create = udf;
216
217   cat->vp = pool_calloc (cat->pool, cat->n_vp, sizeof *cat->vp);
218
219   for (i = 0 ; i < cat->n_vp; ++i)
220     {
221       hmap_init (&cat->vp[i].map);
222       cat->vp[i].var = v[i];
223     }
224
225   return cat;
226 }
227
228
229
230 void
231 categoricals_update (struct categoricals *cat, const struct ccase *c)
232 {
233   size_t i;
234   
235   const double weight = cat->wv ? case_data (c, cat->wv)->f : 1.0;
236
237   assert (NULL == cat->reverse_variable_map);
238
239   for (i = 0 ; i < cat->n_vp; ++i)
240     {
241       const struct variable *var = cat->vp[i].var;
242       unsigned int width = var_get_width (var);
243       const union value *val = case_data (c, var);
244       size_t hash;
245       struct value_node *node ;
246
247       if ( var_is_value_missing (var, val, cat->exclude))
248         continue;
249
250       hash = value_hash (val, width, 0);
251       node = lookup_value (&cat->vp[i].map, var, val);
252
253       if ( NULL == node)
254         {
255           node = pool_malloc (cat->pool, sizeof *node);
256
257           value_init (&node->value, width);
258           value_copy (&node->value, val, width);
259           node->cc = 0.0;
260
261           hmap_insert (&cat->vp[i].map, &node->node,  hash);
262           cat->n_cats_total++;
263           
264           if ( 0 == cat->vp[i].n_cats)
265             cat->n_vars++;
266
267           node->subscript = cat->vp[i].n_cats++ ;
268
269           if ( cat->user_data_create )
270             node->user_data = cat->user_data_create ();
271         }
272
273       node->cc += weight;
274       cat->vp[i].cc += weight;
275
276       if ( cat->update)
277         cat->update (node->user_data, cat->wv, var, c, cat->update_aux);
278     }
279 }
280
281 /* Return the number of categories (distinct values) for variable N */
282 size_t
283 categoricals_n_count (const struct categoricals *cat, size_t n)
284 {
285   return hmap_count (&cat->vp[n].map);
286 }
287
288
289 /* Return the total number of categories */
290 size_t
291 categoricals_total (const struct categoricals *cat)
292 {
293   return cat->n_cats_total;
294 }
295
296
297 /* This function must be called *before* any call to categoricals_get_*_by subscript an
298  *after* all calls to categoricals_update */
299 void
300 categoricals_done (struct categoricals *cat)
301 {
302   /* Implementation Note: Whilst this function is O(n) in cat->n_cats_total, in most
303      uses it will be more efficient that using a tree based structure, since it
304      is called only once, and means that subsequent lookups will be O(1).
305
306      1 call of O(n) + 10^9 calls of O(1) is better than 10^9 calls of O(log n).
307   */
308   int v;
309   int idx = 0;
310   cat->reverse_variable_map = pool_calloc (cat->pool,
311                                            cat->n_cats_total,
312                                            sizeof *cat->reverse_variable_map);
313   
314   for (v = 0 ; v < cat->n_vp; ++v)
315     {
316       int i;
317       struct var_params *vp = &cat->vp[v];
318       int n_cats_total = categoricals_n_count (cat, v);
319       struct hmap_node *node ;
320
321       vp->reverse_value_map = pool_calloc (cat->pool, n_cats_total, sizeof *vp->reverse_value_map);
322
323       vp->base_subscript = idx;
324
325       for (node = hmap_first (&vp->map); node; node = hmap_next (&vp->map, node))
326         {
327           const struct value_node *vn = HMAP_DATA (node, struct value_node, node);
328           vp->reverse_value_map[vn->subscript] = vn;
329         }
330
331       /* Populate the reverse variable map.
332        */
333       for (i = 0; i < vp->n_cats; ++i)
334         cat->reverse_variable_map[idx++] = v;
335     }
336
337   assert (cat->n_vars <= cat->n_vp);
338 }
339
340
341 static int
342 reverse_variable_lookup (const struct categoricals *cat, int subscript)
343 {
344   assert (cat->reverse_variable_map);
345   assert (subscript >= 0);
346   assert (subscript < cat->n_cats_total);
347
348   return cat->reverse_variable_map[subscript];
349 }
350
351
352 /* Return the categorical variable corresponding to SUBSCRIPT */
353 const struct variable *
354 categoricals_get_variable_by_subscript (const struct categoricals *cat, int subscript)
355 {
356   int index = reverse_variable_lookup (cat, subscript);
357
358   return cat->vp[index].var;
359 }
360
361 /* Return the value corresponding to SUBSCRIPT */
362 const union value *
363 categoricals_get_value_by_subscript (const struct categoricals *cat, int subscript)
364 {
365   int vindex = reverse_variable_lookup (cat, subscript);
366   const struct var_params *vp = &cat->vp[vindex];
367   const struct value_node *vn = vp->reverse_value_map [subscript - vp->base_subscript];
368
369   return &vn->value;
370 }
371
372
373 double
374 categoricals_get_weight_by_subscript (const struct categoricals *cat, int subscript)
375 {
376   int vindex = reverse_variable_lookup (cat, subscript);
377   const struct var_params *vp = &cat->vp[vindex];
378
379   return vp->cc;
380 }
381
382 double
383 categoricals_get_sum_by_subscript (const struct categoricals *cat, int subscript)
384 {
385   int vindex = reverse_variable_lookup (cat, subscript);
386   const struct var_params *vp = &cat->vp[vindex];
387
388   const struct value_node *vn = vp->reverse_value_map [subscript - vp->base_subscript];
389   return vn->cc;
390 }
391
392
393 /* Returns unity if the value in case C at SUBSCRIPT is equal to the category
394    for that subscript */
395 double
396 categoricals_get_binary_by_subscript (const struct categoricals *cat, int subscript,
397                                       const struct ccase *c)
398 {
399   const struct variable *var = categoricals_get_variable_by_subscript (cat, subscript);
400   int width = var_get_width (var);
401
402   const union value *val = case_data (c, var);
403
404   return value_equal (val, categoricals_get_value_by_subscript (cat, subscript), width);
405 }
406
407
408 size_t
409 categoricals_get_n_variables (const struct categoricals *cat)
410 {
411   return cat->n_vars;
412 }
413
414
415
416 void *
417 categoricals_get_user_data_by_subscript (const struct categoricals *cat, int subscript)
418 {
419   int vindex = reverse_variable_lookup (cat, subscript);
420   const struct var_params *vp = &cat->vp[vindex];
421
422   const struct value_node *vn = vp->reverse_value_map [subscript - vp->base_subscript];
423   return vn->user_data;
424 }