Coverage for src/bartz/prepcovars/_prepcovars.py: 93%
170 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/prepcovars/_prepcovars.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"""Implementation of the predictor preprocessing utilities."""
27from abc import abstractmethod
28from functools import partial
29from typing import Any, Protocol, runtime_checkable
31from equinox import AbstractVar, Module, field
32from jax import numpy as jnp
33from jax import random, vmap
34from jax.typing import DTypeLike
35from jaxtyping import Array, Float, Float32, Integer, Key, Real, Shaped, UInt
37from bartz._jaxext import autobatch, jit, minimal_unsigned_dtype, unique
38from bartz.npz import serializable
41def _parse_xinfo(
42 xinfo: Float[Array, 'p m'],
43) -> tuple[Float[Array, 'p m'], UInt[Array, ' p']]:
44 """Parse pre-defined splits in the format of the R package BART.
46 Parameters
47 ----------
48 xinfo
49 A matrix with the cutpoins to use to bin each predictor. Each row shall
50 contain a sorted list of cutpoints for a predictor. If there are less
51 cutpoints than the number of columns in the matrix, fill the remaining
52 cells with NaN.
54 `xinfo` shall be a matrix even if `x_train` is a dataframe.
56 Returns
57 -------
58 splits : Float[Array, 'p m']
59 `xinfo` modified by replacing nan with a large value.
60 max_split : UInt[Array, 'p']
61 The number of non-nan elements in each row of `xinfo`.
62 """
63 is_not_nan = ~jnp.isnan(xinfo)
64 max_split = jnp.sum(is_not_nan, axis=1)
65 max_split = max_split.astype(minimal_unsigned_dtype(xinfo.shape[1]))
66 huge = _huge_value(xinfo)
67 splits = jnp.where(is_not_nan, xinfo, huge)
68 return splits, max_split
71@jit(static_argnums=(2,))
72def _subsample(
73 key: Key[Array, ''], X: Real[Array, 'p n'], max_samples: int
74) -> Real[Array, 'p m']:
75 """Randomly thin each predictor row to at most `max_samples` elements.
77 Parameters
78 ----------
79 key
80 A jax random key.
81 X
82 A matrix with `p` predictors and `n` observations.
83 max_samples
84 The target maximum number of samples per row.
86 Returns
87 -------
88 A matrix with `p` rows and ``min(n, max_samples)`` columns. If ``n <= max_samples``, `X` is returned unchanged. Otherwise each row contains `max_samples` values drawn with replacement from the corresponding row of `X`, with rows sampled independently.
90 Raises
91 ------
92 ValueError
93 If `max_samples` is less than 1.
94 """
95 if max_samples < 1:
96 msg = f'{max_samples=}, must be at least 1.'
97 raise ValueError(msg)
99 p, n = X.shape
100 if n <= max_samples:
101 return X
103 keys = random.split(key, p)
105 @partial(autobatch, max_io_nbytes=2**29)
106 @vmap
107 def per_row(k: Key[Array, ''], x: Real[Array, ' n']) -> Real[Array, ' m']:
108 return x[random.randint(k, (max_samples,), 0, n)]
110 return per_row(keys, X)
113@jit(static_argnums=(1,))
114def _quantilized_splits_from_matrix(
115 X: Real[Array, 'p n'], max_bins: int
116) -> tuple[Real[Array, 'p m'], UInt[Array, ' p']]:
117 """
118 Determine bins that make the distribution of each predictor uniform.
120 Parameters
121 ----------
122 X
123 A matrix with `p` predictors and `n` observations.
124 max_bins
125 The maximum number of bins to produce.
127 Returns
128 -------
129 splits : Real[Array, 'p m']
130 A matrix containing, for each predictor, the boundaries between bins.
131 `m` is ``min(max_bins, n) - 1``, which is an upper bound on the number
132 of splits. Each predictor may have a different number of splits; unused
133 values at the end of each row are filled with the maximum value
134 representable in the type of `X`.
135 max_split : UInt[Array, ' p']
136 The number of actually used values in each row of `splits`.
138 Raises
139 ------
140 ValueError
141 If `X` has no columns or if `max_bins` is less than 1.
142 """
143 out_length = min(max_bins, X.shape[1]) - 1
145 if out_length < 0:
146 msg = f'{X.shape[1]=} and {max_bins=}, they should be both at least 1.'
147 raise ValueError(msg)
149 @partial(autobatch, max_io_nbytes=2**29)
150 def quantilize(
151 X: Real[Array, 'p n'],
152 ) -> tuple[Real[Array, 'p m'], UInt[Array, ' p']]:
153 # wrap this function because autobatch needs traceable args
154 return _quantilized_splits_from_vector(X, out_length)
156 return quantilize(X)
159@partial(vmap, in_axes=(0, None))
160def _quantilized_splits_from_vector(
161 x: Real[Array, ' n'], out_length: int
162) -> tuple[Real[Array, ' m'], UInt[Array, '']]:
163 # find the sorted unique values in x
164 huge = _huge_value(x)
165 u, actual_length = unique(x, size=x.size, fill_value=huge)
167 # compute the midpoints between each unique value
168 if jnp.issubdtype(x.dtype, jnp.integer):
169 midpoints = u[:-1] + _ensure_unsigned(u[1:] - u[:-1]) // 2
170 else:
171 midpoints = u[:-1] + (u[1:] - u[:-1]) / 2
172 # using x_i + (x_i+1 - x_i) / 2 instead of (x_i + x_i+1) / 2 is to
173 # avoid overflow
174 actual_length -= 1
175 if midpoints.size:
176 midpoints = midpoints.at[actual_length].set(huge)
178 # take a subset of the midpoints if there are more than the requested maximum
179 indices = jnp.linspace(-1, actual_length, out_length + 2)[1:-1]
180 indices = jnp.around(indices).astype(minimal_unsigned_dtype(midpoints.size - 1))
181 # indices calculation with float rather than int to avoid potential
182 # overflow with int32, and to round to nearest instead of rounding down
183 decimated_midpoints = midpoints[indices]
184 truncated_midpoints = midpoints[:out_length]
185 splits = jnp.where(
186 actual_length > out_length, decimated_midpoints, truncated_midpoints
187 )
188 max_split = jnp.minimum(actual_length, out_length)
189 max_split = max_split.astype(minimal_unsigned_dtype(out_length))
190 return splits, max_split
193def _huge_value(x: Shaped[Array, '...']) -> int | float:
194 """
195 Return the maximum value that can be stored in `x`.
197 Parameters
198 ----------
199 x
200 A numerical numpy or jax array.
202 Returns
203 -------
204 The maximum value allowed by `x`'s type (finite for floats).
205 """
206 if jnp.issubdtype(x.dtype, jnp.integer):
207 return jnp.iinfo(x.dtype).max
208 else:
209 return float(jnp.finfo(x.dtype).max)
212def _ensure_unsigned(x: Integer[Array, '*shape']) -> UInt[Array, '*shape']:
213 """If x has signed integer type, cast it to the unsigned dtype of the same size."""
214 return x.astype(_signed_to_unsigned(x.dtype))
217def _signed_to_unsigned(int_dtype: DTypeLike) -> DTypeLike:
218 """
219 Map a signed integer type to its unsigned counterpart.
221 Unsigned types are passed through.
222 """
223 assert jnp.issubdtype(int_dtype, jnp.integer)
224 if jnp.issubdtype(int_dtype, jnp.unsignedinteger): 224 ↛ 225line 224 didn't jump to line 225 because the condition on line 224 was never true
225 return int_dtype
226 match int_dtype:
227 case jnp.int8: 227 ↛ 228line 227 didn't jump to line 228 because the pattern on line 227 never matched
228 return jnp.uint8
229 case jnp.int16: 229 ↛ 230line 229 didn't jump to line 230 because the pattern on line 229 never matched
230 return jnp.uint16
231 case jnp.int32: 231 ↛ 233line 231 didn't jump to line 233 because the pattern on line 231 always matched
232 return jnp.uint32
233 case jnp.int64:
234 return jnp.uint64
235 case _:
236 msg = f'unexpected integer type {int_dtype}'
237 raise TypeError(msg)
240@jit(static_argnums=(1,))
241def _uniform_splits_from_matrix(
242 X: Real[Array, 'p n'], num_bins: int
243) -> tuple[Real[Array, 'p m'], UInt[Array, ' p']]:
244 """
245 Make an evenly spaced binning grid.
247 Parameters
248 ----------
249 X
250 A matrix with `p` predictors and `n` observations.
251 num_bins
252 The number of bins to produce.
254 Returns
255 -------
256 splits : Real[Array, 'p m']
257 A matrix containing, for each predictor, the boundaries between bins.
258 The excluded endpoints are the minimum and maximum value in each row of
259 `X`.
260 max_split : UInt[Array, ' p']
261 The number of cutpoints in each row of `splits`, see `_uniform_max_split`.
262 """
263 low = jnp.min(X, axis=1)
264 high = jnp.max(X, axis=1)
265 splits = _uniform_splits_from_range(low, high, num_bins)
266 assert splits.shape == (X.shape[0], num_bins - 1)
267 return splits, _uniform_max_split(low, high, num_bins)
270def _uniform_max_split(
271 low: Real[Array, ' p'], high: Real[Array, ' p'], num_bins: int
272) -> UInt[Array, ' p']:
273 """Return ``num_bins - 1``, or 0 for constant predictors (``low == high``)."""
274 max_split = jnp.where(low < high, num_bins - 1, 0)
275 return max_split.astype(minimal_unsigned_dtype(num_bins - 1))
278@jit(static_argnums=(2,))
279def _uniform_splits_from_range(
280 low: Real[Array, ' p'], high: Real[Array, ' p'], num_bins: int
281) -> Real[Array, 'p m']:
282 """
283 Make an evenly spaced binning grid from per-predictor ranges.
285 Parameters
286 ----------
287 low
288 The lower endpoint of the grid for each predictor.
289 high
290 The upper endpoint of the grid for each predictor.
291 num_bins
292 The number of bins to produce.
294 Returns
295 -------
296 A `(p, num_bins - 1)` matrix of cutpoints, with `low` and `high` excluded. Rows of constant predictors are filled with the maximum value of the dtype.
297 """
298 splits = jnp.linspace(low, high, num_bins + 1, axis=1)[:, 1:-1]
299 splits = jnp.where((low < high)[:, None], splits, _huge_value(splits))
300 (p,) = low.shape
301 assert splits.shape == (p, num_bins - 1)
302 return splits
305@jit(static_argnums=(3,))
306def _bin_predictors_uniform(
307 X: Real[Array, 'p n'],
308 low: Real[Array, ' p'],
309 high: Real[Array, ' p'],
310 num_bins: int,
311) -> UInt[Array, 'p n']:
312 """
313 Bin predictors onto an evenly spaced grid without materializing the cutpoints.
315 This is the arithmetic equivalent of binning with the splits from
316 `_uniform_splits_from_range`: cutpoint ``j`` is ``low + (j + 1) * step``
317 with ``step = (high - low) / num_bins``, and ``x`` falls in bin ``i`` iff
318 ``cutpoint[i - 1] < x <= cutpoint[i]``.
320 Parameters
321 ----------
322 X
323 A matrix with `p` predictors and `n` observations.
324 low
325 The minimum value of each predictor's grid.
326 high
327 The maximum value of each predictor's grid.
328 num_bins
329 The number of bins per predictor.
331 Returns
332 -------
333 `X` with each value replaced by the index of the bin it falls into.
334 """
335 step = (high - low) / num_bins
336 safe_step = jnp.where(step > 0, step, 1)
337 # bin = #{cutpoints < x}; right-closed bins make this ceil(t) - 1 (= floor(t)
338 # away from cutpoints), matching `searchsorted(..., side='left')`
339 t = (X - low[:, None]) / safe_step[:, None]
340 bins = jnp.ceil(t) - 1
341 # constant predictors (step == 0) have no cutpoints
342 bins = jnp.where(step[:, None] > 0, bins, 0)
343 bins = jnp.clip(bins, 0, num_bins - 1)
344 return bins.astype(minimal_unsigned_dtype(num_bins - 1))
347@jit(static_argnames=('method',))
348def _bin_predictors(
349 X: Real[Array, 'p n'], splits: Real[Array, 'p m'], **kw: Any
350) -> UInt[Array, 'p n']:
351 """
352 Bin the predictors according to the given splits.
354 A value ``x`` is mapped to bin ``i`` iff ``splits[i - 1] < x <= splits[i]``.
356 Parameters
357 ----------
358 X
359 A matrix with `p` predictors and `n` observations.
360 splits
361 A matrix containing, for each predictor, the boundaries between bins.
362 `m` is the maximum number of splits; each row may have shorter
363 actual length, marked by padding unused locations at the end of the
364 row with the maximum value allowed by the type.
365 **kw
366 Additional arguments are passed to `jax.numpy.searchsorted`.
368 Returns
369 -------
370 `X` but with each value replaced by the index of the bin it falls into.
371 """
373 @partial(autobatch, max_io_nbytes=2**29)
374 @vmap
375 def bin_predictors(
376 x: Real[Array, ' n'], splits: Real[Array, ' m']
377 ) -> UInt[Array, ' n']:
378 dtype = minimal_unsigned_dtype(splits.size)
379 return jnp.searchsorted(splits, x, **kw).astype(dtype)
381 return bin_predictors(X, splits)
384class Binner(Module):
385 """Abstract base class for predictor binners.
387 A binner inspects the training predictors at construction time,
388 chooses cutpoints for each predictor, and encapsulates the logic
389 that maps any predictor matrix (training or test) to bin indices via
390 `bin`.
392 A predictor value ``x`` is mapped to bin ``i`` iff
393 ``c[i - 1] < x <= c[i]``, where ``c`` are the cutpoints chosen for
394 that predictor at construction. A predictor with ``k`` cutpoints
395 therefore has ``k + 1`` bins indexed from ``0`` to ``k``. The number
396 of cutpoints actually used per predictor is exposed as `max_split`
397 and may differ across predictors; the remaining capacity, if any, is
398 padded internally with the maximum value representable in the dtype
399 of the cutpoints, so binning still produces a valid in-range index.
401 The constructor takes the training predictors and an optional random
402 key. Concrete subclasses may add their own keyword arguments. Binners
403 that do not use the key still accept it for protocol uniformity and
404 silently ignore it. Binners that need it raise `ValueError` if it is
405 not provided.
406 """
408 max_split: AbstractVar[UInt[Array, ' p']]
409 """The number of cutpoints actually used for each of the `p` predictors."""
411 _splits: AbstractVar[Real[Array, 'p m']]
412 """The cutpoints for each of the `p` predictors, padded to a common length."""
414 @abstractmethod
415 def __init__(
416 self, X: Real[Array, 'p n'], *, key: Key[Array, ''] | None = None
417 ) -> None: ...
419 @abstractmethod
420 def bin(self, X: Real[Array, 'p n']) -> UInt[Array, 'p n']:
421 """Map predictors to bin indices using the cutpoints chosen at construction.
423 Parameters
424 ----------
425 X
426 A matrix with `p` predictors and `n` observations. Must have
427 the same number of predictors as the training matrix passed
428 to the constructor.
430 Returns
431 -------
432 Quantized `X` with minimal data type.
433 """
434 ...
437@runtime_checkable
438class BinnerFactory(Protocol):
439 """Callable that constructs a `Binner` from training predictors.
441 This is the type of the `binner` argument of `bartz.Bart`. A bare
442 `Binner` subclass satisfies this protocol, as does
443 ``functools.partial(BinnerSubclass, **subclass_kwargs)``.
444 """
446 def __call__(
447 self, X: Real[Array, 'p n'], *, key: Key[Array, ''] | None = None
448 ) -> Binner:
449 """Construct a `Binner` from `X` and an optional random key."""
450 ...
453@serializable
454class RangeEvenBinner(Binner):
455 """Binner with cutpoints evenly spaced over the observed range.
457 For each predictor, ``max_bins - 1`` cutpoints are placed at
458 equally spaced positions strictly between the minimum and the
459 maximum value observed in the training matrix. Constant predictors
460 get no cutpoints.
462 Parameters
463 ----------
464 X
465 Training predictors with `p` predictors and `n` observations.
466 max_bins
467 The number of bins per predictor; ``max_bins - 1`` cutpoints
468 are produced per predictor.
469 key
470 Accepted for protocol uniformity; unused.
471 """
473 _low: Real[Array, ' p']
474 """Minimum observed value per predictor."""
476 _high: Real[Array, ' p']
477 """Maximum observed value per predictor."""
479 # WORKAROUND(jax<0.9.1): use `jax.tree.static` instead of `field(static=True)`
480 _max_bins: int = field(static=True)
481 """Number of bins per predictor."""
483 max_split: UInt[Array, ' p']
485 def __init__(
486 self,
487 X: Real[Array, 'p n'],
488 *,
489 max_bins: int = 256,
490 key: Key[Array, ''] | None = None,
491 ) -> None:
492 del key
493 self._low = jnp.min(X, axis=1)
494 self._high = jnp.max(X, axis=1)
495 self._max_bins = max_bins
496 self.max_split = _uniform_max_split(self._low, self._high, max_bins)
498 # `AbstractVar` admits a property implementation
499 @property
500 def _splits(self) -> Real[Array, 'p m']: # ty:ignore[invalid-property-type-override]
501 """Materialize the cutpoints. Intended for testing only, not library use.
503 The cutpoints are not stored: `bin` works arithmetically from the
504 observed range, since they are evenly spaced. This property reconstructs
505 them only to expose them; the library should rely on `bin` and
506 `max_split` instead.
507 """
508 return _uniform_splits_from_range(self._low, self._high, self._max_bins)
510 def bin(self, X: Real[Array, 'p n']) -> UInt[Array, 'p n']:
511 return _bin_predictors_uniform(X, self._low, self._high, self._max_bins)
514@serializable
515class UniqueQuantileBinner(Binner):
516 """Binner with quantile-based cutpoints from observed unique values.
518 For each predictor, cutpoints are placed between sorted unique
519 values so that the empirical distribution is approximately uniform
520 across bins. The number of cutpoints is at most ``max_bins - 1``
521 and at most one less than the number of unique values, so different
522 predictors may end up with different effective cutpoint counts.
523 Trailing unused entries of the cutpoint matrix are padded with the
524 maximum value representable in the dtype of `X`.
526 Note: the quantiles are over the *unique* values, not over the
527 original distribution.
529 When ``n > max_subsample``, the predictor matrix is randomly thinned
530 along the observation axis to ``max_subsample`` columns before
531 quantilization. Each predictor row is thinned independently and
532 with replacement, so between 63% and 100% of the sampled values are
533 distinct observations. This keeps quantilization tractable on very
534 large datasets at the cost of approximate quantiles.
536 Parameters
537 ----------
538 X
539 Training predictors with `p` predictors and `n` observations.
540 max_bins
541 The maximum number of bins per predictor.
542 max_subsample
543 The maximum number of observations to use when computing
544 quantiles. If `None`, no subsampling is performed. If `n`
545 exceeds this, `key` is required.
546 key
547 Random key for subsampling. Required when ``X.shape[1] >
548 max_subsample``; otherwise unused.
550 Raises
551 ------
552 ValueError
553 If subsampling would trigger but `key` is `None`.
554 """
556 _splits: Real[Array, 'p m']
557 """Cutpoints per predictor, padded on the right with the dtype's maximum value."""
559 max_split: UInt[Array, ' p']
561 def __init__(
562 self,
563 X: Real[Array, 'p n'],
564 *,
565 max_bins: int = 256,
566 max_subsample: int | None = 100_000,
567 key: Key[Array, ''] | None = None,
568 ) -> None:
569 if max_subsample is not None and X.shape[1] > max_subsample:
570 if key is None:
571 msg = (
572 'UniqueQuantileBinner requires a `key` because '
573 f'n={X.shape[1]} exceeds max_subsample={max_subsample}.'
574 )
575 raise ValueError(msg)
576 X = _subsample(key, X, max_subsample)
577 self._splits, self.max_split = _quantilized_splits_from_matrix(X, max_bins)
579 def bin(self, X: Real[Array, 'p n']) -> UInt[Array, 'p n']:
580 return _bin_predictors(X, self._splits)
583@serializable
584class GivenSplitsBinner(Binner):
585 """Binner with cutpoints supplied directly in R BART `xinfo` format.
587 The cutpoints are taken verbatim from `xinfo`: a `(p, m)` matrix
588 whose rows hold per-predictor sorted cutpoints, with NaN-padded
589 trailing entries marking unused capacity. Internally NaNs are
590 replaced by the maximum representable value in the dtype of
591 `xinfo`, and `max_split` is set to the count of non-NaN entries
592 per row, so binning behaves as if the row had been declared with
593 only its non-NaN cutpoints.
595 Parameters
596 ----------
597 X
598 Training predictors. Used only to validate the shape of `xinfo`.
599 xinfo
600 A `(p, m)` matrix of cutpoints. Each row holds a sorted list of
601 cutpoints for one predictor, optionally padded on the right with
602 NaN.
603 key
604 Accepted for protocol uniformity; unused.
606 Raises
607 ------
608 ValueError
609 If `xinfo` is not 2D, or if its first dimension does not match
610 ``X.shape[0]``.
611 """
613 _splits: Float[Array, 'p m']
614 """Cutpoints per predictor, with NaNs replaced by the dtype's maximum value."""
616 max_split: UInt[Array, ' p']
618 def __init__(
619 self,
620 X: Real[Array, 'p n'],
621 *,
622 xinfo: Float[Array, 'p m'],
623 key: Key[Array, ''] | None = None,
624 ) -> None:
625 del key
626 if xinfo.ndim != 2 or xinfo.shape[0] != X.shape[0]:
627 msg = f'{xinfo.shape=} different from expected ({X.shape[0]}, *)'
628 raise ValueError(msg)
629 self._splits, self.max_split = _parse_xinfo(xinfo)
631 def bin(self, X: Real[Array, 'p n']) -> UInt[Array, 'p n']:
632 return _bin_predictors(X, self._splits)
635@jit
636def _sigma2_from_ols(
637 x_train: Shaped[Array, 'p n'], y_train: Float32[Array, ' n'] | Float32[Array, 'k n']
638) -> Float32[Array, ''] | Float32[Array, ' k']:
639 """Return the error variance estimated with OLS with intercept."""
640 # centering is equivalent to adding an intercept column, and also keeps the
641 # rank detection relative to the spread of x instead of its mean
642 x_centered = x_train.T - x_train.mean(axis=1)
643 y_centered = y_train.T - y_train.mean(axis=-1)
644 _, chisq, rank, _ = jnp.linalg.lstsq(x_centered, y_centered)
645 # the rank of the centered x excludes the intercept, also if aliased in x
646 _, n = x_train.shape
647 return chisq.reshape(y_train.shape[:-1]) / (n - rank - 1)