Coverage for src/bartz/BART/_gbart.py: 99%

176 statements  

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

1# bartz/src/bartz/BART/_gbart.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. 

24 

25"""Implement classes `mc_gbart` and `gbart` that mimic the R BART3 package.""" 

26 

27from collections.abc import Mapping 

28from functools import cached_property, partial 

29from types import MappingProxyType 

30from typing import Any, Literal 

31 

32import jax.numpy as jnp 

33from equinox import Module, field 

34from jax.scipy.special import ndtr 

35from jaxtyping import Array, Float, Float32, Int32, Key, Real, Shaped 

36 

37from bartz._interface import ( 

38 ArrayLike, 

39 Bart, 

40 DataFrame, 

41 FloatLike, 

42 PredictKind, 

43 Series, 

44 SparseConfig, 

45 _process_predictor_input, 

46 _process_response_input, 

47) 

48from bartz._jaxext import forbid_x64 

49from bartz._jaxext.scipy.stats import invgamma 

50from bartz.mcmcloop import BurninTrace, MainTrace 

51from bartz.mcmcstep._state import State 

52from bartz.prepcovars import GivenSplitsBinner, RangeEvenBinner, UniqueQuantileBinner 

53from bartz.prepcovars._prepcovars import _sigma2_from_ols 

54 

55 

56class mc_gbart(Module): 

57 R""" 

58 Nonparametric regression with Bayesian Additive Regression Trees (BART). 

59 

60 Regress `y_train` on `x_train` with a latent mean function represented as 

61 a sum of decision trees [2]_. The inference is carried out by sampling the 

62 posterior distribution of the tree ensemble with an MCMC. 

63 

64 Parameters 

65 ---------- 

66 x_train 

67 The training predictors. 

68 y_train 

69 The training responses. 

70 x_test 

71 The test predictors. 

72 type 

73 The type of regression. 'wbart' for continuous regression, 'pbart' for 

74 binary regression with probit link. 

75 sparse 

76 Whether to activate variable selection on the predictors as done in 

77 [1]_. 

78 theta 

79 a 

80 b 

81 rho 

82 Hyperparameters of the sparsity prior used for variable selection. 

83 

84 The prior distribution on the choice of predictor for each decision rule 

85 is 

86 

87 .. math:: 

88 (s_1, \ldots, s_p) \sim 

89 \operatorname{Dirichlet}(\mathtt{theta}/p, \ldots, \mathtt{theta}/p), 

90 

91 where p counts only the predictors with decision rules, as the others 

92 are ignored (see `rm_const`). If `theta` is not specified, it's a 

93 priori distributed according to 

94 

95 .. math:: 

96 \frac{\mathtt{theta}}{\mathtt{theta} + \mathtt{rho}} \sim 

97 \operatorname{Beta}(\mathtt{a}, \mathtt{b}). 

98 

99 If not specified, `rho` is set to the number of predictors p. To tune 

100 the prior, consider setting a lower `rho` to prefer more sparsity. 

101 If setting `theta` directly, it should be in the ballpark of p or lower 

102 as well. 

103 augment 

104 Whether to account exactly for the decision rules forbidden by the 

105 ancestors of each node when updating the variable selection 

106 probabilities, using data augmentation. Only relevant if ``sparse=True``. 

107 Like the ``augment`` option of R BART3, but sampling the exact full 

108 conditional rather than substituting expected counts. 

109 varprob 

110 The probability distribution over the `p` predictors for choosing a 

111 predictor to split on in a decision node a priori. It does not need to 

112 be normalized to sum to 1. A zero excludes a predictor. If not 

113 specified, use a uniform distribution. If ``sparse=True``, this is only 

114 the initial value for the MCMC, and must be > 0. 

115 xinfo 

116 A matrix with the cutpoins to use to bin each predictor. If not 

117 specified, it is generated automatically according to `usequants` and 

118 `numcut`. 

119 

120 Each row shall contain a sorted list of cutpoints for a predictor. If 

121 there are less cutpoints than the number of columns in the matrix, 

122 fill the remaining cells with NaN. 

123 

124 `xinfo` shall be a matrix even if `x_train` is a dataframe. 

125 usequants 

126 Whether to use predictors quantiles instead of a uniform grid to bin 

127 predictors. Ignored if `xinfo` is specified. 

128 rm_const 

129 How to treat predictors with no associated decision rules (i.e., there 

130 are no available cutpoints for that predictor). If `True` (default), 

131 they are ignored. If `False`, an error is raised if there are any, 

132 apart from those excluded by `varprob`. 

133 sigest 

134 An estimate of the residual standard deviation on `y_train`, used to set 

135 `lambda_`. If not specified, it is estimated by linear regression (with 

136 intercept, and without taking into account `w`). Ignored if `lambda_` is 

137 specified. 

138 sigdf 

139 The degrees of freedom of the scaled inverse-chisquared prior on the 

140 noise variance. 

141 sigquant 

142 The quantile of the prior on the noise variance that shall match 

143 `sigest` to set the scale of the prior. Ignored if `lambda_` is specified. 

144 k 

145 The inverse scale of the prior standard deviation on the latent mean 

146 function, relative to half the observed range of `y_train`. If `y_train` 

147 has less than two elements, `k` is ignored and the scale is set to 1. 

148 power 

149 base 

150 Parameters of the prior on tree node generation. The probability that a 

151 node at depth `d` (0-based) is non-terminal is ``base / (1 + d) ** 

152 power``. 

153 lambda_ 

154 The prior harmonic mean of the error variance. (The harmonic mean of x 

155 is 1/mean(1/x).) If not specified, it is set based on `sigest` and 

156 `sigquant`. 

157 tau_num 

158 The numerator in the expression that determines the prior standard 

159 deviation of leaves. If not specified, default to ``(max(y_train) - 

160 min(y_train)) / 2`` (or 1 if `y_train` has less than two elements) for 

161 continuous regression, and 3 for binary regression. 

162 offset 

163 The prior mean of the latent mean function. If not specified, it is set 

164 to the mean of `y_train` for continuous regression, and to 

165 ``Phi^-1(mean(y_train))`` for binary regression. If `y_train` is empty, 

166 `offset` is set to 0. With binary regression, if `y_train` is all 

167 `False` or `True`, it is set to ``Phi^-1(1/(n+1))`` or 

168 ``Phi^-1(n/(n+1))``, respectively. 

169 w 

170 Coefficients that rescale the error standard deviation on each 

171 datapoint. Not specifying `w` is equivalent to setting it to 1 for all 

172 datapoints. Note: `w` is ignored in the automatic determination of 

173 `sigest`, so either the weights should be O(1), or `sigest` should be 

174 specified by the user. Not supported with binary regression 

175 (``type='pbart'``). 

176 ntree 

177 The number of trees used to represent the latent mean function. By 

178 default 200 for continuous regression and 50 for binary regression. 

179 numcut 

180 If `usequants` is `False`: the exact number of cutpoints used to bin the 

181 predictors, ranging between the minimum and maximum observed values 

182 (excluded). 

183 

184 If `usequants` is `True`: the maximum number of cutpoints to use for 

185 binning the predictors. Each predictor is binned such that its 

186 distribution in `x_train` is approximately uniform across bins. The 

187 number of bins is at most the number of unique values appearing in 

188 `x_train`, or ``numcut + 1``. 

189 

190 Before running the algorithm, the predictors are compressed to the 

191 smallest integer type that fits the bin indices, so `numcut` is best set 

192 to the maximum value of an unsigned integer type, like 255. 

193 

194 Ignored if `xinfo` is specified. 

195 ndpost 

196 The number of MCMC samples to save, after burn-in. `ndpost` is the 

197 total number of samples across all chains. `ndpost` is rounded up to the 

198 first multiple of `mc_cores`. 

199 nskip 

200 The number of initial MCMC samples to discard as burn-in. This number 

201 of samples is discarded from each chain. 

202 keepevery 

203 The thinning factor for the MCMC samples, after burn-in. By default, 1 

204 for continuous regression and 10 for binary regression. 

205 printevery 

206 The number of iterations (including thinned-away ones) between each log 

207 line. Set to `None` to disable logging. ^C interrupts the MCMC only 

208 every `printevery` iterations, so with logging disabled it's impossible 

209 to kill the MCMC conveniently. 

210 mc_cores 

211 The number of independent MCMC chains. 

212 seed 

213 The seed for the random number generator. 

214 bart_kwargs 

215 Additional arguments passed to `bartz.Bart`. 

216 

217 Raises 

218 ------ 

219 ValueError 

220 If `w` is set with binary regression (``type='pbart'``). 

221 

222 Notes 

223 ----- 

224 This interface imitates the function ``mc_gbart`` from the R package `BART3 

225 <https://github.com/rsparapa/bnptools>`_, but with these differences: 

226 

227 - If ``usequants=False``, R BART3 switches to quantiles anyway if there are 

228 less predictor values than the required number of bins, while bartz 

229 always follows the specification. 

230 - Some functionality is missing. 

231 - The error variance parameter is called `lambda_` instead of `lambda`, 

232 since the latter is a reserved word in Python. 

233 - There are some additional attributes, and some missing. 

234 - The trees have a maximum depth of 5. 

235 - `rm_const` refers to predictors without decision rules instead of 

236 predictors that are constant in `x_train`. 

237 - If `rm_const=True` and some variables are dropped, the predictors 

238 matrix/dataframe passed to `predict` should still include them. 

239 

240 References 

241 ---------- 

242 .. [1] Linero, Antonio R. (2018). "Bayesian Regression Trees for 

243 High-Dimensional Prediction and Variable Selection". In: Journal of the 

244 American Statistical Association 113.522, pp. 626-636. 

245 .. [2] Hugh A. Chipman, Edward I. George, Robert E. McCulloch "BART: 

246 Bayesian additive regression trees," The Annals of Applied Statistics, 

247 Ann. Appl. Stat. 4(1), 266-298, (March 2010). 

248 """ 

249 

250 _bart: Bart 

251 _x_train_fmt: Any = field(static=True, default=None) 

252 _yhat_test: Float32[Array, 'ndpost m'] | None = None 

253 

254 sigest: Float32[Array, ''] | None = None 

255 """The estimated standard deviation of the error used to set `lambda_`.""" 

256 

257 @forbid_x64 

258 def __init__( 

259 self, 

260 x_train: Real[ArrayLike, 'n p'] | DataFrame, 

261 y_train: Float32[ArrayLike, ' n'] | Series, 

262 *, 

263 x_test: Real[ArrayLike, 'm p'] | DataFrame | None = None, 

264 type: Literal['wbart', 'pbart'] = 'wbart', # noqa: A002 

265 sparse: bool = False, 

266 theta: FloatLike | None = None, 

267 a: FloatLike = 0.5, 

268 b: FloatLike = 1.0, 

269 rho: FloatLike | None = None, 

270 augment: bool = False, 

271 varprob: Float[ArrayLike, ' p'] | None = None, 

272 xinfo: Float[ArrayLike, 'p ncut'] | None = None, 

273 usequants: bool = False, 

274 rm_const: bool = True, 

275 sigest: FloatLike | None = None, 

276 sigdf: FloatLike = 3.0, 

277 sigquant: FloatLike = 0.9, 

278 k: FloatLike = 2.0, 

279 power: FloatLike = 2.0, 

280 base: FloatLike = 0.95, 

281 lambda_: FloatLike | None = None, 

282 tau_num: FloatLike | None = None, 

283 offset: FloatLike | None = None, 

284 w: Float[ArrayLike, ' n'] | Series | None = None, 

285 ntree: int | None = None, 

286 numcut: int = 100, 

287 ndpost: int = 1000, 

288 nskip: int = 100, 

289 keepevery: int | None = None, 

290 printevery: int | None = 100, 

291 mc_cores: int = 2, 

292 seed: int | Key[Array, ''] = 0, 

293 bart_kwargs: Mapping = MappingProxyType({}), 

294 ) -> None: 

295 # BART3 does not support heteroskedastic probit 

296 if type == 'pbart' and w is not None: 

297 msg = ( 

298 "w is not supported with binary regression (type='pbart');" 

299 ' BART3 has no heteroskedastic probit.' 

300 ) 

301 raise ValueError(msg) 

302 

303 # set defaults that depend on type of regression 

304 if keepevery is None: 

305 keepevery = 10 if type == 'pbart' else 1 

306 if ntree is None: 

307 ntree = 50 if type == 'pbart' else 200 

308 

309 # pre-process the data to numeric arrays once, so the OLS estimate of 

310 # `sigest` and `Bart` share a single copy of the (memory-heavy) X matrix. 

311 # `Bart` records the format as plain arrays, so `predict` re-implements 

312 # the input-format consistency check against the original format here. 

313 x_train, self._x_train_fmt = _process_bart3_predictor_input(x_train) 

314 y_train = _process_response_input(y_train) 

315 

316 # map the BART3 error-variance settings to Bart's sigma prior, estimating 

317 # `sigest` by linear regression on x_train when needed 

318 sigma_kw, self.sigest = _resolve_sigma_prior( 

319 x_train, 

320 y_train, 

321 type=type, 

322 sigest=sigest, 

323 sigdf=sigdf, 

324 sigquant=sigquant, 

325 lambda_=lambda_, 

326 ) 

327 

328 # convert to per-chain n_save for Bart 

329 num_chains = None if mc_cores == 1 else mc_cores 

330 actual_num_chains = num_chains or 1 

331 n_save = ndpost // actual_num_chains + bool(ndpost % actual_num_chains) 

332 

333 # translate xinfo/usequants/numcut to a binner factory 

334 if xinfo is not None: 

335 binner = partial(GivenSplitsBinner, xinfo=jnp.asarray(xinfo)) 

336 elif usequants: 

337 binner = partial( 

338 UniqueQuantileBinner, max_bins=numcut + 1, max_subsample=None 

339 ) 

340 else: 

341 binner = partial(RangeEvenBinner, max_bins=numcut + 1) 

342 

343 # set most calling arguments for Bart 

344 kwargs: dict = dict( 

345 x_train=x_train, 

346 y_train=y_train, 

347 outcome_type=dict(wbart='continuous', pbart='binary')[type], 

348 sparse=SparseConfig( 

349 enabled=sparse, theta=theta, a=a, b=b, rho=rho, augment=augment 

350 ), 

351 varprob=varprob, 

352 binner=binner, 

353 rm_const=rm_const, 

354 **sigma_kw, 

355 k=k, 

356 power=power, 

357 base=base, 

358 tau_num=tau_num, 

359 offset=offset, 

360 error_scale=w, 

361 num_trees=ntree, 

362 n_save=n_save, 

363 n_burn=nskip, 

364 n_skip=keepevery, 

365 printevery=printevery, 

366 seed=seed, 

367 maxdepth=5, 

368 num_chains=num_chains, 

369 precompute_predict_train=True, 

370 ) 

371 

372 # default min_points_per_leaf to 5 (unless set by the user) to match 

373 # BART3's hard-coded nl>=5 && nr>=5 birth check. 

374 # min_points_per_decision_node keeps the Bart default of 10 

375 # (= 2 * min_points_per_leaf): it makes the proposal efficient by not 

376 # trying to grow leaves too small to split, without changing the target 

377 # posterior, which thus matches BART3. 

378 if 'min_points_per_leaf' not in bart_kwargs.get('init_kw', {}): 

379 bart_kwargs = dict( 

380 bart_kwargs, 

381 init_kw=dict(bart_kwargs.get('init_kw', {}), min_points_per_leaf=5), 

382 ) 

383 

384 # add user arguments 

385 kwargs.update(bart_kwargs) 

386 

387 # invoke Bart 

388 self._bart = Bart(**kwargs) 

389 

390 # predict at test points 

391 if x_test is not None: 391 ↛ exitline 391 didn't return from function '__init__' because the condition on line 391 was always true

392 self._yhat_test = self.predict(x_test) 

393 

394 # Public attributes from Bart 

395 

396 @property 

397 def ndpost(self) -> int: 

398 """The number of MCMC samples saved, after burn-in.""" 

399 return self._bart.ndpost 

400 

401 @property 

402 def offset(self) -> Float32[Array, '']: 

403 """The prior mean of the latent mean function.""" 

404 return self._bart.offset 

405 

406 # Private attributes from Bart 

407 

408 @property 

409 def _main_trace(self) -> MainTrace: 

410 return self._bart._main_trace # noqa: SLF001 

411 

412 @property 

413 def _burnin_trace(self) -> BurninTrace: 

414 return self._bart._burnin_trace # noqa: SLF001 

415 

416 @property 

417 def _mcmc_state(self) -> State: 

418 return self._bart._mcmc_state # noqa: SLF001 

419 

420 # Properties 

421 

422 @property 

423 def yhat_test(self) -> Float32[Array, 'ndpost m'] | None: 

424 """The conditional posterior mean at `x_test` for each MCMC iteration.""" 

425 return self._yhat_test 

426 

427 @cached_property 

428 def accept( 

429 self, 

430 ) -> ( 

431 Float32[Array, ' nskip_plus_ndpost'] 

432 | Float32[Array, 'nskip_plus_ndpost_per_core mc_cores'] 

433 ): 

434 """The fraction of trees with an accepted move, including burn-in samples. 

435 

436 Unlike BART3, the iterations thinned away by `keepevery` are not 

437 recorded. 

438 """ 

439 # `Bart.accept` is (mc_cores, samples) or (samples,); the public layout 

440 # is (samples, mc_cores), like `sigma` 

441 return self._bart.accept.T 

442 

443 @cached_property 

444 def prob_test(self) -> Float32[Array, 'ndpost m'] | None: 

445 """The posterior probability of y being True at `x_test` for each MCMC iteration.""" 

446 if self._yhat_test is None or self._mcmc_state.z is None: 

447 return None 

448 return ndtr(self._yhat_test) 

449 

450 @cached_property 

451 def prob_test_mean(self) -> Float32[Array, ' m'] | None: 

452 """The marginal posterior probability of y being True at `x_test`.""" 

453 if self.prob_test is None: 

454 return None 

455 return self.prob_test.mean(axis=0) 

456 

457 @cached_property 

458 def prob_train(self) -> Float32[Array, 'ndpost n'] | None: 

459 """The posterior probability of y being True at `x_train` for each MCMC iteration.""" 

460 if self._mcmc_state.z is not None: 

461 return ndtr(self.yhat_train) 

462 else: 

463 return None 

464 

465 @cached_property 

466 def prob_train_mean(self) -> Float32[Array, ' n'] | None: 

467 """The marginal posterior probability of y being True at `x_train`.""" 

468 if self.prob_train is None: 

469 return None 

470 else: 

471 return self.prob_train.mean(axis=0) 

472 

473 @cached_property 

474 def sigma( 

475 self, 

476 ) -> ( 

477 Float32[Array, ' nskip_plus_ndpost'] 

478 | Float32[Array, 'nskip_plus_ndpost_per_core mc_cores'] 

479 | None 

480 ): 

481 """The standard deviation of the error, including burn-in samples.""" 

482 if self._mcmc_state.z is not None: 

483 return None 

484 assert self._burnin_trace.error_cov_inv.ndim <= 2 # chains and samples 

485 # public output is (nskip+ndpost, mc_cores) = (samples, chains) 

486 prec = jnp.concatenate( 

487 [self._burnin_trace.error_cov_inv.T, self._main_trace.error_cov_inv.T] 

488 ) 

489 return jnp.sqrt(jnp.reciprocal(prec)) 

490 

491 @cached_property 

492 def sigma_(self) -> Float32[Array, 'ndpost'] | None: 

493 """The standard deviation of the error, only over the post-burnin samples and flattened.""" 

494 if self._mcmc_state.z is not None: 

495 return None 

496 assert self._main_trace.error_cov_inv.ndim <= 2 # chains and samples 

497 return jnp.sqrt(jnp.reciprocal(self._main_trace.error_cov_inv)).reshape(-1) 

498 

499 @cached_property 

500 def sigma_mean(self) -> Float32[Array, ''] | None: 

501 """The mean of `sigma`, only over the post-burnin samples.""" 

502 if self.sigma_ is None: 

503 return None 

504 return self.sigma_.mean() 

505 

506 @cached_property 

507 def varcount(self) -> Int32[Array, 'ndpost p']: 

508 """Histogram of predictor usage for decision rules in the trees.""" 

509 return self._bart.varcount 

510 

511 @cached_property 

512 def varcount_mean(self) -> Float32[Array, ' p']: 

513 """Average of `varcount` across MCMC iterations.""" 

514 return self._bart.varcount_mean 

515 

516 @cached_property 

517 def varprob(self) -> Float32[Array, 'ndpost p']: 

518 """Posterior samples of the probability of choosing each predictor for a decision rule.""" 

519 return self._bart.varprob 

520 

521 @cached_property 

522 def varprob_mean(self) -> Float32[Array, ' p']: 

523 """The marginal posterior probability of each predictor being chosen for a decision rule.""" 

524 return self._bart.varprob_mean 

525 

526 @cached_property 

527 def yhat_test_mean(self) -> Float32[Array, ' m'] | None: 

528 """The marginal posterior mean at `x_test`. 

529 

530 Not defined with binary regression because it's error-prone, typically 

531 the right thing to consider would be `prob_test_mean`. 

532 """ 

533 if self._yhat_test is None or self._mcmc_state.z is not None: 

534 return None 

535 return self._yhat_test.mean(axis=0) 

536 

537 @cached_property 

538 def yhat_train(self) -> Float32[Array, 'ndpost n']: 

539 """The conditional posterior mean at `x_train` for each MCMC iteration.""" 

540 return self._bart.predict('train', kind=PredictKind.latent_samples) 

541 

542 @cached_property 

543 def yhat_train_mean(self) -> Float32[Array, ' n'] | None: 

544 """The marginal posterior mean at `x_train`. 

545 

546 Not defined with binary regression because it's error-prone, typically 

547 the right thing to consider would be `prob_train_mean`. 

548 """ 

549 if self._mcmc_state.z is not None: 

550 return None 

551 else: 

552 return self.yhat_train.mean(axis=0) 

553 

554 # Public methods from Bart 

555 

556 @forbid_x64 

557 def predict( 

558 self, x_test: Real[ArrayLike, 'm p'] | DataFrame 

559 ) -> Float32[Array, 'ndpost m']: 

560 """ 

561 Evaluate the sum-of-trees at `x_test` for each MCMC iteration. 

562 

563 Parameters 

564 ---------- 

565 x_test 

566 The test predictors. 

567 

568 Returns 

569 ------- 

570 Posterior samples of the latent function value at `x_test`. In the continuous case, this is the conditional mean. 

571 

572 Raises 

573 ------ 

574 ValueError 

575 If `x_test` has a different format than `x_train`. 

576 """ 

577 # pre-process and check the format matches x_train; Bart only sees plain 

578 # arrays, so this consistency check is re-implemented here 

579 x_test, x_test_fmt = _process_bart3_predictor_input(x_test) 

580 if x_test_fmt != self._x_train_fmt: 

581 msg = ( 

582 f'Input format mismatch: {x_test_fmt=} ' 

583 f'!= x_train_fmt={self._x_train_fmt!r}' 

584 ) 

585 raise ValueError(msg) 

586 return self._bart.predict(x_test, kind=PredictKind.latent_samples) 

587 

588 

589class gbart(mc_gbart): 

590 """Subclass of `mc_gbart` that forces `mc_cores=1`.""" 

591 

592 def __init__(self, *args: Any, **kwargs: Any) -> None: 

593 if 'mc_cores' in kwargs: 

594 msg = "gbart.__init__() got an unexpected keyword argument 'mc_cores'" 

595 raise TypeError(msg) 

596 kwargs.update(mc_cores=1) 

597 super().__init__(*args, **kwargs) 

598 

599 

600def _process_bart3_predictor_input( 

601 x: Real[ArrayLike, 'n p'] | DataFrame, 

602) -> tuple[Shaped[Array, 'p n'], Any]: 

603 """Process BART3-style predictors (one predictor per column) to bartz layout. 

604 

605 Unlike `bartz.Bart`, BART3 lays out predictor matrices with one predictor 

606 per column, so plain arrays are transposed to bartz's (p, n) layout. 

607 Dataframes already use one column per predictor, so they are left untouched. 

608 """ 

609 if not isinstance(x, DataFrame): 

610 x = jnp.asarray(x).T 

611 return _process_predictor_input(x) 

612 

613 

614def _resolve_sigma_prior( 

615 x_train: Shaped[Array, 'p n'], 

616 y_train: Float32[Array, ' n'], 

617 *, 

618 type: Literal['wbart', 'pbart'], # noqa: A002 

619 sigest: FloatLike | None, 

620 sigdf: FloatLike, 

621 sigquant: FloatLike, 

622 lambda_: FloatLike | None, 

623) -> tuple[dict, Float32[Array, ''] | None]: 

624 """Map the BART3 error-variance settings to Bart's sigma prior. 

625 

626 Returns (sigma_kwargs, sigest) where sigest is the error standard deviation 

627 estimate, or None for binary regression or when `lambda_` is given. 

628 """ 

629 if type == 'pbart': 

630 if sigest is not None or lambda_ is not None: 

631 msg = 'Do not set `sigest` or `lambda_` for binary regression, they are ignored' 

632 raise ValueError(msg) 

633 return {}, None 

634 

635 if lambda_ is None: 

636 if sigest is None: 

637 sigest2 = _sigest2_ols(x_train, y_train) 

638 else: 

639 sigest2 = jnp.square(jnp.asarray(sigest, jnp.float32)) 

640 sigest_out = jnp.sqrt(sigest2) 

641 # lambda_ such that the sigquant quantile of the prior matches sigest² 

642 invchi2 = invgamma.ppf(sigquant, sigdf / 2) / 2 

643 lambda_ = sigest2 / (invchi2 * sigdf) 

644 else: 

645 if sigest is not None: 

646 msg = "Do not set `sigest` if `lambda_` is specified, it's ignored" 

647 raise ValueError(msg) 

648 lambda_ = jnp.asarray(lambda_, jnp.float32) 

649 sigest_out = None 

650 

651 # Bart's prior reduces to scaled-inv-χ²(sigma_df, sigma_scale²) on the error 

652 # variance, matching BART3's scaled-inv-χ²(sigdf, lambda_); sigma_init keeps 

653 # the initial precision at the prior mean nu/rate = 1 / lambda_ 

654 sigma_scale = jnp.sqrt(lambda_) 

655 sigma_kw = dict(sigma_df=sigdf, sigma_scale=sigma_scale, sigma_init=sigma_scale) 

656 return sigma_kw, sigest_out 

657 

658 

659def _sigest2_ols( 

660 x_train: Shaped[Array, 'p n'], y_train: Float32[Array, ' n'] 

661) -> Float32[Array, '']: 

662 """Estimate the error variance by OLS with intercept.""" 

663 p, n = x_train.shape 

664 if n <= p + 1: 

665 msg = ( 

666 f'cannot estimate `sigest` by OLS with {n} datapoints and {p} ' 

667 'predictors (it requires more datapoints than predictors plus one); ' 

668 'specify `sigest` or `lambda_` explicitly' 

669 ) 

670 raise ValueError(msg) 

671 return _sigma2_from_ols(x_train, y_train)