Coverage for src/bartz/debug/_prior.py: 99%

204 statements  

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

1# bartz/src/bartz/debug/_prior.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"""Sampling from the BART prior.""" 

26 

27import math 

28from abc import abstractmethod 

29from collections.abc import Callable 

30from dataclasses import replace 

31from functools import partial 

32from typing import TypeVar 

33 

34from equinox import Module, error_if 

35from jax import eval_shape, lax, random, tree, vmap 

36from jax import numpy as jnp 

37from jaxtyping import Array, Bool, Float32, Int32, Key, PyTree, Shaped, UInt 

38 

39from bartz._jaxext import jit, minimal_unsigned_dtype, solve_triangular 

40from bartz._jaxext import split as split_key 

41from bartz._jaxext.random import categorical, loggamma 

42from bartz.grove import is_actual_leaf, is_leaves_parent, traverse_forest 

43from bartz.mcmcstep._moves import randint_masked 

44from bartz.mcmcstep._state import chol_with_gersh 

45from bartz.mcmcstep._step import count_selectable 

46 

47FloatLike = float | Float32[Array, ''] 

48 

49 

50class SamplePriorStack(Module): 

51 """Represent the manually managed stack used in `sample_tree_structure`. 

52 

53 Each level of the stack represents a recursion into a child node in a 

54 binary tree of maximum depth `d`. 

55 """ 

56 

57 nonterminal: Bool[Array, ' d'] 

58 """Whether the node is valid or the recursion is into unused node slots.""" 

59 

60 lower: UInt[Array, 'd p'] 

61 """The available cutpoints along ``var`` are in the integer range 

62 ``[1 + lower[var], 1 + upper[var])``.""" 

63 

64 upper: UInt[Array, 'd p'] 

65 """The available cutpoints along ``var`` are in the integer range 

66 ``[1 + lower[var], 1 + upper[var])``.""" 

67 

68 var: UInt[Array, ' d'] 

69 """The variable of a decision node.""" 

70 

71 split: UInt[Array, ' d'] 

72 """The cutpoint of a decision node.""" 

73 

74 @classmethod 

75 def initial( 

76 cls, p_nonterminal: Float32[Array, ' d'], max_split: UInt[Array, ' p'] 

77 ) -> 'SamplePriorStack': 

78 """Initialize the stack. 

79 

80 Parameters 

81 ---------- 

82 p_nonterminal 

83 The prior probability of a node being non-terminal conditional on 

84 its ancestors and on having available decision rules, at each depth. 

85 max_split 

86 The number of cutpoints along each variable. 

87 

88 Returns 

89 ------- 

90 A `SamplePriorStack` initialized to start the recursion. 

91 """ 

92 var_dtype = minimal_unsigned_dtype(max_split.size - 1) 

93 return cls( 

94 nonterminal=jnp.ones(p_nonterminal.size, bool), 

95 lower=jnp.zeros((p_nonterminal.size, max_split.size), max_split.dtype), 

96 upper=jnp.broadcast_to(max_split, (p_nonterminal.size, max_split.size)), 

97 var=jnp.zeros(p_nonterminal.size, var_dtype), 

98 split=jnp.zeros(p_nonterminal.size, max_split.dtype), 

99 ) 

100 

101 

102class TreeStructure(Module): 

103 """The decision rules of a tree, or of a batch of trees.""" 

104 

105 var_tree: UInt[Array, '*batch_shape max_num_leaves'] 

106 """The variables of the decision rules.""" 

107 

108 split_tree: UInt[Array, '*batch_shape max_num_leaves'] 

109 """The cutpoints of the decision rules, 0 at the leaves.""" 

110 

111 @classmethod 

112 def stump( 

113 cls, p_nonterminal: Float32[Array, ' d'], max_split: UInt[Array, ' p'] 

114 ) -> 'TreeStructure': 

115 """Create a tree with only the root.""" 

116 max_num_leaves = 2**p_nonterminal.size 

117 return cls( 

118 var_tree=jnp.zeros( 

119 max_num_leaves, minimal_unsigned_dtype(max_split.size - 1) 

120 ), 

121 split_tree=jnp.zeros(max_num_leaves, max_split.dtype), 

122 ) 

123 

124 

125class SamplePriorCarry(Module): 

126 """Object holding values carried along the recursion in `sample_tree_structure`.""" 

127 

128 key: Key[Array, ''] 

129 """A jax random key used to sample decision rules.""" 

130 

131 stack: SamplePriorStack 

132 """The stack used to manage the recursion.""" 

133 

134 trees: TreeStructure 

135 """The output arrays.""" 

136 

137 @classmethod 

138 def initial( 

139 cls, 

140 key: Key[Array, ''], 

141 p_nonterminal: Float32[Array, ' d'], 

142 max_split: UInt[Array, ' p'], 

143 ) -> 'SamplePriorCarry': 

144 """Initialize the carry object. 

145 

146 Parameters 

147 ---------- 

148 key 

149 A jax random key. 

150 p_nonterminal 

151 The prior probability of a node being non-terminal conditional on 

152 its ancestors and on having available decision rules, at each depth. 

153 max_split 

154 The number of cutpoints along each variable. 

155 

156 Returns 

157 ------- 

158 A `SamplePriorCarry` initialized to start the recursion. 

159 """ 

160 return cls( 

161 key, 

162 SamplePriorStack.initial(p_nonterminal, max_split), 

163 TreeStructure.stump(p_nonterminal, max_split), 

164 ) 

165 

166 

167class SamplePriorX(Module): 

168 """Object representing the recursion scan in `sample_tree_structure`. 

169 

170 The sequence of nodes to visit is pre-computed recursively once, unrolling 

171 the recursion schedule. 

172 """ 

173 

174 node: Int32[Array, ' max_num_leaves_minus_1'] 

175 """The heap index of the node to visit.""" 

176 

177 depth: Int32[Array, ' max_num_leaves_minus_1'] 

178 """The depth of the node.""" 

179 

180 next_depth: Int32[Array, ' max_num_leaves_minus_1'] 

181 """The depth of the next node to visit, either the left child or the right 

182 sibling of the node or of an ancestor.""" 

183 

184 @classmethod 

185 def initial(cls, p_nonterminal: Float32[Array, ' d']) -> 'SamplePriorX': 

186 """Initialize the sequence of nodes to visit. 

187 

188 Parameters 

189 ---------- 

190 p_nonterminal 

191 The prior probability of a node being non-terminal conditional on 

192 its ancestors and on having available decision rules, at each depth. 

193 

194 Returns 

195 ------- 

196 A `SamplePriorX` initialized with the sequence of nodes to visit. 

197 """ 

198 seq = cls._sequence(p_nonterminal.size) 

199 assert len(seq) == 2**p_nonterminal.size - 1 

200 node = [node for node, depth in seq] 

201 depth = [depth for node, depth in seq] 

202 next_depth = [*depth[1:], p_nonterminal.size] 

203 return cls( 

204 node=jnp.array(node), 

205 depth=jnp.array(depth), 

206 next_depth=jnp.array(next_depth), 

207 ) 

208 

209 @classmethod 

210 def _sequence( 

211 cls, max_depth: int, depth: int = 0, node: int = 1 

212 ) -> tuple[tuple[int, int], ...]: 

213 """Recursively generate a sequence [(node, depth), ...].""" 

214 if depth < max_depth: 

215 out = ((node, depth),) 

216 out += cls._sequence(max_depth, depth + 1, 2 * node) 

217 out += cls._sequence(max_depth, depth + 1, 2 * node + 1) 

218 return out 

219 return () 

220 

221 

222def sample_tree_structure( 

223 key: Key[Array, ''], 

224 max_split: UInt[Array, ' p'], 

225 p_nonterminal: Float32[Array, ' d'], 

226 log_s: Float32[Array, ' p'] | None = None, 

227) -> TreeStructure: 

228 """Sample the decision rules of a tree from the BART prior. 

229 

230 Parameters 

231 ---------- 

232 key 

233 A jax random key. 

234 max_split 

235 The maximum split value for each variable. 

236 p_nonterminal 

237 The prior probability of a node being non-terminal conditional on 

238 its ancestors and on having available decision rules, at each depth. 

239 log_s 

240 The logarithm of the unnormalized prior probability of splitting on each 

241 variable. If `None`, variables are chosen uniformly at random. 

242 

243 Returns 

244 ------- 

245 The decision rules of the tree. 

246 """ 

247 carry = SamplePriorCarry.initial(key, p_nonterminal, max_split) 

248 xs = SamplePriorX.initial(p_nonterminal) 

249 

250 def loop(carry: SamplePriorCarry, x: SamplePriorX) -> tuple[SamplePriorCarry, None]: 

251 keys = split_key(carry.key, 4) 

252 

253 # get variables at current stack level 

254 stack = carry.stack 

255 nonterminal = stack.nonterminal[x.depth] 

256 lower = stack.lower[x.depth, :] 

257 upper = stack.upper[x.depth, :] 

258 

259 # sample a random decision rule, drawing the variable from `s` 

260 # (uniformly if `log_s` is None) among those with an available cutpoint 

261 available: Bool[Array, ' p'] = lower < upper 

262 allowed = jnp.any(available) 

263 if log_s is None: 

264 var = randint_masked(keys.pop(), available) 

265 else: 

266 logits = jnp.where(available, log_s, jnp.finfo(log_s.dtype).min) 

267 var = categorical(keys.pop(), logits) 

268 split = 1 + random.randint(keys.pop(), (), lower[var], upper[var]) 

269 

270 # cast to shorter integer types 

271 var = var.astype(carry.trees.var_tree.dtype) 

272 split = split.astype(carry.trees.split_tree.dtype) 

273 

274 # decide whether to try to grow the node if it is growable 

275 pnt = p_nonterminal[x.depth] 

276 try_nonterminal: Bool[Array, ''] = random.bernoulli(keys.pop(), pnt) 

277 nonterminal &= try_nonterminal & allowed 

278 

279 # update trees 

280 trees = carry.trees 

281 trees = replace( 

282 trees, 

283 var_tree=trees.var_tree.at[x.node].set(var), 

284 split_tree=trees.split_tree.at[x.node].set( 

285 jnp.where(nonterminal, split, 0) 

286 ), 

287 ) 

288 

289 def write_push_stack() -> SamplePriorStack: 

290 """Update the stack to go to the left child.""" 

291 return replace( 

292 stack, 

293 nonterminal=stack.nonterminal.at[x.next_depth].set(nonterminal), 

294 lower=stack.lower.at[x.next_depth, :].set(lower), 

295 upper=stack.upper.at[x.next_depth, :].set(upper.at[var].set(split - 1)), 

296 var=stack.var.at[x.depth].set(var), 

297 split=stack.split.at[x.depth].set(split), 

298 ) 

299 

300 def pop_push_stack() -> SamplePriorStack: 

301 """Update the stack to go to the right sibling, possibly at lower depth.""" 

302 var = stack.var[x.next_depth - 1] 

303 split = stack.split[x.next_depth - 1] 

304 lower = stack.lower[x.next_depth - 1, :] 

305 upper = stack.upper[x.next_depth - 1, :] 

306 return replace( 

307 stack, 

308 lower=stack.lower.at[x.next_depth, :].set(lower.at[var].set(split)), 

309 upper=stack.upper.at[x.next_depth, :].set(upper), 

310 ) 

311 

312 # update stack 

313 stack = lax.cond(x.next_depth > x.depth, write_push_stack, pop_push_stack) 

314 

315 # update carry 

316 carry = replace(carry, key=keys.pop(), stack=stack, trees=trees) 

317 return carry, None 

318 

319 carry, _ = lax.scan(loop, carry, xs) 

320 return carry.trees 

321 

322 

323T = TypeVar('T') 

324 

325 

326class RejectionCriterion(Module): 

327 """A criterion to accept or reject the samples in `rejection_sample`.""" 

328 

329 @abstractmethod 

330 def accept(self, sample: PyTree[Array]) -> Bool[Array, '']: 

331 """Whether to accept a single sample.""" 

332 

333 

334class RejectionCarry(Module): 

335 """The loop state of `rejection_sample`.""" 

336 

337 samples: PyTree[Array] 

338 """The accepted samples, stacked along a leading axis.""" 

339 

340 missing: Bool[Array, ' num'] 

341 """Which slots of `samples` are still empty.""" 

342 

343 iteration: Int32[Array, ''] 

344 """The number of iterations done.""" 

345 

346 

347def rejection_sample( 

348 key: Key[Array, ''], 

349 draw: Callable[[Key[Array, ''], int], T], 

350 criterion: RejectionCriterion, 

351 num: int, 

352 *, 

353 max_iter: int = 1000, 

354) -> T: 

355 """Draw independent samples conditional on a criterion. 

356 

357 Parameters 

358 ---------- 

359 key 

360 A jax random key. 

361 draw 

362 A function taking a key and a number of samples, that draws that many 

363 independent samples stacked along a leading axis. 

364 criterion 

365 The criterion the samples must satisfy. 

366 num 

367 The number of samples. 

368 max_iter 

369 The maximum number of iterations, each drawing `num` candidates. If 

370 some samples are still missing after it, it is an error. 

371 

372 Returns 

373 ------- 

374 The accepted samples, stacked along a leading axis. 

375 

376 Notes 

377 ----- 

378 Each iteration draws `num` candidates and fills the empty slots with the 

379 accepted ones. The candidates are independent and identically 

380 distributed, so the slots can take them in any order that depends only on 

381 which are accepted. 

382 """ 

383 

384 def body(carry: RejectionCarry) -> RejectionCarry: 

385 candidates = draw(random.fold_in(key, carry.iteration), num) 

386 accepted = vmap(criterion.accept)(candidates) 

387 

388 # the i-th empty slot takes the i-th accepted candidate 

389 (source,) = jnp.nonzero(accepted, size=num, fill_value=0) 

390 rank = jnp.cumsum(carry.missing) - 1 

391 fill = carry.missing & (rank < jnp.count_nonzero(accepted)) 

392 source = source[jnp.clip(rank, 0, num - 1)] 

393 

394 def update( 

395 old: Shaped[Array, ' num *shape'], new: Shaped[Array, ' num *shape'] 

396 ) -> Shaped[Array, ' num *shape']: 

397 mask = fill.reshape(num, *(1,) * (old.ndim - 1)) 

398 return jnp.where(mask, new[source], old) 

399 

400 return RejectionCarry( 

401 samples=tree.map(update, carry.samples, candidates), 

402 missing=carry.missing & ~fill, 

403 iteration=carry.iteration + 1, 

404 ) 

405 

406 shapes = eval_shape(lambda key: draw(key, num), key) 

407 carry = RejectionCarry( 

408 samples=tree.map(lambda s: jnp.zeros(s.shape, s.dtype), shapes), 

409 missing=jnp.ones(num, bool), 

410 iteration=jnp.int32(0), 

411 ) 

412 carry = lax.while_loop( 

413 lambda carry: jnp.any(carry.missing) & (carry.iteration < max_iter), body, carry 

414 ) 

415 msg = f'rejection sampling accepted too few samples in {max_iter} iterations' 

416 return error_if(carry.samples, jnp.any(carry.missing), msg) 

417 

418 

419class MinPointsCriterion(RejectionCriterion): 

420 """Accept the trees with enough datapoints in their nodes.""" 

421 

422 X: UInt[Array, 'p n'] 

423 """The predictors of the datapoints.""" 

424 

425 min_points_per_decision_node: Int32[Array, ''] | None 

426 """The minimum number of datapoints in a decision node.""" 

427 

428 min_points_per_leaf: Int32[Array, ''] | None 

429 """The minimum number of datapoints in a leaf, but the root.""" 

430 

431 def accept(self, sample: TreeStructure) -> Bool[Array, '']: 

432 """Check the tree has enough datapoints in its nodes.""" 

433 (max_num_leaves,) = sample.split_tree.shape 

434 nodes = traverse_forest( 

435 self.X, sample.var_tree, sample.split_tree, index_type='heap' 

436 ) 

437 count = jnp.zeros(2 * max_num_leaves, jnp.int32).at[nodes].add(1) 

438 

439 ok = jnp.bool_(True) 

440 if self.min_points_per_decision_node is not None: 

441 # any decision node has at least as many datapoints as the 

442 # decision nodes below it, so check only the parents of two leaves 

443 parent_count = count.reshape(max_num_leaves, 2).sum(axis=1) 

444 enough = parent_count >= self.min_points_per_decision_node 

445 ok &= jnp.all(enough | ~is_leaves_parent(sample.split_tree)) 

446 if self.min_points_per_leaf is not None: 

447 is_leaf = is_actual_leaf(sample.split_tree, add_bottom_level=True) 

448 is_child = is_leaf.at[1].set(False) 

449 ok &= jnp.all((count >= self.min_points_per_leaf) | ~is_child) 

450 return ok 

451 

452 

453@jit(static_argnames=('shape',)) 

454def sample_forest_structure( 

455 key: Key[Array, ''], 

456 shape: tuple[int, ...], 

457 *, 

458 max_split: UInt[Array, ' p'], 

459 p_nonterminal: Float32[Array, ' d'], 

460 log_s: Float32[Array, ' p'] | Float32[Array, '*batch p'] | None = None, 

461 criterion: RejectionCriterion | None = None, 

462) -> TreeStructure: 

463 """Sample the decision rules of independent trees from the BART prior. 

464 

465 Parameters 

466 ---------- 

467 key 

468 A jax random key. 

469 shape 

470 The shape ``(*batch, num_trees)`` of the batch of trees. 

471 max_split 

472 The maximum split value for each variable. 

473 p_nonterminal 

474 The prior probability of a node being non-terminal conditional on 

475 its ancestors and on having available decision rules, at each depth. 

476 log_s 

477 The logarithm of the unnormalized prior probability of splitting on each 

478 variable, either shared or with shape ``(*batch, p)``. If `None`, 

479 variables are chosen uniformly at random. 

480 criterion 

481 If set, the trees are conditioned on satisfying it. This requires them 

482 to be identically distributed, so `log_s` must be shared. 

483 

484 Returns 

485 ------- 

486 The decision rules of the trees, with batch shape `shape`. 

487 

488 Raises 

489 ------ 

490 ValueError 

491 If `criterion` is set and `log_s` is not shared. 

492 """ 

493 sample_one = partial( 

494 sample_tree_structure, max_split=max_split, p_nonterminal=p_nonterminal 

495 ) 

496 

497 if criterion is None: 497 ↛ 499line 497 didn't jump to line 499 because the condition on line 497 was never true

498 

499 def onetree( 

500 key: Key[Array, ''], log_s: Float32[Array, ' p'] | None 

501 ) -> tuple[UInt[Array, ' max_num_leaves'], UInt[Array, ' max_num_leaves']]: 

502 tree = sample_one(key, log_s=log_s) 

503 return tree.var_tree, tree.split_tree 

504 

505 if log_s is None: 

506 signature = '()->(h),(h)' 

507 else: 

508 signature = '(),(p)->(h),(h)' 

509 log_s = log_s[..., None, :] # broadcast over the trees 

510 

511 keys = random.split(key, shape) 

512 var_tree, split_tree = jnp.vectorize( 

513 onetree, excluded=set() if log_s is not None else {1}, signature=signature 

514 )(keys, log_s) 

515 return TreeStructure(var_tree=var_tree, split_tree=split_tree) 

516 

517 elif log_s is not None and log_s.ndim > 1: 517 ↛ 523line 517 didn't jump to line 523 because the condition on line 517 was always true

518 msg = 'conditioning on a criterion requires a shared `log_s`' 

519 raise ValueError(msg) 

520 

521 else: 

522 

523 def draw(key: Key[Array, ''], num: int) -> TreeStructure: 

524 return vmap(partial(sample_one, log_s=log_s))(random.split(key, num)) 

525 

526 trees = rejection_sample(key, draw, criterion, math.prod(shape)) 

527 return tree.map(lambda x: x.reshape(*shape, *x.shape[1:]), trees) 

528 

529 

530@jit(static_argnames=('shape',)) 

531def sample_leaves( 

532 key: Key[Array, ''], 

533 shape: tuple[int, ...], 

534 prec_chol: Float32[Array, ''] | Float32[Array, 'k k'], 

535) -> Float32[Array, '*shape']: 

536 """Sample leaves from their prior, a centered Normal. 

537 

538 Parameters 

539 ---------- 

540 key 

541 A jax random key. 

542 shape 

543 The shape of the leaves, ``(*batch, max_num_leaves)``, or ``(*batch, 

544 k, max_num_leaves)`` for vector-valued leaves. 

545 prec_chol 

546 The lower Cholesky factor of the prior precision of a leaf, a scalar 

547 square root for scalar leaves. 

548 

549 Returns 

550 ------- 

551 The leaves. 

552 """ 

553 eps = random.normal(key, shape) 

554 if prec_chol.ndim == 0: 

555 return eps / prec_chol 

556 else: 

557 # solve L^T x = eps, such that cov(x) = (L L^T)^-1 

558 solve = jnp.vectorize( 

559 partial(solve_triangular, lower=True, trans='T'), 

560 signature='(k,k),(k,m)->(k,m)', 

561 ) 

562 return solve(prec_chol, eps) 

563 

564 

565def sample_wishart( 

566 key: Key[Array, ''], 

567 nu: Float32[Array, ''], 

568 rate: Float32[Array, ''] | Float32[Array, 'k k'], 

569) -> tuple[ 

570 Float32[Array, ''] | Float32[Array, 'k k'], 

571 Float32[Array, ''] | Float32[Array, 'k k'], 

572]: 

573 """Sample a precision matrix from its Wishart prior. 

574 

575 Parameters 

576 ---------- 

577 key 

578 A jax random key. 

579 nu 

580 The degrees of freedom. 

581 rate 

582 The rate matrix, such that the mean is ``nu * rate^-1``. A scalar for 

583 a scalar precision, which then is Gamma distributed. 

584 

585 Returns 

586 ------- 

587 value : Float32[Array, ''] | Float32[Array, 'k k'] 

588 The precision. 

589 chol : Float32[Array, ''] | Float32[Array, 'k k'] 

590 Its lower Cholesky factor, a square root for a scalar precision. 

591 """ 

592 if rate.ndim == 0: 

593 value = 2 * jnp.exp(loggamma(key, nu / 2)) / rate 

594 return value, jnp.sqrt(value) 

595 else: 

596 # Bartlett decomposition: value = (L A) (L A)^T, with L L^T = rate^-1 

597 keys = split_key(key) 

598 k, _ = rate.shape 

599 diag = jnp.sqrt(2 * jnp.exp(loggamma(keys.pop(), (nu - jnp.arange(k)) / 2))) 

600 A = jnp.tril(random.normal(keys.pop(), (k, k)), -1) + jnp.diag(diag) 

601 # with rate = U U^T, U upper triangular, L = U^-T is lower triangular; 

602 # U is the lower Cholesky factor with the axes reversed 

603 U = chol_with_gersh(rate[::-1, ::-1])[::-1, ::-1] 

604 chol = solve_triangular(U, A, lower=False, trans='T') 

605 return chol @ chol.T, chol 

606 

607 

608def sample_diag_wishart( 

609 key: Key[Array, ''], nu: Float32[Array, ''], rate: Float32[Array, 'k k'] 

610) -> tuple[Float32[Array, 'k k'], Float32[Array, 'k k']]: 

611 """Sample a diagonal precision matrix with independent Gamma components. 

612 

613 Parameters 

614 ---------- 

615 key 

616 A jax random key. 

617 nu 

618 Twice the shape parameter of the Gamma distributions. 

619 rate 

620 Twice the rate parameters of the Gamma distributions on the diagonal. 

621 

622 Returns 

623 ------- 

624 value : Float32[Array, 'k k'] 

625 The precision. 

626 chol : Float32[Array, 'k k'] 

627 Its lower Cholesky factor. 

628 """ 

629 rate = jnp.diag(rate) 

630 value = 2 * jnp.exp(loggamma(key, nu / 2, rate.shape)) / rate 

631 return jnp.diag(value), jnp.diag(jnp.sqrt(value)) 

632 

633 

634def sample_theta( 

635 key: Key[Array, ''], 

636 rho: FloatLike, 

637 a: FloatLike, 

638 b: FloatLike, 

639 shape: tuple[int, ...] = (), 

640 *, 

641 log_range: FloatLike | None = None, 

642) -> Float32[Array, ' *shape']: 

643 r"""Sample the Dirichlet concentration `theta` from its prior. 

644 

645 The prior is :math:`\theta/(\theta+\rho) \sim \mathrm{Beta}(a, b)`. 

646 

647 Parameters 

648 ---------- 

649 key 

650 A jax random key. 

651 rho 

652 The scale of `theta`. 

653 a 

654 b 

655 The shape parameters of the Beta prior on :math:`\theta/(\theta+\rho)`. 

656 shape 

657 The shape of the sample. A scalar by default. 

658 log_range 

659 If set, the prior is restricted to :math:`|\log(\theta/\rho)| \le` 

660 `log_range`. 

661 

662 Returns 

663 ------- 

664 The sampled concentration parameter(s). 

665 """ 

666 

667 # log(theta / rho) is the log ratio of two Gamma variates, drawn in log 

668 # space such that theta does not underflow 

669 def draw(key: Key[Array, ''], num: int) -> Float32[Array, ' num']: 

670 ab = jnp.stack([jnp.asarray(a), jnp.asarray(b)]) 

671 log_ga, log_gb = loggamma(key, ab[:, None], (2, num)) 

672 return log_ga - log_gb 

673 

674 num = math.prod(shape) 

675 if log_range is None: 

676 v = draw(key, num) 

677 else: 

678 v = rejection_sample(key, draw, WithinRange(jnp.asarray(log_range)), num) 

679 return rho * jnp.exp(v.reshape(shape)) 

680 

681 

682class WithinRange(RejectionCriterion): 

683 """Accept x in [-bound, bound].""" 

684 

685 bound: Float32[Array, ''] 

686 """The bound (inclusive) on the absolute value.""" 

687 

688 def accept(self, sample: Float32[Array, '']) -> Bool[Array, '']: 

689 """Check the sample is within the range.""" 

690 return jnp.abs(sample) <= self.bound 

691 

692 

693def sample_s( 

694 key: Key[Array, ''], 

695 theta: Float32[Array, ' *batch'] | FloatLike, 

696 max_split: UInt[Array, ' p'], 

697) -> Float32[Array, '*batch p']: 

698 r"""Sample the log variable selection probabilities from their prior. 

699 

700 The prior is :math:`s \sim \mathrm{Dirichlet}(\theta/p, \ldots, \theta/p)` 

701 over the `p` variables with ``max_split > 0``, the others being ignored. 

702 The result is `log_s`, the log of unnormalized weights whose `softmax` is 

703 `s`, the representation expected by `sample_forest_structure`. 

704 

705 Parameters 

706 ---------- 

707 key 

708 A jax random key. 

709 theta 

710 The Dirichlet concentration parameter. Batched values draw an 

711 independent `s` for each entry. 

712 max_split 

713 The maximum split value for each variable. 

714 

715 Returns 

716 ------- 

717 The log unnormalized variable selection probabilities, -inf for the ignored variables. 

718 """ 

719 theta = jnp.asarray(theta) 

720 selectable = max_split > 0 

721 p_eff = count_selectable(selectable) 

722 alpha = jnp.broadcast_to(theta[..., None] / p_eff, (*theta.shape, max_split.size)) 

723 return jnp.where(selectable, loggamma(key, alpha), -jnp.inf)