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