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