categoricals.c: Fix memory access problems on empty interactions.
[pspp] / src / math / categoricals.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2011, 2012 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 #include "libpspp/hash-functions.h"
32
33 #include "gl/xalloc.h"
34
35 #define EFFECTS_CODING 1
36
37 struct value_node
38 {
39   struct hmap_node node;      /* Node in hash map. */
40
41   union value val;            /* The value */
42
43   int index;                  /* A zero based unique index for this value */
44 };
45
46 struct interaction_value
47 {
48   struct hmap_node node;      /* Node in hash map */
49
50   struct ccase *ccase;        /* A case (probably the first in the dataset) which matches this value */
51
52   double cc;        /* Total of the weights of cases matching this interaction */
53
54   void *user_data;            /* A pointer to data which the caller can store stuff */
55 };
56
57 static struct value_node *
58 lookup_value (const struct hmap *map, const union value *val, unsigned int hash, int width)
59 {
60   struct value_node *vn = NULL;
61   HMAP_FOR_EACH_WITH_HASH (vn, struct value_node, node, hash, map)
62     {
63       if (value_equal (&vn->val, val, width))
64         break;
65     }
66   
67   return vn;
68 }
69
70 struct variable_node
71 {
72   struct hmap_node node;      /* Node in hash map. */
73   const struct variable *var; /* The variable */
74
75   struct hmap valmap;         /* A map of value nodes */
76   int n_vals;                 /* Number of values for this variable */
77 };
78
79 #if 0
80 static void
81 dump_interaction (const struct interaction *iact)
82 {
83   struct string str = DS_EMPTY_INITIALIZER;
84   interaction_to_string (iact, &str);
85   printf ("Interaction: %s\n", ds_cstr (&str));
86   ds_destroy (&str);
87 }
88 #endif
89
90 static struct variable_node *
91 lookup_variable (const struct hmap *map, const struct variable *var, unsigned int hash)
92 {
93   struct variable_node *vn = NULL;
94   HMAP_FOR_EACH_WITH_HASH (vn, struct variable_node, node, hash, map)
95     {
96       if (vn->var == var)
97         break;
98       
99       fprintf (stderr, "Warning: Hash table collision\n");
100     }
101   
102   return vn;
103 }
104
105
106 struct interact_params
107 {
108   /* A map indexed by a interaction_value */
109   struct hmap ivmap;
110
111   const struct interaction *iact;
112
113   int base_subscript_short;
114   int base_subscript_long;
115
116   /* The number of distinct values of this interaction */
117   int n_cats;
118
119   /* An array of integers df_n * df_{n-1} * df_{n-2} ...
120      These are the products of the degrees of freedom for the current 
121      variable and all preceeding variables */
122   int *df_prod; 
123
124   double *enc_sum;
125
126   /* A map of interaction_values indexed by subscript */
127   struct interaction_value **reverse_interaction_value_map;
128
129   double cc;
130 };
131
132
133 /* Comparison function to sort the reverse_value_map in ascending order */
134 static int
135 compare_interaction_value_3way (const void *vn1_, const void *vn2_, const void *aux)
136 {
137   const struct interaction_value *const *vn1p = vn1_;
138   const struct interaction_value *const *vn2p = vn2_;
139
140   const struct interact_params *iap = aux;
141
142   return interaction_case_cmp_3way (iap->iact, (*vn1p)->ccase, (*vn2p)->ccase);
143 }
144
145 struct categoricals
146 {
147   /* The weight variable */
148   const struct variable *wv;
149
150   /* An array of interact_params */
151   struct interact_params *iap;
152
153   /* Map whose members are the union of the variables which comprise IAP */
154   struct hmap varmap;
155
156   /* The size of IAP. (ie, the number of interactions involved.) */
157   size_t n_iap;
158
159   /* The number of categorical variables which contain entries.
160      In the absence of missing values, this will be equal to N_IAP */
161   size_t n_vars;
162
163   size_t df_sum;
164
165   /* A map to enable the lookup of variables indexed by subscript.
166      This map considers only the N - 1 of the N variables.
167   */
168   int *reverse_variable_map_short;
169
170   /* Like the above, but uses all N variables */
171   int *reverse_variable_map_long;
172
173   size_t n_cats_total;
174
175   struct pool *pool;
176
177   /* Missing values to be excluded */
178   enum mv_class exclude;
179
180   const void *aux1;
181   void *aux2;
182
183   const struct payload *payload;
184 };
185
186 #if 0
187 static void
188 categoricals_dump (const struct categoricals *cat)
189 {
190   int i;
191
192   printf ("Reverse Variable Map (short):\n");
193   for (i = 0; i < cat->df_sum; ++i)
194     {
195       printf (" %d", cat->reverse_variable_map_short[i]);
196     }
197   printf ("\n");
198
199   printf ("Reverse Variable Map (long):\n");
200   for (i = 0; i < cat->n_cats_total; ++i)
201     {
202       printf (" %d", cat->reverse_variable_map_long[i]);
203     }
204   printf ("\n");
205
206
207   printf ("Number of interactions %d\n", cat->n_iap);
208   for (i = 0 ; i < cat->n_iap; ++i)
209     {
210       int v;
211       struct string str;
212       const struct interact_params *iap = &cat->iap[i];
213       const struct interaction *iact = iap->iact;
214
215       ds_init_empty (&str);
216       interaction_to_string (iact, &str);
217
218       printf ("\nInteraction: %s (n: %d); ", ds_cstr (&str), iap->n_cats);
219       ds_destroy (&str);
220       printf ("Base subscript: %d\n", iap->base_subscript_short);
221
222       printf ("\t(");
223       for (v = 0; v < hmap_count (&iap->ivmap); ++v)
224         {
225           int vv;
226           const struct interaction_value *iv = iap->reverse_interaction_value_map[v];
227           
228           if (v > 0)  printf ("   ");
229           printf ("{");
230           for (vv = 0; vv < iact->n_vars; ++vv)
231             {
232               const struct variable *var = iact->vars[vv];
233               const union value *val = case_data (iv->ccase, var);
234               
235               printf ("%g", val->f);
236               if (vv < iact->n_vars - 1)
237                 printf (", ");
238             }
239           printf ("}");
240         }
241       printf (")\n");
242     }
243 }
244 #endif
245
246 void
247 categoricals_destroy (struct categoricals *cat)
248 {
249   struct variable_node *vn = NULL;
250   int i;
251   if (NULL == cat)
252     return;
253   for (i = 0; i < cat->n_iap; ++i)
254     {
255       struct interaction_value *iv = NULL;
256       /* Interate over each interaction value, and unref any cases that we reffed */
257       HMAP_FOR_EACH (iv, struct interaction_value, node, &cat->iap[i].ivmap)
258         {
259 #if 0
260           if (cat->payload)
261             cat->payload->destroy (cat->aux1, iv->user_data);
262 #endif
263           case_unref (iv->ccase);
264         }
265
266       free (cat->iap[i].enc_sum);
267       free (cat->iap[i].df_prod);
268       hmap_destroy (&cat->iap[i].ivmap);
269     }
270
271   /* Interate over each variable and delete its value map */
272   HMAP_FOR_EACH (vn, struct variable_node, node, &cat->varmap)
273     {
274       hmap_destroy (&vn->valmap);
275     }
276
277   hmap_destroy (&cat->varmap);
278
279   pool_destroy (cat->pool);
280
281   free (cat);
282 }
283
284
285
286 static struct interaction_value *
287 lookup_case (const struct hmap *map, const struct interaction *iact, const struct ccase *c)
288 {
289   struct interaction_value *iv = NULL;
290   size_t hash = interaction_case_hash (iact, c, 0);
291
292   HMAP_FOR_EACH_WITH_HASH (iv, struct interaction_value, node, hash, map)
293     {
294       if (interaction_case_equal (iact, c, iv->ccase))
295         break;
296
297       fprintf (stderr, "Warning: Hash table collision\n");
298     }
299
300   return iv;
301 }
302
303
304 struct categoricals *
305 categoricals_create (struct interaction *const*inter, size_t n_inter,
306                      const struct variable *wv, enum mv_class exclude)
307 {
308   size_t i;
309   struct categoricals *cat = xmalloc (sizeof *cat);
310   
311   cat->n_iap = n_inter;
312   cat->wv = wv;
313   cat->n_cats_total = 0;
314   cat->n_vars = 0;
315   cat->reverse_variable_map_short = NULL;
316   cat->reverse_variable_map_long = NULL;
317   cat->pool = pool_create ();
318   cat->exclude = exclude;
319   cat->payload = NULL;
320   cat->aux2 = NULL;
321
322   cat->iap = pool_calloc (cat->pool, cat->n_iap, sizeof *cat->iap);
323
324   hmap_init (&cat->varmap);
325   for (i = 0 ; i < cat->n_iap; ++i)
326     {
327       int v;
328       hmap_init (&cat->iap[i].ivmap);
329       cat->iap[i].iact = inter[i];
330       cat->iap[i].cc = 0.0;
331       for (v = 0; v < inter[i]->n_vars; ++v)
332         {
333           const struct variable *var = inter[i]->vars[v];
334           unsigned int hash = hash_pointer (var, 0);
335           struct variable_node *vn = lookup_variable (&cat->varmap, var, hash);
336           if (vn == NULL)
337             {
338               vn = pool_malloc (cat->pool, sizeof *vn);
339               vn->var = var;
340               vn->n_vals = 0;
341               hmap_init (&vn->valmap);
342
343               hmap_insert (&cat->varmap, &vn->node,  hash);
344             }
345         }
346     }
347
348   return cat;
349 }
350
351
352
353 void
354 categoricals_update (struct categoricals *cat, const struct ccase *c)
355 {
356   int i;
357   struct variable_node *vn = NULL;
358   const double weight = cat->wv ? case_data (c, cat->wv)->f : 1.0;
359
360   assert (NULL == cat->reverse_variable_map_short);
361   assert (NULL == cat->reverse_variable_map_long);
362
363   /* Interate over each variable, and add the value of that variable
364      to the appropriate map, if it's not already present. */
365   HMAP_FOR_EACH (vn, struct variable_node, node, &cat->varmap)
366     {
367       const int width = var_get_width (vn->var);
368       const union value *val = case_data (c, vn->var);
369       unsigned int hash = value_hash (val, width, 0);
370
371       struct value_node *valn = lookup_value (&vn->valmap, val, hash, width);
372       if (valn == NULL)
373         {
374           valn = pool_malloc (cat->pool, sizeof *valn);
375           valn->index = vn->n_vals++;
376           value_init (&valn->val, width);
377           value_copy (&valn->val, val, width);
378           hmap_insert (&vn->valmap, &valn->node, hash);
379         }
380     }     
381   
382   for (i = 0 ; i < cat->n_iap; ++i)
383     {
384       const struct interaction *iact = cat->iap[i].iact;
385
386       size_t hash;
387       struct interaction_value *node;
388
389       if ( interaction_case_is_missing (iact, c, cat->exclude))
390         continue;
391
392       hash = interaction_case_hash (iact, c, 0);
393       node = lookup_case (&cat->iap[i].ivmap, iact, c);
394
395       if ( NULL == node)
396         {
397           node = pool_malloc (cat->pool, sizeof *node);
398
399           node->ccase = case_ref (c);
400           node->cc = weight;
401
402           hmap_insert (&cat->iap[i].ivmap, &node->node, hash);
403
404           if (cat->payload) 
405             {
406               node->user_data = cat->payload->create (cat->aux1, cat->aux2);
407             }
408         }
409       else
410         {
411           node->cc += weight;
412         }
413       cat->iap[i].cc += weight;
414
415       if (cat->payload)
416         {
417           double weight = cat->wv ? case_data (c, cat->wv)->f : 1.0;
418           cat->payload->update (cat->aux1, cat->aux2, node->user_data, c, weight);
419         }
420
421     }
422 }
423
424 /* Return the number of categories (distinct values) for interction N */
425 size_t
426 categoricals_n_count (const struct categoricals *cat, size_t n)
427 {
428   return hmap_count (&cat->iap[n].ivmap);
429 }
430
431
432 size_t
433 categoricals_df (const struct categoricals *cat, size_t n)
434 {
435   const struct interact_params *iap = &cat->iap[n];
436   return iap->df_prod[iap->iact->n_vars - 1];
437 }
438
439
440 /* Return the total number of categories */
441 size_t
442 categoricals_n_total (const struct categoricals *cat)
443 {
444   if (!categoricals_is_complete (cat))
445     return 0;
446
447   return cat->n_cats_total;
448 }
449
450 size_t
451 categoricals_df_total (const struct categoricals *cat)
452 {
453   return cat->df_sum;
454 }
455
456 bool
457 categoricals_is_complete (const struct categoricals *cat)
458 {
459   return (NULL != cat->reverse_variable_map_short);
460 }
461
462
463 /* This function must be called *before* any call to categoricals_get_*_by subscript and
464  *after* all calls to categoricals_update */
465 bool
466 categoricals_done (const struct categoricals *cat_)
467 {
468   /* Implementation Note: Whilst this function is O(n) in cat->n_cats_total, in most
469      uses it will be more efficient that using a tree based structure, since it
470      is called only once, and means that subsequent lookups will be O(1).
471
472      1 call of O(n) + 10^9 calls of O(1) is better than 10^9 calls of O(log n).
473   */
474   struct categoricals *cat = CONST_CAST (struct categoricals *, cat_);
475   int v;
476   int i;
477   int idx_short = 0;
478   int idx_long = 0;
479   cat->df_sum = 0;
480   cat->n_cats_total = 0;
481
482   /* Calculate the degrees of freedom, and the number of categories */
483   for (i = 0 ; i < cat->n_iap; ++i)
484     {
485       int df = 1;
486       const struct interaction *iact = cat->iap[i].iact;
487
488       cat->iap[i].df_prod = iact->n_vars ? xcalloc (iact->n_vars, sizeof (int)) : NULL;
489
490       cat->iap[i].n_cats = 1;
491       
492       for (v = 0 ; v < iact->n_vars; ++v)
493         {
494           const struct variable *var = iact->vars[v];
495
496           struct variable_node *vn = lookup_variable (&cat->varmap, var, hash_pointer (var, 0));
497
498           if  (hmap_count (&vn->valmap) == 0)
499             return false;
500
501           cat->iap[i].df_prod[v] = df * (hmap_count (&vn->valmap) - 1);
502           df = cat->iap[i].df_prod[v];
503
504           cat->iap[i].n_cats *= hmap_count (&vn->valmap);
505         }
506
507       assert (v == iact->n_vars);
508       if (v > 0)
509         cat->df_sum += cat->iap[i].df_prod [v - 1];
510
511       cat->n_cats_total += cat->iap[i].n_cats;
512     }
513
514
515   cat->reverse_variable_map_short = pool_calloc (cat->pool,
516                                                  cat->df_sum,
517                                                  sizeof *cat->reverse_variable_map_short);
518
519   cat->reverse_variable_map_long = pool_calloc (cat->pool,
520                                                 cat->n_cats_total,
521                                                 sizeof *cat->reverse_variable_map_long);
522
523   for (i = 0 ; i < cat->n_iap; ++i)
524     {
525       struct interaction_value *ivn = NULL;
526       int x = 0;
527       int ii;
528       struct interact_params *iap = &cat->iap[i];
529
530       iap->base_subscript_short = idx_short;
531       iap->base_subscript_long = idx_long;
532
533       iap->reverse_interaction_value_map = pool_calloc (cat->pool, iap->n_cats,
534                                                         sizeof *iap->reverse_interaction_value_map);
535
536       HMAP_FOR_EACH (ivn, struct interaction_value, node, &iap->ivmap)
537         {
538           iap->reverse_interaction_value_map[x++] = ivn;
539         }
540
541       assert (x <= iap->n_cats);
542
543       /* For some purposes (eg CONTRASTS in ONEWAY) the values need to be sorted */
544       sort (iap->reverse_interaction_value_map, x, sizeof (*iap->reverse_interaction_value_map),
545             compare_interaction_value_3way, iap);
546
547       /* Fill the remaining values with null */
548       for (ii = x ; ii < iap->n_cats; ++ii)
549         iap->reverse_interaction_value_map[ii] = NULL;
550
551       /* Populate the reverse variable maps. */
552       if (iap->df_prod)
553         {
554           for (ii = 0; ii < iap->df_prod [iap->iact->n_vars - 1]; ++ii)
555             cat->reverse_variable_map_short[idx_short++] = i;
556         }
557
558       for (ii = 0; ii < iap->n_cats; ++ii)
559         cat->reverse_variable_map_long[idx_long++] = i;
560     }
561
562   assert (cat->n_vars <= cat->n_iap);
563
564   //  categoricals_dump (cat);
565
566   /* Tally up the sums for all the encodings */
567   for (i = 0 ; i < cat->n_iap; ++i)
568     {
569       int x, y;
570       struct interact_params *iap = &cat->iap[i];
571       const struct interaction *iact = iap->iact;
572
573       const int df = iap->df_prod ? iap->df_prod [iact->n_vars - 1] : 0;
574
575       iap->enc_sum = xcalloc (df, sizeof (*(iap->enc_sum)));
576
577       for (y = 0; y < hmap_count (&iap->ivmap); ++y)
578         {
579           struct interaction_value *iv = iap->reverse_interaction_value_map[y];
580           for (x = iap->base_subscript_short; x < iap->base_subscript_short + df ;++x)
581             {
582               const double bin = categoricals_get_code_for_case (cat, x, iv->ccase); \
583               iap->enc_sum [x - iap->base_subscript_short] += bin * iv->cc;
584             }
585         }
586     }
587
588   return true;
589 }
590
591
592 static int
593 reverse_variable_lookup_short (const struct categoricals *cat, int subscript)
594 {
595   assert (cat->reverse_variable_map_short);
596   assert (subscript >= 0);
597   assert (subscript < cat->df_sum);
598
599   return cat->reverse_variable_map_short[subscript];
600 }
601
602 static int
603 reverse_variable_lookup_long (const struct categoricals *cat, int subscript)
604 {
605   assert (cat->reverse_variable_map_long);
606   assert (subscript >= 0);
607   assert (subscript < cat->n_cats_total);
608
609   return cat->reverse_variable_map_long[subscript];
610 }
611
612
613 /* Return the interaction corresponding to SUBSCRIPT */
614 const struct interaction *
615 categoricals_get_interaction_by_subscript (const struct categoricals *cat, int subscript)
616 {
617   int index = reverse_variable_lookup_short (cat, subscript);
618
619   return cat->iap[index].iact;
620 }
621
622 double
623 categoricals_get_weight_by_subscript (const struct categoricals *cat, int subscript)
624 {
625   int vindex = reverse_variable_lookup_short (cat, subscript);
626   const struct interact_params *vp = &cat->iap[vindex];
627
628   return vp->cc;
629 }
630
631 double
632 categoricals_get_sum_by_subscript (const struct categoricals *cat, int subscript)
633 {
634   int vindex = reverse_variable_lookup_short (cat, subscript);
635   const struct interact_params *vp = &cat->iap[vindex];
636
637   return   vp->enc_sum[subscript - vp->base_subscript_short];
638 }
639
640 /* Returns unity if the value in case C at SUBSCRIPT is equal to the category
641    for that subscript */
642 double
643 categoricals_get_code_for_case (const struct categoricals *cat, int subscript,
644                                 const struct ccase *c)
645 {
646   const struct interaction *iact = categoricals_get_interaction_by_subscript (cat, subscript);
647
648   const int i = reverse_variable_lookup_short (cat, subscript);
649
650   const int base_index = cat->iap[i].base_subscript_short;
651
652   int v;
653   double result = 1.0;
654
655   const struct interact_params *iap = &cat->iap[i];
656
657   double dfp = 1.0;
658   for (v = 0; v < iact->n_vars; ++v)
659     {
660       const struct variable *var = iact->vars[v];
661
662       const union value *val = case_data (c, var);
663       const int width = var_get_width (var);
664       const struct variable_node *vn = lookup_variable (&cat->varmap, var, hash_pointer (var, 0));
665
666       const unsigned int hash = value_hash (val, width, 0);
667       const struct value_node *valn = lookup_value (&vn->valmap, val, hash, width);
668
669       double bin = 1.0;
670
671       const double df = iap->df_prod[v] / dfp;
672
673       /* Translate the subscript into an index for the individual variable */
674       const int index = ((subscript - base_index) % iap->df_prod[v] ) / dfp;
675       dfp = iap->df_prod [v];
676
677 #if EFFECTS_CODING
678       if ( valn->index == df )
679         bin = -1.0;
680       else 
681 #endif
682         if ( valn->index  != index )
683           bin = 0;
684     
685       result *= bin;
686     }
687
688   return result;
689 }
690
691
692 size_t
693 categoricals_get_n_variables (const struct categoricals *cat)
694 {
695   printf ("%s\n", __FUNCTION__);
696   return cat->n_vars;
697 }
698
699
700 /* Return a case containing the set of values corresponding to 
701    the Nth Category of the IACTth interaction */
702 const struct ccase *
703 categoricals_get_case_by_category_real (const struct categoricals *cat, int iact, int n)
704 {
705   const struct interact_params *vp = &cat->iap[iact];
706   const struct interaction_value *vn = vp->reverse_interaction_value_map [n];
707
708   return vn->ccase;
709 }
710
711 /* Return a the user data corresponding to the Nth Category of the IACTth interaction. */
712 void *
713 categoricals_get_user_data_by_category_real (const struct categoricals *cat, int iact, int n)
714 {
715   const struct interact_params *vp = &cat->iap[iact];
716   const struct interaction_value *iv = vp->reverse_interaction_value_map [n];
717
718   return iv->user_data;
719 }
720
721
722
723 /* Return a case containing the set of values corresponding to SUBSCRIPT */
724 const struct ccase *
725 categoricals_get_case_by_category (const struct categoricals *cat, int subscript)
726 {
727   int vindex = reverse_variable_lookup_long (cat, subscript);
728   const struct interact_params *vp = &cat->iap[vindex];
729   const struct interaction_value *vn = vp->reverse_interaction_value_map [subscript - vp->base_subscript_long];
730
731   return vn->ccase;
732 }
733
734 void *
735 categoricals_get_user_data_by_category (const struct categoricals *cat, int subscript)
736 {
737   int vindex = reverse_variable_lookup_long (cat, subscript);
738   const struct interact_params *vp = &cat->iap[vindex];
739
740   const struct interaction_value *iv = vp->reverse_interaction_value_map [subscript - vp->base_subscript_long];
741   return iv->user_data;
742 }
743
744
745 \f
746
747 void
748 categoricals_set_payload (struct categoricals *cat, const struct payload *p,
749                           const void *aux1, void *aux2)
750 {
751   cat->payload = p;
752   cat->aux1 = aux1;
753   cat->aux2 = aux2;
754 }