Coverage for src/bartz/grove/_grove.py: 98%
216 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
1# bartz/src/bartz/grove/_grove.py
2#
3# Copyright (c) 2024-2026, The Bartz Contributors
4#
5# This file is part of bartz.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
25"""Functions to create and manipulate binary decision trees."""
27import math
28from dataclasses import fields
29from functools import partial
30from typing import Literal, Protocol, runtime_checkable
32from equinox import tree_at
33from jax import lax, vmap
34from jax import numpy as jnp
35from jaxtyping import Array, Bool, Float, Float32, Int32, Integer, Shaped, UInt
36from numpy.lib.array_utils import normalize_axis_tuple
38from bartz._jaxext import (
39 Module,
40 autobatch,
41 field,
42 jit,
43 minimal_unsigned_arange,
44 minimal_unsigned_dtype,
45)
48@runtime_checkable
49class TreeHeaps(Protocol):
50 """A protocol for dataclasses that represent trees.
52 A tree is represented with arrays as a heap. The root node is at index 1.
53 The children nodes of a node at index :math:`i` are at indices :math:`2i`
54 (left child) and :math:`2i + 1` (right child). The array element at index 0
55 is unused. Since the nodes at the bottom level can only be leaves and not
56 decision nodes, `var_tree` and `split_tree` stop at the level above.
58 `leaf_tree` has the same length, the maximum number of leaves, with a
59 different layout: a node and its left child are never both leaves, so a
60 right child (or the root) shares an element with all the nodes reached from
61 it by going left, see `node_to_leaf_index`.
63 Arrays may have additional initial axes to represent multiple trees.
64 """
66 leaf_tree: (
67 Float[Array, '*batch_shape max_num_leaves']
68 | Float[Array, '*batch_shape k max_num_leaves']
69 )
70 """The values in the leaves of the trees. This array can be dirty, i.e.,
71 elements not in use can have whatever value, see `is_leaf_used`. It may
72 have an additional axis for multivariate leaves. The dtype may be narrower
73 than float32."""
75 var_tree: UInt[Array, '*batch_shape max_num_leaves']
76 """The axes along which the decision nodes operate. This array can be
77 dirty but for the always unused node at index 0 which must be set to 0."""
79 split_tree: UInt[Array, '*batch_shape max_num_leaves']
80 """The decision boundaries of the trees. The boundaries are open on the
81 right, i.e., a point belongs to the left child iff x < split. Whether a
82 node is a leaf is indicated by the corresponding 'split' element being
83 0. Unused nodes also have split set to 0. This array can't be dirty."""
85 leaf_unit: Float32[Array, ''] | Float32[Array, ' k']
86 """The storage unit of the leaf values. The leaf values in data units are
87 ``leaf_unit * leaf_tree``."""
89 offset: Float32[Array, ''] | Float32[Array, ' k']
90 """Constant shift added to the function represented by the trees, which is
91 ``offset + leaf_unit * (sum of leaf values over trees)``."""
94def is_multivariate(trees: TreeHeaps) -> bool:
95 """
96 Return whether the trees have vector-valued leaves.
98 Parameters
99 ----------
100 trees
101 The trees to inspect.
103 Returns
104 -------
105 Whether the leaves are vector-valued (an extra `k` axis on `leaf_tree`).
106 """
107 return trees.leaf_tree.ndim > trees.var_tree.ndim
110class TreesTrace(Module):
111 """Implementation of `bartz.grove.TreeHeaps` for an MCMC trace."""
113 # `var_tree`/`split_tree` are declared before `leaf_tree` so their single
114 # (union-free) annotations bind the variadic `*batch_shape` axis first;
115 # otherwise the runtime typechecker (which evaluates union members in a
116 # hash-randomized order) can mis-bind it against the `k` axis of
117 # `leaf_tree`'s union for a multivariate tree (the layouts are
118 # rank-ambiguous). See `bartz.mcmcstep._state.Forest`.
119 var_tree: UInt[Array, '*batch_shape max_num_leaves']
120 """The axes along which the decision nodes operate. This array can be
121 dirty but for the always unused node at index 0 which must be set to 0."""
123 split_tree: UInt[Array, '*batch_shape max_num_leaves']
124 """The decision boundaries of the trees. The boundaries are open on the
125 right, i.e., a point belongs to the left child iff x < split. Whether a
126 node is a leaf is indicated by the corresponding 'split' element being
127 0. Unused nodes also have split set to 0. This array can't be dirty."""
129 leaf_tree: (
130 Float[Array, '*batch_shape max_num_leaves']
131 | Float[Array, '*batch_shape k max_num_leaves']
132 )
133 """The values in the leaves of the trees. This array can be dirty, i.e.,
134 elements not in use can have whatever value. It may have an additional
135 axis for multivariate leaves."""
137 leaf_unit: Float32[Array, ''] | Float32[Array, ' k'] = field(
138 default_factory=lambda: jnp.float32(1.0)
139 )
140 offset: Float32[Array, ''] | Float32[Array, ' k'] = field(
141 default_factory=lambda: jnp.float32(0.0)
142 )
144 def axes_from_dataclass(self, obj: TreeHeaps) -> 'TreesTrace':
145 """Project the per-field vmap axis specs of `obj` onto this template.
147 `self` supplies the (array) pytree; the same-named fields of `obj`
148 (axis specs, i.e. ints or `None`) replace its leaves. Built with
149 `equinox.tree_at`, which bypasses the type-checked `__init__`, so the
150 deliberately off-type axis values are allowed.
151 """
152 names = [f.name for f in fields(type(self))]
153 return tree_at(
154 lambda t: [getattr(t, name) for name in names],
155 self,
156 [getattr(obj, name) for name in names],
157 )
160def node_to_leaf_index(node: Integer[Array, '*shape']) -> Integer[Array, '*shape']:
161 """
162 Return the index in `TreeHeaps.leaf_tree` of the value of a node.
164 Parameters
165 ----------
166 node
167 The index of the node in the heap, not 0.
169 Returns
170 -------
171 The index, which is `node` shifted right until its lowest set bit is dropped.
172 """
173 num_trailing_zeros = lax.population_count(~node & (node - 1))
174 return node >> num_trailing_zeros >> 1
177def is_leaf_used(
178 split_tree: UInt[Array, '*batch_shape max_num_leaves'],
179) -> Bool[Array, '*batch_shape max_num_leaves']:
180 """
181 Return a mask indicating the elements of `TreeHeaps.leaf_tree` in use.
183 Parameters
184 ----------
185 split_tree
186 The decision boundaries of the trees.
188 Returns
189 -------
190 The mask marking the elements that hold the value of a leaf.
191 """
192 # element i is for the leaf reached going left from the right child of
193 # node i, or from the root
194 *_, max_num_leaves = split_tree.shape
195 return split_tree.astype(bool) | (jnp.arange(max_num_leaves) == 0)
198def tree_depth(tree: Shaped[Array, '*batch_shape max_num_leaves']) -> int:
199 """
200 Return the maximum depth of a tree.
202 Parameters
203 ----------
204 tree
205 A tree array like those in a `TreeHeaps`. If the array is ND, the tree
206 structure is assumed to be along the last axis.
208 Returns
209 -------
210 The maximum depth of the tree.
211 """
212 return round(math.log2(tree.shape[-1]))
215def traverse_tree(
216 x: UInt[Array, ' p'],
217 var_tree: UInt[Array, ' max_num_leaves'],
218 split_tree: UInt[Array, ' max_num_leaves'],
219 *,
220 index_type: Literal['heap', 'chain'],
221) -> UInt[Array, '']:
222 """
223 Find the leaf where a point falls into.
225 Parameters
226 ----------
227 x
228 The coordinates to evaluate the tree at.
229 var_tree
230 The decision axes of the tree.
231 split_tree
232 The decision boundaries of the tree.
233 index_type
234 The convention of the returned index: 'heap' for the index of the leaf
235 node in the heap, 'chain' for the index of its value in
236 `TreeHeaps.leaf_tree`, see `node_to_leaf_index`.
238 Returns
239 -------
240 The index of the leaf, in the smallest unsigned integer type that fits it.
241 """
242 leaf_found = jnp.zeros((), bool)
243 index = jnp.ones((), minimal_unsigned_dtype(2 * var_tree.size - 1))
245 # the depth is a small static integer, so a plain python loop is equivalent
246 # to (and clearer than) a fully-unrolled lax.scan
247 for _ in range(tree_depth(var_tree)):
248 split = split_tree[index]
249 var = var_tree[index]
251 leaf_found |= split == 0
252 child_index = (index << 1) + (x[var] >= split)
253 index = jnp.where(leaf_found, index, child_index)
255 if index_type == 'heap':
256 return index
257 else:
258 assert index_type == 'chain'
259 dtype = minimal_unsigned_dtype(var_tree.size - 1)
260 return node_to_leaf_index(index).astype(dtype)
263@jit(static_argnames=('index_type',))
264def traverse_forest(
265 X: UInt[Array, 'p n'],
266 var_trees: UInt[Array, '*forest_shape max_num_leaves'],
267 split_trees: UInt[Array, '*forest_shape max_num_leaves'],
268 *,
269 index_type: Literal['heap', 'chain'],
270) -> UInt[Array, '*forest_shape n']:
271 """
272 Find the leaves where points falls into for each tree in a set.
274 Parameters
275 ----------
276 X
277 The coordinates to evaluate the trees at.
278 var_trees
279 The decision axes of the trees.
280 split_trees
281 The decision boundaries of the trees.
282 index_type
283 The convention of the returned index: 'heap' for the index of the leaf
284 node in the heap, 'chain' for the index of its value in
285 `TreeHeaps.leaf_tree`, see `node_to_leaf_index`.
287 Returns
288 -------
289 The indices of the leaves, in the smallest unsigned integer type that fits them.
290 """
291 traverse = partial(traverse_tree, index_type=index_type)
292 traverse = vmap(traverse, in_axes=(1, None, None))
293 traverse = jnp.vectorize(traverse, excluded=(0,), signature='(mnl),(mnl)->(n)')
294 return traverse(X, var_trees, split_trees)
297@jit(static_argnames=('sum_batch_axis',))
298def evaluate_forest(
299 X: UInt[Array, 'p n'],
300 trees: TreeHeaps,
301 *,
302 sum_batch_axis: int | tuple[int, ...] = (),
303) -> (
304 Float32[Array, '*reduced_batch_size n'] | Float32[Array, '*reduced_batch_size k n']
305):
306 """
307 Evaluate an ensemble of trees at an array of points.
309 Parameters
310 ----------
311 X
312 The coordinates to evaluate the trees at.
313 trees
314 The trees.
315 sum_batch_axis
316 The batch axes to sum over. By default, no summation is performed.
317 Note that negative indices count from the end of the batch dimensions,
318 the core dimensions n and k can't be summed over by this function.
320 Returns
321 -------
322 The (sum of) the values of the trees at the points in `X`, in float32.
324 Notes
325 -----
326 The leaf values are multiplied by ``trees.leaf_unit``, so the result is in
327 data units. ``trees.offset`` is not added: it does not distribute over the
328 per-tree sum, so the caller adds it once to the total.
329 """
330 indices: UInt[Array, '*forest_shape n']
331 indices = traverse_forest(X, trees.var_tree, trees.split_tree, index_type='chain')
333 # make xla finish the indices before it reads the leaves: left free, it
334 # merges the traversal into the kernel that reads them, which is slower,
335 # in particular with vector leaves
336 indices = lax.optimization_barrier(indices)
338 is_mv = is_multivariate(trees)
340 bc_indices: UInt[Array, '*forest_shape n 1'] | UInt[Array, '*forest_shape 1 n 1']
341 bc_indices = indices[..., None, :, None] if is_mv else indices[..., None]
343 bc_leaf_tree: (
344 Float[Array, '*forest_shape 1 max_num_leaves']
345 | Float[Array, '*forest_shape k 1 max_num_leaves']
346 )
347 bc_leaf_tree = (
348 trees.leaf_tree[..., :, None, :] if is_mv else trees.leaf_tree[..., None, :]
349 )
351 bc_leaves: Float[Array, '*forest_shape n 1'] | Float[Array, '*forest_shape k n 1']
352 bc_leaves = jnp.take_along_axis(bc_leaf_tree, bc_indices, -1)
354 leaves: Float[Array, '*forest_shape n'] | Float[Array, '*forest_shape k n']
355 leaves = jnp.squeeze(bc_leaves, -1)
357 # sum in the storage dtype with a float32 accumulator, then convert to
358 # data units with the float32 scale
359 axis = normalize_axis_tuple(sum_batch_axis, trees.var_tree.ndim - 1)
360 return trees.leaf_unit[..., None] * jnp.sum(leaves, axis=axis, dtype=jnp.float32)
363def is_actual_leaf(
364 split_tree: UInt[Array, ' max_num_leaves'], *, add_bottom_level: bool = False
365) -> Bool[Array, ' max_num_leaves'] | Bool[Array, ' 2*max_num_leaves']:
366 """
367 Return a mask indicating the leaf nodes in a tree.
369 Parameters
370 ----------
371 split_tree
372 The splitting points of the tree.
373 add_bottom_level
374 If True, the bottom level of the tree is also considered.
376 Returns
377 -------
378 The mask marking the leaf nodes. Length doubled if `add_bottom_level` is True.
379 """
380 size = split_tree.size
381 is_leaf = split_tree == 0
382 if add_bottom_level:
383 size *= 2
384 is_leaf = jnp.concatenate([is_leaf, jnp.ones_like(is_leaf)])
385 index = minimal_unsigned_arange(size)
386 parent_index = index >> 1
387 parent_nonleaf = split_tree[parent_index].astype(bool)
388 parent_nonleaf = parent_nonleaf.at[1].set(True)
389 return is_leaf & parent_nonleaf
392def is_leaves_parent(
393 split_tree: UInt[Array, ' max_num_leaves'],
394) -> Bool[Array, ' max_num_leaves']:
395 """
396 Return a mask indicating the nodes with leaf (and only leaf) children.
398 Parameters
399 ----------
400 split_tree
401 The decision boundaries of the tree.
403 Returns
404 -------
405 The mask indicating which nodes have leaf children.
406 """
407 index = jnp.arange(
408 split_tree.size, dtype=minimal_unsigned_dtype(2 * split_tree.size - 1)
409 )
410 left_index = index << 1 # left child
411 right_index = left_index + 1 # right child
412 left_leaf = split_tree.at[left_index].get(mode='fill', fill_value=0) == 0
413 right_leaf = split_tree.at[right_index].get(mode='fill', fill_value=0) == 0
414 is_not_leaf = split_tree.astype(bool)
415 return is_not_leaf & left_leaf & right_leaf
416 # the 0-th item has split == 0, so it's not counted
419def tree_depths(heap_size: int) -> UInt[Array, ' {heap_size}']:
420 """
421 Return the depth of each node in a binary tree.
423 Parameters
424 ----------
425 heap_size
426 The length of the heap array.
428 Returns
429 -------
430 The depth of each node.
432 Notes
433 -----
434 The root node (index 1) has depth 0. The depth is the position of the most
435 significant non-zero bit in the index. The first element (the unused node)
436 is marked as depth 0.
437 """
438 depths = []
439 depth = 0
440 for i in range(heap_size):
441 if i == 2**depth:
442 depth += 1
443 depths.append(depth - 1)
444 depths[0] = 0
445 return jnp.array(depths, minimal_unsigned_dtype(max(depths)))
448@jit
449def forest_mean_leaves(
450 split_tree: UInt[Array, '*batch_shape max_num_leaves'],
451 *,
452 where: Bool[Array, '*batch_shape'] | None = None,
453) -> Float32[Array, '']:
454 """
455 Return the average number of leaves per tree in a set of trees.
457 Parameters
458 ----------
459 split_tree
460 The decision boundaries of the trees.
461 where
462 Which trees to average over, all if `None`.
464 Returns
465 -------
466 The mean number of leaves across the trees, NaN if there are no trees.
467 """
468 # a tree with k internal nodes (the nonzero entries of split_tree) has k + 1
469 # leaves; the maximum possible is split_tree.shape[-1]
470 num_internal = jnp.count_nonzero(split_tree, axis=-1)
471 return jnp.mean(num_internal + 1, where=where)
474@jit(static_argnames=('p', 'sum_batch_axis'))
475def var_histogram(
476 p: int,
477 var_tree: UInt[Array, '*batch_shape max_num_leaves'],
478 split_tree: UInt[Array, '*batch_shape max_num_leaves'],
479 *,
480 sum_batch_axis: int | tuple[int, ...] = (),
481) -> Int32[Array, '*reduced_batch_shape {p}']:
482 """
483 Count how many times each variable appears in a tree.
485 Parameters
486 ----------
487 p
488 The number of variables (the maximum value that can occur in `var_tree`
489 is ``p - 1``).
490 var_tree
491 The decision axes of the tree.
492 split_tree
493 The decision boundaries of the tree.
494 sum_batch_axis
495 The batch axes to sum over. By default, no summation is performed. Note
496 that negative indices count from the end of the batch dimensions, the
497 core dimension p can't be summed over by this function.
499 Returns
500 -------
501 The histogram(s) of the variables used in the tree.
502 """
503 is_internal = split_tree.astype(bool)
505 def scatter_add(
506 var_tree: UInt[Array, '*summed_batch_axes max_num_leaves'],
507 is_internal: Bool[Array, '*summed_batch_axes max_num_leaves'],
508 ) -> Int32[Array, ' p']:
509 return jnp.zeros(p, int).at[var_tree].add(is_internal)
511 # vmap scatter_add over non-batched dims
512 batch_ndim = var_tree.ndim - 1
513 axes = normalize_axis_tuple(sum_batch_axis, batch_ndim)
514 for i in reversed(range(batch_ndim)):
515 neg_i = i - var_tree.ndim
516 if i not in axes:
517 scatter_add = vmap(scatter_add, in_axes=neg_i)
519 return scatter_add(var_tree, is_internal)
522def _format_values(values: Float[Array, ''] | Float[Array, ' k']) -> str:
523 """Format a scalar or vector to the decimal precision of its dtype."""
524 ndigits = jnp.finfo(values.dtype).precision
525 if values.ndim:
526 return '[' + ', '.join(f'{v:#.{ndigits}g}' for v in values) + ']'
527 else:
528 return f'{values:#.{ndigits}g}'
531def chain_index(index: int) -> int:
532 """Do `node_to_leaf_index` on a python integer."""
533 lowest_set_bit = index & -index
534 return index // lowest_set_bit >> 1
537def _format_leaf(tree: TreeHeaps, index: int) -> str:
538 """Format the leaf value of the node at `index` as ``<scale> * <leaf>``."""
539 unit = _format_values(tree.leaf_unit)
540 leaf = _format_values(tree.leaf_tree[..., chain_index(index)])
541 return f'{unit} * {leaf}'
544def format_node_contents(
545 tree: TreeHeaps, index: int, var: int, split: int, *, unused: bool
546) -> str:
547 """Format what the arrays hold for a node, in use or not."""
548 if unused:
549 category = 'unused'
550 elif split:
551 category = 'decision'
552 else:
553 category = 'leaf'
554 # the node is the first of its element of `leaf_tree` if it is the root, a
555 # right child, or below a decision node
556 if not split and (index % 2 or not unused):
557 return f'{category}({var}, {split}, {_format_leaf(tree, index)})'
558 else:
559 return f'{category}({var}, {split})'
562def format_tree(tree: TreeHeaps, *, print_all: bool = False) -> str:
563 """Convert a tree to a human-readable string.
565 Parameters
566 ----------
567 tree
568 A single tree to format.
569 print_all
570 If `True`, also print the contents of unused node slots in the arrays.
571 An element of `leaf_tree` is printed at the first node of its own that
572 is not a decision node.
574 Returns
575 -------
576 A string representation of the tree.
578 Notes
579 -----
580 Each line starts with the index of the node in the heap, followed by the
581 index of its value in `TreeHeaps.leaf_tree`, see `node_to_leaf_index`.
582 """
583 tee = '├──'
584 corner = '└──'
585 join = '│ '
586 space = ' '
587 down = '┐'
588 bottom = '╢' # '┨' #
590 *_, max_num_leaves = tree.split_tree.shape
591 heap_size = 2 * max_num_leaves
593 def traverse_tree(
594 lines: list[str],
595 index: int,
596 indent: str,
597 first_indent: str,
598 next_indent: str,
599 *,
600 unused: bool,
601 ) -> None:
602 if index >= heap_size:
603 return
605 var: int = tree.var_tree.at[index].get(mode='fill', fill_value=0).item()
606 split: int = tree.split_tree.at[index].get(mode='fill', fill_value=0).item()
608 is_leaf = split == 0
609 left_child = 2 * index
610 right_child = 2 * index + 1
612 if print_all:
613 node_str = format_node_contents(tree, index, var, split, unused=unused)
614 else:
615 assert not unused
616 if is_leaf:
617 node_str = _format_leaf(tree, index)
618 else:
619 node_str = f'x{var} < {split}'
621 if not is_leaf or (print_all and left_child < heap_size):
622 link = down
623 elif not print_all and left_child >= heap_size:
624 link = bottom
625 else:
626 link = ' '
628 heap = str(index).rjust(len(str(heap_size - 1)))
629 chain = str(chain_index(index)).rjust(len(str(max_num_leaves - 1)))
631 lines.append(f' {heap} {chain} {indent}{first_indent}{link}{node_str}')
633 indent += next_indent
634 unused = unused or is_leaf
636 if unused and not print_all:
637 return
639 traverse_tree(lines, left_child, indent, tee, join, unused=unused)
640 traverse_tree(lines, right_child, indent, corner, space, unused=unused)
642 lines = []
643 traverse_tree(lines, 1, '', '', '', unused=False)
644 return '\n'.join(lines)
647def tree_actual_depth(split_tree: UInt[Array, ' max_num_leaves']) -> UInt[Array, '']:
648 """Measure the depth of the tree.
650 Parameters
651 ----------
652 split_tree
653 The cutpoints of the decision rules.
655 Returns
656 -------
657 The depth of the deepest leaf in the tree. The root is at depth 0.
658 """
659 # this could be done just with split_tree != 0
660 is_leaf = is_actual_leaf(split_tree, add_bottom_level=True)
661 depth = tree_depths(is_leaf.size)
662 depth = jnp.where(is_leaf, depth, 0)
663 return jnp.max(depth)
666@jit
667@partial(jnp.vectorize, signature='(nt,mnl)->(d_plus_1)')
668def forest_depth_distr(
669 split_tree: UInt[Array, '*batch_shape num_trees max_num_leaves'],
670) -> Int32[Array, '*batch_shape d_plus_1']:
671 """Histogram the depths of a set of trees.
673 Parameters
674 ----------
675 split_tree
676 The cutpoints of the decision rules of the trees.
678 Returns
679 -------
680 An integer vector where the i-th element counts how many trees have depth i.
681 """
682 depth = tree_depth(split_tree) + 1
683 depths = vmap(tree_actual_depth)(split_tree)
684 return jnp.bincount(depths, length=depth)
687@jit(static_argnames=('node_type', 'sum_batch_axis'))
688def points_per_node_distr(
689 X: UInt[Array, 'p n'],
690 var_tree: UInt[Array, '*batch_shape max_num_leaves'],
691 split_tree: UInt[Array, '*batch_shape max_num_leaves'],
692 node_type: Literal['leaf', 'leaf-parent'],
693 *,
694 sum_batch_axis: int | tuple[int, ...] = (),
695) -> Int32[Array, '*reduced_batch_shape n+1']:
696 """Histogram points-per-node counts in a set of trees.
698 Count how many nodes in a tree select each possible amount of points,
699 over a certain subset of nodes.
701 Parameters
702 ----------
703 X
704 The set of points to count.
705 var_tree
706 The variables of the decision rules.
707 split_tree
708 The cutpoints of the decision rules.
709 node_type
710 The type of nodes to consider. Can be:
712 'leaf'
713 Count only leaf nodes.
714 'leaf-parent'
715 Count only parent-of-leaf nodes.
716 sum_batch_axis
717 Aggregate the histogram over these batch axes, counting how many nodes
718 have each possible amount of points over subsets of trees instead of
719 in each tree separately.
721 Returns
722 -------
723 A vector where the i-th element counts how many nodes have i points.
724 """
725 batch_ndim = var_tree.ndim - 1
726 axes = normalize_axis_tuple(sum_batch_axis, batch_ndim)
728 def func(
729 var_tree: UInt[Array, '*batch_shape max_num_leaves'],
730 split_tree: UInt[Array, '*batch_shape max_num_leaves'],
731 ) -> Int32[Array, '*reduced_batch_shape n_plus_1']:
732 indices: UInt[Array, '*batch_shape n']
733 indices = traverse_forest(X, var_tree, split_tree, index_type='heap')
735 @partial(jnp.vectorize, signature='(mnl),(n)->(heap),(heap)')
736 def count_points(
737 split_tree: UInt[Array, '*batch_shape max_num_leaves'],
738 indices: UInt[Array, '*batch_shape n'],
739 ) -> (
740 tuple[
741 Int32[Array, '*batch_shape 2*max_num_leaves'],
742 Bool[Array, '*batch_shape 2*max_num_leaves'],
743 ]
744 | tuple[
745 Int32[Array, '*batch_shape max_num_leaves'],
746 Bool[Array, '*batch_shape max_num_leaves'],
747 ]
748 ):
749 if node_type == 'leaf-parent':
750 indices >>= 1
751 predicate = is_leaves_parent(split_tree)
752 elif node_type == 'leaf': 752 ↛ 755line 752 didn't jump to line 755 because the condition on line 752 was always true
753 predicate = is_actual_leaf(split_tree, add_bottom_level=True)
754 else:
755 raise ValueError(node_type)
756 count_tree = jnp.zeros(predicate.size, int).at[indices].add(1).at[0].set(0)
757 return count_tree, predicate
759 count_tree, predicate = count_points(split_tree, indices)
761 def count_nodes(
762 count_tree: Int32[Array, '*summed_batch_axes max_num_leaves'],
763 predicate: Bool[Array, '*summed_batch_axes max_num_leaves'],
764 ) -> Int32[Array, ' n_plus_1']:
765 return jnp.zeros(X.shape[1] + 1, int).at[count_tree].add(predicate)
767 # vmap count_nodes over non-batched dims
768 for i in reversed(range(batch_ndim)):
769 neg_i = i - var_tree.ndim
770 if i not in axes:
771 count_nodes = vmap(count_nodes, in_axes=neg_i)
773 return count_nodes(count_tree, predicate)
775 # automatically batch over all batch dimensions
776 max_io_nbytes = 2**27 # 128 MiB
777 out_dim_shift = len(axes)
778 batched_func = func
779 for i in reversed(range(batch_ndim)):
780 if i in axes:
781 out_dim_shift -= 1
782 else:
783 batched_func = autobatch(batched_func, max_io_nbytes, i, i - out_dim_shift)
784 assert out_dim_shift == 0
786 return batched_func(var_tree, split_tree)