Coverage for src/bartz/stochtree/_preprocess.py: 96%
140 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/stochtree/_preprocess.py
2#
3# Copyright (c) 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"""Auto-preprocessing of covariates for the stochtree-compatible BART interface.
27`Preprocessor` handles any eager dataframe supported by narwhals (pandas,
28polars, pyarrow, modin, cudf), wrapped with `to_narwhals`::
30 pp = Preprocessor()
31 df_train = to_narwhals(X_train) # None if not a dataframe
32 varprob = pp.fit(df_train, variable_weights=w)
33 x_train = pp.transform(df_train)
34 x_new = pp.transform(to_narwhals(X_new)) # at prediction time
36`fit` records the per-column encoding and returns the variable weights expanded
37to match the new column count (or `None`); `transform` returns the
38post-processing covariate matrix as a 2-D numpy float32 array (rows=observations,
39columns=expanded features).
41Per-column handling:
43- ordered categorical (pandas ordered `Categorical`, polars `Enum`, ordered
44 pyarrow dictionary): ordinal encoded into a single integer-valued column, with
45 the declared category order giving the integer mapping.
46- unordered categorical (pandas unordered `Categorical`, polars `Categorical`,
47 unordered pyarrow dictionary): one-hot encoded into one binary column per
48 declared category. A polars `Categorical` has no per-column category list, so
49 its categories are the values observed at `fit`, sorted.
50- boolean: cast to ``{0.0, 1.0}``, single column.
51- numeric (integer, unsigned, float, decimal): pass-through as float.
52- pandas columns with a pyarrow dtype (`pandas.ArrowDtype`): handled like the
53 corresponding pyarrow column.
54- anything else (strings, ``object``, datetime, etc.): raises `ValueError`.
56When a single original column expands into ``k`` output columns (one-hot), the
57original `variable_weights` entry for that column is split evenly across the
58``k`` expansions, preserving each original variable's total splitting budget
59(matching stochtree's `bart.py` behavior).
61Null values in categorical columns, and category values unknown at `transform`
62time, raise `ValueError`.
63"""
65from collections.abc import Sequence
66from dataclasses import dataclass
67from typing import Any, Literal, Protocol, TypeAlias, overload, runtime_checkable
68from warnings import warn
70import narwhals.stable.v2 as nw
71import numpy as np
72from jaxtyping import Float32, Shaped
73from narwhals.stable.v2.dependencies import get_polars
75# Not `numpy.typing.ArrayLike`: that is a PEP 695 type alias since numpy 2.5,
76# which jaxtyping cannot subscript.
77from bartz.mcmcstep._state import ArrayLike
80@runtime_checkable
81class DataFrame(Protocol):
82 """Any eager dataframe supported by narwhals, e.g., pandas, polars, or pyarrow."""
84 @property
85 def columns(self) -> object:
86 """The columns."""
87 ...
89 @property
90 def shape(self) -> tuple[int, int]:
91 """The number of rows and columns."""
92 ...
95_UNSEEN_PREVIEW = 10
97ColumnKind: TypeAlias = Literal['numeric', 'bool', 'ordered_cat', 'unordered_cat']
100@dataclass(frozen=True)
101class _ColumnSpec:
102 """Per-original-column fitted state."""
104 kind: ColumnKind
105 """Encoding to apply to the column."""
107 name: str
108 """Original column name (for error messages)."""
110 categories: tuple[Any, ...] = ()
111 """Declared category list for ordered_cat / unordered_cat."""
113 @property
114 def width(self) -> int:
115 """Number of output columns this spec produces."""
116 if self.kind == 'unordered_cat':
117 return len(self.categories)
118 else:
119 return 1
122def _unseen_error(name: str, unseen: Sequence[Any], known: Sequence[Any]) -> ValueError:
123 """Build the error for category values absent from the fitted list."""
124 msg = (
125 f'column {name!r}: {len(unseen)} distinct value(s) at transform time are'
126 ' not in the fitted category list; unseen sample:'
127 f' {list(unseen)[:_UNSEEN_PREVIEW]}; known categories:'
128 f' {list(known)[:_UNSEEN_PREVIEW]}'
129 )
130 return ValueError(msg)
133def _unsupported_dtype_error(name: str, dtype: object) -> ValueError:
134 """Build the error for a column whose dtype has no supported encoding."""
135 msg = (
136 f'column {name!r} has unsupported dtype {dtype!r}; supported types are'
137 ' numeric, boolean, pandas ordered/unordered Categorical, polars Enum or'
138 ' Categorical, and pyarrow dictionary. Convert strings, objects,'
139 ' datetimes, etc. to one of these (e.g. an explicit Categorical / Enum)'
140 ' before fitting.'
141 )
142 return ValueError(msg)
145def _polars_enum_message(name: str) -> str:
146 """Build the warning about the encoding of a polars `Enum` column."""
147 msg = (
148 f'column {name!r} is a polars Enum, which is ordered, so it is encoded as'
149 ' a single ordinal column; bartz <= 0.14 one-hot encoded it. For one-hot'
150 ' encoding, use a polars Categorical.'
151 )
152 # WORKAROUND(polars<2): drop this note
153 if int(get_polars().__version__.split('.')[0]) < 2:
154 msg += (
155 ' Note that polars < 2 converts an Enum to an unordered categorical in'
156 ' to_pandas() and to_arrow(), which is one-hot encoded.'
157 )
158 return msg
161def _fit_column(series: nw.Series, name: str) -> _ColumnSpec:
162 """Inspect a column's dtype and return its encoding spec."""
163 dtype = series.dtype
164 impl = series.implementation
165 if isinstance(dtype, nw.Enum):
166 if impl.is_polars():
167 warn(_polars_enum_message(name))
168 return _ColumnSpec('ordered_cat', name, tuple(dtype.categories))
169 elif isinstance(dtype, nw.Categorical) and impl.is_polars():
170 # sort to not depend on the order of appearance
171 categories = tuple(sorted(series.drop_nulls().unique().to_list()))
172 return _ColumnSpec('unordered_cat', name, categories)
173 elif isinstance(dtype, nw.Categorical):
174 # narwhals drops the ordered flag of pyarrow dictionaries
175 ordered = impl.is_pyarrow() and series.to_native().type.ordered
176 kind: ColumnKind = 'ordered_cat' if ordered else 'unordered_cat'
177 return _ColumnSpec(kind, name, tuple(series.cat.get_categories().to_list()))
178 elif dtype == nw.Boolean:
179 return _ColumnSpec('bool', name)
180 elif dtype.is_numeric():
181 return _ColumnSpec('numeric', name)
182 else:
183 raise _unsupported_dtype_error(name, dtype)
186def _get_column(df: nw.DataFrame[Any], name: str) -> nw.Series:
187 """Get a column, moving it to pyarrow if it has a pyarrow dtype in pandas."""
188 series = df.get_column(name)
189 if series.implementation.is_pandas_like() and hasattr(
190 series.to_native().dtype, 'pyarrow_dtype'
191 ):
192 # narwhals can't use `.cat` on `pandas.ArrowDtype` dictionaries
193 arrow = series.to_frame().to_arrow().column(0)
194 return nw.from_native(arrow, series_only=True)
195 else:
196 return series
199def _category_lookup(
200 series: nw.Series, spec: _ColumnSpec
201) -> tuple[list[Any], list[int]]:
202 """Return the distinct values and their fitted category codes; raise on null or unseen."""
203 if series.null_count():
204 msg = (
205 f'column {spec.name!r}: null values are not supported in categorical'
206 ' columns'
207 )
208 raise ValueError(msg)
209 table = {c: i for i, c in enumerate(spec.categories)}
210 uniq = series.unique().to_list()
211 codes = [table.get(u, -1) for u in uniq]
212 unseen = [u for u, code in zip(uniq, codes, strict=True) if code < 0]
213 if unseen:
214 raise _unseen_error(spec.name, unseen, spec.categories)
215 return uniq, codes
218def _column_exprs(series: nw.Series, spec: _ColumnSpec) -> list[nw.Expr]:
219 """Build the expressions encoding a column according to its fitted spec."""
220 col = nw.col(series.name)
221 if spec.kind == 'ordered_cat':
222 # keyed on the observed values, which are valid for any column dtype
223 uniq, codes = _category_lookup(series, spec)
224 return [col.replace_strict(uniq, codes).cast(nw.Float32)]
225 elif spec.kind == 'unordered_cat':
226 _category_lookup(series, spec)
227 return [(col == c).cast(nw.Float32) for c in spec.categories]
228 else:
229 return [col.cast(nw.Float32)]
232def _expand_variable_weights(
233 weights: Shaped[ArrayLike, '...'], original_var_indices: Sequence[int], n_orig: int
234) -> Float32[np.ndarray, ' p']:
235 """Split each original weight evenly across its one-hot expansions."""
236 w = np.asarray(weights, dtype=np.float32)
237 if w.shape != (n_orig,):
238 msg = (
239 f'variable_weights must have shape ({n_orig},) matching the number'
240 f' of original columns; got {w.shape}'
241 )
242 raise ValueError(msg)
243 if not original_var_indices: 243 ↛ 244line 243 didn't jump to line 244 because the condition on line 243 was never true
244 return np.empty((0,), dtype=np.float32)
245 counts = np.bincount(np.asarray(original_var_indices), minlength=n_orig)
246 return np.array([w[j] / counts[j] for j in original_var_indices], dtype=np.float32)
249class Preprocessor:
250 """Stochtree-style covariate preprocessor for dataframes."""
252 _fitted: bool = False
253 _specs: Sequence[_ColumnSpec] = ()
254 _original_var_indices: Sequence[int] = ()
256 @property
257 def fitted(self) -> bool:
258 """Whether `fit` has been called."""
259 return self._fitted
261 @property
262 def n_original_columns(self) -> int:
263 """Number of columns in the dataframe given to `fit`."""
264 return len(self._specs)
266 @property
267 def n_processed_columns(self) -> int:
268 """Number of columns in the matrix returned by `transform`."""
269 return len(self._original_var_indices)
271 @property
272 def original_var_indices(self) -> tuple[int, ...]:
273 """For each output column, the index of the original column it came from."""
274 return tuple(self._original_var_indices)
276 @overload
277 def fit(
278 self, df: nw.DataFrame[Any], *, variable_weights: Shaped[ArrayLike, '...']
279 ) -> Float32[np.ndarray, ' p']: ...
281 @overload
282 def fit(
283 self, df: nw.DataFrame[Any], *, variable_weights: None = None
284 ) -> Float32[np.ndarray, ' p'] | None: ...
286 def fit(
287 self,
288 df: nw.DataFrame[Any],
289 *,
290 variable_weights: Shaped[ArrayLike, '...'] | None = None,
291 ) -> Float32[np.ndarray, ' p'] | None:
292 """Record the per-column encoding and return the expanded variable weights.
294 Returns `None` when no weights are supplied and no column expands into
295 several output columns, so the caller can fall back to the native
296 uniform-weights path; otherwise returns the weights split across each
297 original column's one-hot expansion.
298 """
299 self._specs = tuple(_fit_column(_get_column(df, c), str(c)) for c in df.columns)
300 self._original_var_indices = tuple(
301 i for i, spec in enumerate(self._specs) for _ in range(spec.width)
302 )
303 self._fitted = True
304 expanded = len(self._original_var_indices) != len(self._specs)
305 if variable_weights is None:
306 if not expanded:
307 return None
308 variable_weights = np.full(len(self._specs), 1.0 / len(self._specs))
309 return _expand_variable_weights(
310 variable_weights, self._original_var_indices, len(self._specs)
311 )
313 def transform(self, df: nw.DataFrame[Any]) -> Float32[np.ndarray, 'n p']:
314 """Apply the fitted transformation to a new dataframe, from any library."""
315 if not self.fitted: 315 ↛ 316line 315 didn't jump to line 316 because the condition on line 315 was never true
316 msg = 'preprocessor has not been fitted yet; call fit first'
317 raise RuntimeError(msg)
318 n, p = df.shape
319 if p != len(self._specs):
320 msg = (
321 f'transform input has {p} columns; preprocessor was fitted'
322 f' on {len(self._specs)} columns'
323 )
324 raise ValueError(msg)
325 exprs = [
326 expr
327 for c, spec in zip(df.columns, self._specs, strict=True)
328 for expr in _column_exprs(df.get_column(c), spec)
329 ]
330 if exprs: 330 ↛ 334line 330 didn't jump to line 334 because the condition on line 330 was always true
331 out = df.select(*(e.alias(str(i)) for i, e in enumerate(exprs)))
332 return out.to_numpy().astype(np.float32, copy=False)
333 else:
334 return np.empty((n, 0), dtype=np.float32)
337def to_narwhals(X: object) -> nw.DataFrame[Any] | None:
338 """Wrap `X` with narwhals if it is an eager dataframe it supports, else return `None`; reject lazy frames."""
339 df = nw.from_native(X, pass_through=True)
340 if isinstance(df, nw.DataFrame):
341 return df
342 elif isinstance(df, nw.LazyFrame):
343 msg = (
344 f'lazy dataframes are not supported, got {type(X).__name__}; collect it'
345 ' into an eager dataframe first, e.g., with polars `LazyFrame.collect()`'
346 )
347 raise TypeError(msg)
348 else:
349 return None