Coverage for src/bartz/stochtree/_stochtree.py: 95%

557 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-30 12:50 +0000

1# bartz/src/bartz/stochtree/_stochtree.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. 

24 

25"""Implement class `BARTModel` that mimics the Python package stochtree.""" 

26 

27import math 

28from collections.abc import Mapping, Sequence 

29from dataclasses import dataclass, field, fields 

30from functools import partial 

31 

32# WORKAROUND(python<3.15): use frozendict instead of MappingProxyType 

33from types import MappingProxyType 

34from typing import TYPE_CHECKING, Any, Literal, NamedTuple, TypeVar, overload 

35 

36import numpy as np 

37from equinox import error_if 

38from jax import lax, random 

39from jax import numpy as jnp 

40from jax.scipy.special import ndtr, ndtri 

41from jaxtyping import Array, Bool, Float, Float32, Integer, Key, Real, Shaped 

42 

43from bartz._interface import Bart, PredictKind, Series 

44from bartz._jaxext import forbid_x64, is_key, jit, split 

45from bartz.mcmcloop import MainTrace 

46from bartz.mcmcstep import Wishart 

47from bartz.mcmcstep._state import ArrayLike, FloatLike 

48from bartz.prepcovars import RangeEvenBinner 

49from bartz.stochtree._preprocess import DataFrame, Preprocessor, to_narwhals 

50 

51if TYPE_CHECKING: 

52 from _typeshed import DataclassInstance 

53 

54_MAX_DEPTH_LIMIT = 16 

55 

56 

57@dataclass(frozen=True) 

58class OutcomeModel: 

59 """Outcome model specification, matching `stochtree.OutcomeModel`. 

60 

61 Only ``('continuous', 'identity')`` and ``('binary', 'probit')`` are 

62 supported. 

63 """ 

64 

65 outcome: Literal['continuous', 'binary'] = 'continuous' 

66 """Outcome family.""" 

67 

68 link: Literal['identity', 'probit'] | None = None 

69 """Link function. If `None`, defaults to ``'identity'`` for ``'continuous'`` and ``'probit'`` for ``'binary'``.""" 

70 

71 def __post_init__(self) -> None: 

72 if self.link is None: 

73 default_link = {'continuous': 'identity', 'binary': 'probit'}.get( 

74 self.outcome 

75 ) 

76 object.__setattr__(self, 'link', default_link) 

77 if (self.outcome, self.link) not in ( 

78 ('continuous', 'identity'), 

79 ('binary', 'probit'), 

80 ): 

81 msg = ( 

82 f'unsupported outcome_model (outcome={self.outcome!r}, ' 

83 f"link={self.link!r}); only ('continuous', 'identity') " 

84 "and ('binary', 'probit') are supported." 

85 ) 

86 raise NotImplementedError(msg) 

87 

88 

89class NotSampledError(ValueError, AttributeError): 

90 """Raised when calling a method that requires `BARTModel.sample` to have been called.""" 

91 

92 

93@dataclass(frozen=True, kw_only=True) 

94class BaseGeneralParams: 

95 """The keys of stochtree's ``general_params`` dict shared by `BARTModel` and `BCFModel`.""" 

96 

97 standardize: bool = True 

98 """Whether to standardize the outcome before fitting. Ignored for probit binary.""" 

99 

100 sample_sigma2_global: bool = True 

101 """Whether to sample the global error variance, or hold it fixed at its starting value. Ignored for probit binary regression, where the variance is fixed at 1.""" 

102 

103 sigma2_global_shape: FloatLike = 0.0 

104 """Shape parameter of the inverse-gamma prior on the global error variance. bartz does not support shape ``0`` with positive scale, which yields NaN samples.""" 

105 

106 sigma2_global_scale: FloatLike = 0.0 

107 """Scale parameter of the inverse-gamma prior on the global error variance.""" 

108 

109 variable_weights: Float[ArrayLike, ' p'] | None = None 

110 """Relative probability of splitting on each covariate. The trees never split on covariates with weight 0.""" 

111 

112 random_seed: int | Key[Array, ''] | None = None 

113 """Seed for the random number generator. Unlike stochtree, the default 

114 `None` is deterministic (equivalent to seed ``0``) rather than drawing a 

115 random seed, so repeated fits reproduce by default.""" 

116 

117 keep_every: int = 1 

118 """Thinning factor for retained MCMC samples.""" 

119 

120 num_chains: int = 1 

121 """Number of independent MCMC chains.""" 

122 

123 outcome_model: OutcomeModel = field(default_factory=OutcomeModel) 

124 """Outcome family and link specification. Defaults to continuous with 

125 identity link.""" 

126 

127 

128@dataclass(frozen=True, kw_only=True) 

129class GeneralParams(BaseGeneralParams): 

130 """Mirror of stochtree's ``general_params`` dict of `BARTModel.sample`, with the keys bartz handles.""" 

131 

132 sigma2_init: FloatLike | None = None 

133 """Starting value of the global error variance. If `None` (default), uses ``var(resid_train)`` for continuous and ``1.0`` for probit.""" 

134 

135 

136@dataclass(frozen=True, kw_only=True) 

137class BaseForestParams: 

138 """The keys of stochtree's forest parameter dicts shared by all forests.""" 

139 

140 num_trees: int = 200 

141 """Number of trees in the forest.""" 

142 

143 alpha: FloatLike = 0.95 

144 """Tree split prior base.""" 

145 

146 beta: FloatLike = 2.0 

147 """Tree split prior decay.""" 

148 

149 min_samples_leaf: int = 5 

150 """Minimum number of training samples at a leaf.""" 

151 

152 keep_vars: ( 

153 Sequence[str] 

154 | Sequence[int] 

155 | Shaped[np.ndarray, ' k_keep'] 

156 | Integer[Array, ' k_keep'] 

157 | Series 

158 | None 

159 ) = None 

160 """Names (for dataframes) or indices of the only covariates the trees may split on.""" 

161 

162 drop_vars: ( 

163 Sequence[str] 

164 | Sequence[int] 

165 | Shaped[np.ndarray, ' k_drop'] 

166 | Integer[Array, ' k_drop'] 

167 | Series 

168 | None 

169 ) = None 

170 """Names (for dataframes) or indices of covariates the trees may not split on. Ignored if `keep_vars` is set.""" 

171 

172 max_depth: int = 10 

173 """Maximum tree depth. Must be a non-negative integer at most ``16``.""" 

174 

175 sample_sigma2_leaf: bool = True 

176 """Whether to sample the leaf variance with an inverse-gamma prior, or hold it fixed at `sigma2_leaf_init`.""" 

177 

178 sigma2_leaf_init: FloatLike | None = None 

179 """Initial leaf variance. If `None`, use stochtree's default.""" 

180 

181 sigma2_leaf_shape: FloatLike = 3.0 

182 """Twice the shape parameter of the inverse-gamma prior on the leaf variance, i.e., the prior is ``IG(sigma2_leaf_shape / 2, sigma2_leaf_scale / 2)``.""" 

183 

184 sigma2_leaf_scale: FloatLike | None = None 

185 """Twice the scale parameter of the inverse-gamma prior on the leaf variance. If `None`, use stochtree's default.""" 

186 

187 def __post_init__(self) -> None: 

188 if self.max_depth < 0: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 msg = ( 

190 f'max_depth={self.max_depth} is not supported; bartz stores trees' 

191 ' as heap arrays of size 2**max_depth, so the stochtree' 

192 ' convention max_depth=-1 (unbounded) is rejected. Pass a' 

193 f' non-negative integer at most {_MAX_DEPTH_LIMIT}.' 

194 ) 

195 raise NotImplementedError(msg) 

196 if self.max_depth > _MAX_DEPTH_LIMIT: 196 ↛ 197line 196 didn't jump to line 197 because the condition on line 196 was never true

197 msg = ( 

198 f'max_depth={self.max_depth} exceeds {_MAX_DEPTH_LIMIT}; bartz' 

199 ' stores trees as heap arrays of size 2**max_depth, so memory' 

200 ' grows exponentially with depth.' 

201 ) 

202 raise ValueError(msg) 

203 

204 

205@dataclass(frozen=True, kw_only=True) 

206class MeanForestParams(BaseForestParams): 

207 """Mirror of stochtree's ``mean_forest_params`` dict, restricted to the keys bartz handles.""" 

208 

209 sigma2_leaf_init: FloatLike | None = None 

210 """Initial leaf variance. If `None`, matches stochtree's defaults of ``var(resid_train) / num_trees`` for continuous and ``2 / num_trees`` for probit.""" 

211 

212 sigma2_leaf_scale: FloatLike | None = None 

213 """Twice the scale parameter of the inverse-gamma prior on the leaf variance. If `None`, defaults to ``var(resid_train) / num_trees`` for continuous and ``1 / num_trees`` for probit.""" 

214 

215 

216if TYPE_CHECKING: 

217 # static only, beartype does not support type[DataclassInstance] 

218 T = TypeVar('T', bound='DataclassInstance') 

219else: 

220 T = TypeVar('T') 

221 

222 

223def build_dataclass(cls: type[T], params: Mapping[str, Any] | None, name: str) -> T: 

224 """Convert a user-supplied dict to a dataclass, with friendly errors.""" 

225 if params is None: 

226 params = {} 

227 allowed = {f.name for f in fields(cls)} 

228 extra = set(params) - allowed 

229 if extra: 

230 msg = ( 

231 f'{name} contains unsupported key(s) {sorted(extra)}; valid keys' 

232 f' are {sorted(allowed)}' 

233 ) 

234 raise ValueError(msg) 

235 return cls(**params) 

236 

237 

238def unsupported_sampler_args(num_gfr: int, observation_weights: object) -> str | None: 

239 """Explain why bartz does not support the stochtree sampler settings, if so.""" 

240 if num_gfr != 0: 

241 return ( 

242 'num_gfr must be 0; the grow-from-root sampler is not available in bartz.' 

243 ) 

244 elif observation_weights is not None: 

245 return ( 

246 'observation_weights are not supported, because as of stochtree' 

247 ' 0.4.5 they do not work as documented, so there is no' 

248 ' stochtree behavior to mimic.' 

249 ) 

250 else: 

251 return None 

252 

253 

254def not_sampled_msg(model: object) -> str: 

255 """Return the message of `NotSampledError`.""" 

256 return ( 

257 f'This {type(model).__name__} instance is not fitted yet. Call' 

258 " 'sample' before using this model." 

259 ) 

260 

261 

262def random_keys(random_seed: int | Key[Array, ''] | None) -> split: 

263 """Turn ``general_params['random_seed']`` into random keys, with seed 0 by default.""" 

264 seed = 0 if random_seed is None else random_seed 

265 if not is_key(seed): 

266 seed = random.key(seed) 

267 return split(seed) 

268 

269 

270def check_rows( 

271 X: Real[Array, 'n p'], arr: Shaped[Array, ' m'], name: str, X_name: str = 'X_train' 

272) -> None: 

273 """Check `arr` has one entry per row of `X`.""" 

274 n, _ = X.shape 

275 (m,) = arr.shape 

276 if m != n: 

277 msg = ( 

278 f'{X_name} and {name} length mismatch: {X_name} has {n} rows,' 

279 f' {name} has {m} entries' 

280 ) 

281 raise ValueError(msg) 

282 

283 

284def fixed_error_init_kw(sampled: bool, sigma2: FloatLike) -> dict[str, Wishart]: 

285 """Return the `init` arguments that hold the error variance at `sigma2`, unless `sampled`.""" 

286 if sampled: 

287 return {} 

288 else: 

289 return { 

290 'error_cov_inv': Wishart(nu=None, rate=None, value=jnp.reciprocal(sigma2)) 

291 } 

292 

293 

294class Covariates(NamedTuple): 

295 """Training covariates, validated and converted to an array.""" 

296 

297 X: Real[Array, 'n p'] 

298 """Covariates, with dataframes encoded as numerical columns.""" 

299 

300 variable_weights: Float32[Array, ' p'] | None 

301 """Splitting weights, `None` for uniform.""" 

302 

303 columns: tuple[str, ...] | None 

304 """Names of the original covariates, if they were in a dataframe.""" 

305 

306 original_var_indices: Sequence[int] 

307 """For each column of `X`, the index of the original covariate.""" 

308 

309 num_original: int 

310 """Number of original covariates.""" 

311 

312 preprocessor: Preprocessor | None 

313 """The preprocessor fitted on the dataframe, `None` for an array.""" 

314 

315 

316def fit_covariates( 

317 X_train: Real[ArrayLike, 'n p'] | DataFrame, 

318 variable_weights: Float[ArrayLike, ' p'] | None, 

319) -> Covariates: 

320 """Convert the training covariates to an array, fitting a preprocessor on dataframes.""" 

321 df_train = to_narwhals(X_train) 

322 if df_train is None: 

323 X_train_arr = check_X(X_train, name='X_train') 

324 _, p = X_train_arr.shape 

325 return Covariates( 

326 X=X_train_arr, 

327 variable_weights=check_variable_weights(variable_weights, p), 

328 columns=None, 

329 original_var_indices=range(p), 

330 num_original=p, 

331 preprocessor=None, 

332 ) 

333 else: 

334 # The preprocessor decides the default weights: uniform over the 

335 # *original* columns split across each one-hot expansion (so every 

336 # original variable keeps an equal splitting budget), or `None` when 

337 # nothing expands (deferring to bartz's native uniform fast-path). 

338 preprocessor = Preprocessor() 

339 weights_np = preprocessor.fit(df_train, variable_weights=variable_weights) 

340 X_train_np = preprocessor.transform(df_train) 

341 if X_train_np.shape[1] == 0: 341 ↛ 342line 341 didn't jump to line 342 because the condition on line 341 was never true

342 msg = 'X_train has no usable columns after preprocessing' 

343 raise ValueError(msg) 

344 columns = tuple(str(c) for c in df_train.columns) 

345 return Covariates( 

346 X=jnp.asarray(X_train_np), 

347 variable_weights=None if weights_np is None else jnp.asarray(weights_np), 

348 columns=columns, 

349 original_var_indices=preprocessor.original_var_indices, 

350 num_original=len(columns), 

351 preprocessor=preprocessor, 

352 ) 

353 

354 

355def prepare_x( 

356 X: Real[ArrayLike, 'm p'] | DataFrame, 

357 preprocessor: Preprocessor | None, 

358 *, 

359 name: str = 'X', 

360) -> Real[Array, 'm p']: 

361 """Convert covariates to a 2-D jax array, replaying the fitted preprocessor if any.""" 

362 if preprocessor is None: 

363 return check_X(X, name=name) 

364 else: 

365 df = to_narwhals(X) 

366 if df is None: 

367 msg = ( 

368 'this model was fit on a DataFrame, so prediction covariates must' 

369 ' also be a DataFrame with the same columns; got a' 

370 ' non-DataFrame. Passing a raw array would bypass the fitted' 

371 ' preprocessing (e.g. one-hot encoding) and silently misalign the' 

372 ' features.' 

373 ) 

374 raise TypeError(msg) 

375 return jnp.asarray(preprocessor.transform(df)) 

376 

377 

378class BaseModel: 

379 """Common implementation of `BARTModel` and `BCFModel`.""" 

380 

381 # public, set by sample() 

382 sampled: bool 

383 """Whether `sample` has been called.""" 

384 

385 standardize: bool 

386 """Whether the outcome was standardized before fitting.""" 

387 

388 sample_sigma2_global: bool 

389 """Whether the global error variance is sampled (always ``False`` for probit binary regression).""" 

390 

391 probit_outcome_model: bool 

392 """Whether the model uses a binary outcome with probit link.""" 

393 

394 outcome_model: OutcomeModel 

395 """Outcome family and link specification used during fitting.""" 

396 

397 num_gfr: int 

398 """Number of grow-from-root iterations (always ``0``).""" 

399 

400 num_burnin: int 

401 """Number of MCMC burn-in iterations.""" 

402 

403 num_mcmc: int 

404 """Number of retained MCMC iterations per chain.""" 

405 

406 num_chains: int 

407 """Number of independent MCMC chains.""" 

408 

409 keep_every: int 

410 """Thinning factor of the retained MCMC samples.""" 

411 

412 num_samples: int 

413 """Total number of retained posterior samples (``num_mcmc * num_chains``).""" 

414 

415 n_train: int 

416 """Number of training observations.""" 

417 

418 n_test: int 

419 """Number of test observations (``0`` if `X_test` was not supplied).""" 

420 

421 has_test: bool 

422 """Whether `X_test` was supplied to `sample`.""" 

423 

424 sigma2_init: FloatLike 

425 """Starting value of the global error variance actually used to seed the chain.""" 

426 

427 y_bar: Float32[Array, ''] 

428 """Mean used to standardize the outcome (``0`` if not standardized).""" 

429 

430 y_std: Float32[Array, ''] 

431 """Standard deviation used to standardize the outcome (``1`` if not standardized).""" 

432 

433 has_rfx: bool 

434 """Whether the model includes random effects (always ``False``).""" 

435 

436 include_variance_forest: bool 

437 """Whether the model includes a variance forest (always ``False``).""" 

438 

439 y_hat_train: Float32[Array, 'n num_samples'] 

440 """Posterior predictions at the training points, in the original outcome scale.""" 

441 

442 global_var_samples: Float32[Array, ' num_samples'] | None 

443 """Posterior samples of the global error variance, or `None` if not sampled.""" 

444 

445 y_hat_test: Float32[Array, 'm num_samples'] | None 

446 """Posterior predictions at the test points if `X_test` was supplied to `sample`, else `None`.""" 

447 

448 _preprocessor: Preprocessor | None 

449 _ppd_key: Key[Array, ''] 

450 """Base key of `sample_posterior_predictive`.""" 

451 

452 _ppd_count: int 

453 """Number of calls to `sample_posterior_predictive`, folded into `_ppd_key`.""" 

454 

455 def __init__(self) -> None: 

456 self.sampled = False 

457 self._preprocessor = None 

458 

459 def is_sampled(self) -> bool: 

460 """Return whether `sample` has been called.""" 

461 return self.sampled 

462 

463 def _store_settings( 

464 self, 

465 *, 

466 preprocessor: Preprocessor | None, 

467 ppd_key: Key[Array, ''], 

468 outcome_model: OutcomeModel, 

469 num_burnin: int, 

470 num_mcmc: int, 

471 num_chains: int, 

472 keep_every: int, 

473 n_train: int, 

474 sample_sigma2_global: bool, 

475 sigma2_init: FloatLike, 

476 y_bar: Float32[Array, ''], 

477 y_std: Float32[Array, ''], 

478 standardize: bool, 

479 ) -> None: 

480 """Populate the public attributes common to all models, but the predictions.""" 

481 self._preprocessor = preprocessor 

482 self._ppd_key = ppd_key 

483 self._ppd_count = 0 

484 self.sampled = True 

485 self.standardize = standardize 

486 self.sample_sigma2_global = sample_sigma2_global 

487 self.probit_outcome_model = outcome_model.outcome == 'binary' 

488 self.outcome_model = outcome_model 

489 self.num_gfr = 0 

490 self.num_burnin = num_burnin 

491 self.num_mcmc = num_mcmc 

492 self.num_chains = num_chains 

493 self.keep_every = keep_every 

494 self.num_samples = num_mcmc * num_chains 

495 self.n_train = n_train 

496 self.sigma2_init = sigma2_init 

497 self.y_bar = y_bar 

498 self.y_std = y_std 

499 self.has_rfx = False 

500 self.include_variance_forest = False 

501 

502 def _draw_outcomes( 

503 self, eta: Float32[Array, 'm num_samples'], num_draws_per_sample: int | None 

504 ) -> ( 

505 Real[Array, 'm num_samples'] | Real[Array, 'm num_samples num_draws_per_sample'] 

506 ): 

507 """Implement `sample_posterior_predictive` given the predictions.""" 

508 if num_draws_per_sample is None: 

509 num_draws_per_sample = ( 

510 1 if self.num_samples >= 1000 else math.ceil(1000 / self.num_samples) 

511 ) 

512 

513 if self.probit_outcome_model: 

514 sigma2 = None 

515 elif self.global_var_samples is None: 

516 sigma2_fixed = self.sigma2_init * jnp.square(self.y_std) 

517 sigma2 = jnp.broadcast_to(sigma2_fixed, (self.num_samples,)) 

518 else: 

519 sigma2 = self.global_var_samples 

520 

521 key = random.fold_in(self._ppd_key, self._ppd_count) 

522 self._ppd_count += 1 

523 return sample_outcome(key, eta, sigma2, num_draws_per_sample) 

524 

525 def _extract( 

526 self, term: str, parameters: Mapping[str, tuple[str, str]], kind: str 

527 ) -> tuple[Shaped[Array, '*shape'] | None, str]: 

528 """Get a parameter by name, given a map of names to attributes and descriptions, returning also why it may be `None`.""" 

529 if term in parameters: 

530 attr, what = parameters[term] 

531 return getattr(self, attr), f'This model does not have {what}' 

532 else: 

533 return None, f'term {term} is not a valid {kind} model term' 

534 

535 def __str__(self) -> str: 

536 if self.sampled: 

537 return self._describe() 

538 else: 

539 return f'Empty {type(self).__name__}() object: not yet sampled' 

540 

541 __repr__ = __str__ 

542 

543 def _describe(self) -> str: 

544 """Describe the fitted model with the same text as stochtree.""" 

545 raise NotImplementedError 

546 

547 def _describe_sampler(self) -> str: 

548 """Describe the MCMC settings with the same text as stochtree.""" 

549 chains = 'chain' if self.num_chains == 1 else 'chains' 

550 if self.keep_every == 1: 

551 thinning = 'retaining every iteration (i.e. no thinning)' 

552 else: 

553 thinning = f'retaining every {self.keep_every}th iteration (i.e. thinning)' 

554 return ( 

555 f'The sampler was run for {self.num_gfr} GFR iterations, with' 

556 f' {self.num_chains} {chains} of {self.num_burnin} burn-in iterations' 

557 f' and {self.num_mcmc} MCMC iterations, {thinning}\n' 

558 ) 

559 

560 

561# the terms of `BARTModel.predict` and their keys in its output 

562BART_TERMS: Mapping[str, str] = MappingProxyType( 

563 {'y_hat': 'y_hat', 'mean_forest': 'mean_forest_predictions'} 

564) 

565 

566# the terms of `BARTModel.extract_parameter`, their attributes and descriptions 

567BART_PARAMETERS: Mapping[str, tuple[str, str]] = MappingProxyType( 

568 { 

569 **dict.fromkeys( 

570 ('sigma2', 'global_error_scale', 'sigma2_global'), 

571 ('global_var_samples', 'global variance parameter samples'), 

572 ), 

573 **dict.fromkeys( 

574 ('sigma2_leaf', 'leaf_scale'), 

575 ('leaf_scale_samples', 'leaf variance parameter samples'), 

576 ), 

577 'y_hat_train': ('y_hat_train', 'in-sample mean function prediction samples'), 

578 'y_hat_test': ('y_hat_test', 'test set mean function prediction samples'), 

579 } 

580) 

581 

582 

583class BARTModel(BaseModel): 

584 R""" 

585 BART model with a `stochtree`-compatible interface, powered by bartz. 

586 

587 This class mimics `stochtree.BARTModel`. The main difference is that 

588 `bartz` does not implement "grow-from-root" (XBART), so the `stochtree` 

589 defaults of 0 burnin and 100 saved MCMC iterations are best changed:: 

590 

591 m = BARTModel() 

592 m.sample(X_train=X, y_train=y, X_test=X_test, num_gfr=0, num_burnin=1000, num_mcmc=1000) 

593 yhat = m.predict(X_new, terms='y_hat', type='mean') 

594 

595 See `GeneralParams` and `MeanForestParams` for the supported keys in the 

596 ``general_params`` and ``mean_forest_params`` dicts. 

597 

598 Notes 

599 ----- 

600 Differences from `stochtree`: 

601 

602 - ``num_gfr`` has no default and must be set explicitly to ``0``. 

603 - The arguments of `sample` after ``y_train``, and of the other methods 

604 after the covariates, are keyword-only, because some of stochtree's 

605 positional arguments are not supported. 

606 - ``mean_forest_params['max_depth']`` must be a non-negative integer at 

607 most ``16``; stochtree's ``-1`` (unbounded depth) sentinel is not 

608 accepted. 

609 - The deprecated ``general_params['probit_outcome_model']`` flag is not 

610 accepted; pass ``outcome_model=OutcomeModel('binary', 'probit')`` 

611 instead. 

612 - ``general_params['cutpoint_grid_size']`` is not accepted; bartz uses a 

613 fixed grid of 256 evenly-spaced bins per predictor. stochtree only 

614 uses this parameter for the GFR sampler, which bartz does not support. 

615 - Leaf-basis regression, random effects, heteroskedastic variance 

616 forests, and warm-starting from a previous model are not supported. 

617 - ``observation_weights`` are not supported, because as of stochtree 

618 0.4.5 they do not work as documented, so there is no stochtree behavior 

619 to mimic. 

620 - bartz uses single-precision floats, so outputs differ from stochtree 

621 at the float32 precision level. 

622 - ``general_params['random_seed']`` defaults to deterministic behavior 

623 (seed ``0``) when unset, whereas stochtree draws a random seed. This is 

624 intentional, to make repeated fits reproducible by default. 

625 

626 References 

627 ---------- 

628 Herren, A., Hahn, P. R., Murray, J., Carvalho, C. (2026). "StochTree: 

629 BART-based modeling in R and Python". arXiv:2512.12051. 

630 """ 

631 

632 num_covariates: int 

633 """Number of covariates after preprocessing, e.g., after one-hot encoding.""" 

634 

635 include_mean_forest: bool 

636 """Whether the model includes a conditional mean forest (always ``True``).""" 

637 

638 sample_sigma2_leaf: bool 

639 """Whether the leaf variance is sampled.""" 

640 

641 leaf_scale_samples: Float32[Array, ' num_samples'] | None 

642 """Posterior samples of the leaf variance, in the standardized outcome scale, or `None` if not sampled.""" 

643 

644 _bart: Bart 

645 

646 @forbid_x64 

647 def sample( 

648 self, 

649 X_train: Real[ArrayLike, 'n p'] | DataFrame, 

650 y_train: Real[ArrayLike, ' n'] | Series, 

651 *, 

652 X_test: Real[ArrayLike, 'm p'] | DataFrame | None = None, 

653 observation_weights: Float[ArrayLike, ' n'] | Series | None = None, 

654 num_gfr: int, 

655 num_burnin: int = 0, 

656 num_mcmc: int = 100, 

657 general_params: Mapping[str, Any] | None = None, 

658 mean_forest_params: Mapping[str, Any] | None = None, 

659 bart_kwargs: Mapping[str, Any] = MappingProxyType({}), 

660 ) -> None: 

661 """Fit the model. 

662 

663 Parameters 

664 ---------- 

665 X_train 

666 Training covariates with shape ``(n, p)``. Any eager dataframe 

667 supported by narwhals (e.g., pandas, polars, pyarrow) is accepted, 

668 with categorical columns encoded like in stochtree. 

669 y_train 

670 Training outcomes of length ``n``. 

671 X_test 

672 Optional test covariates; if given, predictions are cached on 

673 them in `y_hat_test`. 

674 observation_weights 

675 Not supported, must be `None`. 

676 num_gfr 

677 Number of grow-from-root iterations. Must be set explicitly to ``0``. 

678 num_burnin 

679 Number of MCMC burn-in iterations. Recommended to set it to 1000. 

680 num_mcmc 

681 Number of retained MCMC iterations per chain. Recommended to set it 

682 to 1000. 

683 general_params 

684 Optional override for the keys of `GeneralParams`. 

685 mean_forest_params 

686 Optional override for the keys of `MeanForestParams`. 

687 bart_kwargs 

688 Additional arguments forwarded to `bartz.Bart`. Use this to set 

689 ``devices`` and ``rm_const=False`` when wrapping `sample` in 

690 `jax.jit`. 

691 

692 Raises 

693 ------ 

694 NotImplementedError 

695 If ``num_gfr`` is non-zero or `observation_weights` is set. 

696 

697 Notes 

698 ----- 

699 The signature mirrors `stochtree.BARTModel.sample`, restricted to the 

700 arguments bartz supports. This method invokes `bartz.Bart` under the 

701 hood. 

702 """ 

703 msg = unsupported_sampler_args(num_gfr, observation_weights) 

704 if msg is not None: 

705 raise NotImplementedError(msg) 

706 

707 gp = build_dataclass(GeneralParams, general_params, 'general_params') 

708 mfp = build_dataclass( 

709 MeanForestParams, mean_forest_params, 'mean_forest_params' 

710 ) 

711 

712 is_probit = gp.outcome_model.outcome == 'binary' 

713 

714 cov = fit_covariates(X_train, gp.variable_weights) 

715 variable_weights = select_covariates(cov, mfp.keep_vars, mfp.drop_vars) 

716 y = _coerce_response(y_train, name='y_train') 

717 check_rows(cov.X, y, 'y_train') 

718 x_test = ( 

719 None 

720 if X_test is None 

721 else prepare_x(X_test, cov.preprocessor, name='X_test') 

722 ) 

723 sample_sigma2_global = gp.sample_sigma2_global and not is_probit 

724 

725 y_bar, y_std, y_for_bartz = standardize_y(y, is_probit, gp.standardize) 

726 

727 bart_num_chains = None if gp.num_chains == 1 else gp.num_chains 

728 

729 # variance of the standardized residual, matching stochtree 

730 # (np.var(resid_train) with ddof=0). For standardize=True it is exactly 

731 # 1.0; we hardcode that so the value stays trace-time concrete. 

732 if is_probit: 

733 var_resid_train: FloatLike = 1.0 # bartz ignores σ² for binary 

734 elif gp.standardize: 

735 var_resid_train = 1.0 

736 else: 

737 var_resid_train = jnp.var(y_for_bartz) 

738 

739 # leaf-prior: bartz uses sigma_mu = tau_num / (k * sqrt(num_trees)); 

740 # stochtree's sigma2_leaf is the leaf-variance prior. Hold k=2 and solve 

741 # for tau_num so that the two parameterizations agree. 

742 bartz_k = 2.0 

743 sigma2_leaf_init = resolve_sigma2_leaf_init( 

744 mfp.sigma2_leaf_init, mfp.num_trees, is_probit, var_resid_train 

745 ) 

746 tau_num_arg = bartz_k * jnp.sqrt(mfp.num_trees * sigma2_leaf_init) 

747 

748 if mfp.sample_sigma2_leaf: 

749 leaf_init_kw: dict = { 

750 'sum_trees_prior_cov_inv': resolve_leaf_variance_prior( 

751 mfp.sigma2_leaf_shape, 

752 mfp.sigma2_leaf_scale, 

753 sigma2_leaf_init, 

754 num_trees=mfp.num_trees, 

755 is_probit=is_probit, 

756 var_resid_train=var_resid_train, 

757 ) 

758 } 

759 else: 

760 leaf_init_kw = {} 

761 

762 if is_probit: 

763 # stochtree pins σ²=1 for probit; bartz binary branch ignores the 

764 # variance prior, so we leave the scale/init at their 'auto' 

765 # defaults (bartz rejects explicit values for binary outcomes). 

766 sigma_df_arg: FloatLike = 3.0 

767 sigma_scale_arg: FloatLike | Literal['auto'] = 'auto' 

768 sigma_init_arg: FloatLike | Literal['auto'] = 'auto' 

769 sigma2_init_stored: FloatLike = 1.0 

770 else: 

771 sigma_df_arg, sigma_scale_arg, sigma_init_arg, sigma2_init_stored = ( 

772 resolve_variance_prior( 

773 gp.sigma2_global_shape, 

774 gp.sigma2_global_scale, 

775 gp.sigma2_init, 

776 var_resid_train, 

777 ) 

778 ) 

779 

780 error_init_kw = fixed_error_init_kw( 

781 sample_sigma2_global or is_probit, sigma2_init_stored 

782 ) 

783 

784 keys = random_keys(gp.random_seed) 

785 

786 kwargs: dict = dict( 

787 x_train=cov.X.T, 

788 y_train=y_for_bartz, 

789 outcome_type='binary' if is_probit else 'continuous', 

790 # stochtree centers the forest at `y_bar`, i.e., at 0 on the scale 

791 # of `y_for_bartz` for continuous outcomes, while `Bart` defaults 

792 # to the mean of `y_for_bartz` 

793 offset=None if is_probit else 0.0, 

794 binner=partial(RangeEvenBinner, max_bins=256), 

795 varprob=variable_weights, 

796 sigma_df=sigma_df_arg, 

797 sigma_scale=sigma_scale_arg, 

798 sigma_init=sigma_init_arg, 

799 k=bartz_k, 

800 power=mfp.beta, 

801 base=mfp.alpha, 

802 tau_num=tau_num_arg, 

803 num_trees=mfp.num_trees, 

804 n_save=num_mcmc, 

805 n_burn=num_burnin, 

806 n_skip=gp.keep_every, 

807 printevery=None, 

808 num_chains=bart_num_chains, 

809 seed=keys.pop(), 

810 maxdepth=mfp.max_depth, 

811 precompute_predict_train=True, 

812 ) 

813 kwargs.update(bart_kwargs) 

814 # min_samples_leaf maps to bartz's acceptance-time veto. 

815 # min_points_per_decision_node = 2 * min_samples_leaf makes the 

816 # proposal skip leaves too small to split, without changing the target 

817 # posterior, which thus matches stochtree. The leaf variance prior goes 

818 # through init_kw because Bart's sigma_mu_df ties the prior scale to 

819 # the initial value, while stochtree sets them independently. 

820 # User-supplied init_kw values win on conflicts. 

821 kwargs = dict( 

822 kwargs, 

823 init_kw=dict( 

824 { 

825 'min_points_per_leaf': mfp.min_samples_leaf, 

826 'min_points_per_decision_node': 2 * mfp.min_samples_leaf, 

827 **leaf_init_kw, 

828 **error_init_kw, 

829 }, 

830 **kwargs.get('init_kw', {}), 

831 ), 

832 ) 

833 bart = Bart(**kwargs) 

834 # predicting may raise, so do it before modifying the model 

835 if x_test is None: 

836 latent_test = None 

837 else: 

838 latent_test = bart.predict(x_test.T, kind=PredictKind.latent_samples) 

839 

840 self._bart = bart 

841 n_train, num_covariates = cov.X.shape 

842 self._store_settings( 

843 preprocessor=cov.preprocessor, 

844 ppd_key=keys.pop(), 

845 outcome_model=gp.outcome_model, 

846 num_burnin=num_burnin, 

847 num_mcmc=num_mcmc, 

848 num_chains=gp.num_chains, 

849 keep_every=gp.keep_every, 

850 n_train=n_train, 

851 sample_sigma2_global=sample_sigma2_global, 

852 sigma2_init=sigma2_init_stored, 

853 y_bar=y_bar, 

854 y_std=y_std, 

855 standardize=gp.standardize, 

856 ) 

857 self._store_outputs( 

858 num_covariates=num_covariates, 

859 sample_sigma2_leaf=mfp.sample_sigma2_leaf, 

860 latent_test=latent_test, 

861 ) 

862 

863 def _store_outputs( 

864 self, 

865 *, 

866 num_covariates: int, 

867 sample_sigma2_leaf: bool, 

868 latent_test: Float32[Array, 'num_samples m'] | None, 

869 ) -> None: 

870 """Populate the public attributes specific to `BARTModel`.""" 

871 self.num_covariates = num_covariates 

872 self.include_mean_forest = True 

873 self.sample_sigma2_leaf = sample_sigma2_leaf 

874 

875 # cached outputs in stochtree's (n, num_samples) layout, original scale 

876 self.y_hat_train = self._predict_y_hat_internal('train') 

877 if latent_test is not None: 

878 self.y_hat_test = self._latent_to_y_hat(latent_test) 

879 self.n_test, _ = self.y_hat_test.shape 

880 else: 

881 self.y_hat_test = None 

882 self.n_test = 0 

883 self.has_test = latent_test is not None 

884 

885 if self.sample_sigma2_global: 

886 sigma = self._bart.get_error_sdev() 

887 self.global_var_samples = jnp.square(sigma * self.y_std) 

888 else: 

889 self.global_var_samples = None 

890 

891 if sample_sigma2_leaf: 

892 self.leaf_scale_samples = get_leaf_scale_samples( 

893 self._bart._main_trace # noqa: SLF001 

894 ) 

895 else: 

896 self.leaf_scale_samples = None 

897 

898 @overload 

899 def predict( 

900 self, 

901 X: Real[ArrayLike, 'm p'] | DataFrame, 

902 *, 

903 type: Literal['posterior', 'mean'] = 'posterior', 

904 terms: Literal['y_hat', 'mean_forest'], 

905 scale: Literal['linear', 'probability', 'class'] = 'linear', 

906 ) -> Shaped[Array, 'm num_samples'] | Shaped[Array, ' m']: ... 

907 

908 @overload 

909 def predict( 

910 self, 

911 X: Real[ArrayLike, 'm p'] | DataFrame, 

912 *, 

913 type: Literal['posterior', 'mean'] = 'posterior', 

914 terms: Literal['all'] = 'all', 

915 scale: Literal['linear', 'probability', 'class'] = 'linear', 

916 ) -> dict[str, Shaped[Array, 'm num_samples']] | dict[str, Shaped[Array, ' m']]: ... 

917 

918 @overload 

919 def predict( 

920 self, 

921 X: Real[ArrayLike, 'm p'] | DataFrame, 

922 *, 

923 type: Literal['posterior', 'mean'] = 'posterior', 

924 terms: Sequence[Literal['y_hat', 'mean_forest', 'all']], 

925 scale: Literal['linear', 'probability', 'class'] = 'linear', 

926 ) -> ( 

927 Shaped[Array, 'm num_samples'] 

928 | Shaped[Array, ' m'] 

929 | dict[str, Shaped[Array, 'm num_samples']] 

930 | dict[str, Shaped[Array, ' m']] 

931 ): ... 

932 

933 @forbid_x64 

934 def predict( 

935 self, 

936 X: Real[ArrayLike, 'm p'] | DataFrame, 

937 *, 

938 type: Literal['posterior', 'mean'] = 'posterior', # noqa: A002 

939 terms: Literal['y_hat', 'mean_forest', 'all'] 

940 | Sequence[Literal['y_hat', 'mean_forest', 'all']] = 'all', 

941 scale: Literal['linear', 'probability', 'class'] = 'linear', 

942 ) -> ( 

943 Shaped[Array, 'm num_samples'] 

944 | Shaped[Array, ' m'] 

945 | dict[str, Shaped[Array, 'm num_samples']] 

946 | dict[str, Shaped[Array, ' m']] 

947 ): 

948 """Predict at new covariates. 

949 

950 Parameters 

951 ---------- 

952 X 

953 New covariates with shape ``(m, p)``. 

954 type 

955 ``'posterior'`` returns one prediction per posterior sample, with 

956 shape ``(m, num_samples)``. ``'mean'`` averages the posterior 

957 samples, returning a vector of shape ``(m,)``. 

958 terms 

959 One of ``'y_hat'``, ``'mean_forest'``, ``'all'``, or a list. Since 

960 random effects and a variance forest are not supported, ``'y_hat'`` 

961 and ``'mean_forest'`` produce the same result. 

962 scale 

963 For probit binary regression: ``'linear'`` returns the eta values, 

964 ``'probability'`` returns ``Phi(eta)``, ``'class'`` returns 0 / 1. 

965 Only ``'linear'`` is valid for continuous outcomes. 

966 

967 Returns 

968 ------- 

969 Either a single jax array (for a single requested term) or a dict keyed by term name. 

970 

971 Raises 

972 ------ 

973 NotSampledError 

974 If `sample` has not been called yet. 

975 """ 

976 if not self.sampled: 

977 raise NotSampledError(not_sampled_msg(self)) 

978 terms_tuple = check_predict_args( 

979 type, scale, terms, self.probit_outcome_model, (*BART_TERMS, 'all') 

980 ) 

981 pred = self._predict_y_hat_internal(prepare_x(X, self._preprocessor).T) 

982 pred = transform_prediction(pred, scale, type) 

983 keys = requested_terms(terms_tuple, BART_TERMS) 

984 return pack_terms(dict.fromkeys(keys, pred)) 

985 

986 def compute_contrast( 

987 self, 

988 X_0: Real[ArrayLike, 'm p'] | DataFrame, 

989 X_1: Real[ArrayLike, 'm p'] | DataFrame, 

990 *, 

991 type: Literal['posterior', 'mean'] = 'posterior', # noqa: A002 

992 scale: Literal['linear', 'probability'] = 'linear', 

993 ) -> Float32[Array, 'm num_samples'] | Float32[Array, ' m']: 

994 """Compute the difference between the predictions at `X_1` and at `X_0`. 

995 

996 Parameters 

997 ---------- 

998 X_0 

999 Covariates of the subtracted predictions, with shape ``(m, p)``. 

1000 X_1 

1001 Covariates of the other predictions, with shape ``(m, p)``. 

1002 type 

1003 ``'posterior'`` returns one contrast per posterior sample, with 

1004 shape ``(m, num_samples)``. ``'mean'`` averages them, returning a 

1005 vector of shape ``(m,)``. 

1006 scale 

1007 ``'linear'``, or, for probit binary regression, ``'probability'`` 

1008 to contrast ``Phi(eta)``. 

1009 

1010 Returns 

1011 ------- 

1012 The contrast ``predict(X_1) - predict(X_0)``. 

1013 

1014 Raises 

1015 ------ 

1016 NotSampledError 

1017 If `sample` has not been called yet. 

1018 """ 

1019 if not self.sampled: 

1020 raise NotSampledError(not_sampled_msg(self)) 

1021 check_interval_scale(scale) 

1022 check_predict_args( 

1023 type, scale, 'y_hat', self.probit_outcome_model, (*BART_TERMS, 'all') 

1024 ) 

1025 pred_1 = self.predict(X_1, terms='y_hat', scale=scale) 

1026 pred_0 = self.predict(X_0, terms='y_hat', scale=scale) 

1027 return transform_prediction(pred_1 - pred_0, 'linear', type) 

1028 

1029 @overload 

1030 def compute_posterior_interval( 

1031 self, 

1032 X: Real[ArrayLike, 'm p'] | DataFrame, 

1033 *, 

1034 terms: Literal['y_hat', 'mean_forest'], 

1035 level: FloatLike = 0.95, 

1036 scale: Literal['linear', 'probability'] = 'linear', 

1037 ) -> dict[str, Float32[Array, ' m']]: ... 

1038 

1039 @overload 

1040 def compute_posterior_interval( 

1041 self, 

1042 X: Real[ArrayLike, 'm p'] | DataFrame, 

1043 *, 

1044 terms: Literal['all'] = 'all', 

1045 level: FloatLike = 0.95, 

1046 scale: Literal['linear', 'probability'] = 'linear', 

1047 ) -> dict[str, dict[str, Float32[Array, ' m']]]: ... 

1048 

1049 @overload 

1050 def compute_posterior_interval( 

1051 self, 

1052 X: Real[ArrayLike, 'm p'] | DataFrame, 

1053 *, 

1054 terms: Sequence[Literal['y_hat', 'mean_forest', 'all']], 

1055 level: FloatLike = 0.95, 

1056 scale: Literal['linear', 'probability'] = 'linear', 

1057 ) -> ( 

1058 dict[str, Float32[Array, ' m']] | dict[str, dict[str, Float32[Array, ' m']]] 

1059 ): ... 

1060 

1061 def compute_posterior_interval( 

1062 self, 

1063 X: Real[ArrayLike, 'm p'] | DataFrame, 

1064 *, 

1065 terms: Literal['y_hat', 'mean_forest', 'all'] 

1066 | Sequence[Literal['y_hat', 'mean_forest', 'all']] = 'all', 

1067 level: FloatLike = 0.95, 

1068 scale: Literal['linear', 'probability'] = 'linear', 

1069 ) -> dict[str, Float32[Array, ' m']] | dict[str, dict[str, Float32[Array, ' m']]]: 

1070 """Compute equal-tailed posterior credible intervals of the predictions. 

1071 

1072 Parameters 

1073 ---------- 

1074 X 

1075 Covariates with shape ``(m, p)``. 

1076 terms 

1077 Like in `predict`. 

1078 level 

1079 Posterior probability of the interval, between 0 and 1. 

1080 scale 

1081 ``'linear'``, or, for probit binary regression, ``'probability'`` 

1082 for intervals on ``Phi(eta)``. 

1083 

1084 Returns 

1085 ------- 

1086 A dict with keys ``'lower'`` and ``'upper'``, or, for multiple terms, a dict of such dicts keyed like the output of `predict`. 

1087 

1088 Raises 

1089 ------ 

1090 NotSampledError 

1091 If `sample` has not been called yet. 

1092 """ 

1093 if not self.sampled: 

1094 raise NotSampledError(not_sampled_msg(self)) 

1095 check_interval_scale(scale) 

1096 level = check_level(level) 

1097 return prediction_interval(self.predict(X, terms=terms, scale=scale), level) 

1098 

1099 @forbid_x64 

1100 def sample_posterior_predictive( 

1101 self, 

1102 X: Real[ArrayLike, 'm p'] | DataFrame, 

1103 *, 

1104 num_draws_per_sample: int | None = None, 

1105 ) -> ( 

1106 Real[Array, 'm num_samples'] | Real[Array, 'm num_samples num_draws_per_sample'] 

1107 ): 

1108 """Sample outcomes from the posterior predictive distribution. 

1109 

1110 Parameters 

1111 ---------- 

1112 X 

1113 Covariates with shape ``(m, p)``. 

1114 num_draws_per_sample 

1115 Number of draws per posterior sample. If `None`, it is 1 if 

1116 there are at least 1000 posterior samples, else enough to get at 

1117 least 1000 draws per observation. 

1118 

1119 Returns 

1120 ------- 

1121 The draws, with shape ``(m, num_samples)`` if there is one draw per sample, else ``(m, num_samples, num_draws_per_sample)``. 

1122 

1123 Raises 

1124 ------ 

1125 NotSampledError 

1126 If `sample` has not been called yet. 

1127 

1128 Notes 

1129 ----- 

1130 The draws are random, and change at each call. Their sequence is 

1131 determined by ``general_params['random_seed']``. 

1132 """ 

1133 if not self.sampled: 

1134 raise NotSampledError(not_sampled_msg(self)) 

1135 eta = self._predict_y_hat_internal(prepare_x(X, self._preprocessor).T) 

1136 return self._draw_outcomes(eta, num_draws_per_sample) 

1137 

1138 def has_term(self, term: Literal['mean_forest', 'y_hat', 'all']) -> bool: 

1139 """Return whether the model includes a term. 

1140 

1141 Parameters 

1142 ---------- 

1143 term 

1144 The term to check. 

1145 

1146 Returns 

1147 ------- 

1148 `True` for the terms in the signature, else `False`. 

1149 """ 

1150 return term in ('mean_forest', 'y_hat', 'all') 

1151 

1152 def extract_parameter( 

1153 self, 

1154 term: Literal[ 

1155 'sigma2', 

1156 'global_error_scale', 

1157 'sigma2_global', 

1158 'sigma2_leaf', 

1159 'leaf_scale', 

1160 'y_hat_train', 

1161 'y_hat_test', 

1162 ], 

1163 ) -> Float32[Array, ' num_samples'] | Float32[Array, 'n num_samples']: 

1164 """Return the posterior samples of a parameter by name. 

1165 

1166 Parameters 

1167 ---------- 

1168 term 

1169 ``'sigma2'`` (alias ``'global_error_scale'`` or 

1170 ``'sigma2_global'``) for `global_var_samples`, ``'sigma2_leaf'`` 

1171 (alias ``'leaf_scale'``) for `leaf_scale_samples`, 

1172 ``'y_hat_train'``, or ``'y_hat_test'``. 

1173 

1174 Returns 

1175 ------- 

1176 The samples, indexed by the last axis. 

1177 

1178 Raises 

1179 ------ 

1180 NotSampledError 

1181 If `sample` has not been called yet. 

1182 ValueError 

1183 If `term` is not valid or the model does not have it. 

1184 """ 

1185 if not self.sampled: 

1186 raise NotSampledError(not_sampled_msg(self)) 

1187 value, msg = self._extract(term, BART_PARAMETERS, 'BART') 

1188 if value is None: 

1189 raise ValueError(msg) 

1190 return value 

1191 

1192 def summary(self) -> None: 

1193 """Print a description of the model and summaries of its posterior samples. 

1194 

1195 Raises 

1196 ------ 

1197 NotSampledError 

1198 If `sample` has not been called yet. 

1199 """ 

1200 if not self.sampled: 

1201 raise NotSampledError(not_sampled_msg(self)) 

1202 out = f'BART Model Summary:\n-------------------\n{self}\n' 

1203 if self.global_var_samples is not None: 

1204 out += summarize_samples( 

1205 'Summary of sigma^2 posterior: ', 'samples', self.global_var_samples 

1206 ) 

1207 if self.leaf_scale_samples is not None: 

1208 out += summarize_samples( 

1209 'Summary of leaf scale posterior: ', 'samples', self.leaf_scale_samples 

1210 ) 

1211 out += summarize_predictions(self.y_hat_train, self.y_hat_test, 'predictions') 

1212 print(out) # noqa: T201 

1213 

1214 def _describe(self) -> str: 

1215 terms = ['mean forest'] 

1216 if self.sample_sigma2_global: 

1217 terms.append('global error variance model') 

1218 if self.sample_sigma2_leaf: 

1219 terms.append('mean forest leaf scale model') 

1220 link = 'with a probit link' if self.probit_outcome_model else 'as gaussian' 

1221 out = ( 

1222 f'BARTModel run with {join_terms(terms)}\nOutcome was modeled {link}' 

1223 ' with a constant leaf prior for the mean forest' 

1224 ) 

1225 if self.standardize: 1225 ↛ 1227line 1225 didn't jump to line 1227 because the condition on line 1225 was always true

1226 out += '\nOutcome was standardized' 

1227 return f'{out}\n{self._describe_sampler()}' 

1228 

1229 def _predict_y_hat_internal( 

1230 self, x: Real[ArrayLike, 'p m'] | Literal['train'] 

1231 ) -> Float32[Array, 'm num_samples']: 

1232 """Return predictions on the original outcome scale, layout ``(m, num_samples)``.""" 

1233 latent = self._bart.predict(x, kind=PredictKind.latent_samples) 

1234 return self._latent_to_y_hat(latent) 

1235 

1236 def _latent_to_y_hat( 

1237 self, latent: Float32[Array, 'num_samples m'] 

1238 ) -> Float32[Array, 'm num_samples']: 

1239 """Convert the predictions of `Bart` to the original outcome scale.""" 

1240 if self.probit_outcome_model: 

1241 # bartz integrates the binary offset into latent; result already on probit scale. 

1242 return latent.T 

1243 if self.standardize: 

1244 return (latent * self.y_std + self.y_bar).T 

1245 return latent.T 

1246 

1247 

1248def standardize_y( 

1249 y_train: Real[ArrayLike, ' n'], is_probit: bool, standardize: bool 

1250) -> tuple[Float32[Array, ''], Float32[Array, ''], Float32[Array, ' n']]: 

1251 """Return ``(y_bar, y_std, y_for_bartz)`` matching stochtree's standardization.""" 

1252 y = jnp.asarray(y_train, jnp.float32) 

1253 if is_probit: 

1254 return ndtri(y.mean()), jnp.float32(1.0), (y != 0).astype(jnp.float32) 

1255 if standardize: 

1256 y_bar = y.mean() 

1257 y_std_val = y.std() 

1258 y_std = jnp.where(y_std_val > 0, y_std_val, 1.0) 

1259 return y_bar, y_std, (y - y_bar) / y_std 

1260 return jnp.float32(0.0), jnp.float32(1.0), y 

1261 

1262 

1263def resolve_sigma2_leaf_init( 

1264 sigma2_leaf_init: FloatLike | None, 

1265 num_trees: int, 

1266 is_probit: bool, 

1267 var_resid_train: FloatLike, 

1268) -> FloatLike: 

1269 """Default `sigma2_leaf_init` per stochtree: probit→2/num_trees, continuous→var(resid)/num_trees.""" 

1270 if sigma2_leaf_init is not None: 

1271 return sigma2_leaf_init 

1272 if is_probit: 

1273 return 2.0 / num_trees 

1274 return var_resid_train / num_trees 

1275 

1276 

1277def resolve_leaf_variance_prior( 

1278 shape: FloatLike, 

1279 scale: FloatLike | None, 

1280 sigma2_leaf_init: FloatLike, 

1281 *, 

1282 num_trees: int, 

1283 is_probit: bool, 

1284 var_resid_train: FloatLike, 

1285) -> Wishart: 

1286 """Translate stochtree's leaf variance prior to a `Wishart` on the sum of trees precision. 

1287 

1288 Despite the documented ``IG(shape, scale)``, stochtree's sampler uses the 

1289 posterior ``IG(shape / 2 + L / 2, scale / 2 + S / 2)``, i.e., the prior is 

1290 ``IG(shape / 2, scale / 2)``, which is `Wishart` with ``nu = shape`` and 

1291 ``rate = scale`` on the leaf precision. The variance of the sum of trees is 

1292 `num_trees` times the one of a leaf, so its scale is too. 

1293 """ 

1294 if scale is None: 

1295 sum_scale = 1.0 if is_probit else var_resid_train 

1296 else: 

1297 sum_scale = num_trees * scale 

1298 return Wishart( 

1299 nu=shape, rate=sum_scale, value=jnp.reciprocal(num_trees * sigma2_leaf_init) 

1300 ) 

1301 

1302 

1303@jit 

1304def get_leaf_scale_samples(trace: MainTrace) -> Float32[Array, ' num_samples']: 

1305 """Return the leaf variance samples, chains concatenated.""" 

1306 # the trace has the precision of the sum of trees 

1307 *_, num_trees, _ = trace.split_tree.shape 

1308 prec = trace.sum_trees_prior_cov_inv * num_trees 

1309 if trace.has_chains: 

1310 prec = lax.collapse(prec, 0, 2) 

1311 return jnp.reciprocal(prec) 

1312 

1313 

1314def resolve_variance_prior( 

1315 shape: FloatLike, 

1316 scale: FloatLike, 

1317 sigma2_init: FloatLike | None, 

1318 var_resid_train: FloatLike, 

1319) -> tuple[Float32[Array, ''], Float32[Array, ''], Float32[Array, ''], FloatLike]: 

1320 """Translate stochtree's IG(shape, scale) prior to bartz's error variance prior. 

1321 

1322 The IG(shape, scale) prior on σ² is the scaled-inverse-χ² with 

1323 ``sigma_df = 2*shape`` and prior harmonic mean ``square(sigma_scale) = 

1324 scale/shape``; the chain starts at `sigma2_init` (default 

1325 ``var(resid_train)``), decoupled from the prior. The mapping is branchless so 

1326 `shape` / `scale` may be traced; the unrepresentable IG(0, scale>0) (positive 

1327 rate, zero df) yields a NaN that surfaces downstream rather than an error. 

1328 

1329 Parameters 

1330 ---------- 

1331 shape 

1332 Stochtree's ``sigma2_global_shape``. 

1333 scale 

1334 Stochtree's ``sigma2_global_scale``. 

1335 sigma2_init 

1336 Stochtree's ``sigma2_init``. If `None`, defaults to `var_resid_train`. 

1337 var_resid_train 

1338 Variance of the residual, the default chain start for σ². 

1339 

1340 Returns 

1341 ------- 

1342 sigma_df : Float32[Array, ''] 

1343 Degrees of freedom of bartz's error variance prior. 

1344 sigma_scale : Float32[Array, ''] 

1345 Scale of bartz's prior (sqrt of the prior harmonic mean of the variance). 

1346 sigma_init : Float32[Array, ''] 

1347 Initial error standard deviation seeding the chain. 

1348 sigma2_init_stored : FloatLike 

1349 The chain starting value of σ², suitable for ``BARTModel.sigma2_init``. 

1350 """ 

1351 shape = jnp.asarray(shape, jnp.float32) 

1352 scale = jnp.asarray(scale, jnp.float32) 

1353 sigma2_start = sigma2_init if sigma2_init is not None else var_resid_train 

1354 sigma_init = jnp.sqrt(jnp.asarray(sigma2_start, jnp.float32)) 

1355 # IG(shape, scale) <=> scaled-inv-chi2(df=2*shape, harmonic mean=scale/shape). 

1356 # The `scale > 0` guard keeps IG(0, 0) at harmonic mean 0 (avoiding 0/0) while 

1357 # letting IG(0, scale>0) overflow to inf -> NaN rate, flagging it as invalid. 

1358 harmonic_mean = jnp.where(scale > 0, scale / shape, 0.0) 

1359 return 2.0 * shape, jnp.sqrt(harmonic_mean), sigma_init, sigma2_start 

1360 

1361 

1362def check_variable_weights( 

1363 variable_weights: Float[ArrayLike, ' p'] | None, p: int 

1364) -> Float32[Array, ' p'] | None: 

1365 """Validate `variable_weights`, returning the jax array (or None).""" 

1366 if variable_weights is None: 

1367 return None 

1368 arr = jnp.asarray(variable_weights, jnp.float32) 

1369 if arr.shape != (p,): 1369 ↛ 1370line 1369 didn't jump to line 1370 because the condition on line 1369 was never true

1370 msg = f'variable_weights must have shape (p,)=({p},), got {arr.shape}' 

1371 raise ValueError(msg) 

1372 return arr 

1373 

1374 

1375def select_covariates( 

1376 cov: Covariates, 

1377 keep_vars: Sequence[str] 

1378 | Sequence[int] 

1379 | Shaped[np.ndarray, ' k_keep'] 

1380 | Integer[Array, ' k_keep'] 

1381 | Series 

1382 | None, 

1383 drop_vars: Sequence[str] 

1384 | Sequence[int] 

1385 | Shaped[np.ndarray, ' k_drop'] 

1386 | Integer[Array, ' k_drop'] 

1387 | Series 

1388 | None, 

1389) -> Float32[Array, ' p'] | None: 

1390 """Return the splitting weights, zeroed for the covariates excluded by `keep_vars` or `drop_vars`.""" 

1391 mask = covariate_mask(keep_vars, drop_vars, cov.columns, cov.num_original) 

1392 if mask is None: 

1393 return cov.variable_weights 

1394 else: 

1395 mask = mask[np.asarray(cov.original_var_indices)] 

1396 # like stochtree, exclude covariates by zeroing their weights, which 

1397 # are uniform over the original covariates by default 

1398 weights = ( 

1399 1.0 / cov.num_original 

1400 if cov.variable_weights is None 

1401 else cov.variable_weights 

1402 ) 

1403 return jnp.where(mask, weights, 0.0) 

1404 

1405 

1406def covariate_mask( 

1407 keep_vars: Sequence[str] 

1408 | Sequence[int] 

1409 | Shaped[np.ndarray, ' k_keep'] 

1410 | Integer[Array, ' k_keep'] 

1411 | Series 

1412 | None, 

1413 drop_vars: Sequence[str] 

1414 | Sequence[int] 

1415 | Shaped[np.ndarray, ' k_drop'] 

1416 | Integer[Array, ' k_drop'] 

1417 | Series 

1418 | None, 

1419 columns: Sequence[str] | None, 

1420 p: int, 

1421) -> Bool[Array, ' p'] | None: 

1422 """Mark the covariates the trees may split on, or return `None` if all.""" 

1423 if keep_vars is not None: 

1424 keep = covariate_indices(keep_vars, columns, p, 'keep_vars') 

1425 return jnp.zeros(p, bool).at[keep].set(True) 

1426 elif drop_vars is not None: 

1427 drop = covariate_indices(drop_vars, columns, p, 'drop_vars') 

1428 return jnp.ones(p, bool).at[drop].set(False) 

1429 else: 

1430 return None 

1431 

1432 

1433def covariate_indices( 

1434 covariates: Sequence[str] 

1435 | Sequence[int] 

1436 | Shaped[np.ndarray, ' k'] 

1437 | Integer[Array, ' k'] 

1438 | Series, 

1439 columns: Sequence[str] | None, 

1440 p: int, 

1441 name: str, 

1442) -> Integer[Array, ' k']: 

1443 """Convert covariate names or indices to indices, with friendly errors.""" 

1444 arr = covariates if isinstance(covariates, Array) else np.asarray(covariates) 

1445 if arr.ndim != 1: 

1446 msg = f'{name} must be a list or 1d array of covariate names or indices' 

1447 raise ValueError(msg) 

1448 

1449 if arr.size == 0: 

1450 indices = jnp.zeros(0, int) 

1451 elif arr.dtype.kind == 'U' or ( 

1452 arr.dtype.kind == 'O' and all(isinstance(c, str) for c in arr.tolist()) 

1453 ): 

1454 if columns is None: 

1455 msg = f'{name} may contain covariate names only if X_train is a dataframe' 

1456 raise ValueError(msg) 

1457 unknown = sorted(set(arr.tolist()) - set(columns)) 

1458 if unknown: 

1459 msg = f'{name} contains names not in X_train: {unknown}' 

1460 raise ValueError(msg) 

1461 indices = jnp.array([columns.index(c) for c in arr.tolist()]) 

1462 elif arr.dtype.kind in 'iu': 

1463 indices = jnp.asarray(arr) 

1464 else: 

1465 msg = f'{name} must contain covariate names or indices, got {arr.dtype}' 

1466 raise ValueError(msg) 

1467 

1468 out_of_range = jnp.any((indices < 0) | (indices >= p)) 

1469 return error_if(indices, out_of_range, f'{name} contains indices outside [0, {p})') 

1470 

1471 

1472def check_predict_args( 

1473 type_: Literal['posterior', 'mean'], 

1474 scale: Literal['linear', 'probability', 'class'], 

1475 terms: str | Sequence[str], 

1476 probit_outcome_model: bool, 

1477 valid_terms: Sequence[str], 

1478) -> tuple[str, ...]: 

1479 """Validate the arguments of `predict`, returning the normalized terms tuple.""" 

1480 if scale not in ('linear', 'probability', 'class'): 1480 ↛ 1481line 1480 didn't jump to line 1481 because the condition on line 1480 was never true

1481 msg = f"scale must be 'linear', 'probability', or 'class'; got {scale!r}" 

1482 raise ValueError(msg) 

1483 if type_ not in ('posterior', 'mean'): 1483 ↛ 1484line 1483 didn't jump to line 1484 because the condition on line 1483 was never true

1484 msg = f"type must be 'posterior' or 'mean'; got {type_!r}" 

1485 raise ValueError(msg) 

1486 if not probit_outcome_model and scale != 'linear': 

1487 msg = ( 

1488 "scale must be 'linear' for non-probit (continuous) regression;" 

1489 f' got {scale!r}' 

1490 ) 

1491 raise ValueError(msg) 

1492 if type_ == 'mean' and scale == 'class': 1492 ↛ 1493line 1492 didn't jump to line 1493 because the condition on line 1492 was never true

1493 msg = "scale='class' is incompatible with type='mean'" 

1494 raise ValueError(msg) 

1495 terms_tuple = (terms,) if isinstance(terms, str) else tuple(terms) 

1496 for t in terms_tuple: 

1497 if t not in valid_terms: 

1498 msg = f'unknown term {t!r}; valid terms are {", ".join(valid_terms)}' 

1499 raise ValueError(msg) 

1500 if scale == 'class' and set(terms_tuple) != {'y_hat'}: 

1501 # match stochtree: 'class' converts only the single 'y_hat' term, so it 

1502 # rejects 'mean_forest' and 'all' (the latter also pulls in mean_forest) 

1503 msg = "scale='class' is only supported when requesting a single 'y_hat' term" 

1504 raise ValueError(msg) 

1505 return terms_tuple 

1506 

1507 

1508def check_interval_scale(scale: str) -> None: 

1509 """Validate `scale` for the methods that do not support ``'class'``.""" 

1510 if scale not in ('linear', 'probability'): 

1511 msg = f"scale must be 'linear' or 'probability'; got {scale!r}" 

1512 raise ValueError(msg) 

1513 

1514 

1515@jit(static_argnames=('scale', 'type_')) 

1516def transform_prediction( 

1517 pred: Float32[Array, 'm num_samples'], 

1518 scale: Literal['linear', 'probability', 'class'], 

1519 type_: Literal['posterior', 'mean'], 

1520) -> Shaped[Array, 'm num_samples'] | Shaped[Array, ' m']: 

1521 """Convert the latent predictions to `scale` and average them if ``type_='mean'``.""" 

1522 if scale == 'probability': 

1523 pred = ndtr(pred) 

1524 elif scale == 'class': 

1525 pred = jnp.where(ndtr(pred) < 0.5, 0, 1) 

1526 if type_ == 'mean': 

1527 pred = jnp.mean(pred, axis=1) 

1528 return pred 

1529 

1530 

1531def requested_terms(terms: tuple[str, ...], keys: Mapping[str, str]) -> tuple[str, ...]: 

1532 """Map the requested terms to their output keys, in the order of `keys`.""" 

1533 return tuple(key for term, key in keys.items() if term in terms or 'all' in terms) 

1534 

1535 

1536def pack_terms( 

1537 values: Mapping[str, Shaped[Array, '*shape']], 

1538) -> Shaped[Array, '*shape'] | dict[str, Shaped[Array, '*shape']]: 

1539 """Return the only requested term as is, else a dict of all of them.""" 

1540 if len(values) == 1: 

1541 (value,) = values.values() 

1542 return value 

1543 else: 

1544 return dict(values) 

1545 

1546 

1547def check_level(level: FloatLike) -> Float32[Array, '']: 

1548 """Check the level of a posterior interval is in (0, 1).""" 

1549 level = jnp.asarray(level) 

1550 return error_if(level, ~((level > 0) & (level < 1)), 'level must be in (0, 1)') 

1551 

1552 

1553def prediction_interval( 

1554 pred: Float32[Array, 'm num_samples'] 

1555 | Mapping[str, Float32[Array, 'm num_samples']], 

1556 level: Float32[Array, ''], 

1557) -> dict[str, Float32[Array, ' m']] | dict[str, dict[str, Float32[Array, ' m']]]: 

1558 """Compute the posterior intervals of one or more predicted terms.""" 

1559 if isinstance(pred, Mapping): 

1560 # some terms are the same array under two names 

1561 distinct = {id(v): v for v in pred.values()} 

1562 intervals = {i: posterior_interval(v, level) for i, v in distinct.items()} 

1563 return {k: dict(intervals[id(v)]) for k, v in pred.items()} 

1564 else: 

1565 return posterior_interval(pred, level) 

1566 

1567 

1568@jit 

1569def posterior_interval( 

1570 samples: Float32[Array, 'm num_samples'], level: FloatLike 

1571) -> dict[str, Float32[Array, ' m']]: 

1572 """Compute the equal-tailed interval along the samples axis.""" 

1573 tail = (1 - level) / 2 

1574 lower, upper = jnp.quantile(samples, jnp.array([tail, 1 - tail]), axis=1) 

1575 return {'lower': lower, 'upper': upper} 

1576 

1577 

1578@jit(static_argnames='num_draws') 

1579def sample_outcome( 

1580 key: Key[Array, ''], 

1581 eta: Float32[Array, 'm num_samples'], 

1582 sigma2: Float32[Array, ' num_samples'] | None, 

1583 num_draws: int, 

1584) -> Real[Array, 'm num_samples'] | Real[Array, 'm num_samples num_draws']: 

1585 """Sample outcomes with mean `eta` and variance `sigma2`, or probit if `sigma2` is `None`.""" 

1586 noise = random.normal(key, (*eta.shape, num_draws)) 

1587 if sigma2 is None: 

1588 draws = jnp.where(eta[..., None] + noise > 0, 1, 0) 

1589 else: 

1590 draws = eta[..., None] + jnp.sqrt(sigma2)[:, None] * noise 

1591 if num_draws == 1: 

1592 return draws.squeeze(-1) 

1593 else: 

1594 return draws 

1595 

1596 

1597def summarize_samples(header: str, unit: str, x: Float32[Array, ' n']) -> str: 

1598 """Format the mean, standard deviation and quantiles of `x` like stochtree.""" 

1599 (n,) = x.shape 

1600 return ( 

1601 f'{header}{n} {unit}, mean = {x.mean().item():.3f}, standard deviation' 

1602 f' = {x.std().item():.3f}, quantiles:\n{quantile_lines(x)}' 

1603 ) 

1604 

1605 

1606def quantile_lines(x: Float32[Array, ' n']) -> str: 

1607 """Format the quantiles of `x` like stochtree, one per line.""" 

1608 probs = (0.025, 0.1, 0.25, 0.5, 0.75, 0.9, 0.975) 

1609 quantiles = jnp.quantile(x, jnp.array(probs)).tolist() 

1610 return ''.join( 

1611 f' {p * 100:5.1f}%: {q:.3f}\n' for p, q in zip(probs, quantiles, strict=True) 

1612 ) 

1613 

1614 

1615def summarize_predictions( 

1616 train: Float32[Array, 'n num_samples'], 

1617 test: Float32[Array, 'm num_samples'] | None, 

1618 what: str, 

1619) -> str: 

1620 """Summarize the posterior means at the training and test points like stochtree.""" 

1621 out = summarize_samples( 

1622 f'Summary of in-sample posterior mean {what}: \n', 

1623 'observations', 

1624 train.mean(axis=1), 

1625 ) 

1626 if test is not None: 1626 ↛ 1632line 1626 didn't jump to line 1632 because the condition on line 1626 was always true

1627 out += summarize_samples( 

1628 f'Summary of test-set posterior mean {what}: \n', 

1629 'observations', 

1630 test.mean(axis=1), 

1631 ) 

1632 return out 

1633 

1634 

1635def join_terms(terms: Sequence[str]) -> str: 

1636 """Join the descriptions of the terms of a model like stochtree.""" 

1637 if len(terms) > 2: 

1638 return f'{", ".join(terms[:-1])}, and {terms[-1]}' 

1639 else: 

1640 return ' and '.join(terms) 

1641 

1642 

1643def check_X( 

1644 X: Real[ArrayLike, 'n p'] | DataFrame, *, name: str = 'X' 

1645) -> Real[Array, 'n p']: 

1646 """Convert a DataFrame/array-like to a 2-D jax array in ``(n, p)`` layout.""" 

1647 df = to_narwhals(X) 

1648 if df is not None: 1648 ↛ 1649line 1648 didn't jump to line 1649 because the condition on line 1648 was never true

1649 X = df.to_numpy() 

1650 arr = jnp.asarray(X) 

1651 if arr.ndim == 1: 1651 ↛ 1652line 1651 didn't jump to line 1652 because the condition on line 1651 was never true

1652 arr = arr[:, None] 

1653 if arr.ndim != 2: 1653 ↛ 1654line 1653 didn't jump to line 1654 because the condition on line 1653 was never true

1654 msg = f'{name} must be 2D (n, p); got shape {arr.shape}' 

1655 raise ValueError(msg) 

1656 return arr 

1657 

1658 

1659def _coerce_response( 

1660 y: Real[ArrayLike, ' n'] | Series, *, name: str 

1661) -> Real[Array, ' n']: 

1662 """Convert a Series/array-like response to a 1-D jax array.""" 

1663 if isinstance(y, Series): 1663 ↛ 1664line 1663 didn't jump to line 1664 because the condition on line 1663 was never true

1664 y = y.to_numpy() 

1665 arr = jnp.asarray(y) 

1666 if arr.ndim != 1: 1666 ↛ 1667line 1666 didn't jump to line 1667 because the condition on line 1666 was never true

1667 msg = f'{name} must be 1D (n,); got shape {arr.shape}' 

1668 raise ValueError(msg) 

1669 return arr