1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2009, 2010, 2011, 2012, 2014 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include "math/categoricals.h"
20 #include "math/interaction.h"
25 #include "data/case.h"
26 #include "data/value.h"
27 #include "data/variable.h"
28 #include "libpspp/array.h"
29 #include "libpspp/hmap.h"
30 #include "libpspp/pool.h"
31 #include "libpspp/str.h"
32 #include "libpspp/hash-functions.h"
34 #include "gl/xalloc.h"
36 #define CATEGORICALS_DEBUG 0
40 struct hmap_node node; /* Node in hash map. */
42 union value val; /* The value */
44 int index; /* A zero based unique index for this value */
48 struct interaction_value
50 struct hmap_node node; /* Node in hash map */
52 struct ccase *ccase; /* A case (probably the first in the dataset) which matches
55 double cc; /* Total of the weights of cases matching this interaction */
57 void *user_data; /* A pointer to data which the caller can store stuff */
60 static struct value_node *
61 lookup_value (const struct hmap *map, const union value *val, unsigned int hash, int width)
63 struct value_node *vn = NULL;
64 HMAP_FOR_EACH_WITH_HASH (vn, struct value_node, node, hash, map)
66 if (value_equal (&vn->val, val, width))
75 struct hmap_node node; /* Node in hash map. */
76 const struct variable *var; /* The variable */
78 struct hmap valmap; /* A map of value nodes */
79 int n_vals; /* Number of values for this variable */
83 /* Comparison function to sort value_nodes in ascending order */
85 compare_value_node_3way (const void *vn1_, const void *vn2_, const void *aux)
87 const struct value_node *const *vn1p = vn1_;
88 const struct value_node *const *vn2p = vn2_;
90 const struct variable_node *vn = aux;
93 return value_compare_3way (&(*vn1p)->val, &(*vn2p)->val, var_get_width (vn->var));
98 static struct variable_node *
99 lookup_variable (const struct hmap *map, const struct variable *var, unsigned int hash)
101 struct variable_node *vn = NULL;
102 HMAP_FOR_EACH_WITH_HASH (vn, struct variable_node, node, hash, map)
112 struct interact_params
114 /* An example of each interaction that appears in the data, like a frequency
115 table for 'iact'. By construction, the number of elements must be less
116 than or equal to 'n_cats'.
118 categoricals_update() updates 'ivmap' case-by-case, then
119 categoricals_done() dumps 'ivmap' into 'ivs' and sorts it. */
121 struct interaction_value **ivs;
123 const struct interaction *iact;
128 /* Product of hmap_count(&varnodes[*]->valmap), that is, the maximum number
129 of distinct values of this interaction. */
132 /* An array of integers df_n * df_{n-1} * df_{n-2} ...
133 These are the products of the degrees of freedom for the current
134 variable and all preceding variables */
139 /* Sum of ivs[*]->cc. */
145 compare_interaction_value_3way (const void *vn1_, const void *vn2_, const void *aux)
147 const struct interaction_value *const *vn1p = vn1_;
148 const struct interaction_value *const *vn2p = vn2_;
150 const struct interact_params *iap = aux;
152 return interaction_case_cmp_3way (iap->iact, (*vn1p)->ccase, (*vn2p)->ccase);
157 /* The weight variable */
158 const struct variable *wv;
160 /* An array of interact_params */
161 struct interact_params *iap;
164 /* Map whose members are the union of the variables which comprise IAP */
167 /* The number of categorical variables which contain entries.
168 In the absence of missing values, this will be equal to N_IAP */
171 /* A map to enable the lookup of variables indexed by subscript.
172 This map considers only the N - 1 of the N variables.
174 int *df_to_iact; /* 'df_sum' elements. */
177 /* Like the above, but uses all N variables */
178 int *cat_to_iact; /* 'n_cats_total' elements. */
183 /* Missing values in the factor variables to be excluded */
184 enum mv_class fctr_excl;
191 const struct payload *payload;
196 categoricals_isbalanced (const struct categoricals *cat)
200 for (i = 0 ; i < cat->n_iap; ++i)
203 const struct interact_params *iap = &cat->iap[i];
206 for (v = 0; v < hmap_count (&iap->ivmap); ++v)
208 const struct interaction_value *iv = iap->ivs[v];
220 categoricals_dump (const struct categoricals *cat)
222 if (CATEGORICALS_DEBUG)
226 printf ("df to interaction map:\n");
227 for (i = 0; i < cat->df_sum; ++i)
229 printf (" %d", cat->df_to_iact[i]);
233 printf ("Category to interaction map:\n");
234 for (i = 0; i < cat->n_cats_total; ++i)
236 printf (" %d", cat->cat_to_iact[i]);
240 printf ("Number of interactions %zu\n", cat->n_iap);
241 for (i = 0 ; i < cat->n_iap; ++i)
245 const struct interact_params *iap = &cat->iap[i];
246 const struct interaction *iact = iap->iact;
248 ds_init_empty (&str);
249 interaction_to_string (iact, &str);
251 printf ("\nInteraction: \"%s\" (number of categories: %d); ", ds_cstr (&str), iap->n_cats);
253 printf ("Base index (df/categories): %d/%d\n", iap->base_df, iap->base_cats);
256 for (v = 0; v < hmap_count (&iap->ivmap); ++v)
259 const struct interaction_value *iv = iap->ivs[v];
261 if (v > 0) printf (" ");
263 for (vv = 0; vv < iact->n_vars; ++vv)
265 const struct variable *var = iact->vars[vv];
266 const union value *val = case_data (iv->ccase, var);
267 unsigned int varhash = hash_pointer (var, 0);
268 struct variable_node *vn = lookup_variable (&cat->varmap, var, varhash);
270 const int width = var_get_width (var);
271 unsigned int valhash = value_hash (val, width, 0);
272 struct value_node *valn = lookup_value (&vn->valmap, val, valhash, width);
274 assert (vn->var == var);
276 printf ("%.*g(%d)", DBL_DIG + 1, val->f, valn->index);
277 if (vv < iact->n_vars - 1)
288 categoricals_destroy (struct categoricals *cat)
290 struct variable_node *vn = NULL;
295 for (i = 0; i < cat->n_iap; ++i)
297 struct interaction_value *iv = NULL;
298 /* Interate over each interaction value, and unref any cases that we reffed */
299 HMAP_FOR_EACH (iv, struct interaction_value, node, &cat->iap[i].ivmap)
301 if (cat->payload && cat->payload->destroy)
302 cat->payload->destroy (cat->aux1, cat->aux2, iv->user_data);
303 case_unref (iv->ccase);
306 free (cat->iap[i].enc_sum);
307 free (cat->iap[i].df_prod);
308 hmap_destroy (&cat->iap[i].ivmap);
311 /* Interate over each variable and delete its value map */
312 HMAP_FOR_EACH (vn, struct variable_node, node, &cat->varmap)
314 hmap_destroy (&vn->valmap);
317 hmap_destroy (&cat->varmap);
319 pool_destroy (cat->pool);
326 static struct interaction_value *
327 lookup_case (const struct hmap *map, const struct interaction *iact, const struct ccase *c)
329 struct interaction_value *iv = NULL;
330 size_t hash = interaction_case_hash (iact, c, 0);
332 HMAP_FOR_EACH_WITH_HASH (iv, struct interaction_value, node, hash, map)
334 if (interaction_case_equal (iact, c, iv->ccase))
341 /* Returns true iff CAT is sane, that is, if it is complete and has at least
344 categoricals_sane (const struct categoricals *cat)
349 /* Creates and returns a new categoricals object whose variables come from the
350 N_INTER interactions objects in the array starting at INTER. (The INTER
351 objects must outlive the categoricals object because it uses them
354 FCTR_EXCL determines which cases are listwise ignored by
355 categoricals_update(). */
356 struct categoricals *
357 categoricals_create (struct interaction *const*inter, size_t n_inter,
358 const struct variable *wv, enum mv_class fctr_excl)
361 struct categoricals *cat = xmalloc (sizeof *cat);
363 cat->n_iap = n_inter;
365 cat->n_cats_total = 0;
367 cat->df_to_iact = NULL;
368 cat->cat_to_iact = NULL;
369 cat->pool = pool_create ();
370 cat->fctr_excl = fctr_excl;
375 cat->iap = pool_calloc (cat->pool, cat->n_iap, sizeof *cat->iap);
377 hmap_init (&cat->varmap);
378 for (i = 0 ; i < cat->n_iap; ++i)
381 hmap_init (&cat->iap[i].ivmap);
382 cat->iap[i].iact = inter[i];
383 cat->iap[i].cc = 0.0;
384 for (v = 0; v < inter[i]->n_vars; ++v)
386 const struct variable *var = inter[i]->vars[v];
387 unsigned int hash = hash_pointer (var, 0);
388 struct variable_node *vn = lookup_variable (&cat->varmap, var, hash);
391 vn = pool_malloc (cat->pool, sizeof *vn);
394 hmap_init (&vn->valmap);
396 hmap_insert (&cat->varmap, &vn->node, hash);
407 categoricals_update (struct categoricals *cat, const struct ccase *c)
410 struct variable_node *vn = NULL;
416 weight = cat->wv ? case_data (c, cat->wv)->f : 1.0;
417 weight = var_force_valid_weight (cat->wv, weight, NULL);
419 assert (NULL == cat->df_to_iact);
420 assert (NULL == cat->cat_to_iact);
422 /* Interate over each variable, and add the value of that variable
423 to the appropriate map, if it's not already present. */
424 HMAP_FOR_EACH (vn, struct variable_node, node, &cat->varmap)
426 const int width = var_get_width (vn->var);
427 const union value *val = case_data (c, vn->var);
428 unsigned int hash = value_hash (val, width, 0);
430 struct value_node *valn = lookup_value (&vn->valmap, val, hash, width);
433 valn = pool_malloc (cat->pool, sizeof *valn);
436 value_init (&valn->val, width);
437 value_copy (&valn->val, val, width);
438 hmap_insert (&vn->valmap, &valn->node, hash);
442 for (i = 0 ; i < cat->n_iap; ++i)
444 const struct interaction *iact = cat->iap[i].iact;
447 struct interaction_value *node;
449 if ( interaction_case_is_missing (iact, c, cat->fctr_excl))
452 hash = interaction_case_hash (iact, c, 0);
453 node = lookup_case (&cat->iap[i].ivmap, iact, c);
457 node = pool_malloc (cat->pool, sizeof *node);
458 node->ccase = case_ref (c);
461 hmap_insert (&cat->iap[i].ivmap, &node->node, hash);
465 node->user_data = cat->payload->create (cat->aux1, cat->aux2);
472 cat->iap[i].cc += weight;
476 cat->payload->update (cat->aux1, cat->aux2, node->user_data, c, weight);
481 /* Return the number of categories (distinct values) for interaction IDX in
484 categoricals_n_count (const struct categoricals *cat, size_t n)
486 return hmap_count (&cat->iap[n].ivmap);
490 /* Returns the number of degrees of freedom for interaction IDX within CAT. */
492 categoricals_df (const struct categoricals *cat, size_t n)
494 const struct interact_params *iap = &cat->iap[n];
495 return iap->df_prod[iap->iact->n_vars - 1];
499 /* Return the total number of categories across all interactions in CAT. */
501 categoricals_n_total (const struct categoricals *cat)
503 if (!categoricals_is_complete (cat))
506 return cat->n_cats_total;
509 /* Returns the total degrees of freedom for CAT. */
511 categoricals_df_total (const struct categoricals *cat)
519 /* Returns true iff categoricals_done() has been called for CAT. */
521 categoricals_is_complete (const struct categoricals *cat)
523 return (NULL != cat->df_to_iact);
527 /* This function must be called (once) before any call to the *_by_subscript or
528 *_by_category functions, but AFTER any calls to categoricals_update. If this
529 function returns false, then no calls to _by_subscript or *_by_category are
532 categoricals_done (const struct categoricals *cat_)
534 /* Implementation Note: Whilst this function is O(n) in cat->n_cats_total, in most
535 uses it will be more efficient that using a tree based structure, since it
536 is called only once, and means that subsequent lookups will be O(1).
538 1 call of O(n) + 10^9 calls of O(1) is better than 10^9 calls of O(log n).
540 struct categoricals *cat = CONST_CAST (struct categoricals *, cat_);
550 cat->n_cats_total = 0;
552 /* Calculate the degrees of freedom, and the number of categories */
553 for (i = 0 ; i < cat->n_iap; ++i)
556 const struct interaction *iact = cat->iap[i].iact;
558 cat->iap[i].df_prod = iact->n_vars ? xcalloc (iact->n_vars, sizeof (int)) : NULL;
560 cat->iap[i].n_cats = 1;
562 for (v = 0 ; v < iact->n_vars; ++v)
565 const struct variable *var = iact->vars[v];
567 struct variable_node *vn = lookup_variable (&cat->varmap, var, hash_pointer (var, 0));
569 struct value_node *valnd = NULL;
570 struct value_node **array ;
572 assert (vn->n_vals == hmap_count (&vn->valmap));
580 /* Sort the VALMAP here */
581 array = xcalloc (sizeof *array, vn->n_vals);
583 HMAP_FOR_EACH (valnd, struct value_node, node, &vn->valmap)
585 /* Note: This loop is probably superfluous, it could be done in the
586 update stage (at the expense of a realloc) */
590 sort (array, vn->n_vals, sizeof (*array),
591 compare_value_node_3way, vn);
593 for (x = 0; x < vn->n_vals; ++x)
595 struct value_node *vvv = array[x];
600 cat->iap[i].df_prod[v] = df * (vn->n_vals - 1);
601 df = cat->iap[i].df_prod[v];
603 cat->iap[i].n_cats *= vn->n_vals;
607 cat->df_sum += cat->iap[i].df_prod [v - 1];
609 cat->n_cats_total += cat->iap[i].n_cats;
613 cat->df_to_iact = pool_calloc (cat->pool, cat->df_sum,
614 sizeof *cat->df_to_iact);
616 cat->cat_to_iact = pool_calloc (cat->pool, cat->n_cats_total,
617 sizeof *cat->cat_to_iact);
619 for (i = 0 ; i < cat->n_iap; ++i)
621 struct interaction_value *ivn = NULL;
624 struct interact_params *iap = &cat->iap[i];
626 iap->base_df = idx_df;
627 iap->base_cats = idx_cat;
629 iap->ivs = pool_calloc (cat->pool, iap->n_cats, sizeof *iap->ivs);
631 HMAP_FOR_EACH (ivn, struct interaction_value, node, &iap->ivmap)
636 assert (x <= iap->n_cats);
638 /* For some purposes (eg CONTRASTS in ONEWAY) the values need to be sorted */
639 sort (iap->ivs, x, sizeof *iap->ivs,
640 compare_interaction_value_3way, iap);
642 /* Fill the remaining values with null */
643 for (ii = x ; ii < iap->n_cats; ++ii)
646 /* Populate the variable maps. */
649 for (ii = 0; ii < iap->df_prod [iap->iact->n_vars - 1]; ++ii)
650 cat->df_to_iact[idx_df++] = i;
653 for (ii = 0; ii < iap->n_cats; ++ii)
654 cat->cat_to_iact[idx_cat++] = i;
657 assert (cat->n_vars <= cat->n_iap);
659 categoricals_dump (cat);
661 /* Tally up the sums for all the encodings */
662 for (i = 0 ; i < cat->n_iap; ++i)
665 struct interact_params *iap = &cat->iap[i];
666 const struct interaction *iact = iap->iact;
668 const int df = iap->df_prod ? iap->df_prod [iact->n_vars - 1] : 0;
670 iap->enc_sum = xcalloc (df, sizeof (*(iap->enc_sum)));
672 for (y = 0; y < hmap_count (&iap->ivmap); ++y)
674 struct interaction_value *iv = iap->ivs[y];
675 for (x = iap->base_df; x < iap->base_df + df ;++x)
677 const double bin = categoricals_get_effects_code_for_case (cat, x, iv->ccase);
678 iap->enc_sum [x - iap->base_df] += bin * iv->cc;
680 if (cat->payload && cat->payload->calculate)
681 cat->payload->calculate (cat->aux1, cat->aux2, iv->user_data);
690 df_to_iap (const struct categoricals *cat, int subscript)
692 assert (cat->df_to_iact);
693 assert (subscript >= 0);
694 assert (subscript < cat->df_sum);
696 return cat->df_to_iact[subscript];
700 cat_index_to_iap (const struct categoricals *cat, int subscript)
702 assert (cat->cat_to_iact);
703 assert (subscript >= 0);
704 assert (subscript < cat->n_cats_total);
706 return cat->cat_to_iact[subscript];
710 /* Return the interaction corresponding to SUBSCRIPT */
711 const struct interaction *
712 categoricals_get_interaction_by_subscript (const struct categoricals *cat, int subscript)
714 int index = df_to_iap (cat, subscript);
716 return cat->iap[index].iact;
720 categoricals_get_weight_by_subscript (const struct categoricals *cat, int subscript)
722 int vindex = df_to_iap (cat, subscript);
723 const struct interact_params *vp = &cat->iap[vindex];
729 categoricals_get_sum_by_subscript (const struct categoricals *cat, int subscript)
731 int vindex = df_to_iap (cat, subscript);
732 const struct interact_params *vp = &cat->iap[vindex];
734 return vp->enc_sum[subscript - vp->base_df];
738 /* Returns unity if the value in case C at SUBSCRIPT is equal to the category
739 for that subscript */
741 categoricals_get_code_for_case (const struct categoricals *cat, int subscript,
742 const struct ccase *c,
745 const struct interaction *iact = categoricals_get_interaction_by_subscript (cat, subscript);
747 const int i = df_to_iap (cat, subscript);
749 const int base_index = cat->iap[i].base_df;
754 const struct interact_params *iap = &cat->iap[i];
757 for (v = 0; v < iact->n_vars; ++v)
759 const struct variable *var = iact->vars[v];
761 const union value *val = case_data (c, var);
762 const int width = var_get_width (var);
763 const struct variable_node *vn = lookup_variable (&cat->varmap, var, hash_pointer (var, 0));
765 const unsigned int hash = value_hash (val, width, 0);
766 const struct value_node *valn = lookup_value (&vn->valmap, val, hash, width);
770 const double df = iap->df_prod[v] / dfp;
772 /* Translate the subscript into an index for the individual variable */
773 const int index = ((subscript - base_index) % iap->df_prod[v] ) / dfp;
774 dfp = iap->df_prod [v];
776 if (effects_coding && valn->index == df )
778 else if ( valn->index != index )
788 /* Returns unity if the value in case C at SUBSCRIPT is equal to the category
789 for that subscript */
791 categoricals_get_dummy_code_for_case (const struct categoricals *cat, int subscript,
792 const struct ccase *c)
794 return categoricals_get_code_for_case (cat, subscript, c, false);
797 /* Returns unity if the value in case C at SUBSCRIPT is equal to the category
799 Else if it is the last category, return -1.
803 categoricals_get_effects_code_for_case (const struct categoricals *cat, int subscript,
804 const struct ccase *c)
806 return categoricals_get_code_for_case (cat, subscript, c, true);
809 /* Return a case containing the set of values corresponding to
810 the Nth Category of the IACTth interaction */
812 categoricals_get_case_by_category_real (const struct categoricals *cat, int iact, int n)
814 const struct interaction_value *vn;
816 const struct interact_params *vp = &cat->iap[iact];
818 if ( n >= hmap_count (&vp->ivmap))
826 /* Return a the user data corresponding to the Nth Category of the IACTth interaction. */
828 categoricals_get_user_data_by_category_real (const struct categoricals *cat, int iact, int n)
830 const struct interact_params *vp = &cat->iap[iact];
831 const struct interaction_value *iv ;
833 if ( n >= hmap_count (&vp->ivmap))
838 return iv->user_data;
843 /* Return a case containing the set of values corresponding to SUBSCRIPT */
845 categoricals_get_case_by_category (const struct categoricals *cat, int subscript)
847 int vindex = cat_index_to_iap (cat, subscript);
848 const struct interact_params *vp = &cat->iap[vindex];
849 const struct interaction_value *vn = vp->ivs [subscript - vp->base_cats];
855 categoricals_get_user_data_by_category (const struct categoricals *cat, int subscript)
857 int vindex = cat_index_to_iap (cat, subscript);
858 const struct interact_params *vp = &cat->iap[vindex];
860 const struct interaction_value *iv = vp->ivs [subscript - vp->base_cats];
861 return iv->user_data;
868 categoricals_set_payload (struct categoricals *cat, const struct payload *p,
869 const void *aux1, void *aux2)