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