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