Terms and priors
Choose a predictor term, attach a prior to the quantity it creates, and inspect the resulting declaration before fitting. A term may allocate a coefficient, a group-effect block or a latent function; these have different prior addresses.
Prior targets
The three forms below name an authored parameter, a formula coefficient, or a quantity owned by a term or group block. Distribution arguments use Julia's conventions: Exponential and Gamma take a scale, not Stan's rate.
| Target | Prior statement | Quantity |
|---|---|---|
| Authored parameter | sigma ~ Exponential(1) | A positive scalar |
| Formula coefficient | effect(mu, x) ~ Normal(0, 0.3) | The coefficient multiplying x |
| Term or group parameter | sd(mu, subject) ~ Exponential(0.5) | The subject-effect SD |
Population coefficients default to independent standard normals. A smooth's amplitude belongs to the smooth, so use sd(mu, hsgp(x)); it has no additional population multiplier. offset(x) fixes the multiplier at one and allocates no coefficient. The terms reference lists defaults, prior families and backend coverage by term.
This model overrides the population slope, the group SD and the HSGP amplitude. It retains the HSGP's approximation-validity bound on its length scale.
Coefficient, group and smooth priors
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
mu ~ 1 + x + hsgp(t; k=5) + (1 | subject)
y ~ Normal(mu, sigma)
sigma ~ Exponential(0.5)
effect(:, x) ~ Normal(0, 1)
effect(mu, x) ~ Normal(0, 0.3)
sd(mu, subject) ~ Exponential(0.5)
sd(mu, hsgp(t)) ~ Exponential(0.7)
end)((; x=[-1., 0., 1., -1., 0., 1.],
t=[0., 0.5, 1., 1.5, 2., 2.5], subject=["a", "a", "a", "b", "b", "b"],
y=[-0.4, 0.2, 0.6, -0.1, 0.3, 0.8]))SBBRMI with data keys = [:PHI_hsgp_t, :n_subject, :n_terms_mu__subject_subject, :omega2_hsgp_t, :rho_lower_hsgp_t, :subject_idx, :t, :x, :y]
configured submodels:
ranef_correlated_draws_single_margin_1 = Base.merge(BayesianRegressionModels._sb_single_margin_ranef(BayesianRegressionModels.ranef_correlated_draws), quote
tau ~ (StanBlocks.builtin.restricted)(exponential, 1.0 ./ 0.5; n = n_terms, lower = 0.0)
end)
_sb_hsgp_configured_1 = Base.merge(BayesianRegressionModels._sb_hsgp, quote
sigma ~ (StanBlocks.builtin.restricted)(exponential, 1.0 ./ 0.7; lower = 0.0)
end)
emitted @slic body:
begin
b_mu__subject_subject ~ ranef_correlated_draws_single_margin_1(; group_idx = subject_idx, n_groups = n_subject, n_terms = n_terms_mu__subject_subject)
X_mu = hcat(rep_vector(1.0, num_elements(x)), x)
pop_mu ~ _popefs_normal(; X = X_mu, beta_loc = [0.0, 0], beta_scale = [1.0, 0.3])
hsgp_t ~ _sb_hsgp_configured_1(; PHI = PHI_hsgp_t, omega2 = omega2_hsgp_t, rho_lower = rho_lower_hsgp_t)
r_mu_mu__subject_subject = b_mu__subject_subject[subject_idx, 1]
mu = pop_mu + hsgp_t + r_mu_mu__subject_subject
sigma ~ exponential(1.0 ./ 0.5)
y ~ normal(mu, sigma)
end"""
Group-level (varying) effects of grouping `g`.
Non-centered, from the scale `tau[1]` (drawn from its prior) and standardized effects
`z[1:length(levels(g)), 1:1] ~ Normal(0, 1)`. Returns the
level-by-margin matrix `z .* tau[1]`, one row per level of `g` in order.
"""
brm_group_effects(g) = begin
tau[1:1] .~ Exponential.(0.5)
z[1:length(levels(g)), 1:1] .~ Normal.(0, 1)
return z .* tau[1]
end
"""
The fitted interval of an HSGP term's basis, from its training (fit-role) axes.
Returns one vector `fit`: each axis's center and half-width. The basis and
length-scale floor graphs read it, so a prediction uses the training interval.
"""
ReactiveKernels.@kernel(brm_hsgp_fit_graph(axis_fit, settings) = begin
center = sum(axis_fit) / length(axis_fit)
width = settings[1] * maximum(abs.(axis_fit .- center))
fit = [center, width]
return fit
end)
"""
The smallest length scale an HSGP term's basis resolves, per axis.
For `m` basis functions on an axis of half-width `L` the floor is
`(4L / pi) * sqrt(log(threshold) / (m^2 - 1))` (`0.0` for one function), below
which the omitted frequencies would carry too much weight.
"""
ReactiveKernels.@kernel(brm_hsgp_rho_floor_graph(fit, modes) = begin
width = fit[2]
rho_floor = if modes[1] == 1
0.0
else
((4width) / pi) * sqrt(log(100.0) / (modes[1] ^ 2 - 1))
end
return rho_floor
end)
"""
The Hilbert-space basis of an HSGP term at the rows.
Returns `(PHI, omega2)`: `PHI` holds one column per basis function, the Laplacian
eigenfunctions on the term's interval evaluated at each row's axes, and `omega2`
the matching squared frequencies, which the spectral density reads.
"""
ReactiveKernels.@kernel(brm_hsgp_basis_graph(axis, fit, modes) = begin
B = prod(modes)
center = fit[1]
width = fit[2]
omega2 = ReactiveKernels.plate(1:B) do mode
return ((mode * pi) / (2width)) ^ 2
end
basis_rows = ReactiveKernels.plate(axis) do x
values = ReactiveKernels.plate(1:B) do b
return sin(sqrt(omega2[b]) * ((x - center) + width)) / sqrt(width)
end
return values
end
PHI = stack(basis_rows; dims = 1)
return (PHI, omega2)
end)
"""
The weight of each HSGP basis function: the square root of the covariance's
spectral density at its frequency, for the marginal scale `sigma` and length
scale `rho`.
"""
ReactiveKernels.@kernel(brm_hsgp_spectral_scales(axis, fit, modes, sigma, rho) = begin
(PHI, omega2) = brm_hsgp_basis_graph(axis, fit, modes)
weights = ReactiveKernels.plate(axes(omega2, 1)) do b
return (sigma * (rho * sqrt(2pi)) ^ (1 / 2)) * exp(-0.25 * (rho ^ 2 * omega2[b]))
end
return weights
end)
"""
An HSGP term's value at each row: the basis `PHI` times the basis weights `scales`
times the standardized coefficients `z`, `PHI * (scales .* z)`.
"""
ReactiveKernels.@kernel(brm_hsgp_spectral_graph(axis, fit, modes, scales, z) = begin
(PHI, omega2) = brm_hsgp_basis_graph(axis, fit, modes)
value = PHI * (scales .* z)
return value
end)
"""
A Hilbert-space Gaussian-process (HSGP) effect.
Draws the length scale `rho_iso`, each truncated below at the floor `rho_floor` the basis resolves, the marginal scale `sigma` and standardized basis
coefficients `beta_raw ~ Normal(0, 1)`. Each basis function is weighted by the
square root of the covariance's spectral density (`spectral_scale`), and the
effect at the rows is the basis times the weighted coefficients.
"""
brm_hsgp_effect(axis, fit, modes, rho_floor) = begin
rho_iso ~ restricted(LogNormal(0.0, 1.0), rho_floor, Inf)
sigma ~ Exponential(0.7)
beta_raw[1:prod(modes)] .~ Normal.(0, 1)
spectral_scale = brm_hsgp_spectral_scales(axis, fit, modes, sigma, rho_iso)
return brm_hsgp_spectral_graph(axis, fit, modes, spectral_scale, beta_raw)
end
"""
Population-level effects: one coefficient per column of the design matrix `X`.
Draws `beta_pop[1:ncoef] ~ Normal(loc, scale)` and returns the linear predictor
`X * beta_pop`. `ncoef` is the number of columns of `X`. Each prior argument (`loc`, `scale`) is one value for all coefficients or a vector with one per coefficient.
"""
brm_population_effects(X, ncoef, loc, scale) = begin
beta_pop[1:ncoef] .~ Normal.(loc, scale)
return X * beta_pop
end
begin
subject_fit_levels = brm_fit_levels(subject_fit)
b_mu__subject_subject ~ brm_group_effects(subject_fit_levels)
subject_level = brm_level_indices(subject, subject_fit_levels)
ranef_mu_mu__subject_subject = b_mu__subject_subject[subject_level, 1]
hsgp_t_modes = copy(hsgp_t_modes_fit)
hsgp_t_settings = copy(hsgp_t_settings_fit)
hsgp_t_fit = brm_hsgp_fit_graph(t_fit, hsgp_t_settings)
hsgp_t_rho_floor = brm_hsgp_rho_floor_graph(hsgp_t_fit, hsgp_t_modes)
hsgp_t ~ brm_hsgp_effect(t, hsgp_t_fit, hsgp_t_modes, hsgp_t_rho_floor)
X_mu = hcat(ones(length(t)), x)
pop_mu ~ brm_population_effects(X_mu, 2, 0.0, [1.0, 0.3])
mu = .+(pop_mu, ranef_mu_mu__subject_subject, hsgp_t)
sigma ~ Exponential(0.5)
y .~ Normal.(mu, sigma)
endfunctions {
matrix hcat(
vector x,
vector y
) {
int n = dims(x)[1];
if (dims(y)[1] != n) reject("hcat: dim mismatch — `y` dim 1 (= ", dims(y)[1], ") does not match `n` (= ", n, "), inferred from `x` dim 1. `n` sizes: `x` dim 1 (= ", dims(x)[1], "), `y` dim 1 (= ", dims(y)[1], ").");
return append_col(x, y);
}
vector brm_hsgp_sqrt_spd(
matrix omega2,
real sigma,
vector rho
) {
int m = dims(omega2)[1];
int d = dims(omega2)[2];
if (dims(rho)[1] != d) reject("brm_hsgp_sqrt_spd: dim mismatch — `rho` dim 1 (= ", dims(rho)[1], ") does not match `d` (= ", d, "), inferred from `omega2` dim 2. `d` sizes: `omega2` dim 2 (= ", dims(omega2)[2], "), `rho` dim 1 (= ", dims(rho)[1], ").");
vector[m] rv;
real scale = sigma;
for(axis in 1:d) {
scale *= sqrt((rho[axis] * 2.5066282746310002));
}
for(b in 1:m) {
real exponent = 0.0;
for(axis in 1:d) {
exponent += (rho[axis] * rho[axis] * omega2[b, axis]);
}
rv[b] = (scale * exp((-0.25 * exponent)));
}
return rv;
}
vector normal_lpdfs(
vector obs,
vector loc,
real scale
) {
return jbroadcasted_normal_lpdfs(obs, loc, scale);
}
vector jbroadcasted_normal_lpdfs(
vector x1,
vector x2,
real x3
) {
int n = dims(x1)[1];
vector[n] rv;
for(i in 1:n) {
rv[i] = normal_lpdfs(broadcasted_getindex(x1, i), broadcasted_getindex(x2, i), x3);
}
return rv;
}
real normal_lpdfs(
real args1,
real args2,
real args3
) {
return normal_lpdf(args1 | args2, args3);
}
real broadcasted_getindex(vector x, int i) {
return x[i];
}
vector normal_vector_rng(
int anontok__1,
vector a,
real b
) {
int n = anontok__1;
if((n == 0)) {
vector[n] rv;
return rv;
} else {
return to_vector(normal_rng(a, b));
}
}
}
data {
int n_terms_mu__subject_subject;
int n_subject;
int x_n;
vector[x_n] x;
int omega2_hsgp_t_m;
int omega2_hsgp_t_n;
real rho_lower_hsgp_t;
matrix[omega2_hsgp_t_m, omega2_hsgp_t_n] omega2_hsgp_t;
int PHI_hsgp_t_m;
int PHI_hsgp_t_n;
matrix[PHI_hsgp_t_m, PHI_hsgp_t_n] PHI_hsgp_t;
int subject_idx_n;
array[subject_idx_n] int subject_idx;
int y_n;
vector[y_n] y;
}
transformed data {
matrix[x_n, 2] X_mu = hcat(rep_vector(1.0, num_elements(x)), x);
int pop_mu_n_covariates = 2;
int hsgp_t_n_basis = omega2_hsgp_t_m;
int hsgp_t_n_axes = omega2_hsgp_t_n;
}
parameters {
vector<lower=0.0>[n_terms_mu__subject_subject] b_mu__subject_subject_tau;
vector[(n_terms_mu__subject_subject * n_subject)] b_mu__subject_subject_z_flat;
vector[pop_mu_n_covariates] pop_mu_beta_pop;
real<lower=rho_lower_hsgp_t> hsgp_t_rho_iso;
real<lower=0.0> hsgp_t_sigma;
vector[hsgp_t_n_basis] hsgp_t_beta_raw;
real<lower=0.0> sigma;
}
transformed parameters {
matrix[n_terms_mu__subject_subject, n_subject] b_mu__subject_subject_z = to_matrix(b_mu__subject_subject_z_flat, n_terms_mu__subject_subject, n_subject);
matrix[n_subject, n_terms_mu__subject_subject] b_mu__subject_subject = ((diag_matrix(b_mu__subject_subject_tau) * b_mu__subject_subject_z)');
vector[x_n] pop_mu = (X_mu * pop_mu_beta_pop);
vector[hsgp_t_n_axes] hsgp_t_rho = rep_vector(hsgp_t_rho_iso, hsgp_t_n_axes);
vector[omega2_hsgp_t_m] hsgp_t_sqrt_spd = brm_hsgp_sqrt_spd(omega2_hsgp_t, hsgp_t_sigma, hsgp_t_rho);
vector[PHI_hsgp_t_m] hsgp_t = (PHI_hsgp_t * (hsgp_t_sqrt_spd .* hsgp_t_beta_raw));
vector[subject_idx_n] r_mu_mu__subject_subject = b_mu__subject_subject[subject_idx, 1];
vector[x_n] mu = (pop_mu + hsgp_t + r_mu_mu__subject_subject);
}
model {
b_mu__subject_subject_tau ~ exponential((1.0 ./ 0.5));
b_mu__subject_subject_z_flat ~ std_normal();
pop_mu_beta_pop ~ normal([0.0, 0]', [1.0, 0.3]');
hsgp_t_rho_iso ~ lognormal(0.0, 1.0);
hsgp_t_sigma ~ exponential((1.0 ./ 0.7));
hsgp_t_beta_raw ~ std_normal();
sigma ~ exponential((1.0 ./ 0.5));
y ~ normal(mu, sigma);
}
generated quantities {
vector[y_n] y_likelihood = normal_lpdfs(y, mu, sigma);
vector[y_n] y_gen = normal_vector_rng(y_n, mu, sigma);
}using ReactiveKernels, ReactiveKernelsPPL
rk = RKBRMI(model)
source = jax_source(rk.model, rk_bound_plan(rk))
write("model.py", source)
inputs = rk_bound_data(rk, source) # exactly the inputs prepare_data readsimport jax
import model as m
prepared = m.prepare_data(**inputs)
lp = m.log_density(u, **prepared) # u: unconstrained, length m.dimension(prepared)
lp = jax.jit(m.log_density)(u, **prepared) # one compiled function for every dataset of these shapes"""Generated by ReactiveKernelsPPL.jax_source from a built @rkppl program; do not edit.
Data: hsgp_t_modes_fit, hsgp_t_settings_fit, subject, subject_fit, t, t_fit, x, y.
Model documentation:
- `b_mu__subject_subject`: Group-level (varying) effects of grouping `g`.
Non-centered, from the scale `tau[1]` (drawn from its prior) and standardized effects
`z[1:length(levels(g)), 1:1] ~ Normal(0, 1)`. Returns the
level-by-margin matrix `z .* tau[1]`, one row per level of `g` in order.
- `hsgp_t`: A Hilbert-space Gaussian-process (HSGP) effect.
Draws the length scale `rho_iso`, each truncated below at the floor `rho_floor` the basis resolves, the marginal scale `sigma` and standardized basis
coefficients `beta_raw ~ Normal(0, 1)`. Each basis function is weighted by the
square root of the covariance's spectral density (`spectral_scale`), and the
effect at the rows is the basis times the weighted coefficients.
- `pop_mu`: Population-level effects: one coefficient per column of the design matrix `X`.
Draws `beta_pop[1:ncoef] ~ Normal(loc, scale)` and returns the linear predictor
`X * beta_pop`. `ncoef` is the number of columns of `X`. Each prior argument (`loc`, `scale`) is one value for all coefficients or a vector with one per coefficient.
"""
import numpy as np
import scipy.special as ssp
from typing import Any
import jax
import jax.numpy as jnp
import jax.scipy.linalg
import jax.scipy.special as jsp
from jax.typing import ArrayLike
jax.config.update("jax_enable_x64", True)
DATA = {"hsgp_t_modes_fit": {"dtype": "int64", "ndim": 1, "ragged": False}, "hsgp_t_settings_fit": {"dtype": "float64", "ndim": 1, "ragged": False}, "subject": {"dtype": "object", "ndim": 1, "ragged": False}, "subject_fit": {"dtype": "object", "ndim": 1, "ragged": False}, "t": {"dtype": "float64", "ndim": 1, "ragged": False}, "t_fit": {"dtype": "float64", "ndim": 1, "ragged": False}, "x": {"dtype": "float64", "ndim": 1, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "hsgp_t_rho_floor", "ppl_last_b_mu_subject_subject_z", "ppl_axis1_b_mu_subject_subject_z", "ppl_first_hsgp_t_beta_raw", "ppl_last_hsgp_t_beta_raw", "ppl_first_pop_mu_beta_pop", "ppl_last_pop_mu_beta_pop", "plate_argument", "hsgp_t_spectral_scale_omega2", "hsgp_t_spectral_scale_PHI", "X_mu", "subject_level", "y", "ppl_axis1_hsgp_t_beta_raw")
PREPARED = {"hsgp_t_rho_floor": {"dtype": "float64", "ndim": 0, "ragged": False}, "ppl_last_b_mu_subject_subject_z": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_axis1_b_mu_subject_subject_z": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_first_hsgp_t_beta_raw": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_last_hsgp_t_beta_raw": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_first_pop_mu_beta_pop": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_last_pop_mu_beta_pop": {"dtype": "int64", "ndim": 0, "ragged": False}, "plate_argument": {"dtype": "int64", "ndim": 1, "ragged": False}, "hsgp_t_spectral_scale_omega2": {"dtype": "float64", "ndim": 1, "ragged": False}, "hsgp_t_spectral_scale_PHI": {"dtype": "float64", "ndim": 2, "ragged": False}, "X_mu": {"dtype": "float64", "ndim": 2, "ragged": False}, "subject_level": {"dtype": "int64", "ndim": 1, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}, "ppl_axis1_hsgp_t_beta_raw": {"dtype": "int64", "ndim": 0, "ragged": False}}
UNTRANSLATED = {}
def _fit_np(axis_fit, settings):
axis_fit = np.asarray(axis_fit)
settings = np.asarray(settings)
center = np.sum(axis_fit) / len(axis_fit)
width = settings[0] * np.max(np.abs(axis_fit - center))
fit = np.stack([center, width])
return fit
def _rho_floor_np(fit, modes):
fit = np.asarray(fit)
modes = np.asarray(modes)
width = fit[1]
if modes[0] == 1:
value = 0.0
else:
value = 4 * width / np.pi * np.sqrt(np.log(100.0) / (modes[0] ** 2 - 1))
rho_floor = value
return rho_floor
def _rk_order_key_np(x):
# Julia's isless order of an array as sortable keys: a float is an integer
# key, -0.0 before 0.0 and every NaN last, equal for values isequal treats
# as equal. Integer and string arrays are their own keys.
x = np.asarray(x)
if x.dtype.kind != "f":
return x
bits = np.where(np.isnan(x), np.nan, x).astype(np.float64).view(np.int64)
return np.where(bits < 0, bits ^ np.int64(0x7FFFFFFFFFFFFFFF), bits)
def _rk_unique_np(x):
# Julia's unique of a vector: the first value of each isequal class, in
# order.
x = np.asarray(x)
_, first = np.unique(_rk_order_key_np(x), return_index=True)
return x[np.sort(first)]
def _rk_sort_np(x):
# Julia's sort of a vector: ascending in isless order, equal values in
# their order.
x = np.asarray(x)
return x[np.argsort(_rk_order_key_np(x), kind="stable")]
def _brm_sorted_labels_np(source):
labels = _rk_unique_np(source)
sorted_ = _rk_sort_np(labels)
return sorted_
def _brm_fit_levels_np(source):
value = _brm_sorted_labels_np(source)
levels = value
return levels
def _rk_dict_key(x):
if isinstance(x, tuple):
return (1, tuple(map(_rk_dict_key, x)))
if isinstance(x, np.ndarray):
return (2, x.shape, tuple(map(_rk_dict_key, x.ravel(order="F"))))
if isinstance(x, (complex, np.complexfloating)):
if x.imag == 0 and not np.signbit(x.imag):
return _rk_dict_key(x.real)
return (3, _rk_dict_key(x.real), _rk_dict_key(x.imag))
if isinstance(x, (float, np.floating)):
if np.isnan(x):
return (4,)
if x == 0 and np.signbit(x):
return (5,)
return (0, x)
class _RKDict:
def __init__(self, pairs=()):
self.data = {}
for key, value in pairs:
self[key] = value
def __len__(self):
return len(self.data)
def __contains__(self, key):
return _rk_dict_key(key) in self.data
def __getitem__(self, key):
return self.data[_rk_dict_key(key)][1]
def __setitem__(self, key, value):
self.data[_rk_dict_key(key)] = (key, value)
def get(self, key, default):
item = self.data.get(_rk_dict_key(key))
return default if item is None else item[1]
def setdefault(self, key, default):
return self.data.setdefault(_rk_dict_key(key), (key, default))[1]
def pop(self, key, default):
item = self.data.pop(_rk_dict_key(key), None)
return default if item is None else item[1]
def items(self):
return self.data.values()
def keys(self):
return (item[0] for item in self.items())
def values(self):
return (item[1] for item in self.items())
def copy(self):
return _RKDict(self.items())
def _brm_level_indices_np(labels, source):
value = _brm_fit_levels_np(source)
levels = value
lookup = _RKDict()
for k in range(1, len(levels) + 1):
lookup[levels[k - 1]] = k
indices = np.zeros((len(labels),), dtype=np.int64)
for r in range(1, len(labels) + 1):
position = lookup.get(labels[r - 1], 0)
if position == 0:
raise ValueError("".join([str("RK backend: group label `"), str(labels[r - 1]), str("` is not one of the "), str(len(levels)), str(" fitted levels. A replay keeps the fitted levels of every grouping it does not resample; name the grouping in `resample_groups` to take the new data's own levels.")]))
indices[r - 1] = position
return indices
def _rk_levels_np(x):
arr = np.asarray(x)
values = sorted(set(v for v in arr.tolist() if v is not None))
return np.array(values, dtype=object if arr.dtype == object else arr.dtype)
class StaticInt(int):
"""An integer of the prepared data that sets a shape.
It is an `int` everywhere, and `jax.jit` treats it as static, so the
functions jit with the prepared data as arguments; a new value traces
them again.
"""
def __repr__(self):
return "StaticInt(%d)" % int(self)
jax.tree_util.register_pytree_node(StaticInt, lambda s: ((), int(s)), lambda v, _: StaticInt(v))
def brm_hsgp_effect(
beta_raw: ArrayLike,
plate_argument: ArrayLike,
rho_iso: ArrayLike,
sigma: ArrayLike,
value_PHI: ArrayLike,
value_omega2: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""A Hilbert-space Gaussian-process (HSGP) effect.
Draws the length scale `rho_iso`, each truncated below at the floor `rho_floor` the basis resolves, the marginal scale `sigma` and standardized basis
coefficients `beta_raw ~ Normal(0, 1)`. Each basis function is weighted by the
square root of the covariance's spectral density (`spectral_scale`), and the
effect at the rows is the basis times the weighted coefficients.
"""
results = {}
if any(name in outputs for name in ("spectral_scale", "value")):
def weights_cell(b, sigma_2, rho, omega2):
return_ = sigma_2 * (rho * np.sqrt(2 * np.pi)) ** (1 / 2) * jnp.exp(-0.25 * (rho ** 2 * omega2[b - 1]))
return return_
spectral_scale = (jnp.zeros(plate_argument.shape[:1], dtype=jnp.float64) if 0 in plate_argument.shape[:1] else jax.vmap(weights_cell, in_axes=(0, None, None, None))(plate_argument, sigma, rho_iso, value_omega2))
if any(name in outputs for name in ("value",)):
value = value_PHI @ (spectral_scale * beta_raw)
if any(name in outputs for name in ("ppl_prior_rho_iso", "ppl_prior_rho_iso_logpdf")):
ppl_prior_rho_iso_location = 0.0
ppl_prior_rho_iso_scale = 1.0
ppl_prior_rho_iso_log_scale = np.log(ppl_prior_rho_iso_scale)
if any(name in outputs for name in ("ppl_prior_rho_iso", "ppl_prior_rho_iso_logpdf", "ppl_prior_rho_iso_logpdf_jacobian")):
ppl_prior_rho_iso_logpdf_log_x = jax.lax.cond(rho_iso <= 0, lambda: -jnp.inf, lambda: jnp.log(rho_iso))
if any(name in outputs for name in ("ppl_prior_rho_iso", "ppl_prior_rho_iso_logpdf_jacobian")):
ppl_prior_rho_iso_logpdf_jacobian = jnp.where(rho_iso <= 0, 0.0, ppl_prior_rho_iso_logpdf_log_x)
if any(name in outputs for name in ("ppl_prior_rho_iso", "ppl_prior_rho_iso_logpdf")):
ppl_prior_rho_iso_logpdf_logpdf_logpdf_z = (ppl_prior_rho_iso_logpdf_log_x - ppl_prior_rho_iso_location) / jnp.where((ppl_prior_rho_iso_logpdf_log_x == ppl_prior_rho_iso_location if ppl_prior_rho_iso_scale == 0 else False), 1.0, ppl_prior_rho_iso_scale)
ppl_prior_rho_iso_logpdf_logpdf_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_rho_iso_logpdf_logpdf_logpdf_z ** 2
ppl_prior_rho_iso_logpdf = ppl_prior_rho_iso_logpdf_logpdf_standard_logpdf - jnp.where((ppl_prior_rho_iso_logpdf_log_x != ppl_prior_rho_iso_location if ppl_prior_rho_iso_scale == 0 else False), 0.0, ppl_prior_rho_iso_log_scale)
if any(name in outputs for name in ("ppl_prior_rho_iso",)):
ppl_prior_rho_iso = ppl_prior_rho_iso_logpdf - ppl_prior_rho_iso_logpdf_jacobian
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_log_scale", "ppl_prior_sigma_scale")):
ppl_prior_sigma_scale = 0.7
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_log_scale")):
ppl_prior_sigma_log_scale = np.log(ppl_prior_sigma_scale)
if any(name in outputs for name in ("ppl_prior_sigma",)):
ppl_prior_sigma = jax.lax.cond(sigma < 0, lambda: -jnp.inf, lambda: -ppl_prior_sigma_log_scale - sigma / ppl_prior_sigma_scale)
if any(name in outputs for name in ("ppl_prior_beta_raw", "ppl_pw_prior_beta_raw")):
def ppl_pw_prior_beta_raw_cell(beta_raw_2):
log_scale = np.log(1.0)
standardized = (beta_raw_2 - 0.0) / jnp.where((beta_raw_2 == 0.0 if 1.0 == 0 else False), 1.0, 1.0)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf = standard_logpdf - jnp.where((beta_raw_2 != 0.0 if 1.0 == 0 else False), 0.0, log_scale)
return logpdf
ppl_pw_prior_beta_raw = (jnp.zeros(beta_raw.shape[:1], dtype=jnp.float64) if 0 in beta_raw.shape[:1] else jax.vmap(ppl_pw_prior_beta_raw_cell, in_axes=(0,))(beta_raw))
if any(name in outputs for name in ("ppl_prior_beta_raw",)):
ppl_prior_beta_raw = jnp.sum(ppl_pw_prior_beta_raw)
if "ppl_prior_beta_raw" in outputs:
results["ppl_prior_beta_raw"] = ppl_prior_beta_raw
if "ppl_prior_rho_iso" in outputs:
results["ppl_prior_rho_iso"] = ppl_prior_rho_iso
if "ppl_prior_sigma" in outputs:
results["ppl_prior_sigma"] = ppl_prior_sigma
if "ppl_pw_prior_beta_raw" in outputs:
results["ppl_pw_prior_beta_raw"] = ppl_pw_prior_beta_raw
if "ppl_prior_rho_iso_logpdf" in outputs:
results["ppl_prior_rho_iso_logpdf"] = ppl_prior_rho_iso_logpdf
if "ppl_prior_rho_iso_logpdf_jacobian" in outputs:
results["ppl_prior_rho_iso_logpdf_jacobian"] = ppl_prior_rho_iso_logpdf_jacobian
if "ppl_prior_sigma_log_scale" in outputs:
results["ppl_prior_sigma_log_scale"] = ppl_prior_sigma_log_scale
if "ppl_prior_sigma_scale" in outputs:
results["ppl_prior_sigma_scale"] = ppl_prior_sigma_scale
if "spectral_scale" in outputs:
results["spectral_scale"] = spectral_scale
if "value" in outputs:
results["value"] = value
return results
def brm_population_effects(X: ArrayLike, beta_pop: ArrayLike, *, outputs: tuple[str, ...]) -> dict:
"""Population-level effects: one coefficient per column of the design matrix `X`.
Draws `beta_pop[1:ncoef] ~ Normal(loc, scale)` and returns the linear predictor
`X * beta_pop`. `ncoef` is the number of columns of `X`. Each prior argument (`loc`, `scale`) is one value for all coefficients or a vector with one per coefficient.
"""
results = {}
if any(name in outputs for name in ("value",)):
value = X @ beta_pop
if any(name in outputs for name in ("ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
ppl_parg_beta_pop_2 = jnp.asarray([1.0, 0.3], dtype=jnp.float64)
def ppl_pw_prior_beta_pop_cell(beta_pop_2, scale):
log_scale = jnp.log(scale)
standardized = (beta_pop_2 - 0.0) / jnp.where(jnp.logical_and(scale == 0, beta_pop_2 == 0.0), 1.0, scale)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf = standard_logpdf - jnp.where(jnp.logical_and(scale == 0, beta_pop_2 != 0.0), 0.0, log_scale)
return logpdf
ppl_pw_prior_beta_pop = (jnp.zeros(beta_pop.shape[:1], dtype=jnp.float64) if 0 in beta_pop.shape[:1] and ppl_parg_beta_pop_2.shape[:1] == beta_pop.shape[:1] else jax.vmap(ppl_pw_prior_beta_pop_cell, in_axes=(0, 0))(beta_pop, ppl_parg_beta_pop_2))
if any(name in outputs for name in ("ppl_prior_beta_pop",)):
ppl_prior_beta_pop = jnp.sum(ppl_pw_prior_beta_pop)
if "ppl_prior_beta_pop" in outputs:
results["ppl_prior_beta_pop"] = ppl_prior_beta_pop
if "ppl_pw_prior_beta_pop" in outputs:
results["ppl_pw_prior_beta_pop"] = ppl_pw_prior_beta_pop
if "value" in outputs:
results["value"] = value
return results
def brm_group_effects_density(
ppl_last_z: ArrayLike,
tau: ArrayLike,
unconstrained: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Group-level (varying) effects of grouping `g`.
Non-centered, from the scale `tau[1]` (drawn from its prior) and standardized effects
`z[1:length(levels(g)), 1:1] ~ Normal(0, 1)`. Returns the
level-by-margin matrix `z .* tau[1]`, one row per level of `g` in order.
"""
results = {}
if any(name in outputs for name in ("ppl_arrflat_z", "ppl_prior_z", "ppl_pw_prior_z")):
ppl_arrflat_z = unconstrained[4:ppl_last_z]
if any(name in outputs for name in ("ppl_prior_tau", "ppl_pw_prior_tau")):
def ppl_pw_prior_tau_cell(tau_2):
log_scale = np.log(0.5)
logpdf = jax.lax.cond(tau_2 < 0, lambda: -jnp.inf, lambda: -log_scale - tau_2 / 0.5)
return logpdf
ppl_pw_prior_tau = (jnp.zeros(tau.shape[:1], dtype=jnp.float64) if 0 in tau.shape[:1] else jax.vmap(ppl_pw_prior_tau_cell, in_axes=(0,))(tau))
if any(name in outputs for name in ("ppl_prior_tau",)):
ppl_prior_tau = jnp.sum(ppl_pw_prior_tau)
if any(name in outputs for name in ("ppl_prior_z", "ppl_pw_prior_z")):
def ppl_pw_prior_z_cell(z):
log_scale = np.log(1.0)
standardized = (z - 0.0) / jnp.where((z == 0.0 if 1.0 == 0 else False), 1.0, 1.0)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf = standard_logpdf - jnp.where((z != 0.0 if 1.0 == 0 else False), 0.0, log_scale)
return logpdf
ppl_pw_prior_z = (jnp.zeros(ppl_arrflat_z.shape[:1], dtype=jnp.float64) if 0 in ppl_arrflat_z.shape[:1] else jax.vmap(ppl_pw_prior_z_cell, in_axes=(0,))(ppl_arrflat_z))
if any(name in outputs for name in ("ppl_prior_z",)):
ppl_prior_z = jnp.sum(ppl_pw_prior_z)
if "ppl_arrflat_z" in outputs:
results["ppl_arrflat_z"] = ppl_arrflat_z
if "ppl_prior_tau" in outputs:
results["ppl_prior_tau"] = ppl_prior_tau
if "ppl_prior_z" in outputs:
results["ppl_prior_z"] = ppl_prior_z
if "ppl_pw_prior_tau" in outputs:
results["ppl_pw_prior_tau"] = ppl_pw_prior_tau
if "ppl_pw_prior_z" in outputs:
results["ppl_pw_prior_z"] = ppl_pw_prior_z
return results
def brm_group_effects(tau: ArrayLike, z: ArrayLike, *, outputs: tuple[str, ...]) -> dict:
"""Group-level (varying) effects of grouping `g`.
Non-centered, from the scale `tau[1]` (drawn from its prior) and standardized effects
`z[1:length(levels(g)), 1:1] ~ Normal(0, 1)`. Returns the
level-by-margin matrix `z .* tau[1]`, one row per level of `g` in order.
"""
results = {}
if any(name in outputs for name in ("value",)):
value = z * tau[0]
if "value" in outputs:
results["value"] = value
return results
def prepare_data(hsgp_t_modes_fit: ArrayLike, hsgp_t_settings_fit: ArrayLike, subject: Any, subject_fit: Any, t: ArrayLike, t_fit: ArrayLike, x: ArrayLike, y: ArrayLike) -> dict:
"""The functions' data inputs, computed from the raw data once per dataset.
Pass the data by the names the model reads them; a list of arrays is a ragged
column. Call the other functions with the result: `f(u, **prepared)`.
"""
hsgp_t_modes_fit = np.asarray(hsgp_t_modes_fit, dtype=np.int64)
hsgp_t_settings_fit = np.asarray(hsgp_t_settings_fit, dtype=np.float64)
subject = np.asarray(subject, dtype=object)
subject_fit = np.asarray(subject_fit, dtype=object)
t = np.asarray(t, dtype=np.float64)
t_fit = np.asarray(t_fit, dtype=np.float64)
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
X_mu = np.asarray(np.concatenate([np.ones((len(t),), dtype=np.float64)[:, None], x[:, None]], axis=1), dtype=np.float64)
hsgp_t_settings = np.asarray(hsgp_t_settings_fit.copy(), dtype=np.float64)
value = _fit_np(t_fit, hsgp_t_settings)
hsgp_t_fit = np.asarray(value, dtype=np.float64)
hsgp_t_modes = np.asarray(hsgp_t_modes_fit.copy(), dtype=np.int64)
value_2 = _rho_floor_np(hsgp_t_fit, hsgp_t_modes)
hsgp_t_rho_floor = value_2
value_3 = _brm_fit_levels_np(subject_fit)
subject_fit_levels = value_3
value_4 = _brm_level_indices_np(subject, subject_fit_levels)
subject_level = np.asarray(value_4, dtype=np.int64)
ppl_axis1_b_mu_subject_subject_z = len(_rk_levels_np(subject_fit_levels))
ppl_last_b_mu_subject_subject_z = 4 + ppl_axis1_b_mu_subject_subject_z
ppl_axis1_hsgp_t_beta_raw = np.prod(hsgp_t_modes)
ppl_first_hsgp_t_beta_raw = ppl_last_b_mu_subject_subject_z + 1
ppl_last_hsgp_t_beta_raw = ppl_first_hsgp_t_beta_raw + (ppl_axis1_hsgp_t_beta_raw - 1)
ppl_first_pop_mu_beta_pop = ppl_last_hsgp_t_beta_raw + 1
ppl_last_pop_mu_beta_pop = ppl_first_pop_mu_beta_pop + 1
hsgp_t_spectral_scale_B = np.prod(hsgp_t_modes)
hsgp_t_spectral_scale_center = hsgp_t_fit[0]
hsgp_t_spectral_scale_width = hsgp_t_fit[1]
plate_argument = np.arange(1, hsgp_t_spectral_scale_B + 1)
def cell(mode, width):
return_ = (mode * np.pi / (2 * width)) ** 2
return return_
hsgp_t_spectral_scale_omega2 = np.asarray([cell(element, hsgp_t_spectral_scale_width) for element in plate_argument], dtype=np.float64)
def cell_2(x_2, B, omega2, center, width):
plate_argument_2 = np.arange(1, B + 1)
def cell_3(b, omega2_2, x_3, center_2, width_2):
return_ = np.sin(np.sqrt(omega2_2[b - 1]) * (x_3 - center_2 + width_2)) / np.sqrt(width_2)
return return_
values = np.asarray([cell_3(element_2, omega2, x_2, center, width) for element_2 in plate_argument_2], dtype=np.float64)
return values
hsgp_t_spectral_scale_basis_rows = [cell_2(element_2, hsgp_t_spectral_scale_B, hsgp_t_spectral_scale_omega2, hsgp_t_spectral_scale_center, hsgp_t_spectral_scale_width) for element_2 in t]
hsgp_t_spectral_scale_PHI = np.stack(hsgp_t_spectral_scale_basis_rows, axis=0)
plate_argument_2 = np.arange(1, len(hsgp_t_spectral_scale_omega2) + 1)
return {"hsgp_t_rho_floor": hsgp_t_rho_floor, "ppl_last_b_mu_subject_subject_z": StaticInt(ppl_last_b_mu_subject_subject_z), "ppl_axis1_b_mu_subject_subject_z": StaticInt(ppl_axis1_b_mu_subject_subject_z), "ppl_first_hsgp_t_beta_raw": StaticInt(ppl_first_hsgp_t_beta_raw), "ppl_last_hsgp_t_beta_raw": StaticInt(ppl_last_hsgp_t_beta_raw), "ppl_first_pop_mu_beta_pop": StaticInt(ppl_first_pop_mu_beta_pop), "ppl_last_pop_mu_beta_pop": StaticInt(ppl_last_pop_mu_beta_pop), "plate_argument": np.asarray(plate_argument_2, dtype=np.int64), "hsgp_t_spectral_scale_omega2": np.asarray(hsgp_t_spectral_scale_omega2, dtype=np.float64), "hsgp_t_spectral_scale_PHI": np.asarray(hsgp_t_spectral_scale_PHI, dtype=np.float64), "X_mu": np.asarray(X_mu, dtype=np.float64), "subject_level": np.asarray(subject_level, dtype=np.int64), "y": np.asarray(y, dtype=np.float64), "ppl_axis1_hsgp_t_beta_raw": StaticInt(ppl_axis1_hsgp_t_beta_raw)}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
hsgp_t_rho_floor = prepared["hsgp_t_rho_floor"]
ppl_last_b_mu_subject_subject_z = prepared["ppl_last_b_mu_subject_subject_z"]
ppl_axis1_b_mu_subject_subject_z = prepared["ppl_axis1_b_mu_subject_subject_z"]
ppl_first_hsgp_t_beta_raw = prepared["ppl_first_hsgp_t_beta_raw"]
ppl_last_hsgp_t_beta_raw = prepared["ppl_last_hsgp_t_beta_raw"]
ppl_first_pop_mu_beta_pop = prepared["ppl_first_pop_mu_beta_pop"]
ppl_last_pop_mu_beta_pop = prepared["ppl_last_pop_mu_beta_pop"]
plate_argument = prepared["plate_argument"]
hsgp_t_spectral_scale_omega2 = prepared["hsgp_t_spectral_scale_omega2"]
hsgp_t_spectral_scale_PHI = prepared["hsgp_t_spectral_scale_PHI"]
X_mu = prepared["X_mu"]
subject_level = prepared["subject_level"]
y = prepared["y"]
ppl_axis1_hsgp_t_beta_raw = prepared["ppl_axis1_hsgp_t_beta_raw"]
unconstrained = jnp.asarray(unconstrained)
plate_argument = jnp.asarray(plate_argument)
hsgp_t_spectral_scale_omega2 = jnp.asarray(hsgp_t_spectral_scale_omega2)
hsgp_t_spectral_scale_PHI = jnp.asarray(hsgp_t_spectral_scale_PHI)
X_mu = jnp.asarray(X_mu)
subject_level = jnp.asarray(subject_level)
y = jnp.asarray(y)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
ppl_fl_hsgp_t_rho_iso = unconstrained[0]
hsgp_t_rho_iso = jnp.maximum(hsgp_t_rho_floor, 0.0) + jnp.exp(ppl_fl_hsgp_t_rho_iso)
u_argument = unconstrained[1]
constrain_2 = jnp.exp(u_argument)
u_argument_2 = unconstrained[2]
constrain_3 = jnp.exp(u_argument_2)
plate_argument_2 = unconstrained[3:4]
def b_mu_subject_subject_tau_cell(ppl_cell_b_mu_subject_subject_tau):
constrain_4 = jnp.exp(ppl_cell_b_mu_subject_subject_tau)
return constrain_4
b_mu_subject_subject_tau = (jnp.zeros(plate_argument_2.shape[:1], dtype=jnp.float64) if 0 in plate_argument_2.shape[:1] else jax.vmap(b_mu_subject_subject_tau_cell, in_axes=(0,))(plate_argument_2))
if _entry in ("log_density", "log_jacobian"):
plate_argument_3 = unconstrained[3:4]
def ppl_ljcells_b_mu_subject_subject_tau_cell(ppl_cell_b_mu_subject_subject_tau):
return ppl_cell_b_mu_subject_subject_tau
ppl_ljcells_b_mu_subject_subject_tau = (jnp.zeros(plate_argument_3.shape[:1], dtype=jnp.float64) if 0 in plate_argument_3.shape[:1] else jax.vmap(ppl_ljcells_b_mu_subject_subject_tau_cell, in_axes=(0,))(plate_argument_3))
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
hsgp_t_beta_raw = unconstrained[ppl_first_hsgp_t_beta_raw - 1:ppl_last_hsgp_t_beta_raw]
if _entry in ("log_density", "log_prior", "log_likelihood"):
hsgp_t = brm_hsgp_effect(
beta_raw=(hsgp_t_beta_raw if _entry in ("log_density", "log_prior", "log_likelihood") else None),
plate_argument=(plate_argument if _entry in ("log_density", "log_likelihood") else None),
rho_iso=(hsgp_t_rho_iso if _entry in ("log_density", "log_prior", "log_likelihood") else None),
sigma=(constrain_2 if _entry in ("log_density", "log_prior", "log_likelihood") else None),
value_PHI=(hsgp_t_spectral_scale_PHI if _entry in ("log_density", "log_likelihood") else None),
value_omega2=(hsgp_t_spectral_scale_omega2 if _entry in ("log_density", "log_likelihood") else None),
outputs=tuple(
name for name, needed in (
("ppl_prior_beta_raw", ("log_density", "log_prior")),
("ppl_prior_rho_iso", ("log_density", "log_prior")),
("ppl_prior_sigma", ("log_density", "log_prior")),
("ppl_pw_prior_beta_raw", ("log_density", "log_prior")),
("ppl_prior_rho_iso_logpdf", ("log_density", "log_prior")),
("ppl_prior_rho_iso_logpdf_jacobian", ("log_density", "log_prior")),
("ppl_prior_sigma_log_scale", ("log_density", "log_prior")),
("ppl_prior_sigma_scale", ("log_density", "log_prior")),
("spectral_scale", ("log_density", "log_likelihood")),
("value", ("log_density", "log_likelihood")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
pop_mu_beta_pop = unconstrained[ppl_first_pop_mu_beta_pop - 1:ppl_last_pop_mu_beta_pop]
if _entry in ("log_density", "log_prior", "log_likelihood"):
pop_mu = brm_population_effects(
X=(X_mu if _entry in ("log_density", "log_likelihood") else None),
beta_pop=(pop_mu_beta_pop if _entry in ("log_density", "log_prior", "log_likelihood") else None),
outputs=tuple(
name for name, needed in (
("ppl_prior_beta_pop", ("log_density", "log_prior")),
("ppl_pw_prior_beta_pop", ("log_density", "log_prior")),
("value", ("log_density", "log_likelihood")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_prior"):
ppl_prior_sigma_log_scale = np.log(0.5)
logpdf = jax.lax.cond(constrain_3 < 0, lambda: -jnp.inf, lambda: -ppl_prior_sigma_log_scale - constrain_3 / 0.5)
if _entry in ("log_density", "log_jacobian"):
u_argument_3 = unconstrained[1]
u_argument_4 = unconstrained[2]
plate_fold = jnp.sum(ppl_ljcells_b_mu_subject_subject_tau)
log_jacobian_2 = unconstrained[0] + u_argument_3 + u_argument_4 + plate_fold
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
b_mu_subject_subject = brm_group_effects_density(
ppl_last_z=(ppl_last_b_mu_subject_subject_z if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") else None),
tau=(b_mu_subject_subject_tau if _entry in ("log_density", "log_prior") else None),
unconstrained=(unconstrained if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") else None),
outputs=tuple(
name for name, needed in (
("ppl_arrflat_z", ("log_density", "log_prior", "log_likelihood", "constrain")),
("ppl_prior_tau", ("log_density", "log_prior")),
("ppl_prior_z", ("log_density", "log_prior")),
("ppl_pw_prior_tau", ("log_density", "log_prior")),
("ppl_pw_prior_z", ("log_density", "log_prior")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_likelihood", "constrain"):
b_mu_subject_subject_z = jnp.reshape(b_mu_subject_subject["ppl_arrflat_z"], (ppl_axis1_b_mu_subject_subject_z, 1), order="F")
if _entry in ("log_density", "log_prior"):
prior = hsgp_t["ppl_prior_rho_iso"] + hsgp_t["ppl_prior_sigma"] + logpdf + b_mu_subject_subject["ppl_prior_tau"] + b_mu_subject_subject["ppl_prior_z"] + hsgp_t["ppl_prior_beta_raw"] + pop_mu["ppl_prior_beta_pop"]
if _entry in ("log_density", "log_likelihood"):
b_mu_subject_subject_2 = brm_group_effects(
tau=(b_mu_subject_subject_tau if _entry in ("log_density", "log_likelihood") else None),
z=(b_mu_subject_subject_z if _entry in ("log_density", "log_likelihood") else None),
outputs=tuple(
name for name, needed in (
("value", ("log_density", "log_likelihood")),
)
if _entry in needed
),
)
ppl_column_b_mu_subject_subject_1 = b_mu_subject_subject_2["value"][:, 0]
plate_argument_4 = ppl_column_b_mu_subject_subject_1[subject_level - 1]
def ppl_offset_mu_cell(pop_mu_2, value):
plate_value = pop_mu_2 + value
return plate_value
ppl_offset_mu = (jnp.zeros(pop_mu["value"].shape[:1], dtype=jnp.float64) if 0 in pop_mu["value"].shape[:1] and plate_argument_4.shape[:1] == pop_mu["value"].shape[:1] else jax.vmap(ppl_offset_mu_cell, in_axes=(0, 0))(pop_mu["value"], plate_argument_4))
ppl_located_mu = ppl_offset_mu + hsgp_t["value"]
mu = jnp.ones(max(y.shape[0], X_mu.shape[0], subject_level.shape[0])) * ppl_located_mu
def ppl_pw_y_resp_cell(y_2, mu_2, sigma):
def then_arm():
log_scale = jnp.log(sigma)
standardized = (y_2 - mu_2) / jnp.where(jnp.logical_and(sigma == 0, y_2 == mu_2), 1.0, sigma)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
return standard_logpdf - jnp.where(jnp.logical_and(sigma == 0, y_2 != mu_2), 0.0, log_scale)
ppl_density = jax.lax.cond(sigma > 0, then_arm, lambda: -jnp.inf)
return ppl_density
ppl_pw_y_resp = (jnp.zeros(y.shape[:1], dtype=jnp.float64) if 0 in y.shape[:1] and mu.shape[:1] == y.shape[:1] else jax.vmap(ppl_pw_y_resp_cell, in_axes=(0, 0, None))(y, mu, constrain_3))
ppl_lik_y_resp = jnp.sum(ppl_pw_y_resp)
if _entry in ("log_density",):
posterior = prior + ppl_lik_y_resp + log_jacobian_2
if not (unconstrained.size == ppl_last_pop_mu_beta_pop):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
if _entry == "log_density":
return jnp.asarray(posterior, dtype=jnp.float64)
if _entry == "log_prior":
return jnp.asarray(prior, dtype=jnp.float64)
if _entry == "log_likelihood":
return jnp.asarray(ppl_lik_y_resp, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(log_jacobian_2, dtype=jnp.float64)
if _entry == "constrain":
return {"hsgp_t": {"rho_iso": jnp.asarray(hsgp_t_rho_iso, dtype=jnp.float64), "sigma": jnp.asarray(constrain_2, dtype=jnp.float64), "beta_raw": jnp.asarray(hsgp_t_beta_raw)}, "sigma": jnp.asarray(constrain_3, dtype=jnp.float64), "b_mu__subject_subject": {"tau": jnp.asarray(b_mu_subject_subject_tau), "z": jnp.asarray(b_mu_subject_subject_z)}, "pop_mu": {"beta_pop": jnp.asarray(pop_mu_beta_pop)}}
def log_density(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log density a sampler targets at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`.
The sum of `log_prior`, `log_likelihood` and `log_jacobian`.
"""
return model("log_density", unconstrained, **prepared)
def log_prior(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log prior density of the constrained parameters at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_prior", unconstrained, **prepared)
def log_likelihood(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log likelihood of the observations at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_likelihood", unconstrained, **prepared)
def log_jacobian(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log Jacobian of the constraining transforms at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_jacobian", unconstrained, **prepared)
def constrain(unconstrained: ArrayLike, **prepared: ArrayLike) -> dict:
"""The constrained value of each parameter, and of each requested value, at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`. Returns a dict, a submodel's values nested under its name:
- `hsgp_t.rho_iso`
- `hsgp_t.sigma`
- `sigma`
- `b_mu__subject_subject.tau`
- `b_mu__subject_subject.z`
- `hsgp_t.beta_raw`
- `pop_mu.beta_pop`
"""
return model("constrain", unconstrained, **prepared)
def dimension(prepared: dict) -> int:
"""The length of `unconstrained` for the data `prepared` (what `prepare_data` returned)."""
return int(prepared["ppl_last_pop_mu_beta_pop"])
def parameters(prepared: dict) -> dict:
"""Each parameter's 0-based `start`/`stop` in `unconstrained`, its transform and dimensions,
for the data `prepared` (what `prepare_data` returned)."""
return {"hsgp_t.rho_iso": {"start": 0, "stop": 1, "transform": "floored", "dims": ()}, "hsgp_t.sigma": {"start": 1, "stop": 2, "transform": "exp", "dims": ()}, "sigma": {"start": 2, "stop": 3, "transform": "exp", "dims": ()}, "b_mu__subject_subject.tau": {"start": 3, "stop": 4, "transform": "exp", "dims": (1,)}, "b_mu__subject_subject.z": {"start": 4, "stop": int(prepared["ppl_last_b_mu_subject_subject_z"]), "transform": "identity", "dims": (int(prepared["ppl_axis1_b_mu_subject_subject_z"]), 1)}, "hsgp_t.beta_raw": {"start": int(prepared["ppl_first_hsgp_t_beta_raw"]) - 1, "stop": int(prepared["ppl_last_hsgp_t_beta_raw"]), "transform": "identity", "dims": (int(prepared["ppl_axis1_hsgp_t_beta_raw"]),)}, "pop_mu.beta_pop": {"start": int(prepared["ppl_first_pop_mu_beta_pop"]) - 1, "stop": int(prepared["ppl_last_pop_mu_beta_pop"]), "transform": "identity", "dims": (2,)}}using BayesianRegressionModels
model = Main.BRMDocsComparisons.example_module(:PriorGuide).model
(coefficient_priors=effect_priors(model), term_priors=term_priors(model))(coefficient_priors = NamedTuple[(predictor = 😦😃, coefficient = :x, family = Normal, arguments = (0, 1), keywords = NamedTuple(), expression = Normal(0, 1), elementwise = false), (predictor = :mu, coefficient = :x, family = Normal, arguments = (0, 0.3), keywords = NamedTuple(), expression = Normal(0, 0.3), elementwise = false)], term_priors = NamedTuple[(class = :term_sd, term = Symbol("hsgp(t)"), predictor = :mu, component = nothing, family = Exponential, arguments = (0.7,), keywords = NamedTuple(), expression = Exponential(0.7), qualifiers = NamedTuple())])
A colon supplies a default for every matching predictor or coefficient; the more specific address wins. Equal-specificity ties and unmatched addresses raise errors during lowering. optional(address) ~ prior is for a reusable prior block whose target may be absent in some members of a model family.
A linked formula such as log(sigma) ~ 1 + x takes addresses under sigma, with coefficient priors on the log scale. A categorical column uses its column name, effect(mu, site). Cell means also accept site_lvl_k for the level in fitted-order position k. For a shared |p| group block, sd(:, p) reaches all margins and cor(:, p) sets its LKJ prior; sd(mu, p) selects the margins belonging to mu. The LKJ dimension must match the block width.
Term addresses omit numeric and keyword arguments: address me(x, 0.3) as me(x). A tensor smooth also needs its penalty component, for example sd(mu, t2(x, z), rr). Standardized innovations retain their standard-normal law; changing their scale would duplicate the term's amplitude.
Bounds and vectors
restricted(D; lower, upper) evaluates the original density on the bounded support. truncated(D; lower, upper) also divides by the probability mass inside the bounds. They give the same posterior when that mass is constant; with sampled hyperparameters, their joint laws differ.
The vector statement here declares one independent positive scale per observation.
A declared vector of positive parameters
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
@plate for i in eachindex(y)
y[i] ~ Normal(location, scales[i])
end
location ~ Normal(0, 1)
scales[1:length(y)] .~ truncated.(Normal.(0.0, 0.5), 0.0, Inf)
end)((; y=[-0.2, 0.1, 0.7]))SBBRMI with data keys = [:kernel_nsub_y_cell, :scales_n, :y]
emitted @slic body:
begin
location ~ normal(0, 1)
scales::vector[scales_n] ~ (StanBlocks.builtin.lower_conditioning)(StanBlocks.builtin.normal, 0.0, 0.0, 0.5; lower = 0.0)
y_cell ~ plate(y, scales; outer = (kernel_nsub_y_cell,)) do y, scales
#= brm-docs-example.jl:3 =#
y ~ normal(location, scales)
#= brm-docs-example.jl:4 =#
nothing
end
endbegin
location ~ Normal(0.0, 1.0)
scales[1:scales_length] .~ HalfNormal.(0.5)
@plate for i = eachindex(y_cell_input_y)
y_cell_argument_y_1[i] = location
y_cell_argument_y_2[i] = scales[i]
end
y .~ Normal.(y_cell_argument_y_1, y_cell_argument_y_2)
endfunctions {
real lower_conditioning_normal_lpdf(
vector y,
real lo,
real args1,
real args2
) {
return sum(lower_conditioning_normal_lpdfs(y, lo, args1, args2));
}
vector lower_conditioning_normal_lpdfs(
vector y,
real lo,
real args1,
real args2
) {
int n = dims(y)[1];
return jbroadcasted_lower_conditioning_lpdf_normal(y, lo, args1, args2);
}
vector jbroadcasted_lower_conditioning_lpdf_normal(
vector x1,
real x3,
real x4,
real x5
) {
int n = dims(x1)[1];
vector[n] rv;
for(i in 1:n) {
rv[i] = lower_conditioning_normal_lpdf(broadcasted_getindex(x1, i) | x3, x4, x5);
}
return rv;
}
real lower_conditioning_normal_lpdf(
real y,
real lo,
real args1,
real args2
) {
array[1] real rv;
rv[1] = negative_infinity();
if((y >= lo)) {
rv[1] = (normal_lpdf(y | args1, args2) - normal_lccdf_stable(lo, args1, args2));
}
return rv[1];
}
real normal_lccdf_stable(
real x,
real loc,
real scale
) {
return (is_inf(x) ? ((x > 0) ? negative_infinity() : 0.0) : ((((x - loc) / scale) > 35) ? std_normal_lcdf_tail(((loc - x) / scale)) : ((((x - loc) / scale) >= 0) ? (log(erfc(((x - loc) / (scale * sqrt(2.0))))) - log(2.0)) : log1m((0.5 * erfc(((-(x - loc)) / (scale * sqrt(2.0)))))))));
}
real std_normal_lcdf_tail(
real z
) {
return ((-0.5 * square(z)) + std_normal_scaled_lcdf_tail(z));
}
real std_normal_scaled_lcdf_tail(
real z
) {
real w = inv(square(z));
return (
((-log((-z))) - 0.9189385332046728) +
log1p((w * (-1 + (w * (3 + (w * (-15 + (w * (105 + (w * (-945 + (w * 10395))))))))))))
);
}
real broadcasted_getindex(vector x, int i) {
return x[i];
}
real normal_lpdfs(
real args1,
real args2,
real args3
) {
return normal_lpdf(args1 | args2, args3);
}
}
data {
int scales_n;
int y_n;
int kernel_nsub_y_cell;
vector[y_n] y;
}
transformed data {
}
parameters {
real location;
vector<lower=0.0>[scales_n] scales;
}
transformed parameters {
}
model {
location ~ normal(0, 1);
scales ~ lower_conditioning_normal(0.0, 0.0, 0.5);
for(plate_i__pl_1 in 1:kernel_nsub_y_cell) {
y[plate_i__pl_1] ~ normal(location, scales[plate_i__pl_1]);
}
}
generated quantities {
vector[y_n] y_gen;
for(plate_i__pl_1 in 1:kernel_nsub_y_cell) {
y_gen[plate_i__pl_1] = normal_rng(location, scales[plate_i__pl_1]);
}
}using ReactiveKernels, ReactiveKernelsPPL
rk = RKBRMI(model)
source = jax_source(rk.model, rk_bound_plan(rk))
write("model.py", source)
inputs = rk_bound_data(rk, source) # exactly the inputs prepare_data readsimport jax
import model as m
prepared = m.prepare_data(**inputs)
lp = m.log_density(u, **prepared) # u: unconstrained, length m.dimension(prepared)
lp = jax.jit(m.log_density)(u, **prepared) # one compiled function for every dataset of these shapes"""Generated by ReactiveKernelsPPL.jax_source from a built @rkppl program; do not edit.
Data: scales_length, y, y_cell_input_y.
"""
import numpy as np
import scipy.special as ssp
from typing import Any
import jax
import jax.numpy as jnp
import jax.scipy.linalg
import jax.scipy.special as jsp
from jax.typing import ArrayLike
jax.config.update("jax_enable_x64", True)
DATA = {"scales_length": {"dtype": "int64", "ndim": 0, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}, "y_cell_input_y": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "_ppl_last_scales", "plate_argument", "y", "scales_length")
PREPARED = {"_ppl_last_scales": {"dtype": "int64", "ndim": 0, "ragged": False}, "plate_argument": {"dtype": "int64", "ndim": 1, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}, "scales_length": {"dtype": "int64", "ndim": 0, "ragged": False}}
UNTRANSLATED = {}
class StaticInt(int):
"""An integer of the prepared data that sets a shape.
It is an `int` everywhere, and `jax.jit` treats it as static, so the
functions jit with the prepared data as arguments; a new value traces
them again.
"""
def __repr__(self):
return "StaticInt(%d)" % int(self)
jax.tree_util.register_pytree_node(StaticInt, lambda s: ((), int(s)), lambda v, _: StaticInt(v))
def prepare_data(scales_length: ArrayLike, y: ArrayLike, y_cell_input_y: ArrayLike) -> dict:
"""The functions' data inputs, computed from the raw data once per dataset.
Pass the data by the names the model reads them; a list of arrays is a ragged
column. Call the other functions with the result: `f(u, **prepared)`.
"""
y = np.asarray(y, dtype=np.float64)
y_cell_input_y = np.asarray(y_cell_input_y, dtype=np.float64)
rkppl_value_scales_length = scales_length
ppl_last_scales = 1 + scales_length
plate_argument = np.arange(1, len(y_cell_input_y) + 1)
return {"_ppl_last_scales": StaticInt(ppl_last_scales), "plate_argument": np.asarray(plate_argument, dtype=np.int64), "y": np.asarray(y, dtype=np.float64), "scales_length": StaticInt(scales_length)}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
_ppl_last_scales = prepared["_ppl_last_scales"]
plate_argument = prepared["plate_argument"]
y = prepared["y"]
scales_length = prepared["scales_length"]
unconstrained = jnp.asarray(unconstrained)
plate_argument = jnp.asarray(plate_argument)
y = jnp.asarray(y)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
location = unconstrained[0]
plate_argument_2 = unconstrained[1:_ppl_last_scales]
def scales_cell(ppl_cell_scales):
constrain_2 = jnp.exp(ppl_cell_scales)
return constrain_2
scales = (jnp.zeros(plate_argument_2.shape[:1], dtype=jnp.float64) if 0 in plate_argument_2.shape[:1] else jax.vmap(scales_cell, in_axes=(0,))(plate_argument_2))
if _entry in ("log_density", "log_jacobian"):
plate_argument_3 = unconstrained[1:_ppl_last_scales]
def ppl_ljcells_scales_cell(ppl_cell_scales):
return ppl_cell_scales
ppl_ljcells_scales = (jnp.zeros(plate_argument_3.shape[:1], dtype=jnp.float64) if 0 in plate_argument_3.shape[:1] else jax.vmap(ppl_ljcells_scales_cell, in_axes=(0,))(plate_argument_3))
if _entry in ("log_density", "log_likelihood"):
def y_cell_argument_y_1_cell(ppl_pi_y_cell_argument_y_1, location_2):
return location_2
y_cell_argument_y_1 = (jnp.zeros(plate_argument.shape[:1], dtype=jnp.float64) if 0 in plate_argument.shape[:1] else jax.vmap(y_cell_argument_y_1_cell, in_axes=(0, None))(plate_argument, location))
def ppl_pw_y_resp_cell(y_2, y_cell_argument_y_1_2, y_cell_argument_y_2):
def then_arm():
log_scale = jnp.log(y_cell_argument_y_2)
standardized = (y_2 - y_cell_argument_y_1_2) / jnp.where(jnp.logical_and(y_cell_argument_y_2 == 0, y_2 == y_cell_argument_y_1_2), 1.0, y_cell_argument_y_2)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
return standard_logpdf - jnp.where(jnp.logical_and(y_cell_argument_y_2 == 0, y_2 != y_cell_argument_y_1_2), 0.0, log_scale)
ppl_density = jax.lax.cond(y_cell_argument_y_2 > 0, then_arm, lambda: -jnp.inf)
return ppl_density
ppl_pw_y_resp = (jnp.zeros(y.shape[:1], dtype=jnp.float64) if 0 in y.shape[:1] and y_cell_argument_y_1.shape[:1] == y.shape[:1] and scales.shape[:1] == y.shape[:1] else jax.vmap(ppl_pw_y_resp_cell, in_axes=(0, 0, 0))(y, y_cell_argument_y_1, scales))
ppl_lik_y_resp = jnp.sum(ppl_pw_y_resp)
if _entry in ("log_density", "log_prior"):
ppl_prior_location_log_scale = np.log(1.0)
ppl_prior_location_standardized = (location - 0.0) / jnp.where((location == 0.0 if 1.0 == 0 else False), 1.0, 1.0)
ppl_prior_location_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_location_standardized ** 2
logpdf = ppl_prior_location_standard_logpdf - jnp.where((location != 0.0 if 1.0 == 0 else False), 0.0, ppl_prior_location_log_scale)
def ppl_pw_prior_scales_cell(scales_2):
log_scale = np.log(0.5)
standardized = (scales_2 - 0.0) / jnp.where((scales_2 == 0.0 if 0.5 == 0 else False), 1.0, 0.5)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf_2 = standard_logpdf - jnp.where((scales_2 != 0.0 if 0.5 == 0 else False), 0.0, log_scale)
plate_value = logpdf_2 + np.log(2)
return plate_value
ppl_pw_prior_scales = (jnp.zeros(scales.shape[:1], dtype=jnp.float64) if 0 in scales.shape[:1] else jax.vmap(ppl_pw_prior_scales_cell, in_axes=(0,))(scales))
ppl_prior_scales = jnp.sum(ppl_pw_prior_scales)
prior = logpdf + ppl_prior_scales
if _entry in ("log_density", "log_jacobian"):
log_jacobian_2 = jnp.sum(ppl_ljcells_scales)
if _entry in ("log_density",):
posterior = prior + ppl_lik_y_resp + log_jacobian_2
if not (unconstrained.size == _ppl_last_scales):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
if _entry == "log_density":
return jnp.asarray(posterior, dtype=jnp.float64)
if _entry == "log_prior":
return jnp.asarray(prior, dtype=jnp.float64)
if _entry == "log_likelihood":
return jnp.asarray(ppl_lik_y_resp, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(log_jacobian_2, dtype=jnp.float64)
if _entry == "constrain":
return {"location": jnp.asarray(location, dtype=jnp.float64), "scales": jnp.asarray(scales)}
def log_density(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log density a sampler targets at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`.
The sum of `log_prior`, `log_likelihood` and `log_jacobian`.
"""
return model("log_density", unconstrained, **prepared)
def log_prior(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log prior density of the constrained parameters at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_prior", unconstrained, **prepared)
def log_likelihood(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log likelihood of the observations at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_likelihood", unconstrained, **prepared)
def log_jacobian(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log Jacobian of the constraining transforms at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_jacobian", unconstrained, **prepared)
def constrain(unconstrained: ArrayLike, **prepared: ArrayLike) -> dict:
"""The constrained value of each parameter, and of each requested value, at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`. Returns a dict, a submodel's values nested under its name:
- `location`
- `scales`
"""
return model("constrain", unconstrained, **prepared)
def dimension(prepared: dict) -> int:
"""The length of `unconstrained` for the data `prepared` (what `prepare_data` returned)."""
return int(prepared["_ppl_last_scales"])
def parameters(prepared: dict) -> dict:
"""Each parameter's 0-based `start`/`stop` in `unconstrained`, its transform and dimensions,
for the data `prepared` (what `prepare_data` returned)."""
return {"location": {"start": 0, "stop": 1, "transform": "identity", "dims": ()}, "scales": {"start": 1, "stop": int(prepared["_ppl_last_scales"]), "transform": "exp", "dims": (int(prepared["scales_length"]),)}}using Distributions
mass_inside(mu) = ccdf(Normal(mu, 1), 0)
locations = [-1., 0., 1.]
mass = mass_inside.(locations)
@assert issorted(mass)
collect(zip(locations, mass))(-1.0, 0.15865525393145702)(0.0, 0.5)(1.0, 0.841344746068543)
The mass changes with the Normal location. Dropping a truncation normalizer when that location is sampled would change its prior.
| Declaration | Use |
|---|---|
x[1:n] .~ Normal.(0, scales) | Independent elements; scalar arguments broadcast, data vectors apply elementwise |
x ~ MvNormal(mean, covariance) | A joint Gaussian vector; Diagonal(v) contains variances |
share ~ Dirichlet(K, a) | A simplex with concentration a per component |
share ~ Dirichlet(alpha) | A simplex with a data-valued concentration vector |
The length of a declared vector comes from an integer or data expression. An undeclared x ~ Normal(0, scales) with vector data has omitted-response semantics; it is not a vector-parameter declaration. mo(c) returns a monotonic effect on observation rows, so it is not a substitute for a standalone simplex.
Structured shrinkage
effect(mu, :) ~ r2d2(R2=Beta(1, 1), tau_bsv=0.5) allocates a predictor's variance between its non-intercept coefficients and one random-intercept residual. sd(:, p) ~ r2d2(reference_scale=sigma) instead allocates a shared group block's variance; include=(:population, :contrasts) extends that budget to its predictors' coefficients. The reference documents exclusions and reference-scale choices. These constructions replace independent priors; they are not extra priors on top of them.
beta ~ Horseshoe(...) declares a coefficient used through an assignment such as mu = beta * x. effect(mu, x) ~ Horseshoe(...) addresses an existing population coefficient. Inspect the backend's supported form before sharing a shrinkage scale across coefficients.
For a fitted application of group and scale priors, continue to the Warfarin example.