Coverage for src/bartz/stochtree/_bcf.py: 97%

308 statements  

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

1# bartz/src/bartz/stochtree/_bcf.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 `BCFModel` that mimics the Python package stochtree.""" 

26 

27from collections.abc import Mapping, Sequence 

28from dataclasses import dataclass 

29from functools import partial 

30 

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

32from types import MappingProxyType 

33from typing import Any, Literal, overload 

34from warnings import warn 

35 

36from jax import numpy as jnp 

37from jax.scipy.special import ndtri 

38from jaxtyping import Array, Float, Float32, Real 

39 

40from bartz._interface import Series 

41from bartz._jaxext import forbid_x64, jit 

42from bartz.bcf import bcf 

43from bartz.bcf._bcf import any_not_binary, fold_chains 

44from bartz.mcmcstep._state import ArrayLike, FloatLike 

45from bartz.prepcovars import RangeEvenBinner 

46from bartz.stochtree._preprocess import DataFrame, Preprocessor 

47from bartz.stochtree._stochtree import ( 

48 BaseForestParams, 

49 BaseGeneralParams, 

50 BaseModel, 

51 Covariates, 

52 NotSampledError, 

53 _coerce_response, 

54 build_dataclass, 

55 check_interval_scale, 

56 check_level, 

57 check_predict_args, 

58 check_rows, 

59 fit_covariates, 

60 fixed_error_init_kw, 

61 get_leaf_scale_samples, 

62 join_terms, 

63 not_sampled_msg, 

64 pack_terms, 

65 prediction_interval, 

66 prepare_x, 

67 quantile_lines, 

68 random_keys, 

69 requested_terms, 

70 resolve_variance_prior, 

71 select_covariates, 

72 summarize_predictions, 

73 summarize_samples, 

74 transform_prediction, 

75 unsupported_sampler_args, 

76) 

77 

78PropensityCovariate = Literal['none', 'prognostic', 'treatment_effect', 'both'] 

79 

80 

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

82class BCFGeneralParams(BaseGeneralParams): 

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

84 

85 sigma2_global_init: FloatLike | None = None 

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

87 

88 propensity_covariate: PropensityCovariate = 'prognostic' 

89 """The forests that split on the propensity score, which then has splitting weight ``1 / p``, with ``p`` the number of columns of `X_train`. Unless ``'none'``, `propensity_train` is required.""" 

90 

91 adaptive_coding: bool = False 

92 """Whether to code the treatment as ``b_0 (1 - Z) + b_1 Z``, sampling ``b_0`` and ``b_1`` with independent priors ``N(0, 1/2)``, truncated to ``|b| >= 0.01``. Ignored if `Z_train` is constant.""" 

93 

94 control_coding_init: FloatLike = -0.5 

95 """Initial value of ``b_0`` with adaptive coding.""" 

96 

97 treated_coding_init: FloatLike = 0.5 

98 """Initial value of ``b_1`` with adaptive coding.""" 

99 

100 def __post_init__(self) -> None: 

101 if self.propensity_covariate not in ( 

102 'none', 

103 'prognostic', 

104 'treatment_effect', 

105 'both', 

106 ): 

107 msg = ( 

108 "propensity_covariate must be one of 'prognostic'," 

109 " 'treatment_effect', 'both', or 'none'" 

110 ) 

111 raise ValueError(msg) 

112 

113 

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

115class PrognosticForestParams(BaseForestParams): 

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

117 

118 num_trees: int = 250 

119 """Number of trees in the prognostic forest.""" 

120 

121 sigma2_leaf_init: FloatLike | None = None 

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

123 

124 sigma2_leaf_scale: FloatLike | None = None 

125 """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.""" 

126 

127 

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

129class TreatmentEffectForestParams(BaseForestParams): 

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

131 

132 num_trees: int = 100 

133 """Number of trees in the treatment effect forest.""" 

134 

135 alpha: FloatLike = 0.25 

136 """Tree split prior base.""" 

137 

138 beta: FloatLike = 3.0 

139 """Tree split prior decay.""" 

140 

141 max_depth: int = 5 

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

143 

144 sample_sigma2_leaf: bool = False 

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

146 

147 sigma2_leaf_init: FloatLike | None = None 

148 """Initial leaf variance. If `None`, matches stochtree's defaults of ``var(resid_train) / (2 * num_trees)`` for continuous and ``square(delta_max / (q * phi(0))) / num_trees`` for probit, with ``q = Phi^-1(0.84135) ≈ 1``.""" 

149 

150 sigma2_leaf_scale: FloatLike | None = None 

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

152 

153 delta_max: FloatLike = 0.9 

154 """Maximum plausible treatment effect on the probability scale, setting the default `sigma2_leaf_init` for probit.""" 

155 

156 sample_intercept: bool = True 

157 """Whether to sample a global treatment effect intercept ``tau_0``, included in the treatment effect.""" 

158 

159 tau_0_prior_var: FloatLike | None = None 

160 """Variance of the normal prior on ``tau_0``. If `None`, ``var(resid_train)``.""" 

161 

162 

163# the terms of `BCFModel.predict` and their keys in its output 

164BCF_TERMS: Mapping[str, str] = MappingProxyType( 

165 { 

166 'y_hat': 'y_hat', 

167 'mu': 'mu_hat', 

168 'tau': 'tau_hat', 

169 'prognostic_function': 'prognostic_function', 

170 'cate': 'cate', 

171 } 

172) 

173 

174# the terms of `BCFModel.extract_parameter`, their attributes and descriptions 

175BCF_PARAMETERS: Mapping[str, tuple[str, str]] = MappingProxyType( 

176 { 

177 **dict.fromkeys( 

178 ('sigma2', 'global_error_scale', 'sigma2_global'), 

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

180 ), 

181 **dict.fromkeys( 

182 ('sigma2_leaf_mu', 'leaf_scale_mu', 'mu_leaf_scale'), 

183 ( 

184 'leaf_scale_mu_samples', 

185 'prognostic forest leaf variance parameter samples', 

186 ), 

187 ), 

188 **dict.fromkeys( 

189 ('sigma2_leaf_tau', 'leaf_scale_tau', 'tau_leaf_scale'), 

190 ( 

191 'leaf_scale_tau_samples', 

192 'treatment effect forest leaf variance parameter samples', 

193 ), 

194 ), 

195 'adaptive_coding': ('_coding_samples', 'adaptive coding parameter samples'), 

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

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

198 **dict.fromkeys( 

199 ('tau_hat_train', 'cate_train'), 

200 ('tau_hat_train', 'in-sample treatment effect forest predictions'), 

201 ), 

202 **dict.fromkeys( 

203 ('tau_hat_test', 'cate_test'), 

204 ('tau_hat_test', 'test set treatment effect forest predictions'), 

205 ), 

206 **dict.fromkeys( 

207 ('mu_hat_train', 'prognostic_function_train'), 

208 ('mu_hat_train', 'in-sample prognostic function predictions'), 

209 ), 

210 **dict.fromkeys( 

211 ('mu_hat_test', 'prognostic_function_test'), 

212 ('mu_hat_test', 'test set prognostic function predictions'), 

213 ), 

214 **dict.fromkeys( 

215 ('tau_0', 'treatment_intercept', 'tau_intercept'), 

216 ('tau_0_samples', 'treatment effect intercept (tau_0) samples'), 

217 ), 

218 } 

219) 

220 

221BCFTerm = Literal['y_hat', 'mu', 'tau', 'prognostic_function', 'cate', 'all'] 

222 

223 

224class BCFModel(BaseModel): 

225 R""" 

226 Bayesian Causal Forests with a `stochtree`-compatible interface, powered by bartz. 

227 

228 This class mimics `stochtree.BCFModel` with `bartz.bcf.bcf`. Like for 

229 `BARTModel`, the `stochtree` defaults of 0 burnin and 100 saved MCMC 

230 iterations are best changed:: 

231 

232 m = BCFModel() 

233 m.sample(X, Z, y, pihat, num_gfr=0, num_burnin=1000, num_mcmc=1000) 

234 cate = m.predict(X_new, Z_new, pihat_new, terms='cate', type='mean') 

235 

236 See `BCFGeneralParams`, `PrognosticForestParams`, and 

237 `TreatmentEffectForestParams` for the supported keys in the 

238 ``general_params``, ``prognostic_forest_params``, and 

239 ``treatment_effect_forest_params`` dicts. 

240 

241 Notes 

242 ----- 

243 The differences from `stochtree` listed in `BARTModel` apply, and in 

244 addition: 

245 

246 - The treatment must be binary, coded as 0 / 1. 

247 - The propensity score is not estimated internally, so ``propensity_train`` 

248 is required unless ``general_params['propensity_covariate']`` is 

249 ``'none'``. 

250 - The prior of the adaptive coding weights is truncated to ``|b| >= 0.01``. 

251 - The output of `predict` contains only the requested terms. 

252 """ 

253 

254 p_x: int 

255 """Number of covariates after preprocessing, e.g., after one-hot encoding, excluding the propensity score.""" 

256 

257 treatment_dim: int 

258 """Number of treatment variables (always ``1``).""" 

259 

260 multivariate_treatment: bool 

261 """Whether there are multiple treatment variables (always ``False``).""" 

262 

263 binary_treatment: bool 

264 """Whether `Z_train` has both values 0 and 1.""" 

265 

266 adaptive_coding: bool 

267 """Whether adaptive coding was used.""" 

268 

269 propensity_covariate: PropensityCovariate 

270 """The forests that split on the propensity score.""" 

271 

272 internal_propensity_model: bool 

273 """Whether the propensity score was estimated internally (always ``False``).""" 

274 

275 sample_tau_0: bool 

276 """Whether the treatment effect intercept is sampled.""" 

277 

278 sample_sigma2_leaf_mu: bool 

279 """Whether the leaf variance of the prognostic forest is sampled.""" 

280 

281 sample_sigma2_leaf_tau: bool 

282 """Whether the leaf variance of the treatment effect forest is sampled.""" 

283 

284 leaf_scale_mu_samples: Float32[Array, ' num_samples'] | None 

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

286 

287 leaf_scale_tau_samples: Float32[Array, ' num_samples'] | None 

288 """Posterior samples of the leaf variance of the treatment effect forest, in the standardized outcome scale, or `None` if not sampled.""" 

289 

290 tau_0_samples: Float32[Array, '1 num_samples'] | None 

291 """Posterior samples of the treatment effect intercept, or `None` if not sampled.""" 

292 

293 b0_samples: Float32[Array, ' num_samples'] | None 

294 """Posterior samples of the coding weight of untreated units, or `None` without adaptive coding.""" 

295 

296 b1_samples: Float32[Array, ' num_samples'] | None 

297 """Posterior samples of the coding weight of treated units, or `None` without adaptive coding.""" 

298 

299 mu_hat_train: Float32[Array, 'n num_samples'] 

300 """Posterior samples of the prognostic function at the training points.""" 

301 

302 tau_hat_train: Float32[Array, 'n num_samples'] 

303 """Posterior samples of the treatment effect at the training points.""" 

304 

305 mu_hat_test: Float32[Array, 'm num_samples'] | None 

306 """Posterior samples of the prognostic function at the test points, or `None`.""" 

307 

308 tau_hat_test: Float32[Array, 'm num_samples'] | None 

309 """Posterior samples of the treatment effect at the test points, or `None`.""" 

310 

311 _bcf: bcf 

312 _coding_samples: Float32[Array, '2 num_samples'] | None 

313 

314 @forbid_x64 

315 def sample( 

316 self, 

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

318 Z_train: Real[ArrayLike, ' n'] | Series, 

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

320 propensity_train: Float[ArrayLike, ' n'] | Series | None = None, 

321 *, 

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

323 Z_test: Real[ArrayLike, ' m'] | Series | None = None, 

324 propensity_test: Float[ArrayLike, ' m'] | Series | None = None, 

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

326 num_gfr: int, 

327 num_burnin: int = 0, 

328 num_mcmc: int = 100, 

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

330 prognostic_forest_params: Mapping[str, Any] | None = None, 

331 treatment_effect_forest_params: Mapping[str, Any] | None = None, 

332 bcf_kwargs: Mapping[str, Any] = MappingProxyType({}), 

333 ) -> None: 

334 """Fit the model. 

335 

336 Parameters 

337 ---------- 

338 X_train 

339 Training covariates with shape ``(n, p)``, like in 

340 `BARTModel.sample`. 

341 Z_train 

342 Training treatment assignments of length ``n``, 0 or 1. 

343 y_train 

344 Training outcomes of length ``n``. 

345 propensity_train 

346 Training propensity scores of length ``n``. Required unless 

347 ``general_params['propensity_covariate']`` is ``'none'``, else 

348 ignored. 

349 X_test 

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

351 them in `mu_hat_test`, `tau_hat_test`, and `y_hat_test`. 

352 Z_test 

353 Test treatment assignments, required with `X_test`. 

354 propensity_test 

355 Test propensity scores, required with `X_test` if 

356 `propensity_train` is. 

357 observation_weights 

358 Not supported, must be `None`. 

359 num_gfr 

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

361 num_burnin 

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

363 num_mcmc 

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

365 to 1000. 

366 general_params 

367 Optional override for the keys of `BCFGeneralParams`. 

368 prognostic_forest_params 

369 Optional override for the keys of `PrognosticForestParams`. 

370 treatment_effect_forest_params 

371 Optional override for the keys of `TreatmentEffectForestParams`. 

372 bcf_kwargs 

373 Additional arguments forwarded to `bartz.bcf.bcf`. 

374 

375 Raises 

376 ------ 

377 NotImplementedError 

378 If ``num_gfr`` is non-zero, `observation_weights` is set, 

379 `Z_train` is not binary, or `propensity_train` is missing. 

380 

381 Notes 

382 ----- 

383 The signature mirrors `stochtree.BCFModel.sample`, restricted to the 

384 arguments bartz supports. This method invokes `bartz.bcf.bcf` under 

385 the hood. 

386 """ 

387 msg = unsupported_sampler_args(num_gfr, observation_weights) 

388 if msg is not None: 

389 raise NotImplementedError(msg) 

390 

391 gp = build_dataclass(BCFGeneralParams, general_params, 'general_params') 

392 pfp = build_dataclass( 

393 PrognosticForestParams, prognostic_forest_params, 'prognostic_forest_params' 

394 ) 

395 tfp = build_dataclass( 

396 TreatmentEffectForestParams, 

397 treatment_effect_forest_params, 

398 'treatment_effect_forest_params', 

399 ) 

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

401 use_propensity = gp.propensity_covariate != 'none' 

402 

403 cov = fit_covariates(X_train, gp.variable_weights) 

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

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

406 Z, binary_treatment = check_treatment(Z_train, cov.X) 

407 pihat = check_propensity(propensity_train, cov.X, use_propensity) 

408 if X_test is None: 

409 test = None 

410 else: 

411 test = prepare_inputs( 

412 X_test, 

413 Z_test, 

414 propensity_test, 

415 preprocessor=cov.preprocessor, 

416 use_propensity=use_propensity, 

417 suffix='_test', 

418 ) 

419 

420 adaptive_coding = gp.adaptive_coding 

421 if adaptive_coding and not binary_treatment: 

422 msg = ( 

423 'Adaptive coding is only compatible with binary (univariate)' 

424 ' treatment and, as a result, will be ignored in sampling this' 

425 ' model' 

426 ) 

427 warn(msg) 

428 adaptive_coding = False 

429 

430 sample_sigma2_global = gp.sample_sigma2_global and not is_probit 

431 prior_kw, sigma2_init = resolve_priors( 

432 gp, pfp, tfp, y, adaptive_coding=adaptive_coding 

433 ) 

434 keys = random_keys(gp.random_seed) 

435 

436 kwargs: dict = dict( 

437 x_train=cov.X, 

438 y_train=y.astype(jnp.float32), 

439 z_train=Z, 

440 pihat_train=pihat, 

441 include_pihat_in_mu=gp.propensity_covariate in ('prognostic', 'both'), 

442 include_pihat_in_tau=gp.propensity_covariate 

443 in ('treatment_effect', 'both'), 

444 num_trees_mu=pfp.num_trees, 

445 num_trees_tau=tfp.num_trees, 

446 ndpost=num_mcmc, 

447 nskip=num_burnin, 

448 keepevery=gp.keep_every, 

449 num_chains=None if gp.num_chains == 1 else gp.num_chains, 

450 **prior_kw, 

451 min_points_per_leaf_mu=pfp.min_samples_leaf, 

452 min_points_per_leaf_tau=tfp.min_samples_leaf, 

453 maxdepth_mu=pfp.max_depth, 

454 maxdepth_tau=tfp.max_depth, 

455 base_mu=pfp.alpha, 

456 power_mu=pfp.beta, 

457 base_tau=tfp.alpha, 

458 power_tau=tfp.beta, 

459 varprob_mu=forest_varprob(cov, pfp, use_propensity), 

460 varprob_tau=forest_varprob(cov, tfp, use_propensity), 

461 sample_intercept=tfp.sample_intercept, 

462 adaptive_coding=adaptive_coding, 

463 standardize=gp.standardize, 

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

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

466 printevery=None, 

467 seed=keys.pop(), 

468 ) 

469 kwargs = dict(kwargs, **bcf_kwargs) 

470 # user-supplied init_kw values win on conflicts 

471 kwargs = dict( 

472 kwargs, init_kw=dict(prior_kw['init_kw'], **bcf_kwargs.get('init_kw', {})) 

473 ) 

474 _bcf = bcf(**kwargs) 

475 

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

477 terms_test = None if test is None else predict_terms(_bcf, *test) 

478 

479 self._bcf = _bcf 

480 

481 # read the outcome scale back from `bcf`, which applied it 

482 y_bar = self._bcf.offset if is_probit else self._bcf._y_mean # noqa: SLF001 

483 n_train, p_x = cov.X.shape 

484 self._store_settings( 

485 preprocessor=cov.preprocessor, 

486 ppd_key=keys.pop(), 

487 outcome_model=gp.outcome_model, 

488 num_burnin=num_burnin, 

489 num_mcmc=num_mcmc, 

490 num_chains=gp.num_chains, 

491 keep_every=gp.keep_every, 

492 n_train=n_train, 

493 sample_sigma2_global=sample_sigma2_global, 

494 sigma2_init=sigma2_init, 

495 y_bar=y_bar, 

496 y_std=self._bcf._y_std, # noqa: SLF001 

497 standardize=gp.standardize, 

498 ) 

499 self.p_x = p_x 

500 self.treatment_dim = 1 

501 self.multivariate_treatment = False 

502 self.binary_treatment = binary_treatment 

503 self.adaptive_coding = adaptive_coding 

504 self.propensity_covariate = gp.propensity_covariate 

505 self.internal_propensity_model = False 

506 self.sample_tau_0 = tfp.sample_intercept 

507 self.sample_sigma2_leaf_mu = pfp.sample_sigma2_leaf 

508 self.sample_sigma2_leaf_tau = tfp.sample_sigma2_leaf 

509 self._store_outputs(cov, Z, pihat, terms_test) 

510 

511 def _store_outputs( 

512 self, 

513 cov: Covariates, 

514 Z: Real[Array, ' n'], 

515 pihat: Float[Array, ' n'] | None, 

516 terms_test: tuple[ 

517 Float32[Array, 'm num_samples'], 

518 Float32[Array, 'm num_samples'], 

519 Float32[Array, 'm num_samples'], 

520 ] 

521 | None, 

522 ) -> None: 

523 """Populate the public attributes with the outputs of the MCMC.""" 

524 self.mu_hat_train, self.tau_hat_train, self.y_hat_train = self._predict_terms( 

525 cov.X, Z, pihat 

526 ) 

527 if terms_test is None: 

528 self.mu_hat_test = self.tau_hat_test = self.y_hat_test = None 

529 self.n_test = 0 

530 else: 

531 self.mu_hat_test, self.tau_hat_test, self.y_hat_test = terms_test 

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

533 self.has_test = terms_test is not None 

534 

535 trace = self._bcf._main_trace # noqa: SLF001 

536 if self.sample_sigma2_global: 

537 self.global_var_samples = jnp.square(self._bcf.sigma_trace) 

538 else: 

539 self.global_var_samples = None 

540 if self.sample_sigma2_leaf_mu: 

541 self.leaf_scale_mu_samples = get_leaf_scale_samples(trace.mu) 

542 else: 

543 self.leaf_scale_mu_samples = None 

544 if self.sample_sigma2_leaf_tau: 544 ↛ 545line 544 didn't jump to line 545 because the condition on line 544 was never true

545 self.leaf_scale_tau_samples = get_leaf_scale_samples(trace.tau) 

546 else: 

547 self.leaf_scale_tau_samples = None 

548 if self.sample_tau_0: 548 ↛ 551line 548 didn't jump to line 551 because the condition on line 548 was always true

549 self.tau_0_samples = fold_chains(trace, 'tau_0')[None, :] * self.y_std 

550 else: 

551 self.tau_0_samples = None 

552 if self.adaptive_coding: 

553 self._coding_samples = fold_chains(trace, 'b').T 

554 self.b0_samples, self.b1_samples = self._coding_samples 

555 else: 

556 self._coding_samples = self.b0_samples = self.b1_samples = None 

557 

558 def _prepare_inputs( 

559 self, 

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

561 Z: Real[ArrayLike, ' m'] | Series | None, 

562 propensity: Float[ArrayLike, ' m'] | Series | None, 

563 *, 

564 suffix: str = '', 

565 ) -> tuple[Real[Array, 'm p'], Real[Array, ' m'], Float[Array, ' m'] | None]: 

566 """Validate the prediction inputs, named with `suffix`, and convert them to arrays.""" 

567 return prepare_inputs( 

568 X, 

569 Z, 

570 propensity, 

571 preprocessor=self._preprocessor, 

572 use_propensity=self.propensity_covariate != 'none', 

573 suffix=suffix, 

574 ) 

575 

576 def _predict_terms( 

577 self, 

578 X: Real[Array, 'm p'], 

579 Z: Real[Array, ' m'], 

580 pihat: Float[Array, ' m'] | None, 

581 *, 

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

583 type_: Literal['posterior', 'mean'] = 'posterior', 

584 ) -> tuple[ 

585 Float32[Array, 'm ...'], Float32[Array, 'm ...'], Float32[Array, 'm ...'] 

586 ]: 

587 """Return the prognostic function, the treatment effect, and the expected outcome, see `transform_prediction`.""" 

588 return predict_terms(self._bcf, X, Z, pihat, scale=scale, type_=type_) 

589 

590 @overload 

591 def predict( 

592 self, 

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

594 Z: Real[ArrayLike, ' m'] | Series, 

595 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

596 *, 

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

598 terms: Literal['y_hat', 'mu', 'tau', 'prognostic_function', 'cate'], 

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

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

601 

602 @overload 

603 def predict( 

604 self, 

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

606 Z: Real[ArrayLike, ' m'] | Series, 

607 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

608 *, 

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

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

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

612 ) -> ( 

613 dict[str, Float32[Array, 'm num_samples']] | dict[str, Float32[Array, ' m']] 

614 ): ... 

615 

616 @overload 

617 def predict( 

618 self, 

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

620 Z: Real[ArrayLike, ' m'] | Series, 

621 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

622 *, 

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

624 terms: Sequence[BCFTerm], 

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

626 ) -> ( 

627 Float32[Array, 'm num_samples'] 

628 | Float32[Array, ' m'] 

629 | dict[str, Float32[Array, 'm num_samples']] 

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

631 ): ... 

632 

633 @forbid_x64 

634 def predict( 

635 self, 

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

637 Z: Real[ArrayLike, ' m'] | Series, 

638 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

639 *, 

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

641 terms: BCFTerm | Sequence[BCFTerm] = 'all', 

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

643 ) -> ( 

644 Float32[Array, 'm num_samples'] 

645 | Float32[Array, ' m'] 

646 | dict[str, Float32[Array, 'm num_samples']] 

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

648 ): 

649 """Predict at new covariates and treatments. 

650 

651 Parameters 

652 ---------- 

653 X 

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

655 Z 

656 New treatment assignments of length ``m``. 

657 propensity 

658 New propensity scores of length ``m``, required if the model uses 

659 them, else ignored. 

660 type 

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

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

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

664 terms 

665 One of ``'y_hat'`` for the expected outcome ``mu + Z * tau``, 

666 ``'mu'`` or ``'prognostic_function'`` for the prognostic 

667 function, ``'tau'`` or ``'cate'`` for the treatment effect, 

668 ``'all'``, or a list. With adaptive coding, the prognostic 

669 function is the expected outcome at ``Z = 0``. 

670 scale 

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

672 to apply ``Phi`` to each term. 

673 

674 Returns 

675 ------- 

676 Either a single jax array (for a single requested term) or a dict keyed by ``'y_hat'``, ``'mu_hat'``, ``'tau_hat'``, ``'prognostic_function'``, ``'cate'``. 

677 

678 Raises 

679 ------ 

680 NotSampledError 

681 If `sample` has not been called yet. 

682 """ 

683 if not self.sampled: 

684 raise NotSampledError(not_sampled_msg(self)) 

685 check_interval_scale(scale) 

686 terms_tuple = check_predict_args( 

687 type, scale, terms, self.probit_outcome_model, (*BCF_TERMS, 'all') 

688 ) 

689 mu, tau, y_hat = self._predict_terms( 

690 *self._prepare_inputs(X, Z, propensity), scale=scale, type_=type 

691 ) 

692 values = { 

693 'y_hat': y_hat, 

694 'mu_hat': mu, 

695 'tau_hat': tau, 

696 'prognostic_function': mu, 

697 'cate': tau, 

698 } 

699 return pack_terms( 

700 {k: values[k] for k in requested_terms(terms_tuple, BCF_TERMS)} 

701 ) 

702 

703 def compute_contrast( # noqa: PLR0917, positional like in stochtree 

704 self, 

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

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

707 Z_0: Real[ArrayLike, ' m'] | Series, 

708 Z_1: Real[ArrayLike, ' m'] | Series, 

709 propensity_0: Float[ArrayLike, ' m'] | Series | None = None, 

710 propensity_1: Float[ArrayLike, ' m'] | Series | None = None, 

711 *, 

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

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

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

715 """Compute the difference between the predicted outcomes at `X_1`, `Z_1` and at `X_0`, `Z_0`. 

716 

717 Parameters 

718 ---------- 

719 X_0 

720 X_1 

721 Covariates of the subtracted and of the other predictions, with 

722 shape ``(m, p)``. 

723 Z_0 

724 Z_1 

725 Treatment assignments of the subtracted and of the other 

726 predictions, of length ``m``. 

727 propensity_0 

728 propensity_1 

729 Propensity scores of the subtracted and of the other predictions, 

730 required if the model uses them, else ignored. 

731 type 

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

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

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

735 scale 

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

737 to contrast ``Phi(y_hat)``. 

738 

739 Returns 

740 ------- 

741 The contrast ``predict(X_1, Z_1) - predict(X_0, Z_0)`` of ``'y_hat'``. 

742 

743 Raises 

744 ------ 

745 NotSampledError 

746 If `sample` has not been called yet. 

747 """ 

748 if not self.sampled: 

749 raise NotSampledError(not_sampled_msg(self)) 

750 check_interval_scale(scale) 

751 check_predict_args( 

752 type, scale, 'y_hat', self.probit_outcome_model, (*BCF_TERMS, 'all') 

753 ) 

754 args_1 = self._prepare_inputs(X_1, Z_1, propensity_1, suffix='_1') 

755 args_0 = self._prepare_inputs(X_0, Z_0, propensity_0, suffix='_0') 

756 *_, pred_1 = self._predict_terms(*args_1, scale=scale) 

757 *_, pred_0 = self._predict_terms(*args_0, scale=scale) 

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

759 

760 @overload 

761 def compute_posterior_interval( 

762 self, 

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

764 Z: Real[ArrayLike, ' m'] | Series, 

765 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

766 *, 

767 terms: Literal['y_hat', 'mu', 'tau', 'prognostic_function', 'cate'], 

768 level: FloatLike = 0.95, 

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

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

771 

772 @overload 

773 def compute_posterior_interval( 

774 self, 

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

776 Z: Real[ArrayLike, ' m'] | Series, 

777 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

778 *, 

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

780 level: FloatLike = 0.95, 

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

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

783 

784 @overload 

785 def compute_posterior_interval( 

786 self, 

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

788 Z: Real[ArrayLike, ' m'] | Series, 

789 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

790 *, 

791 terms: Sequence[BCFTerm], 

792 level: FloatLike = 0.95, 

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

794 ) -> ( 

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

796 ): ... 

797 

798 def compute_posterior_interval( 

799 self, 

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

801 Z: Real[ArrayLike, ' m'] | Series, 

802 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

803 *, 

804 terms: BCFTerm | Sequence[BCFTerm] = 'all', 

805 level: FloatLike = 0.95, 

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

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

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

809 

810 Parameters 

811 ---------- 

812 X 

813 Z 

814 propensity 

815 terms 

816 Like in `predict`. 

817 level 

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

819 scale 

820 Like in `predict`. 

821 

822 Returns 

823 ------- 

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

825 

826 Raises 

827 ------ 

828 NotSampledError 

829 If `sample` has not been called yet. 

830 """ 

831 if not self.sampled: 

832 raise NotSampledError(not_sampled_msg(self)) 

833 level = check_level(level) 

834 pred = self.predict(X, Z, propensity, terms=terms, scale=scale) 

835 return prediction_interval(pred, level) 

836 

837 @forbid_x64 

838 def sample_posterior_predictive( 

839 self, 

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

841 Z: Real[ArrayLike, ' m'] | Series, 

842 propensity: Float[ArrayLike, ' m'] | Series | None = None, 

843 *, 

844 num_draws_per_sample: int | None = None, 

845 ) -> ( 

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

847 ): 

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

849 

850 Parameters 

851 ---------- 

852 X 

853 Z 

854 propensity 

855 Like in `predict`. 

856 num_draws_per_sample 

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

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

859 least 1000 draws per observation. 

860 

861 Returns 

862 ------- 

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

864 

865 Raises 

866 ------ 

867 NotSampledError 

868 If `sample` has not been called yet. 

869 

870 Notes 

871 ----- 

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

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

874 """ 

875 if not self.sampled: 

876 raise NotSampledError(not_sampled_msg(self)) 

877 *_, y_hat = self._predict_terms(*self._prepare_inputs(X, Z, propensity)) 

878 return self._draw_outcomes(y_hat, num_draws_per_sample) 

879 

880 def has_term(self, term: BCFTerm) -> bool: 

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

882 

883 Parameters 

884 ---------- 

885 term 

886 The term to check. 

887 

888 Returns 

889 ------- 

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

891 """ 

892 return term in (*BCF_TERMS, 'all') 

893 

894 def extract_parameter( 

895 self, 

896 term: Literal[ 

897 'sigma2', 

898 'global_error_scale', 

899 'sigma2_global', 

900 'sigma2_leaf_mu', 

901 'leaf_scale_mu', 

902 'mu_leaf_scale', 

903 'sigma2_leaf_tau', 

904 'leaf_scale_tau', 

905 'tau_leaf_scale', 

906 'adaptive_coding', 

907 'y_hat_train', 

908 'y_hat_test', 

909 'tau_hat_train', 

910 'cate_train', 

911 'tau_hat_test', 

912 'cate_test', 

913 'mu_hat_train', 

914 'prognostic_function_train', 

915 'mu_hat_test', 

916 'prognostic_function_test', 

917 'tau_0', 

918 'treatment_intercept', 

919 'tau_intercept', 

920 ], 

921 ) -> Float32[Array, ' num_samples'] | Float32[Array, 'k num_samples']: 

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

923 

924 Parameters 

925 ---------- 

926 term 

927 The name of the parameter, see stochtree for the aliases. With 

928 ``'adaptive_coding'``, the coding weights of untreated and treated 

929 units are stacked along the first axis. 

930 

931 Returns 

932 ------- 

933 The samples, indexed by the last axis. 

934 

935 Raises 

936 ------ 

937 NotSampledError 

938 If `sample` has not been called yet. 

939 ValueError 

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

941 """ 

942 if not self.sampled: 

943 raise NotSampledError(not_sampled_msg(self)) 

944 value, msg = self._extract(term, BCF_PARAMETERS, 'BCF') 

945 if value is None: 

946 raise ValueError(msg) 

947 return value 

948 

949 def summary(self) -> None: 

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

951 

952 Raises 

953 ------ 

954 NotSampledError 

955 If `sample` has not been called yet. 

956 """ 

957 if not self.sampled: 

958 raise NotSampledError(not_sampled_msg(self)) 

959 out = f'BCF Model Summary:\n------------------\n{self}\n' 

960 if self.global_var_samples is not None: 

961 out += summarize_samples( 

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

963 ) 

964 if self.leaf_scale_mu_samples is not None: 964 ↛ 970line 964 didn't jump to line 970 because the condition on line 964 was always true

965 out += summarize_samples( 

966 'Summary of prognostic forest leaf scale posterior: ', 

967 'samples', 

968 self.leaf_scale_mu_samples, 

969 ) 

970 if self.leaf_scale_tau_samples is not None: 970 ↛ 971line 970 didn't jump to line 971 because the condition on line 970 was never true

971 out += summarize_samples( 

972 'Summary of treatment effect forest leaf scale posterior: ', 

973 'samples', 

974 self.leaf_scale_tau_samples, 

975 ) 

976 if self.b0_samples is not None and self.b1_samples is not None: 

977 out += ( 

978 'Summary of adaptive coding parameters: \n' 

979 f'{self.num_samples} samples, mean (control) =' 

980 f' {self.b0_samples.mean().item():.3f}, mean (treated) =' 

981 f' {self.b1_samples.mean().item():.3f}, standard deviation' 

982 f' (control) = {self.b0_samples.std().item():.3f}, standard' 

983 f' deviation (treated) = {self.b1_samples.std().item():.3f}\n' 

984 f'quantiles (control):\n{quantile_lines(self.b0_samples)}' 

985 f'\nquantiles (treated):\n{quantile_lines(self.b1_samples)}' 

986 ) 

987 if self.tau_0_samples is not None: 987 ↛ 993line 987 didn't jump to line 993 because the condition on line 987 was always true

988 out += summarize_samples( 

989 'Summary of treatment effect intercept (tau_0) posterior: ', 

990 'samples', 

991 self.tau_0_samples.squeeze(0), 

992 ) 

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

994 out += summarize_predictions(self.tau_hat_train, self.tau_hat_test, 'CATEs') 

995 print(out) # noqa: T201 

996 

997 def _describe(self) -> str: 

998 terms = ['prognostic forest', 'treatment effect forest'] 

999 if self.sample_sigma2_global: 

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

1001 if self.sample_sigma2_leaf_mu: 1001 ↛ 1003line 1001 didn't jump to line 1003 because the condition on line 1001 was always true

1002 terms.append('prognostic forest leaf scale model') 

1003 if self.sample_sigma2_leaf_tau: 1003 ↛ 1004line 1003 didn't jump to line 1004 because the condition on line 1003 was never true

1004 terms.append('treatment effect forest leaf scale model') 

1005 if self.sample_tau_0: 1005 ↛ 1007line 1005 didn't jump to line 1007 because the condition on line 1005 was always true

1006 terms.append('treatment effect intercept model') 

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

1008 out = f'BCFModel run with {join_terms(terms)}\nOutcome was modeled {link}' 

1009 if self.binary_treatment: 

1010 coding = 'adaptive coding' if self.adaptive_coding else 'default coding' 

1011 out += f'\nTreatment was binary and its effect was estimated with {coding}' 

1012 else: 

1013 out += '\nTreatment was univariate but not binary' 

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

1015 out += '\nOutcome was standardized' 

1016 if self.propensity_covariate == 'none': 

1017 out += '\nPropensity scores were not used in either forest of the model' 

1018 else: 

1019 out += '\nUser-provided propensity scores were included in the model' 

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

1021 

1022 

1023def prepare_inputs( 

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

1025 Z: Real[ArrayLike, ' m'] | Series | None, 

1026 propensity: Float[ArrayLike, ' m'] | Series | None, 

1027 *, 

1028 preprocessor: Preprocessor | None, 

1029 use_propensity: bool, 

1030 suffix: str = '', 

1031) -> tuple[Real[Array, 'm p'], Real[Array, ' m'], Float[Array, ' m'] | None]: 

1032 """Validate the prediction inputs, named with `suffix`, and convert them to arrays.""" 

1033 X_arr = prepare_x(X, preprocessor, name=f'X{suffix}') 

1034 if Z is None: 

1035 msg = f'Z{suffix} must be provided with X{suffix}' 

1036 raise ValueError(msg) 

1037 Z_arr = _coerce_response(Z, name=f'Z{suffix}') 

1038 check_rows(X_arr, Z_arr, f'Z{suffix}', f'X{suffix}') 

1039 if not use_propensity: 

1040 pihat = None 

1041 elif propensity is None: 

1042 msg = ( 

1043 f'propensity{suffix} must be provided, since the model uses' 

1044 ' propensity scores' 

1045 ) 

1046 raise ValueError(msg) 

1047 else: 

1048 pihat = _coerce_response(propensity, name=f'propensity{suffix}') 

1049 check_rows(X_arr, pihat, f'propensity{suffix}', f'X{suffix}') 

1050 return X_arr, Z_arr, pihat 

1051 

1052 

1053def check_treatment( 

1054 Z_train: Real[ArrayLike, ' n'] | Series, X: Real[Array, 'n p'] 

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

1056 """Check the treatment is binary, and return whether it has both values.""" 

1057 Z = _coerce_response(Z_train, name='Z_train').astype(jnp.float32) 

1058 check_rows(X, Z, 'Z_train') 

1059 if any_not_binary(Z): 

1060 msg = ( 

1061 'Z_train must be a binary treatment with values 0 and 1;' 

1062 ' continuous and multivariate treatments are not supported' 

1063 ) 

1064 raise NotImplementedError(msg) 

1065 return Z, jnp.unique(Z).size == 2 

1066 

1067 

1068def check_propensity( 

1069 propensity_train: Float[ArrayLike, ' n'] | Series | None, 

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

1071 use_propensity: bool, 

1072) -> Float[Array, ' n'] | None: 

1073 """Check the training propensity scores, returning them only if used.""" 

1074 if not use_propensity: 

1075 return None 

1076 elif propensity_train is None: 

1077 msg = ( 

1078 "propensity_train is required unless general_params['propensity_" 

1079 "covariate'] is 'none', because stochtree would estimate it with" 

1080 ' an internal grow-from-root BARTModel, which bartz does not support' 

1081 ) 

1082 raise NotImplementedError(msg) 

1083 else: 

1084 pihat = _coerce_response(propensity_train, name='propensity_train') 

1085 check_rows(X, pihat, 'propensity_train') 

1086 return pihat 

1087 

1088 

1089def resolve_priors( 

1090 gp: BCFGeneralParams, 

1091 pfp: PrognosticForestParams, 

1092 tfp: TreatmentEffectForestParams, 

1093 y: Real[Array, ' n'], 

1094 *, 

1095 adaptive_coding: bool, 

1096) -> tuple[dict[str, Any], FloatLike]: 

1097 """Translate stochtree's prior settings to the arguments of `bartz.bcf.bcf`. 

1098 

1099 Return the arguments, and the starting value of the error variance. 

1100 """ 

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

1102 

1103 # variance of stochtree's residual, which sets the default prior scales; 

1104 # with probit, the residual is y - mean(y) 

1105 var_resid = 1.0 if gp.standardize and not is_probit else jnp.var(y) 

1106 

1107 if is_probit: 

1108 # stochtree pins σ²=1 for probit, and bartz rejects explicit values 

1109 # of the error variance settings with binary outcomes 

1110 error_kw: dict = {} 

1111 sigma2_init: FloatLike = 1.0 

1112 mu_leaf = 1 / pfp.num_trees, 1 / pfp.num_trees 

1113 q = ndtri((0.6827 + 1) / 2) 

1114 tau_init = jnp.square(tfp.delta_max * jnp.sqrt(2 * jnp.pi) / q) 

1115 tau_leaf = tau_init / tfp.num_trees, 1 / (2 * tfp.num_trees) 

1116 else: 

1117 sigma_df, sigma_scale, sigma_init, sigma2_init = resolve_variance_prior( 

1118 gp.sigma2_global_shape, 

1119 gp.sigma2_global_scale, 

1120 gp.sigma2_global_init, 

1121 var_resid, 

1122 ) 

1123 error_kw = dict( 

1124 sigma_df=sigma_df, sigma_scale=sigma_scale, sigma_init=sigma_init 

1125 ) 

1126 mu_leaf = 2 * var_resid / pfp.num_trees, var_resid / pfp.num_trees 

1127 tau_leaf = (var_resid / (2 * tfp.num_trees),) * 2 

1128 

1129 init_kw = fixed_error_init_kw(gp.sample_sigma2_global or is_probit, sigma2_init) 

1130 if adaptive_coding: 

1131 init_kw = dict(init_kw, b_init=(gp.control_coding_init, gp.treated_coding_init)) 

1132 

1133 kw = dict( 

1134 **error_kw, 

1135 **leaf_prior_kw(pfp, *mu_leaf, 'mu'), 

1136 **leaf_prior_kw(tfp, *tau_leaf, 'tau'), 

1137 tau_0_prior_var=var_resid 

1138 if tfp.tau_0_prior_var is None 

1139 else tfp.tau_0_prior_var, 

1140 # stochtree centers the prognostic forest at 0 on the internal scale 

1141 # for continuous outcomes, while `bcf` defaults to the mean of the 

1142 # internal response, which is 0 only if standardized 

1143 offset=None if is_probit else 0.0, 

1144 init_kw=init_kw, 

1145 ) 

1146 return kw, sigma2_init 

1147 

1148 

1149def leaf_prior_kw( 

1150 params: BaseForestParams, 

1151 default_init: FloatLike, 

1152 default_scale: FloatLike, 

1153 suffix: Literal['mu', 'tau'], 

1154) -> dict[str, Any]: 

1155 """Translate stochtree's leaf variance settings to the arguments of `bartz.bcf.bcf`.""" 

1156 init = default_init if params.sigma2_leaf_init is None else params.sigma2_leaf_init 

1157 scale = ( 

1158 default_scale if params.sigma2_leaf_scale is None else params.sigma2_leaf_scale 

1159 ) 

1160 # despite the documented IG(shape, scale), stochtree's sampler uses 

1161 # IG(shape / 2, scale / 2), see `resolve_leaf_variance_prior` 

1162 return { 

1163 f'leaf_prior_cov_inv_{suffix}': jnp.reciprocal(init), 

1164 f'sample_sigma2_leaf_{suffix}': params.sample_sigma2_leaf, 

1165 f'sigma2_leaf_shape_{suffix}': params.sigma2_leaf_shape / 2, 

1166 f'sigma2_leaf_scale_{suffix}': scale / 2, 

1167 } 

1168 

1169 

1170def forest_varprob( 

1171 cov: Covariates, params: BaseForestParams, use_propensity: bool 

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

1173 """Return the splitting weights of a forest, with the propensity score last if used.""" 

1174 weights = select_covariates(cov, params.keep_vars, params.drop_vars) 

1175 if weights is None or not use_propensity: 

1176 return weights 

1177 else: 

1178 # like stochtree, weigh the propensity score as an original covariate 

1179 # with default weights; `bcf` excludes it from the forests not using it 

1180 return jnp.append(weights, 1.0 / cov.num_original) 

1181 

1182 

1183def predict_terms( 

1184 model: bcf, 

1185 X: Real[Array, 'm p'], 

1186 Z: Real[Array, ' m'], 

1187 pihat: Float[Array, ' m'] | None, 

1188 *, 

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

1190 type_: Literal['posterior', 'mean'] = 'posterior', 

1191) -> tuple[Float32[Array, 'm ...'], Float32[Array, 'm ...'], Float32[Array, 'm ...']]: 

1192 """Predict with `model` the terms returned by `combine_terms`.""" 

1193 pred = model.predict(X, pihat_test=pihat) 

1194 return combine_terms(pred['mu'], pred['tau'], Z, scale, type_) 

1195 

1196 

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

1198def combine_terms( 

1199 mu: Float32[Array, 'num_samples m'], 

1200 tau: Float32[Array, 'num_samples m'], 

1201 Z: Real[Array, ' m'], 

1202 scale: Literal['linear', 'probability'], 

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

1204) -> tuple[Float32[Array, 'm ...'], Float32[Array, 'm ...'], Float32[Array, 'm ...']]: 

1205 """Compute ``mu + Z * tau``, and convert the terms to stochtree's layout, see `transform_prediction`.""" 

1206 terms = mu, tau, mu + Z * tau 

1207 mu, tau, y_hat = (transform_prediction(t.T, scale, type_) for t in terms) 

1208 return mu, tau, y_hat