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