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