Coverage for src/bartz/bcf/_bcf.py: 99%
248 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
1# bartz/src/bartz/bcf/_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.
25"""Bayesian Causal Forests (BCF) interface."""
27from collections.abc import Mapping
28from operator import attrgetter
29from os import PathLike
30from types import MappingProxyType
31from typing import Any, Literal, NotRequired, TypedDict, cast
33import jax.numpy as jnp
34from equinox import Module, error_if, field
35from jax import lax, random
36from jax.scipy.special import ndtr
37from jaxtyping import Array, Bool, Float, Float32, Key, Real, Shaped, UInt
39from bartz._interface import (
40 ArrayLike,
41 DataFrame,
42 FloatLike,
43 Series,
44 _flatten_chain_sample,
45 _guarded_response_variance,
46 _process_error_variance_settings,
47 _process_leaf_variance_settings,
48 _process_offset_settings,
49 _process_predictor_input,
50 _process_response_input,
51 _run_mcmc,
52 any_nan,
53 apply_varprob,
54 check_length,
55 predict_latent,
56 raise_if_nan,
57 start_nan_check,
58)
59from bartz._jaxext import forbid_x64, is_key, jit, jit_active, split
60from bartz.bcf._state import BCFState, init_bcf
61from bartz.bcf._step import step_bcf
62from bartz.bcf._trace import BCFBurninTrace, BCFMainTrace
63from bartz.mcmcloop import MainTrace
64from bartz.mcmcloop._trace import Trace
65from bartz.mcmcstep import OutcomeType, Wishart, make_p_nonterminal
66from bartz.mcmcstep._axes import get_has_chains
67from bartz.npz import serializable
68from bartz.npz._npz import check_class, load_npz, save_npz
69from bartz.prepcovars import Binner, BinnerFactory, UniqueQuantileBinner
72def process_bcf_predictor_input(
73 x: Real[ArrayLike, 'n p'] | DataFrame,
74) -> tuple[Shaped[Array, 'p n'], Any]:
75 """Transpose predictors with one per column to the (p, n) layout, and get their format."""
76 if not isinstance(x, DataFrame):
77 x = jnp.asarray(x).T
78 x, fmt = _process_predictor_input(x)
79 raise_if_nan(start_nan_check(x))
80 return x, fmt
83def fold_chains(trace: Trace, path: str) -> Float32[Array, 'num_samples ...']:
84 """Fold the chain axis of a trace field into its sample axis, like `predict_latent`."""
85 arr = attrgetter(path)(trace)
86 return _flatten_chain_sample(arr, has_chains=get_has_chains(trace))
89@jit
90def any_not_binary(x: Float32[Array, ' n']) -> Bool[Array, '']:
91 """Check whether any value of `x` is neither 0 nor 1."""
92 return jnp.any((x != 0) & (x != 1))
95def check_binary(x: Float32[Array, ' n'], name: str) -> Float32[Array, ' n']:
96 """Check that the values of the variable `name` are all 0 or 1, outside of jit."""
97 if not jit_active() and any_not_binary(x):
98 msg = f'Values in `{name}` must be 0 or 1.'
99 raise ValueError(msg)
100 return x
103def stack_pihat(
104 x: Shaped[Array, 'p n'],
105 pihat: Float32[ArrayLike, ' n'] | Series,
106 which: Literal['train', 'test'],
107) -> Shaped[Array, 'p_plus_1 n']:
108 """Append `pihat_train` or `pihat_test` to the predictors as the last one."""
109 pihat = _process_response_input(pihat)
110 check_length(pihat, f'pihat_{which}', x, f'x_{which}')
111 if not jit_active() and any_nan(pihat):
112 msg = f'`pihat_{which}` contains NaN; missing values are not supported'
113 raise ValueError(msg)
114 return jnp.concatenate((x, pihat[None, :]))
117def make_sum_trees_prior_cov_inv(
118 value: FloatLike, sample: bool, shape: FloatLike, scale: FloatLike
119) -> Wishart:
120 """Bundle the precision of a sum of trees with its prior, if sampled.
122 `shape` and `scale` are the parameters of the inverse-gamma prior on the
123 variance of the sum of trees.
124 """
125 if sample:
126 return Wishart(nu=2 * shape, rate=2 * scale, value=value)
127 else:
128 return Wishart(nu=None, rate=None, value=value)
131class BCFPrediction(TypedDict):
132 """The posterior samples returned by `bcf.predict`, chains concatenated."""
134 mu: Float32[Array, 'num_samples m']
135 """The control mean, on the latent probit scale for binary outcomes."""
137 tau: Float32[Array, 'num_samples m']
138 """The treatment effect, on the latent probit scale for binary outcomes."""
140 tau_prob: NotRequired[Float32[Array, 'num_samples m']]
141 """The treatment effect on the probability scale, only for binary outcomes."""
143 p1: NotRequired[Float32[Array, 'num_samples m']]
144 """The probability of y being True if treated, only for binary outcomes."""
146 p0: NotRequired[Float32[Array, 'num_samples m']]
147 """The probability of y being True if untreated, only for binary outcomes."""
150class BCFPotentialOutcomes(BCFPrediction):
151 """
152 The posterior predictive samples returned by `bcf.predict_potential_outcomes`.
154 Also has all the fields of `BCFPrediction`.
155 """
157 y0: Float32[Array, 'num_samples m']
158 """The outcome if untreated."""
160 y1: Float32[Array, 'num_samples m']
161 """The outcome if treated."""
163 delta: Float32[Array, 'num_samples m']
164 """The individual treatment effect ``y1 - y0``."""
167@jit(static_argnames='probabilities')
168def predict(
169 x_test: UInt[Array, 'p_or_p_plus_1 m'],
170 trace: BCFMainTrace,
171 *,
172 y_mean: Float32[Array, ''],
173 y_std: Float32[Array, ''],
174 probabilities: bool,
175) -> BCFPrediction:
176 """Implement `bcf.predict` on the binned test predictors.
178 Return the probit outputs of binary models only if `probabilities`.
179 """
180 # Evaluate the sum-of-trees (both forests walk the same unified test matrix)
181 mu_latent = predict_latent(x_test, trace.mu)
182 tau_latent = predict_latent(x_test, trace.tau)
183 # fold the chains like `predict_latent` does to align the samples
184 tau_latent += fold_chains(trace, 'tau_0')[:, None]
186 b = fold_chains(trace, 'b')
187 b0_expanded = b[:, 0, None]
188 b1_expanded = b[:, 1, None]
189 # Control mean: mu(X) + b_0 * (tau(X) + tau_0)
190 mu_adjusted = mu_latent + b0_expanded * tau_latent
191 # Compute CATE via adaptive coding difference
192 cate = (b1_expanded - b0_expanded) * tau_latent
194 if probabilities:
195 p1 = ndtr(mu_latent + tau_latent * b1_expanded)
196 p0 = ndtr(mu_latent + tau_latent * b0_expanded)
197 return BCFPrediction(mu=mu_adjusted, tau=cate, tau_prob=p1 - p0, p1=p1, p0=p0)
198 else:
199 # y_mean and y_std are exactly 0 and 1 if the response is not
200 # standardized, which is always the case for binary outcomes
201 return BCFPrediction(mu=mu_adjusted * y_std + y_mean, tau=cate * y_std)
204@jit(static_argnums=(3,))
205def expected_outcome(
206 mu: Float32[Array, 'num_samples m'],
207 tau: Float32[Array, 'num_samples m'],
208 z: Bool[Array, ' m'],
209 probability: bool,
210 /,
211) -> Float32[Array, 'num_samples m']:
212 """Implement `bcf.yhat_test`, or `bcf.prob_test` if `probability`."""
213 yhat = mu + z * tau
214 if probability:
215 return ndtr(yhat)
216 else:
217 return yhat
220@jit
221def sigma_trace(
222 trace: MainTrace, y_std: Float32[Array, ''], /
223) -> Float32[Array, ' num_samples']:
224 """Implement `bcf.sigma_trace`, jitted such that folding the chains does not copy."""
225 # y_std is exactly 1 if the response is not standardized
226 return lax.rsqrt(fold_chains(trace, 'error_cov_inv')) * y_std
229@jit(static_argnames='binary')
230def sample_potential_outcomes(
231 key: Key[Array, ''],
232 mu: Float32[Array, 'num_samples m'],
233 tau: Float32[Array, 'num_samples m'],
234 *,
235 sigma: Float32[Array, ' num_samples'],
236 rho: Float32[Array, ''],
237 binary: bool,
238) -> tuple[
239 Float32[Array, 'num_samples m'],
240 Float32[Array, 'num_samples m'],
241 Float32[Array, 'num_samples m'],
242]:
243 """Implement the sampling of `bcf.predict_potential_outcomes`."""
244 u0, u1 = random.normal(key, (2, *mu.shape))
246 eps0 = sigma[:, None] * u0
247 # factored for accuracy at |rho| ~ 1
248 eps1 = sigma[:, None] * (rho * u0 + jnp.sqrt((1 - rho) * (1 + rho)) * u1)
250 y0 = mu + eps0
251 y1 = mu + tau + eps1
252 if binary:
253 y0 = (y0 > 0.0).astype(jnp.float32)
254 y1 = (y1 > 0.0).astype(jnp.float32)
255 delta = y1 - y0
256 else:
257 delta = tau + (eps1 - eps0)
258 return y0, y1, delta
261@serializable
262class bcf(Module):
263 R"""
264 Bayesian Causal Forests (BCF).
266 Regress `y_train` on `x_train` and `z_train` (treatment) with two latent
267 mean functions represented as sums of decision trees:
268 Y = mu(X, pihat) + tau(X, pihat) * Z + error
270 For continuous outcomes, the hyperparameters with units are on the scale
271 of the standardized response, see `standardize`, while the outputs are on
272 the scale of `y_train`.
274 Parameters
275 ----------
276 x_train
277 The training predictors (confounders/modifiers).
278 y_train
279 The training responses.
280 z_train
281 The binary treatment assignment (0 or 1).
282 pihat_train
283 The estimated propensity scores. If provided, appended to `x_train`.
284 x_test
285 The test predictors. If provided, predictions at these points are
286 computed and stored in `mu_test` and `tau_test`.
287 z_test
288 The test treatment assignment (0 or 1). If provided together with
289 `x_test`, the outcome prediction is stored in `yhat_test`.
290 pihat_test
291 The test propensity scores. Must be passed together with `pihat_train`.
292 include_pihat_in_mu
293 include_pihat_in_tau
294 Whether to include the propensity scores in the prognostic/treatment
295 effect forest.
296 num_trees_mu
297 num_trees_tau
298 The number of trees in the prognostic/treatment effect forest.
299 ndpost
300 The number of MCMC samples to save, after burn-in, per chain. The
301 posterior samples of all chains are concatenated, for a total of
302 ``num_chains * ndpost``.
303 nskip
304 The number of initial MCMC samples to discard as burn-in, per chain.
305 keepevery
306 The thinning factor for the MCMC samples, after burn-in.
307 num_chains
308 The number of independent MCMC chains. `None` for a single chain
309 without an explicit chain axis, which is equivalent to 1.
310 k_mu
311 k_tau
312 Prior parameter k of the prognostic/treatment effect forest.
313 sigma_df
314 Prior degrees of freedom for error variance.
315 sigma_scale
316 Prior scale of the error standard deviation.
317 sigma_init
318 Initial value of the error standard deviation.
319 leaf_prior_cov_inv_mu
320 leaf_prior_cov_inv_tau
321 Custom leaf prior precision of the prognostic/treatment effect forest.
322 min_points_per_leaf_mu
323 min_points_per_leaf_tau
324 The minimum number of data points per leaf in the prognostic/treatment
325 effect forest. Both forests count all units, untreated ones included.
326 maxdepth_mu
327 maxdepth_tau
328 The maximum depth of the trees in the prognostic/treatment effect
329 forest, with the root at depth 0.
330 base_mu
331 power_mu
332 base_tau
333 power_tau
334 Parameters of the prior on tree node generation in the
335 prognostic/treatment effect forest. The probability that a node at
336 depth `d` (0-based) is non-terminal is ``base / (1 + d) ** power``.
337 varprob_mu
338 varprob_tau
339 The probability distribution over the predictors for choosing one to
340 split on in the prognostic/treatment effect forest. It does not need
341 to be normalized; zero excludes a predictor from the forest. With
342 `pihat_train`, the last entry is the one of the propensity score. If
343 not specified, use a uniform distribution.
344 tau_0_prior_var
345 Prior variance for global intercept tau_0.
346 sample_intercept
347 Whether to sample a global treatment intercept `tau_0`.
348 adaptive_coding
349 Whether to use adaptive coding for the treatment effect, i.e., to
350 sample the coding weights of untreated and treated units. Their
351 priors are independent N(0, 1/2), truncated to ``|b| >= 0.01`` for
352 numerical accuracy.
353 sample_sigma2_leaf_mu
354 sample_sigma2_leaf_tau
355 Whether to sample the leaf variance of the prognostic/treatment effect
356 forest.
357 sigma2_leaf_shape_mu
358 sigma2_leaf_shape_tau
359 sigma2_leaf_scale_mu
360 sigma2_leaf_scale_tau
361 The shape and scale of the inverse gamma prior on the leaf variance of
362 the prognostic/treatment effect forest.
363 offset
364 The prior mean of the prognostic function, on the latent probit scale
365 for binary outcomes. If not specified, for continuous outcomes it is
366 set to the mean of `y_train` if `standardize` is `False`, and to 0 if
367 `standardize` is `True`, which are equivalent, since the standardized
368 `y_train` has mean 0. For binary outcomes, it is set to
369 ``Phi^-1(mean(y_train))``.
370 standardize
371 Whether to standardize `y_train` internally, ignored for binary
372 outcomes. If `False`, the hyperparameters with units (`sigma_scale`,
373 `sigma_init`, `leaf_prior_cov_inv_*`, `tau_0_prior_var`,
374 `sigma2_leaf_scale_*`, `offset`) are on the scale of `y_train` instead
375 of the standardized one.
376 outcome_type
377 Either 'continuous' or 'binary' (probit link).
378 delta_max
379 Maximum plausible treatment effect on the probability scale for binary probit models.
380 binner
381 A callable that, given the training predictors and a random key,
382 returns a `~bartz.prepcovars.Binner` instance, see `bartz.Bart`.
383 printevery
384 The number of iterations between each progress report, `None` to
385 disable reporting.
386 seed
387 The seed for the random number generator.
388 init_kw
389 Additional arguments passed to `init_bcf`, overriding the ones computed
390 from the other parameters.
392 Raises
393 ------
394 ValueError
395 If `z_train`, `z_test`, or `y_train` for binary outcomes, has values
396 other than 0 or 1, or if the format of `x_test` does not match
397 `x_train` format, or if `z_test` or `pihat_test` is passed without
398 `x_test`, or if only one of `pihat_train` and `pihat_test` is passed,
399 or if the length of `y_train`, `z_train` or `pihat_train` does not
400 match `x_train`, or the length of `z_test` or `pihat_test` does not
401 match `x_test`, or if `pihat_train` is passed but excluded from both
402 forests, or if `x_train`, `x_test`, `pihat_train` or `pihat_test`
403 contains NaN.
404 """
406 # `_mcmc_state` and `_burnin_trace` are `None` in models loaded from
407 # prediction-only archives
408 _mcmc_state: BCFState | None
409 _binner: Binner
410 _main_trace: BCFMainTrace
411 _burnin_trace: BCFBurninTrace | None
412 # WORKAROUND(jax<0.9.1): use `jax.tree.static` instead of `field(static=True)`
413 _x_train_fmt: Any = field(static=True)
414 _has_pihat: bool = field(static=True)
415 _outcome_type: str = field(static=True)
416 _y_mean: Float32[Array, '']
417 _y_std: Float32[Array, '']
418 _mu_test: Float32[Array, 'num_samples m'] | None = None
419 _tau_test: Float32[Array, 'num_samples m'] | None = None
420 _z_test: Bool[Array, ' m'] | None = None
422 @forbid_x64
423 def __init__( # noqa: C901, PLR0915
424 self,
425 x_train: Real[ArrayLike, 'n p'] | DataFrame,
426 y_train: Float32[ArrayLike, ' n'] | Series,
427 z_train: Float32[ArrayLike, ' n'] | Series,
428 *,
429 pihat_train: Float32[ArrayLike, ' n'] | Series | None = None,
430 x_test: Real[ArrayLike, 'm p'] | DataFrame | None = None,
431 z_test: Float32[ArrayLike, ' m'] | Series | None = None,
432 pihat_test: Float32[ArrayLike, ' m'] | Series | None = None,
433 include_pihat_in_mu: bool = True,
434 include_pihat_in_tau: bool = False,
435 num_trees_mu: int = 250,
436 num_trees_tau: int = 100,
437 ndpost: int = 1000,
438 nskip: int = 100,
439 keepevery: int = 1,
440 num_chains: int | None = None,
441 k_mu: FloatLike = 2.0,
442 k_tau: FloatLike = 10.0,
443 sigma_df: FloatLike = 3.0,
444 sigma_scale: FloatLike | Literal['auto'] = 'auto',
445 sigma_init: FloatLike | Literal['auto'] = 'auto',
446 leaf_prior_cov_inv_mu: FloatLike | None = None,
447 leaf_prior_cov_inv_tau: FloatLike | None = None,
448 min_points_per_leaf_mu: int = 5,
449 min_points_per_leaf_tau: int = 5,
450 maxdepth_mu: int = 5,
451 maxdepth_tau: int = 5,
452 base_mu: FloatLike = 0.95,
453 power_mu: FloatLike = 2.0,
454 base_tau: FloatLike = 0.25,
455 power_tau: FloatLike = 3.0,
456 varprob_mu: Float[ArrayLike, ' p_or_p_plus_1'] | None = None,
457 varprob_tau: Float[ArrayLike, ' p_or_p_plus_1'] | None = None,
458 tau_0_prior_var: FloatLike | None = None,
459 sample_intercept: bool = True,
460 adaptive_coding: bool = False,
461 sample_sigma2_leaf_mu: bool = True,
462 sample_sigma2_leaf_tau: bool = False,
463 sigma2_leaf_shape_mu: FloatLike = 3.0,
464 sigma2_leaf_shape_tau: FloatLike = 3.0,
465 sigma2_leaf_scale_mu: FloatLike | None = None,
466 sigma2_leaf_scale_tau: FloatLike | None = None,
467 offset: FloatLike | None = None,
468 standardize: bool = True,
469 outcome_type: Literal['continuous', 'binary'] = 'continuous',
470 delta_max: FloatLike = 0.9,
471 binner: BinnerFactory = UniqueQuantileBinner,
472 printevery: int | None = 100,
473 seed: int | Key[Array, ''] = 0,
474 init_kw: Mapping[str, Any] = MappingProxyType({}),
475 ) -> None:
477 # 1. Pre-process the data (convert to arrays and transpose X to (p, n))
478 x_train, self._x_train_fmt = process_bcf_predictor_input(x_train)
479 y_train = _process_response_input(y_train)
480 check_length(y_train, 'y_train', x_train, 'x_train')
481 z_train = _process_response_input(z_train)
482 check_length(z_train, 'z_train', x_train, 'x_train')
483 z_train = check_binary(z_train, 'z_train').astype(bool)
485 self._outcome_type = outcome_type
487 if outcome_type == 'binary':
488 y_train = check_binary(y_train, 'y_train')
489 standardize = False
491 if standardize:
492 y_mean = jnp.mean(y_train)
493 y_std = jnp.std(y_train)
494 y_std = jnp.where(y_std == 0, 1.0, y_std)
495 y_train_internal = (y_train - y_mean) / y_std
496 else:
497 y_mean = jnp.float32(0.0)
498 y_std = jnp.float32(1.0)
499 y_train_internal = y_train
501 self._y_mean = y_mean
502 self._y_std = y_std
504 if pihat_train is not None:
505 if not include_pihat_in_mu and not include_pihat_in_tau:
506 msg = (
507 '`pihat_train` is unused if `include_pihat_in_mu` and'
508 ' `include_pihat_in_tau` are both False.'
509 )
510 raise ValueError(msg)
511 x_train = stack_pihat(x_train, pihat_train, 'train')
512 self._has_pihat = pihat_train is not None
514 if x_test is None:
515 if z_test is not None or pihat_test is not None:
516 msg = '`z_test` and `pihat_test` require `x_test`.'
517 raise ValueError(msg)
518 else:
519 x_test = self._process_x_test(x_test, pihat_test)
520 if z_test is not None: 520 ↛ 526line 520 didn't jump to line 526 because the condition on line 520 was always true
521 z_test = _process_response_input(z_test)
522 check_length(z_test, 'z_test', x_test, 'x_test')
523 z_test = check_binary(z_test, 'z_test').astype(bool)
525 # 3. Resolve priors for both mu and tau forests
526 binary_mask = (
527 jnp.ones((), dtype=bool)
528 if outcome_type == 'binary'
529 else jnp.zeros((), dtype=bool)
530 )
532 offset = _process_offset_settings(
533 y_train_internal,
534 binary_mask,
535 None,
536 None if offset is None else jnp.asarray(offset, jnp.float32),
537 )
539 # the precision of a sum of trees is the one of a leaf over the trees
540 if leaf_prior_cov_inv_mu is not None:
541 sum_trees_prior_cov_inv_mu = leaf_prior_cov_inv_mu / num_trees_mu
542 elif outcome_type == 'binary':
543 sum_trees_prior_cov_inv_mu = 1.0
544 else:
545 sum_trees_prior_cov_inv_mu = _process_leaf_variance_settings(
546 y_train_internal,
547 binary_mask,
548 missing=None,
549 k=jnp.array(k_mu),
550 tau_num=None,
551 sigma_mu_df=None,
552 ).value
554 if leaf_prior_cov_inv_tau is not None:
555 sum_trees_prior_cov_inv_tau = leaf_prior_cov_inv_tau / num_trees_tau
556 elif outcome_type == 'binary':
557 # give the treatment effect the prior sd delta_max / phi(0) on
558 # the latent scale, the effect that moves the probability by
559 # delta_max from 1/2 under the linear approximation of the
560 # probit there
561 sum_trees_prior_cov_inv_tau = jnp.reciprocal(
562 2 * jnp.pi * jnp.square(delta_max)
563 )
564 else:
565 sum_trees_prior_cov_inv_tau = _process_leaf_variance_settings(
566 y_train_internal,
567 binary_mask,
568 missing=None,
569 k=jnp.array(k_tau),
570 tau_num=None,
571 sigma_mu_df=None,
572 ).value
574 error_cov_inv = _process_error_variance_settings(
575 y_train_internal,
576 binary_mask,
577 None,
578 outcome_type=OutcomeType(outcome_type),
579 sigma_df=sigma_df,
580 sigma_scale=sigma_scale,
581 sigma_init=sigma_init,
582 error_scale=None,
583 )
585 p_nonterminal_mu = make_p_nonterminal(maxdepth_mu, base_mu, power_mu)
586 p_nonterminal_tau = make_p_nonterminal(maxdepth_tau, base_tau, power_tau)
588 if outcome_type == 'binary':
589 var_y = 1.0
590 else:
591 var_y = _guarded_response_variance(y_train_internal, None, None)
592 # the variance of a sum of trees is the one of a leaf times the trees
593 if sigma2_leaf_scale_mu is None:
594 sum_trees_scale_mu = var_y
595 else:
596 sum_trees_scale_mu = sigma2_leaf_scale_mu * num_trees_mu
597 if sigma2_leaf_scale_tau is None:
598 sum_trees_scale_tau = 0.5 * var_y
599 else:
600 sum_trees_scale_tau = sigma2_leaf_scale_tau * num_trees_tau
602 # 3.5 Bin the unified data
603 rng = seed if is_key(seed) else random.key(seed)
604 keys = split(rng)
606 binner_obj = binner(x_train, key=keys.pop())
607 x_train_binned = binner_obj.bin(x_train)
608 # copies because `init_bcf` may donate them
609 max_split_mu, log_s_mu = apply_varprob(
610 varprob_mu, jnp.copy(binner_obj.max_split), 'varprob_mu'
611 )
612 max_split_tau, log_s_tau = apply_varprob(
613 varprob_tau, jnp.copy(binner_obj.max_split), 'varprob_tau'
614 )
616 # pihat is the last predictor
617 if self._has_pihat:
618 if not include_pihat_in_mu:
619 max_split_mu = max_split_mu.at[-1].set(0)
620 if not include_pihat_in_tau:
621 max_split_tau = max_split_tau.at[-1].set(0)
623 # 4. Initialize BCFState
624 init_bcf_kw: dict = dict(
625 X_unified=x_train_binned,
626 trt=z_train,
627 y=y_train_internal,
628 outcome_type=outcome_type,
629 offset=offset,
630 max_split_mu=max_split_mu,
631 max_split_tau=max_split_tau,
632 num_trees_mu=num_trees_mu,
633 num_trees_tau=num_trees_tau,
634 p_nonterminal_mu=p_nonterminal_mu,
635 p_nonterminal_tau=p_nonterminal_tau,
636 sum_trees_prior_cov_inv_mu=make_sum_trees_prior_cov_inv(
637 sum_trees_prior_cov_inv_mu,
638 sample_sigma2_leaf_mu,
639 sigma2_leaf_shape_mu,
640 sum_trees_scale_mu,
641 ),
642 sum_trees_prior_cov_inv_tau=make_sum_trees_prior_cov_inv(
643 sum_trees_prior_cov_inv_tau,
644 sample_sigma2_leaf_tau,
645 sigma2_leaf_shape_tau,
646 sum_trees_scale_tau,
647 ),
648 min_points_per_leaf_mu=min_points_per_leaf_mu,
649 min_points_per_leaf_tau=min_points_per_leaf_tau,
650 # ignore all predictors without splits, like `Bart(..., rm_const=True)`
651 filter_splitless_vars_mu=jnp.sum(max_split_mu == 0).item(),
652 filter_splitless_vars_tau=jnp.sum(max_split_tau == 0).item(),
653 log_s_mu=log_s_mu,
654 log_s_tau=log_s_tau,
655 tau_0_prior_var=tau_0_prior_var,
656 sample_intercept=sample_intercept,
657 adaptive_coding=adaptive_coding,
658 error_cov_inv=error_cov_inv,
659 num_chains=num_chains,
660 )
661 initial_state = init_bcf(**dict(init_bcf_kw, **init_kw))
663 # 5. Run the MCMC loop
664 # WORKAROUND(python<3.12): once `run_mcmc` is generic over the state
665 # subclass (PEP 695), the state and the traces will come out typed,
666 # dropping the casts.
667 result = _run_mcmc(
668 mcmc_state=initial_state,
669 n_save=ndpost,
670 n_burn=nskip,
671 n_skip=keepevery,
672 printevery=printevery,
673 pbar=True,
674 key=keys.pop(),
675 precompute_predict_train=False,
676 run_mcmc_kw=dict(
677 step=step_bcf,
678 burnin_trace_type=BCFBurninTrace,
679 main_trace_type=BCFMainTrace,
680 ),
681 check_platform=None,
682 )
683 self._mcmc_state = cast(BCFState, result.final_state)
684 self._binner = binner_obj
685 self._main_trace = cast(BCFMainTrace, result.main_trace)
686 self._burnin_trace = cast(BCFBurninTrace, result.burnin_trace)
688 # 6. Predict at the test points, now that the traces are available
689 if x_test is not None:
690 test_pred = self._predict_unified(x_test, probabilities=False)
691 self._mu_test = test_pred['mu']
692 self._tau_test = test_pred['tau']
693 self._z_test = z_test
695 def save_npz(self, path: str | PathLike) -> None:
696 """
697 Save the fitted model to a compressed npz archive.
699 Parameters
700 ----------
701 path
702 The file to write to.
704 Notes
705 -----
706 Files written by a bartz release can be loaded by later releases, but
707 not by earlier ones; files written by development versions may not be.
708 """
709 save_npz(path, self)
711 @classmethod
712 def load_npz(cls, path: str | PathLike) -> 'bcf':
713 """
714 Load a model saved with `save_npz`.
716 Archives written by `save_npz` in bartz 0.13 load as models that
717 can only predict.
719 Parameters
720 ----------
721 path
722 The file to read from.
724 Returns
725 -------
726 The loaded model, on the default device.
727 """
728 return check_class(load_npz(path), cls, path)
730 @forbid_x64
731 def predict(
732 self,
733 x_test: Real[ArrayLike, 'm p'] | DataFrame,
734 *,
735 pihat_test: Float32[ArrayLike, ' m'] | Series | None = None,
736 ) -> BCFPrediction:
737 """
738 Compute the control mean and the treatment effect at `x_test`.
740 Parameters
741 ----------
742 x_test
743 The test predictors.
744 pihat_test
745 The test propensity scores, required iff the model was fit with
746 `pihat_train`.
748 Returns
749 -------
750 The posterior samples at `x_test`.
751 """
752 return self._predict_unified(
753 self._process_x_test(x_test, pihat_test),
754 probabilities=self._outcome_type == 'binary',
755 )
757 def _process_x_test(
758 self,
759 x_test: Real[ArrayLike, 'm p'] | DataFrame,
760 pihat_test: Float32[ArrayLike, ' m'] | Series | None,
761 ) -> Shaped[Array, 'p m'] | Shaped[Array, 'p+1 m']:
762 """Check the test inputs against the training ones and stack them."""
763 x_test, x_test_fmt = process_bcf_predictor_input(x_test)
764 if x_test_fmt != self._x_train_fmt:
765 msg = (
766 f'Format of x_test {x_test_fmt} does not match x_train'
767 f' {self._x_train_fmt}'
768 )
769 raise ValueError(msg)
771 if self._has_pihat and pihat_test is None:
772 msg = '`pihat_test` is required, the model was fit with `pihat_train`.'
773 raise ValueError(msg)
774 elif not self._has_pihat and pihat_test is not None:
775 msg = (
776 '`pihat_test` is not allowed, the model was fit without `pihat_train`.'
777 )
778 raise ValueError(msg)
779 elif pihat_test is None:
780 return x_test
781 else:
782 return stack_pihat(x_test, pihat_test, 'test')
784 def _predict_unified(
785 self, x_test_unified: Shaped[Array, 'p_or_p_plus_1 m'], *, probabilities: bool
786 ) -> BCFPrediction:
787 """Implement `predict` on the test predictors stacked with pihat."""
788 return predict(
789 self._binner.bin(x_test_unified),
790 self._main_trace,
791 y_mean=self._y_mean,
792 y_std=self._y_std,
793 probabilities=probabilities,
794 )
796 @property
797 def offset(self) -> Float32[Array, '']:
798 """The prior mean of the prognostic function.
800 On the scale of `y_train` even if `standardize` is set, unlike the
801 `offset` argument, and on the latent probit scale for binary outcomes.
802 """
803 # y_mean and y_std are exactly 0 and 1 if the response is not standardized
804 return self._main_trace.mu.offset * self._y_std + self._y_mean
806 @property
807 def sigma_trace(self) -> Float32[Array, ' num_samples']:
808 """The posterior trace of residual standard deviation on the outcome scale, chains concatenated."""
809 return sigma_trace(self._main_trace.mu, self._y_std)
811 @property
812 def mu_test(self) -> Float32[Array, 'num_samples m'] | None:
813 """The control mean at `x_test` for each MCMC iteration.
815 On the latent probit scale for binary outcomes.
816 """
817 return self._mu_test
819 @property
820 def tau_test(self) -> Float32[Array, 'num_samples m'] | None:
821 """The treatment effect at `x_test` for each MCMC iteration.
823 On the latent probit scale for binary outcomes.
824 """
825 return self._tau_test
827 @property
828 def yhat_test(self) -> Float32[Array, 'num_samples m'] | None:
829 """The expected outcome at `x_test` under `z_test` for each MCMC iteration.
831 On the latent probit scale for binary outcomes; see `prob_test`.
832 """
833 if self._z_test is None:
834 return None
835 else:
836 assert self._mu_test is not None
837 assert self._tau_test is not None
838 return expected_outcome(self._mu_test, self._tau_test, self._z_test, False)
840 @property
841 def prob_test(self) -> Float32[Array, 'num_samples m'] | None:
842 """The probability of y being True at `x_test` under `z_test`.
844 `None` unless the outcome is binary and `x_test` and `z_test` were
845 passed to the constructor.
846 """
847 if self._z_test is None or self._outcome_type != 'binary':
848 return None
849 else:
850 assert self._mu_test is not None
851 assert self._tau_test is not None
852 return expected_outcome(self._mu_test, self._tau_test, self._z_test, True)
854 @forbid_x64
855 def predict_potential_outcomes(
856 self,
857 x_test: Real[ArrayLike, 'm p'] | DataFrame,
858 *,
859 key: int | Key[Array, ''],
860 pihat_test: Float32[ArrayLike, ' m'] | Series | None = None,
861 rho: FloatLike = 0.0,
862 ) -> BCFPotentialOutcomes:
863 """
864 Sample joint posterior predictive potential outcomes Y(0), Y(1), and "lift" Y(1) - Y(0).
866 Parameters
867 ----------
868 x_test
869 The test predictors.
870 key
871 A jax random key or an integer seed for sampling the errors.
872 pihat_test
873 The test propensity scores, required iff the model was fit with
874 `pihat_train`.
875 rho
876 The correlation in [-1, 1] between the errors of `y0` and `y1`.
877 The data carry no information on it, see [1]_. It affects only
878 `delta` in `BCFPotentialOutcomes`, widening it as `rho` decreases.
880 Returns
881 -------
882 The posterior predictive samples at `x_test`.
884 References
885 ----------
886 .. [1] Imbens, Guido W., and Donald B. Rubin (2015). "Causal Inference
887 for Statistics, Social, and Biomedical Sciences: An Introduction".
888 Cambridge University Press, section 8.6.
889 """
890 rho = jnp.asarray(rho)
891 # written to also catch nan
892 rho = error_if(rho, ~(jnp.abs(rho) <= 1), 'rho must be in [-1, 1]')
894 if not is_key(key):
895 key = random.key(key)
897 preds = self.predict(x_test=x_test, pihat_test=pihat_test)
898 y0, y1, delta = sample_potential_outcomes(
899 key,
900 preds['mu'],
901 preds['tau'],
902 sigma=self.sigma_trace,
903 rho=rho,
904 binary=self._outcome_type == 'binary',
905 )
906 return BCFPotentialOutcomes(**preds, y0=y0, y1=y1, delta=delta)