Response families
Specify the sampling distribution beside each response and use formulas for any of its parameters. Links are explicit: log(sigma) ~ 1 + x declares a positive scale, while sigma ~ 1 + x declares an unconstrained predictor.
Support and parameters
Choose support first, then a parameterization whose priors you can interpret. The terms reference lists every mapped constructor and the supported compositions.
| Response | Family examples | Parameters | Common explicit link |
|---|---|---|---|
| Real | Normal(mu, sigma), LocationScale(mu, sigma, TDist(nu)) | Location, scale; degrees of freedom | Identity for mu, log for scale |
| Positive | Gamma(shape, scale), InverseGaussian(mu, lambda) | Shape/scale or mean/concentration | Log |
| Probability | Beta(a, b) | Two positive shapes | Log on shapes, or transform mean and precision |
| Binary/trials | BernoulliLogit(eta), BinomialLogit(n, eta) | Log odds; trials are data | Identity on the log odds |
| Count | Poisson(lambda), NegativeBinomial2(mu, phi) | Rate or mean/precision | Log |
| Unordered category | CategoricalLogit(eta2, eta3, ...) | Log odds against the first level | Identity on each log odds |
| Ordered category | Ordinal(Cumulative(), ProbitLink(), eta) | Predictor and inferred thresholds | Link supplied by the tag |
| Ordered category, thresholds given | Ordinal(Cumulative(), ProbitLink(), eta, cuts) | Predictor and the model's threshold vector (per group in a @plate cell) | Response holds codes 1:(length(cuts) + 1) |
| Direction | CircularVonMises(mu, kappa) | Direction and concentration | Identity for direction, log for concentration |
| Joint real vector | MvNormalCholesky([mu1, mu2], L) | Mean vector, covariance factor | Identity for means |
Julia's Exponential and Gamma arguments are scales. BRM converts them to Stan's rate convention when emitting Stan. NormalCanon(eta, lambda) uses precision, NegativeBinomial2(mu, phi) has variance mu + mu^2 / phi, and the scale in a Student-t model is not its standard deviation.
This model uses one covariate in a real-valued measurement and a positive waiting time. Each response has its own distributional predictors.
Real and positive responses
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
mu ~ 1 + x
log(sigma) ~ 1
log(wait_mean) ~ 1 + x
y ~ Normal(mu, sigma)
waiting ~ InverseGaussian(wait_mean, concentration)
effect(mu, :) ~ Normal(0, 1)
effect(sigma, Intercept) ~ Normal(-1, 0.5)
effect(wait_mean, :) ~ Normal(0, 0.5)
concentration ~ Exponential(1)
end)((; x=[-1., 0., 1.], y=[-0.2, 0.4, 0.8], waiting=[0.5, 0.9, 1.8]))SBBRMI with data keys = [:waiting, :x, :y]
emitted @slic body:
begin
X_mu = hcat(rep_vector(1.0, num_elements(x)), x)
pop_mu ~ _popefs_normal_coefs(; X = X_mu, beta_loc = [0, 0], beta_scale = [1, 1])
X_log_sigma = hcat(rep_vector(1.0, num_elements(y)))
pop_log_sigma ~ _popefs_normal(; X = X_log_sigma, beta_loc = [-1], beta_scale = [0.5])
log_sigma = pop_log_sigma
sigma = exp(log_sigma)
X_log_wait_mean = hcat(rep_vector(1.0, num_elements(x)), x)
pop_log_wait_mean ~ _popefs_normal(; X = X_log_wait_mean, beta_loc = [0, 0], beta_scale = [0.5, 0.5])
log_wait_mean = pop_log_wait_mean
wait_mean = exp(log_wait_mean)
y ~ normal_id_glm(X_mu, 0.0, pop_mu, sigma)
mu = X_mu * pop_mu
concentration ~ exponential(1.0 ./ 1)
waiting ~ brm_inverse_gaussian(wait_mean, concentration)
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
"""
Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
brm_joint_population_effects(X, ncoef, ntargets, loc, scale) = begin
beta_pop[1:ncoef, 1:ntargets] .~ Normal.(loc, scale)
return X * beta_pop
end
begin
X_Intercept_x = hcat(ones(length(x)), x)
pop_Intercept_x ~ brm_joint_population_effects(X_Intercept_x, 2, 2, 0.0, hcat([1.0, 1.0], [0.5, 0.5]))
pop_mu = pop_Intercept_x[:, 1]
mu = pop_mu
sigma_Intercept ~ Normal(-1.0, 0.5)
log_sigma = sigma_Intercept
sigma = exp.(log_sigma)
pop_log_wait_mean = pop_Intercept_x[:, 2]
log_wait_mean = pop_log_wait_mean
wait_mean = exp.(log_wait_mean)
concentration ~ Exponential(1.0)
y .~ Normal.(mu, exp.(log_sigma))
waiting .~ InverseGaussian.(exp.(log_wait_mean), concentration)
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);
}
matrix hcat(vector x) {
int n = dims(x)[1];
return to_matrix(x, n, 1);
}
vector normal_id_glm_lpdfs(
vector y,
matrix X,
real alpha,
vector beta,
vector sigma
) {
int n = dims(y)[1];
if (dims(X)[1] != n) reject("normal_id_glm_lpdfs: dim mismatch — `X` dim 1 (= ", dims(X)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `X` dim 1 (= ", dims(X)[1], ").");
vector[n] rv;
for(i in 1:n) {
rv[i] = normal_lpdf(y[i] | (alpha + (X[i, :] * beta)), sigma);
}
return rv;
}
vector normal_id_glm_vector_rng(
int anontok__1,
matrix X,
real alpha,
vector beta,
vector sigma
) {
int m = anontok__1;
if (dims(X)[1] != m) reject("normal_id_glm_rng: dim mismatch — `X` dim 1 (= ", dims(X)[1], ") does not match `m` (= ", m, "), inferred from `anontok__1` dim 1. `m` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `X` dim 1 (= ", dims(X)[1], ").");
if((m == 0)) {
vector[m] rv;
return rv;
} else {
return normal_id_glm_rng(X, alpha, beta, sigma);
}
}
vector normal_id_glm_rng(
matrix X,
real alpha,
vector beta,
vector sigma
) {
int m = dims(X)[1];
if((m == 0)) {
vector[m] rv;
return rv;
} else {
return to_vector(normal_rng((rep_vector(alpha, m) + (X * beta)), sigma));
}
}
real brm_inverse_gaussian_lpdf(
vector y,
vector mu,
real lambda
) {
int n = dims(y)[1];
if (dims(mu)[1] != n) reject("brm_inverse_gaussian_lpdf: dim mismatch — `mu` dim 1 (= ", dims(mu)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `mu` dim 1 (= ", dims(mu)[1], ").");
return brm_inverse_gaussian_lpdf(y | mu, rep_vector(lambda, n));
}
real brm_inverse_gaussian_lpdf(
vector y,
vector mu,
vector lambda
) {
int n = dims(y)[1];
if (dims(mu)[1] != n) reject("brm_inverse_gaussian_lpdf: dim mismatch — `mu` dim 1 (= ", dims(mu)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `mu` dim 1 (= ", dims(mu)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], ").");
if (dims(lambda)[1] != n) reject("brm_inverse_gaussian_lpdf: dim mismatch — `lambda` dim 1 (= ", dims(lambda)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `mu` dim 1 (= ", dims(mu)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], ").");
real rv = 0.0;
for(i in 1:n) {
rv += brm_inverse_gaussian_lpdf(y[i] | mu[i], lambda[i]);
}
return rv;
}
real brm_inverse_gaussian_lpdf(
real y,
real mu,
real lambda
) {
if((mu <= 0.0)) {
return negative_infinity();
} else {
if((lambda <= 0.0)) {
return negative_infinity();
} else {
if((y <= 0.0)) {
return negative_infinity();
} else {
return (
(
(log(lambda) - (1.8378770664093456 + (3.0 * log(y)))) -
((lambda * (y - mu) * (y - mu)) / (mu * mu * y))
) /
2.0
);
}
}
}
}
vector brm_inverse_gaussian_lpdfs(
vector y,
vector mu,
real lambda
) {
int n = dims(y)[1];
if (dims(mu)[1] != n) reject("brm_inverse_gaussian_lpdfs: dim mismatch — `mu` dim 1 (= ", dims(mu)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `mu` dim 1 (= ", dims(mu)[1], ").");
return brm_inverse_gaussian_lpdfs(y, mu, rep_vector(lambda, n));
}
vector brm_inverse_gaussian_lpdfs(
vector y,
vector mu,
vector lambda
) {
int n = dims(y)[1];
if (dims(mu)[1] != n) reject("brm_inverse_gaussian_lpdfs: dim mismatch — `mu` dim 1 (= ", dims(mu)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `mu` dim 1 (= ", dims(mu)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], ").");
if (dims(lambda)[1] != n) reject("brm_inverse_gaussian_lpdfs: dim mismatch — `lambda` dim 1 (= ", dims(lambda)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `mu` dim 1 (= ", dims(mu)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], ").");
vector[n] rv;
for(i in 1:n) {
rv[i] = brm_inverse_gaussian_lpdf(y[i] | mu[i], lambda[i]);
}
return rv;
}
vector brm_inverse_gaussian_vector_rng(
int anontok__1,
vector mu,
real lambda
) {
int n = anontok__1;
if (dims(mu)[1] != n) reject("brm_inverse_gaussian_rng: dim mismatch — `mu` dim 1 (= ", dims(mu)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `mu` dim 1 (= ", dims(mu)[1], ").");
vector[n] rv;
for(i in 1:n) {
rv[i] = brm_inverse_gaussian_rng(mu[i], lambda);
}
return rv;
}
real brm_inverse_gaussian_rng(
real mu,
real lambda
) {
if((mu <= 0.0)) {
reject("brm_inverse_gaussian_rng: mu must be strictly positive");
return 0.0;
} else {
if((lambda <= 0.0)) {
reject("brm_inverse_gaussian_rng: lambda must be strictly positive");
return 0.0;
} else {
real z = normal_rng(0.0, 1.0);
real v = (z * z);
real w = (mu * v);
real x = (mu + ((mu / (2.0 * lambda)) * (w - sqrt((w * ((4.0 * lambda) + w))))));
real u = uniform_rng(0.0, 1.0);
if((u < (mu / (mu + x)))) {
return x;
} else {
return ((mu * mu) / x);
}
}
}
}
}
data {
int x_n;
vector[x_n] x;
int y_n;
vector[y_n] y;
int waiting_n;
vector[waiting_n] waiting;
}
transformed data {
matrix[x_n, 2] X_mu = hcat(rep_vector(1.0, num_elements(x)), x);
int pop_mu_n_covariates = 2;
matrix[num_elements(y), 1] X_log_sigma = hcat(rep_vector(1.0, num_elements(y)));
int pop_log_sigma_n_covariates = 1;
matrix[x_n, 2] X_log_wait_mean = hcat(rep_vector(1.0, num_elements(x)), x);
int pop_log_wait_mean_n_covariates = 2;
}
parameters {
vector[pop_mu_n_covariates] pop_mu_beta_pop;
vector[pop_log_sigma_n_covariates] pop_log_sigma_beta_pop;
vector[pop_log_wait_mean_n_covariates] pop_log_wait_mean_beta_pop;
real<lower=0.0> concentration;
}
transformed parameters {
vector[pop_mu_n_covariates] pop_mu = pop_mu_beta_pop;
vector[num_elements(y)] pop_log_sigma = (X_log_sigma * pop_log_sigma_beta_pop);
vector[num_elements(y)] log_sigma = pop_log_sigma;
vector[num_elements(y)] sigma = exp(log_sigma);
vector[x_n] pop_log_wait_mean = (X_log_wait_mean * pop_log_wait_mean_beta_pop);
vector[x_n] log_wait_mean = pop_log_wait_mean;
vector[x_n] wait_mean = exp(log_wait_mean);
}
model {
pop_mu_beta_pop ~ normal([0, 0]', [1, 1]');
pop_log_sigma_beta_pop ~ normal([-1]', [0.5]');
pop_log_wait_mean_beta_pop ~ normal([0, 0]', [0.5, 0.5]');
y ~ normal_id_glm(X_mu, 0.0, pop_mu, sigma);
concentration ~ exponential((1.0 ./ 1));
waiting ~ brm_inverse_gaussian(wait_mean, concentration);
}
generated quantities {
vector[x_n] y_likelihood = normal_id_glm_lpdfs(y, X_mu, 0.0, pop_mu, sigma);
vector[x_n] y_gen = normal_id_glm_vector_rng(y_n, X_mu, 0.0, pop_mu, sigma);
vector[x_n] mu = (X_mu * pop_mu);
vector[x_n] waiting_likelihood = brm_inverse_gaussian_lpdfs(waiting, wait_mean, concentration);
vector[x_n] waiting_gen = brm_inverse_gaussian_vector_rng(waiting_n, wait_mean, concentration);
}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: X_Intercept_x, waiting, x, y.
Model documentation:
- `pop_Intercept_x`: Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
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)
DIMENSION = 6
PARAMETERS = {"sigma_Intercept": {"start": 0, "stop": 1, "transform": "identity", "dims": ()}, "concentration": {"start": 1, "stop": 2, "transform": "exp", "dims": ()}, "pop_Intercept_x.beta_pop": {"start": 2, "stop": 6, "transform": "identity", "dims": (2, 2)}}
DATA = {"X_Intercept_x": {"dtype": "float64", "ndim": 2, "ragged": False}, "waiting": {"dtype": "float64", "ndim": 1, "ragged": False}, "x": {"dtype": "float64", "ndim": 1, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "X_Intercept_x", "y", "waiting")
PREPARED = {"X_Intercept_x": {"dtype": "float64", "ndim": 2, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}, "waiting": {"dtype": "float64", "ndim": 1, "ragged": False}}
UNTRANSLATED = {}
def brm_joint_population_effects_density(
unconstrained: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
results = {}
if any(name in outputs for name in ("ppl_arrflat_beta_pop", "ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
ppl_arrflat_beta_pop = unconstrained[2:6]
if any(name in outputs for name in ("ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
def _array_prior_cells() -> jax.Array:
"""Compute `_array_prior_cells` from its authored source."""
if not (jnp.concatenate([jnp.stack([1.0, 1.0])[:, None], jnp.stack([0.5, 0.5])[:, None]], axis=1).shape == (2, 2)):
raise ValueError("_array_prior_cells_mismatch threw")
return jnp.ravel(jnp.concatenate([jnp.stack([1.0, 1.0])[:, None], jnp.stack([0.5, 0.5])[:, None]], axis=1), order="F")
array_prior_cells = _array_prior_cells()
ppl_parg_beta_pop_2 = array_prior_cells
def ppl_pw_prior_beta_pop_cell(beta_pop, scale):
scale_binding = 1.0 * scale
log_scale = jnp.log(scale_binding)
standardized = (beta_pop - 0.0) / jnp.where(jnp.logical_and(scale_binding == 0, beta_pop == 0.0), 1.0, scale_binding)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf = standard_logpdf - jnp.where(jnp.logical_and(scale_binding == 0, beta_pop != 0.0), 0.0, log_scale)
return logpdf
ppl_pw_prior_beta_pop = (jnp.zeros(ppl_arrflat_beta_pop.shape[:1], dtype=jnp.float64) if 0 in ppl_arrflat_beta_pop.shape[:1] and ppl_parg_beta_pop_2.shape[:1] == ppl_arrflat_beta_pop.shape[:1] else jax.vmap(ppl_pw_prior_beta_pop_cell, in_axes=(0, 0))(ppl_arrflat_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_arrflat_beta_pop" in outputs:
results["ppl_arrflat_beta_pop"] = ppl_arrflat_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
return results
def brm_joint_population_effects(
X: ArrayLike,
beta_pop: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
results = {}
if any(name in outputs for name in ("value",)):
value = X @ beta_pop
if "value" in outputs:
results["value"] = value
return results
def prepare_data(X_Intercept_x: ArrayLike, waiting: 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)`.
"""
X_Intercept_x = np.asarray(X_Intercept_x, dtype=np.float64)
waiting = np.asarray(waiting, dtype=np.float64)
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
return {"X_Intercept_x": np.asarray(X_Intercept_x, dtype=np.float64), "y": np.asarray(y, dtype=np.float64), "waiting": np.asarray(waiting, dtype=np.float64)}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
X_Intercept_x = prepared["X_Intercept_x"]
y = prepared["y"]
waiting = prepared["waiting"]
unconstrained = jnp.asarray(unconstrained)
X_Intercept_x = jnp.asarray(X_Intercept_x)
y = jnp.asarray(y)
waiting = jnp.asarray(waiting)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
sigma_Intercept = unconstrained[0]
u_argument = unconstrained[1]
constrain_2 = jnp.exp(u_argument)
if _entry in ("log_density", "log_likelihood"):
rkppl_arg_1 = jnp.exp(sigma_Intercept)
if _entry in ("log_density", "log_prior"):
ppl_prior_sigma_Intercept_log_scale = np.log(0.5)
ppl_prior_sigma_Intercept_standardized = (sigma_Intercept - -1.0) / jnp.where((sigma_Intercept == -1.0 if 0.5 == 0 else False), 1.0, 0.5)
ppl_prior_sigma_Intercept_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_sigma_Intercept_standardized ** 2
logpdf = ppl_prior_sigma_Intercept_standard_logpdf - jnp.where((sigma_Intercept != -1.0 if 0.5 == 0 else False), 0.0, ppl_prior_sigma_Intercept_log_scale)
ppl_prior_concentration_log_scale = np.log(1.0)
logpdf_2 = jax.lax.cond(constrain_2 < 0, lambda: -jnp.inf, lambda: -ppl_prior_concentration_log_scale - constrain_2 / 1.0)
if _entry in ("log_density", "log_jacobian"):
u_argument_2 = unconstrained[1]
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
pop_Intercept_x = brm_joint_population_effects_density(
unconstrained=(unconstrained if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") else None),
outputs=tuple(
name for name, needed in (
("ppl_arrflat_beta_pop", ("log_density", "log_prior", "log_likelihood", "constrain")),
("ppl_prior_beta_pop", ("log_density", "log_prior")),
("ppl_pw_prior_beta_pop", ("log_density", "log_prior")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_likelihood", "constrain"):
pop_Intercept_x_beta_pop = jnp.reshape(pop_Intercept_x["ppl_arrflat_beta_pop"], (2, 2), order="F")
if _entry in ("log_density", "log_prior"):
prior = logpdf + logpdf_2 + pop_Intercept_x["ppl_prior_beta_pop"]
if _entry in ("log_density", "log_likelihood"):
pop_Intercept_x_2 = brm_joint_population_effects(
X=(X_Intercept_x if _entry in ("log_density", "log_likelihood") else None),
beta_pop=(pop_Intercept_x_beta_pop 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
),
)
pop_mu = pop_Intercept_x_2["value"][:, 0]
pop_log_wait_mean = pop_Intercept_x_2["value"][:, 1]
def ppl_pw_y_resp_cell(y_2, mu, rkppl_arg_1_2):
def then_arm():
log_scale = jnp.log(rkppl_arg_1_2)
standardized = (y_2 - mu) / jnp.where(jnp.logical_and(rkppl_arg_1_2 == 0, y_2 == mu), 1.0, rkppl_arg_1_2)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
return standard_logpdf - jnp.where(jnp.logical_and(rkppl_arg_1_2 == 0, y_2 != mu), 0.0, log_scale)
ppl_density = jax.lax.cond(rkppl_arg_1_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 pop_mu.shape[:1] == y.shape[:1] else jax.vmap(ppl_pw_y_resp_cell, in_axes=(0, 0, None))(y, pop_mu, rkppl_arg_1))
ppl_lik_y_resp = jnp.sum(ppl_pw_y_resp)
ppl_mu_waiting_resp = jnp.exp(pop_log_wait_mean)
def ppl_pw_waiting_resp_cell(waiting_2, ppl_mu_waiting_resp_2, concentration):
def then_arm():
log_normalizer = 0.5 * (jnp.log(concentration) - np.log(2 * np.pi))
return jax.lax.cond(waiting_2 > 0, lambda: jax.lax.cond(waiting_2 == jnp.inf, lambda: -jnp.inf, lambda: log_normalizer - 1.5 * jnp.log(waiting_2) - 0.5 * concentration * ((waiting_2 / ppl_mu_waiting_resp_2 - 1) / jnp.sqrt(waiting_2)) ** 2), lambda: -jnp.inf)
ppl_density = jax.lax.cond(jnp.logical_and(concentration > 0, ppl_mu_waiting_resp_2 > 0), then_arm, lambda: -jnp.inf)
return ppl_density
ppl_pw_waiting_resp = (jnp.zeros(waiting.shape[:1], dtype=jnp.float64) if 0 in waiting.shape[:1] and ppl_mu_waiting_resp.shape[:1] == waiting.shape[:1] else jax.vmap(ppl_pw_waiting_resp_cell, in_axes=(0, 0, None))(waiting, ppl_mu_waiting_resp, constrain_2))
ppl_lik_waiting_resp = jnp.sum(ppl_pw_waiting_resp)
likelihood = ppl_lik_y_resp + ppl_lik_waiting_resp
if _entry in ("log_density",):
posterior = prior + likelihood + u_argument_2
if not (unconstrained.size == 6):
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(likelihood, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(u_argument_2, dtype=jnp.float64)
if _entry == "constrain":
return {"sigma_Intercept": jnp.asarray(sigma_Intercept, dtype=jnp.float64), "concentration": jnp.asarray(constrain_2, dtype=jnp.float64), "pop_Intercept_x": {"beta_pop": jnp.asarray(pop_Intercept_x_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:
- `sigma_Intercept`
- `concentration`
- `pop_Intercept_x.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 6
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 {"sigma_Intercept": {"start": 0, "stop": 1, "transform": "identity", "dims": ()}, "concentration": {"start": 1, "stop": 2, "transform": "exp", "dims": ()}, "pop_Intercept_x.beta_pop": {"start": 2, "stop": 6, "transform": "identity", "dims": (2, 2)}}Counts and extra zeros
HurdlePoisson(lambda, p_zero) assigns probability p_zero to zero and uses a zero-truncated Poisson for positive counts. With ZeroInflatedPoisson(lambda, zi), the ordinary Poisson component can also produce zeros. These probabilities therefore have different meanings.
Hurdle counts and trial outcomes
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
log(lambda) ~ 1 + x
logit(p_zero) ~ 1
eta ~ 1 + x
count ~ HurdlePoisson(lambda, p_zero)
successes ~ BinomialLogit(trials, eta)
effect(lambda, :) ~ Normal(0, 0.5)
effect(p_zero, Intercept) ~ Normal(0, 1)
effect(eta, :) ~ Normal(0, 1)
end)((; x=[-1., 0., 1., 2.], count=[0, 1, 0, 4],
trials=[10, 10, 12, 12], successes=[2, 5, 8, 10]))SBBRMI with data keys = [:count, :successes, :trials, :x]
emitted @slic body:
begin
X_log_lambda = hcat(rep_vector(1.0, num_elements(x)), x)
pop_log_lambda ~ _popefs_normal(; X = X_log_lambda, beta_loc = [0, 0], beta_scale = [0.5, 0.5])
log_lambda = pop_log_lambda
lambda = exp(log_lambda)
X_logit_p_zero = hcat(rep_vector(1.0, num_elements(count)))
pop_logit_p_zero ~ _popefs_normal(; X = X_logit_p_zero, beta_loc = [0], beta_scale = [1])
logit_p_zero = pop_logit_p_zero
p_zero = inv_logit(logit_p_zero)
X_eta = hcat(rep_vector(1.0, num_elements(x)), x)
pop_eta ~ _popefs_normal(; X = X_eta, beta_loc = [0, 0], beta_scale = [1, 1])
eta = pop_eta
count ~ hurdle_poisson(lambda, p_zero)
successes ~ binomial_logit(trials, eta)
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
"""
Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
brm_joint_population_effects(X, ncoef, ntargets, loc, scale) = begin
beta_pop[1:ncoef, 1:ntargets] .~ Normal.(loc, scale)
return X * beta_pop
end
begin
X_Intercept_x = hcat(ones(length(x)), x)
pop_Intercept_x ~ brm_joint_population_effects(X_Intercept_x, 2, 2, 0.0, hcat([0.5, 0.5], [1.0, 1.0]))
pop_log_lambda = pop_Intercept_x[:, 1]
log_lambda = pop_log_lambda
lambda = exp.(log_lambda)
p_zero_Intercept ~ Normal(0.0, 1.0)
logit_p_zero = p_zero_Intercept
p_zero = logistic.(logit_p_zero)
pop_eta = pop_Intercept_x[:, 2]
eta = pop_eta
count .~ HurdlePoisson.(lambda, p_zero)
successes .~ BinomialLogit.(trials, eta)
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);
}
matrix hcat(vector x) {
int n = dims(x)[1];
return to_matrix(x, n, 1);
}
real hurdle_poisson_lpmf(
array[] int y,
vector lambda,
vector p_zero
) {
int n = dims(y)[1];
if (dims(lambda)[1] != n) reject("hurdle_poisson_lpmf: dim mismatch — `lambda` dim 1 (= ", dims(lambda)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], "), `p_zero` dim 1 (= ", dims(p_zero)[1], ").");
if (dims(p_zero)[1] != n) reject("hurdle_poisson_lpmf: dim mismatch — `p_zero` dim 1 (= ", dims(p_zero)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], "), `p_zero` dim 1 (= ", dims(p_zero)[1], ").");
real rv = 0.0;
for(i in 1:n) {
rv += hurdle_poisson_lpmf(y[i] | lambda[i], p_zero[i]);
}
return rv;
}
real hurdle_poisson_lpmf(
int y,
real lambda,
real p_zero
) {
if((y == 0)) {
return log(p_zero);
} else {
return ((log1m(p_zero) + poisson_lpmf(y | lambda)) - poisson_lccdf(0 | lambda));
}
}
vector hurdle_poisson_lpmfs(
array[] int y,
vector lambda,
vector p_zero
) {
int n = dims(y)[1];
if (dims(lambda)[1] != n) reject("hurdle_poisson_lpmfs: dim mismatch — `lambda` dim 1 (= ", dims(lambda)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], "), `p_zero` dim 1 (= ", dims(p_zero)[1], ").");
if (dims(p_zero)[1] != n) reject("hurdle_poisson_lpmfs: dim mismatch — `p_zero` dim 1 (= ", dims(p_zero)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `lambda` dim 1 (= ", dims(lambda)[1], "), `p_zero` dim 1 (= ", dims(p_zero)[1], ").");
vector[n] rv;
for(i in 1:n) {
rv[i] = hurdle_poisson_lpmf(y[i] | lambda[i], p_zero[i]);
}
return rv;
}
array[] int hurdle_poisson_int_rng(
int anontok__1,
vector lambda,
vector p_zero
) {
int n = anontok__1;
if (dims(lambda)[1] != n) reject("hurdle_poisson_rng: dim mismatch — `lambda` dim 1 (= ", dims(lambda)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `lambda` dim 1 (= ", dims(lambda)[1], "), `p_zero` dim 1 (= ", dims(p_zero)[1], ").");
if (dims(p_zero)[1] != n) reject("hurdle_poisson_rng: dim mismatch — `p_zero` dim 1 (= ", dims(p_zero)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `lambda` dim 1 (= ", dims(lambda)[1], "), `p_zero` dim 1 (= ", dims(p_zero)[1], ").");
array[n] int rv;
for(i in 1:n) {
rv[i] = hurdle_poisson_rng(lambda[i], p_zero[i]);
}
return rv;
}
int hurdle_poisson_rng(
real lambda,
real p_zero
) {
if((bernoulli_rng(p_zero) == 1)) {
return 0;
} else {
return hurdle_poisson_positive_rng(lambda);
}
}
int hurdle_poisson_positive_rng(
real lambda
) {
array[1] int draw;
draw[1] = poisson_rng(lambda);
while((draw[1] == 0)) {
draw[1] = poisson_rng(lambda);
}
return draw[1];
}
vector binomial_logit_lpmfs(
array[] int y,
array[] int args1,
vector args2
) {
return jbroadcasted_binomial_logit_lpmfs(y, args1, args2);
}
vector jbroadcasted_binomial_logit_lpmfs(
array[] int x1,
array[] int x2,
vector x3
) {
int n = dims(x1)[1];
vector[n] rv;
for(i in 1:n) {
rv[i] = binomial_logit_lpmfs(
broadcasted_getindex(x1, i),
broadcasted_getindex(x2, i),
broadcasted_getindex(x3, i)
);
}
return rv;
}
real binomial_logit_lpmfs(
int args1,
int args2,
real args3
) {
return binomial_logit_lpmf(args1 | args2, args3);
}
int broadcasted_getindex(array[] int x, int i) {
return x[i];
}
real broadcasted_getindex(vector x, int i) {
return x[i];
}
array[] int binomial_logit_int_rng(
int anontok__1,
array[] int N,
vector eta
) {
int n = anontok__1;
if (dims(N)[1] != n) reject("binomial_logit_rng: dim mismatch — `N` dim 1 (= ", dims(N)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `N` dim 1 (= ", dims(N)[1], ").");
if((n == 0)) {
array[n] int rv;
return rv;
} else {
return binomial_rng(N, inv_logit(eta));
}
}
}
data {
int x_n;
vector[x_n] x;
int count_n;
array[count_n] int count;
int successes_n;
array[successes_n] int successes;
int trials_n;
array[trials_n] int trials;
}
transformed data {
matrix[x_n, 2] X_log_lambda = hcat(rep_vector(1.0, num_elements(x)), x);
int pop_log_lambda_n_covariates = 2;
matrix[num_elements(count), 1] X_logit_p_zero = hcat(rep_vector(1.0, num_elements(count)));
int pop_logit_p_zero_n_covariates = 1;
matrix[x_n, 2] X_eta = hcat(rep_vector(1.0, num_elements(x)), x);
int pop_eta_n_covariates = 2;
}
parameters {
vector[pop_log_lambda_n_covariates] pop_log_lambda_beta_pop;
vector[pop_logit_p_zero_n_covariates] pop_logit_p_zero_beta_pop;
vector[pop_eta_n_covariates] pop_eta_beta_pop;
}
transformed parameters {
vector[x_n] pop_log_lambda = (X_log_lambda * pop_log_lambda_beta_pop);
vector[x_n] log_lambda = pop_log_lambda;
vector[x_n] lambda = exp(log_lambda);
vector[num_elements(count)] pop_logit_p_zero = (X_logit_p_zero * pop_logit_p_zero_beta_pop);
vector[num_elements(count)] logit_p_zero = pop_logit_p_zero;
vector[num_elements(count)] p_zero = inv_logit(logit_p_zero);
vector[x_n] pop_eta = (X_eta * pop_eta_beta_pop);
vector[x_n] eta = pop_eta;
}
model {
pop_log_lambda_beta_pop ~ normal([0, 0]', [0.5, 0.5]');
pop_logit_p_zero_beta_pop ~ normal([0]', [1]');
pop_eta_beta_pop ~ normal([0, 0]', [1, 1]');
count ~ hurdle_poisson(lambda, p_zero);
successes ~ binomial_logit(trials, eta);
}
generated quantities {
vector[num_elements(count)] count_likelihood = hurdle_poisson_lpmfs(count, lambda, p_zero);
array[num_elements(count)] int count_gen = hurdle_poisson_int_rng(count_n, lambda, p_zero);
vector[successes_n] successes_likelihood = binomial_logit_lpmfs(successes, trials, eta);
array[trials_n] int successes_gen = binomial_logit_int_rng(successes_n, trials, eta);
}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: X_Intercept_x, count, successes, trials, x.
Model documentation:
- `pop_Intercept_x`: Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
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)
DIMENSION = 5
PARAMETERS = {"p_zero_Intercept": {"start": 0, "stop": 1, "transform": "identity", "dims": ()}, "pop_Intercept_x.beta_pop": {"start": 1, "stop": 5, "transform": "identity", "dims": (2, 2)}}
DATA = {"X_Intercept_x": {"dtype": "float64", "ndim": 2, "ragged": False}, "count": {"dtype": "int64", "ndim": 1, "ragged": False}, "successes": {"dtype": "int64", "ndim": 1, "ragged": False}, "trials": {"dtype": "int64", "ndim": 1, "ragged": False}, "x": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "X_Intercept_x", "count", "_ppl_pw_count_resp_lanes_1", "_ppl_pw_count_resp_lanes_2", "_ppl_pw_count_resp_lane_order", "successes", "trials", "_ppl_lnorm_successes_resp")
PREPARED = {"X_Intercept_x": {"dtype": "float64", "ndim": 2, "ragged": False}, "count": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_count_resp_lanes_1": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_count_resp_lanes_2": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_count_resp_lane_order": {"dtype": "int64", "ndim": 1, "ragged": False}, "successes": {"dtype": "int64", "ndim": 1, "ragged": False}, "trials": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_lnorm_successes_resp": {"dtype": "float64", "ndim": 0, "ragged": False}}
UNTRANSLATED = {}
def brm_joint_population_effects_density(
unconstrained: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
results = {}
if any(name in outputs for name in ("ppl_arrflat_beta_pop", "ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
ppl_arrflat_beta_pop = unconstrained[1:5]
if any(name in outputs for name in ("ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
def _array_prior_cells() -> jax.Array:
"""Compute `_array_prior_cells` from its authored source."""
if not (jnp.concatenate([jnp.stack([0.5, 0.5])[:, None], jnp.stack([1.0, 1.0])[:, None]], axis=1).shape == (2, 2)):
raise ValueError("_array_prior_cells_mismatch threw")
return jnp.ravel(jnp.concatenate([jnp.stack([0.5, 0.5])[:, None], jnp.stack([1.0, 1.0])[:, None]], axis=1), order="F")
array_prior_cells = _array_prior_cells()
ppl_parg_beta_pop_2 = array_prior_cells
def ppl_pw_prior_beta_pop_cell(beta_pop, scale):
scale_binding = 1.0 * scale
log_scale = jnp.log(scale_binding)
standardized = (beta_pop - 0.0) / jnp.where(jnp.logical_and(scale_binding == 0, beta_pop == 0.0), 1.0, scale_binding)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf = standard_logpdf - jnp.where(jnp.logical_and(scale_binding == 0, beta_pop != 0.0), 0.0, log_scale)
return logpdf
ppl_pw_prior_beta_pop = (jnp.zeros(ppl_arrflat_beta_pop.shape[:1], dtype=jnp.float64) if 0 in ppl_arrflat_beta_pop.shape[:1] and ppl_parg_beta_pop_2.shape[:1] == ppl_arrflat_beta_pop.shape[:1] else jax.vmap(ppl_pw_prior_beta_pop_cell, in_axes=(0, 0))(ppl_arrflat_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_arrflat_beta_pop" in outputs:
results["ppl_arrflat_beta_pop"] = ppl_arrflat_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
return results
def brm_joint_population_effects(
X: ArrayLike,
beta_pop: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Population-level effects of several predictors that share one design matrix `X`.
Draws one coefficient per column of `X` and predictor,
`beta_pop[1:ncoef, 1:ntargets] ~ Normal(loc, scale)`, and returns the
linear predictors `X * beta_pop`, one column per predictor.
"""
results = {}
if any(name in outputs for name in ("value",)):
value = X @ beta_pop
if "value" in outputs:
results["value"] = value
return results
def _integer_observation(x: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `_integer_observation` from its authored source."""
return True
@jax.custom_jvp
def _loggamma(x1):
return jsp.gammaln(x1)
def _loggamma_partials_1(x1):
return (jsp.gammaln(x1), jsp.digamma(x1))
def _loggamma_jvp(primals, tangents):
active = tuple(not isinstance(t, jax.custom_derivatives.SymbolicZero) for t in tangents)
mask = sum((1 << i) for i, a in enumerate(active) if a)
if mask == 0:
value = _loggamma(*primals)
return value, jnp.zeros_like(value)
if mask == 1:
values = _loggamma_partials_1(*primals)
return values[0], values[1] * tangents[0]
_loggamma.defjvp(_loggamma_jvp, symbolic_zeros=True)
def prepare_data(X_Intercept_x: ArrayLike, count: ArrayLike, successes: ArrayLike, trials: ArrayLike, x: 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)`.
"""
X_Intercept_x = np.asarray(X_Intercept_x, dtype=np.float64)
count = np.asarray(count, dtype=np.int64)
successes = np.asarray(successes, dtype=np.int64)
trials = np.asarray(trials, dtype=np.int64)
x = np.asarray(x, dtype=np.float64)
def cell(successes_2, trials_2):
if (successes_2 > 0) & (successes_2 < trials_2):
value_2 = ssp.gammaln(trials_2 + 1.0)
value_3 = ssp.gammaln(successes_2 + 1.0)
value_4 = ssp.gammaln(trials_2 - successes_2 + 1.0)
value = value_2 - value_3 - value_4
else:
value = 0.0
lognormalizer = value
return lognormalizer
ppl_pwn_successes_resp = np.asarray([cell(element, element_2) for element, element_2 in zip(successes, trials)], dtype=np.float64)
ppl_lnorm_successes_resp = np.sum(ppl_pwn_successes_resp)
def lane_conditions(lane_input_1):
return (bool(lane_input_1 == 0),)
lane_conditions_2 = np.asarray([lane_conditions(entry) for entry in count], dtype=bool).reshape((-1, 1))
lanes = np.flatnonzero(lane_conditions_2[:, 0])
lanes_2 = np.flatnonzero(~lane_conditions_2[:, 0])
ppl_pw_count_resp_lanes_1 = lanes
ppl_pw_count_resp_lanes_2 = lanes_2
ppl_pw_count_resp_lane_order = np.argsort(np.concatenate((lanes, lanes_2,)), kind="stable")
return {"X_Intercept_x": np.asarray(X_Intercept_x, dtype=np.float64), "count": np.asarray(count, dtype=np.int64), "_ppl_pw_count_resp_lanes_1": np.asarray(ppl_pw_count_resp_lanes_1, dtype=np.int64), "_ppl_pw_count_resp_lanes_2": np.asarray(ppl_pw_count_resp_lanes_2, dtype=np.int64), "_ppl_pw_count_resp_lane_order": np.asarray(ppl_pw_count_resp_lane_order, dtype=np.int64), "successes": np.asarray(successes, dtype=np.int64), "trials": np.asarray(trials, dtype=np.int64), "_ppl_lnorm_successes_resp": ppl_lnorm_successes_resp}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
X_Intercept_x = prepared["X_Intercept_x"]
count = prepared["count"]
_ppl_pw_count_resp_lanes_1 = prepared["_ppl_pw_count_resp_lanes_1"]
_ppl_pw_count_resp_lanes_2 = prepared["_ppl_pw_count_resp_lanes_2"]
_ppl_pw_count_resp_lane_order = prepared["_ppl_pw_count_resp_lane_order"]
successes = prepared["successes"]
trials = prepared["trials"]
_ppl_lnorm_successes_resp = prepared["_ppl_lnorm_successes_resp"]
unconstrained = jnp.asarray(unconstrained)
X_Intercept_x = jnp.asarray(X_Intercept_x)
count = jnp.asarray(count)
_ppl_pw_count_resp_lanes_1 = jnp.asarray(_ppl_pw_count_resp_lanes_1)
_ppl_pw_count_resp_lanes_2 = jnp.asarray(_ppl_pw_count_resp_lanes_2)
_ppl_pw_count_resp_lane_order = jnp.asarray(_ppl_pw_count_resp_lane_order)
successes = jnp.asarray(successes)
trials = jnp.asarray(trials)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
p_zero_Intercept = unconstrained[0]
if _entry in ("log_density", "log_likelihood"):
p_zero = jax.nn.sigmoid(p_zero_Intercept)
if _entry in ("log_density", "log_prior"):
ppl_prior_p_zero_Intercept_log_scale = np.log(1.0)
ppl_prior_p_zero_Intercept_standardized = (p_zero_Intercept - 0.0) / jnp.where((p_zero_Intercept == 0.0 if 1.0 == 0 else False), 1.0, 1.0)
ppl_prior_p_zero_Intercept_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_p_zero_Intercept_standardized ** 2
logpdf = ppl_prior_p_zero_Intercept_standard_logpdf - jnp.where((p_zero_Intercept != 0.0 if 1.0 == 0 else False), 0.0, ppl_prior_p_zero_Intercept_log_scale)
if _entry in ("log_density", "log_jacobian"):
log_jacobian_2 = 0.0
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
pop_Intercept_x = brm_joint_population_effects_density(
unconstrained=(unconstrained if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") else None),
outputs=tuple(
name for name, needed in (
("ppl_arrflat_beta_pop", ("log_density", "log_prior", "log_likelihood", "constrain")),
("ppl_prior_beta_pop", ("log_density", "log_prior")),
("ppl_pw_prior_beta_pop", ("log_density", "log_prior")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_likelihood", "constrain"):
pop_Intercept_x_beta_pop = jnp.reshape(pop_Intercept_x["ppl_arrflat_beta_pop"], (2, 2), order="F")
if _entry in ("log_density", "log_prior"):
prior = logpdf + pop_Intercept_x["ppl_prior_beta_pop"]
if _entry in ("log_density", "log_likelihood"):
pop_Intercept_x_2 = brm_joint_population_effects(
X=(X_Intercept_x if _entry in ("log_density", "log_likelihood") else None),
beta_pop=(pop_Intercept_x_beta_pop 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
),
)
pop_log_lambda = pop_Intercept_x_2["value"][:, 0]
lambda_ = jnp.exp(pop_log_lambda)
pop_eta = pop_Intercept_x_2["value"][:, 1]
lane_entries = jnp.asarray(count)[_ppl_pw_count_resp_lanes_1]
lane_entries_2 = jnp.asarray(lambda_)[_ppl_pw_count_resp_lanes_1]
def ppl_pw_count_resp_cell(count_2, lambda__2, p_zero_2):
ppl_density = jax.lax.cond(jnp.logical_and(lambda__2 > 0, (p_zero_2 >= 0) & (p_zero_2 <= 1)), lambda: jnp.log(p_zero_2), lambda: -jnp.inf)
return ppl_density
plate_part = (jnp.zeros(lane_entries.shape[:1], dtype=jnp.float64) if 0 in lane_entries.shape[:1] and lane_entries_2.shape[:1] == lane_entries.shape[:1] else jax.vmap(ppl_pw_count_resp_cell, in_axes=(0, 0, None))(lane_entries, lane_entries_2, p_zero))
lane_entries_3 = jnp.asarray(count)[_ppl_pw_count_resp_lanes_2]
lane_entries_4 = jnp.asarray(lambda_)[_ppl_pw_count_resp_lanes_2]
def ppl_pw_count_resp_cell_2(count_2, lambda__2, p_zero_2):
def then_arm_2():
integer_observation = _integer_observation(count_2, jnp.logical_and(lambda__2 > 0, (p_zero_2 >= 0) & (p_zero_2 <= 1)))
def then_arm():
def else_arm():
value = _loggamma(count_2 + 1.0)
return count_2 * jnp.log(lambda__2) - lambda__2 - value
return jax.lax.cond(count_2 == 0, lambda: -lambda__2, else_arm)
return jnp.log1p(-p_zero_2) + jax.lax.cond((count_2 >= 0 if integer_observation else False), then_arm, lambda: -jnp.inf) - jnp.log(-jnp.expm1(-lambda__2))
ppl_density = jax.lax.cond(jnp.logical_and(lambda__2 > 0, (p_zero_2 >= 0) & (p_zero_2 <= 1)), then_arm_2, lambda: -jnp.inf)
return ppl_density
plate_part_2 = (jnp.zeros(lane_entries_3.shape[:1], dtype=jnp.float64) if 0 in lane_entries_3.shape[:1] and lane_entries_4.shape[:1] == lane_entries_3.shape[:1] else jax.vmap(ppl_pw_count_resp_cell_2, in_axes=(0, 0, None))(lane_entries_3, lane_entries_4, p_zero))
ppl_pw_count_resp = jnp.concatenate((plate_part, plate_part_2,))[_ppl_pw_count_resp_lane_order]
ppl_lik_count_resp = jnp.sum(ppl_pw_count_resp)
def ppl_pwk_successes_resp_cell(successes_2, eta, trials_2):
def then_arm_2():
def else_arm_4():
def else_arm_3():
def else_arm_2():
def then_arm():
l1pe = jax.nn.softplus(-eta)
return -successes_2 * l1pe - (trials_2 - successes_2) * (l1pe + eta)
def else_arm():
l1pe_2 = jax.nn.softplus(eta)
return -successes_2 * (l1pe_2 - eta) - (trials_2 - successes_2) * l1pe_2
return jax.lax.cond(eta >= 0, then_arm, else_arm)
return jax.lax.cond(successes_2 == trials_2, lambda: -trials_2 * jax.nn.softplus(-eta), else_arm_2)
return jax.lax.cond(successes_2 == 0, lambda: -trials_2 * jax.nn.softplus(eta), else_arm_3)
return jax.lax.cond(trials_2 == 0, lambda: 0.0, else_arm_4)
logkernel_lp = jax.lax.cond((successes_2 >= 0) & (successes_2 <= trials_2), then_arm_2, lambda: -jnp.inf)
return logkernel_lp
ppl_pwk_successes_resp = (jnp.zeros(successes.shape[:1], dtype=jnp.float64) if 0 in successes.shape[:1] and pop_eta.shape[:1] == successes.shape[:1] and trials.shape[:1] == successes.shape[:1] else jax.vmap(ppl_pwk_successes_resp_cell, in_axes=(0, 0, 0))(successes, pop_eta, trials))
ppl_kernel_successes_resp = jnp.sum(ppl_pwk_successes_resp)
ppl_lik_successes_resp = ppl_kernel_successes_resp + _ppl_lnorm_successes_resp
likelihood = ppl_lik_count_resp + ppl_lik_successes_resp
if _entry in ("log_density",):
posterior = prior + likelihood + log_jacobian_2
if _entry == "log_density":
if not (unconstrained.size == 5):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
return jnp.asarray(posterior, dtype=jnp.float64)
if _entry == "log_prior":
if not (unconstrained.size == 5):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
return jnp.asarray(prior, dtype=jnp.float64)
if _entry == "log_likelihood":
if not (unconstrained.size == 5):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
return jnp.asarray(likelihood, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(log_jacobian_2, dtype=jnp.float64)
if _entry == "constrain":
if not (unconstrained.size == 5):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
return {"p_zero_Intercept": jnp.asarray(p_zero_Intercept, dtype=jnp.float64), "pop_Intercept_x": {"beta_pop": jnp.asarray(pop_Intercept_x_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:
- `p_zero_Intercept`
- `pop_Intercept_x.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 5
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 {"p_zero_Intercept": {"start": 0, "stop": 1, "transform": "identity", "dims": ()}, "pop_Intercept_x.beta_pop": {"start": 1, "stop": 5, "transform": "identity", "dims": (2, 2)}}Categories and thresholds
A nested formula gives CategoricalLogit its own coefficients for each non-reference level. Plain vectors use sorted unique levels; a categorical vector uses its declared level order. The first level has logit zero. Fitted levels remain fixed during replay. effect(choice, x) ~ Normal(0, s) addresses the nested formula's coefficients through the response: it sets x's coefficient in every non-reference level. When the formula is an intercept and continuous data columns, as below, it is one predictor with a coefficient column per non-reference level, and the number of levels is data: 3 and 4 levels build one program on both backends. Any other term, such as a factor column or group-level effects, gives one predictor per non-reference level, and there the number of levels sets the number of predictors. On the ReactiveKernels backend the level labels are data, so responses that differ only in their labels share one program.
An ordinal model supplies its location through thresholds, so its common predictor has no intercept. Cumulative() has ordered thresholds; StoppingRatio() has separate stage intercepts. Both accept LogitLink(), ProbitLink() or CloglogLink().
Unordered and ordered categories
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
choice ~ CategoricalLogit(@brm(1 + x))
eta ~ 0 + x
rating ~ Ordinal(Cumulative(), ProbitLink(), eta)
effect(eta, x) ~ Normal(0, 1)
end)((; x=[-1., -0.5, 0., 0.5, 1., 1.5],
choice=["a", "b", "c", "a", "c", "b"], rating=[1, 1, 2, 2, 3, 3]))SBBRMI with data keys = [:choice, :choice_nonreference, :rating, :rating_thresholds_length, :x]
emitted @slic body:
begin
X_choice_nested_arg1 = hcat(rep_vector(1.0, num_elements(x)), x)
pop_choice_nested_arg1 ~ _popefs_classes(; X = X_choice_nested_arg1, n_classes = choice_nonreference)
choice_nested_arg1 = pop_choice_nested_arg1
choice_categorical_logits = adjoint(append_col(rep_vector(0.0, num_elements(choice)), choice_nested_arg1))
choice ~ categorical_logit(choice_categorical_logits)
X_eta = hcat(x)
pop_eta ~ _popefs_normal(; X = X_eta, beta_loc = [0], beta_scale = [1])
eta = pop_eta
rating_thresholds::ordered[rating_thresholds_length] ~ std_normal()
rating_threshold_effect = rep_matrix(0.0, num_elements(rating), rating_thresholds_length)
rating ~ brm_ordinal(eta, rating_thresholds, 1.0, 1, 2, rating_threshold_effect)
end"""
Each value's position (1-based) in `level_values`: the level codes of a grouping or factor.
"""
ReactiveKernels.@kernel(brm_prepared_indices(values, level_values) = begin
indices = ReactiveKernels.plate(values) do value
Int(findfirst(isequal(value), level_values))
end
return indices
end)
"""
Class-block population effects: one coefficient per design column and non-reference class.
Draws `beta_pop[1:ncoef, 1:nclass] ~ Normal(loc, scale)` and returns `X * beta_pop`, one
linear predictor column per non-reference class. `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 design column, shared by that column's classes.
"""
brm_class_population_effects(X, ncoef, nclass, loc, scale) = begin
beta_pop[1:ncoef, 1:nclass] .~ Normal.(loc, scale)
return X * beta_pop
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
choice_fit_levels = brm_fit_levels(choice_fit)
choice = brm_prepared_indices(choice_raw, choice_fit_levels)
rating_fit_levels = brm_fit_levels(rating_fit)
rating = brm_prepared_indices(rating_raw, rating_fit_levels)
choice_nonreference = length(choice_fit_levels) - 1
X_choice_nested_arg1 = hcat(ones(length(choice)), x)
pop_choice_nested_arg1 ~ brm_class_population_effects(X_choice_nested_arg1, 2, choice_nonreference, 0.0, 1.0)
choice_nested_arg1 = pop_choice_nested_arg1
X_eta = hcat(x)
pop_eta ~ brm_population_effects(X_eta, 1, 0.0, 1.0)
eta = pop_eta
rating_thresholds ~ Ordered(Normal(0.0, 1.0), 2)
choice .~ CategoricalLogit.(eachrow(choice_nested_arg1))
rating .~ Ordinal.(Cumulative(), ProbitLink(), eta, Ref(rating_thresholds), 1.0)
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);
}
real categorical_logit_lpmf(
array[] int y,
matrix eta
) {
int n = dims(y)[1];
if (dims(eta)[2] != n) reject("categorical_logit_lpmf: dim mismatch — `eta` dim 2 (= ", dims(eta)[2], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 2 (= ", dims(eta)[2], ").");
real rv = 0.0;
for(i in 1:n) {
rv += categorical_logit_lpmf(y[i] | eta[:, i]);
}
return rv;
}
vector categorical_logit_lpmfs(
array[] int y,
matrix eta
) {
int n = dims(y)[1];
if (dims(eta)[2] != n) reject("categorical_logit_lpmfs: dim mismatch — `eta` dim 2 (= ", dims(eta)[2], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 2 (= ", dims(eta)[2], ").");
vector[n] rv;
for(i in 1:n) {
rv[i] = categorical_logit_lpmf(y[i] | eta[:, i]);
}
return rv;
}
array[] int categorical_logit_int_rng(
int anontok__1,
matrix eta
) {
int n = anontok__1;
if (dims(eta)[2] != n) reject("categorical_logit_rng: dim mismatch — `eta` dim 2 (= ", dims(eta)[2], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `eta` dim 2 (= ", dims(eta)[2], ").");
array[n] int rv;
for(i in 1:n) {
rv[i] = categorical_logit_rng(eta[:, i]);
}
return rv;
}
matrix hcat(vector x) {
int n = dims(x)[1];
return to_matrix(x, n, 1);
}
real brm_ordinal_lpmf(
array[] int y,
vector eta,
vector thresholds,
real discrimination,
int structure,
int link,
matrix threshold_effect
) {
int n = dims(y)[1];
int k = dims(thresholds)[1];
if (dims(eta)[1] != n) reject("brm_ordinal_lpmf: dim mismatch — `eta` dim 1 (= ", dims(eta)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[1] != n) reject("brm_ordinal_lpmf: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[2] != k) reject("brm_ordinal_lpmf: dim mismatch — `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ").");
return brm_ordinal_lpmf(y |
eta,
thresholds,
rep_vector(discrimination, n),
structure,
link,
threshold_effect
);
}
real brm_ordinal_lpmf(
array[] int y,
vector eta,
vector thresholds,
vector discrimination,
int structure,
int link,
matrix threshold_effect
) {
int n = dims(y)[1];
int k = dims(thresholds)[1];
if (dims(eta)[1] != n) reject("brm_ordinal_lpmf: dim mismatch — `eta` dim 1 (= ", dims(eta)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(discrimination)[1] != n) reject("brm_ordinal_lpmf: dim mismatch — `discrimination` dim 1 (= ", dims(discrimination)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[1] != n) reject("brm_ordinal_lpmf: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[2] != k) reject("brm_ordinal_lpmf: dim mismatch — `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ").");
real rv = 0.0;
for(i in 1:n) {
rv += brm_ordinal_lpmf(y[i] |
eta[i],
thresholds,
discrimination[i],
structure,
link,
to_vector(threshold_effect[i, :])
);
}
return rv;
}
real brm_ordinal_lpmf(
int y,
real eta,
vector thresholds,
real discrimination,
int structure,
int link,
vector threshold_effect
) {
int k = dims(thresholds)[1];
if (dims(threshold_effect)[1] != k) reject("brm_ordinal_lpmf: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
int K = (k + 1);
if((discrimination <= 0.0)) {
return negative_infinity();
} else {
if((y < 1)) {
return negative_infinity();
} else {
if((y > K)) {
return negative_infinity();
} else {
if((structure == 1)) {
if((link == 1)) {
return ordered_logistic_lpmf(y | (discrimination * eta), (discrimination .* thresholds));
} else {
if((y == 1)) {
real z_first = (discrimination * (thresholds[1] - eta));
return brm_ordinal_logcdf(z_first, link);
} else {
if((y == K)) {
real z_last = (discrimination * (thresholds[k] - eta));
return brm_ordinal_logccdf(z_last, link);
} else {
real z_hi = (discrimination * (thresholds[y] - eta));
real z_lo = (discrimination * (thresholds[(y - 1)] - eta));
real lower_tail = brm_ordinal_logcdf(z_lo, link);
if((lower_tail > -0.6931471805599453)) {
return log_diff_exp(brm_ordinal_logccdf(z_lo, link), brm_ordinal_logccdf(z_hi, link));
} else {
return log_diff_exp(brm_ordinal_logcdf(z_hi, link), lower_tail);
}
}
}
}
} else {
real rv = 0.0;
for(j in 1:k) {
real z_stage = (discrimination * ((thresholds[j] - eta) - threshold_effect[j]));
if((j < y)) {
rv += brm_ordinal_logccdf(z_stage, link);
} else {
if((j == y)) {
rv += brm_ordinal_logcdf(z_stage, link);
}
}
}
return rv;
}
}
}
}
}
real brm_ordinal_logcdf(
real z,
int link
) {
if((link == 1)) {
return log_inv_logit(z);
} else {
if((link == 2)) {
return normal_lcdf(z | 0.0, 1.0);
} else {
return log1m_exp((-exp(z)));
}
}
}
real brm_ordinal_logccdf(
real z,
int link
) {
if((link == 1)) {
return log_inv_logit((-z));
} else {
if((link == 2)) {
return normal_lcdf((-z) | 0.0, 1.0);
} else {
return (-exp(z));
}
}
}
vector brm_ordinal_lpmfs(
array[] int y,
vector eta,
vector thresholds,
real discrimination,
int structure,
int link,
matrix threshold_effect
) {
int n = dims(y)[1];
int k = dims(thresholds)[1];
if (dims(eta)[1] != n) reject("brm_ordinal_lpmfs: dim mismatch — `eta` dim 1 (= ", dims(eta)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[1] != n) reject("brm_ordinal_lpmfs: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[2] != k) reject("brm_ordinal_lpmfs: dim mismatch — `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ").");
return brm_ordinal_lpmfs(
y,
eta,
thresholds,
rep_vector(discrimination, n),
structure,
link,
threshold_effect
);
}
vector brm_ordinal_lpmfs(
array[] int y,
vector eta,
vector thresholds,
vector discrimination,
int structure,
int link,
matrix threshold_effect
) {
int n = dims(y)[1];
int k = dims(thresholds)[1];
if (dims(eta)[1] != n) reject("brm_ordinal_lpmfs: dim mismatch — `eta` dim 1 (= ", dims(eta)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(discrimination)[1] != n) reject("brm_ordinal_lpmfs: dim mismatch — `discrimination` dim 1 (= ", dims(discrimination)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[1] != n) reject("brm_ordinal_lpmfs: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `n` (= ", n, "), inferred from `y` dim 1. `n` sizes: `y` dim 1 (= ", dims(y)[1], "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[2] != k) reject("brm_ordinal_lpmfs: dim mismatch — `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ").");
vector[n] rv;
for(i in 1:n) {
rv[i] = brm_ordinal_lpmf(y[i] |
eta[i],
thresholds,
discrimination[i],
structure,
link,
to_vector(threshold_effect[i, :])
);
}
return rv;
}
array[] int brm_ordinal_int_rng(
int anontok__1,
vector eta,
vector thresholds,
real discrimination,
int structure,
int link,
matrix threshold_effect
) {
int n = anontok__1;
int k = dims(thresholds)[1];
if (dims(eta)[1] != n) reject("brm_ordinal_rng: dim mismatch — `eta` dim 1 (= ", dims(eta)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `eta` dim 1 (= ", dims(eta)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[1] != n) reject("brm_ordinal_rng: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `eta` dim 1 (= ", dims(eta)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[2] != k) reject("brm_ordinal_rng: dim mismatch — `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ").");
return brm_ordinal_int_rng(
n,
eta,
thresholds,
rep_vector(discrimination, n),
structure,
link,
threshold_effect
);
}
array[] int brm_ordinal_int_rng(
int anontok__1,
vector eta,
vector thresholds,
vector discrimination,
int structure,
int link,
matrix threshold_effect
) {
int n = anontok__1;
int k = dims(thresholds)[1];
if (dims(eta)[1] != n) reject("brm_ordinal_rng: dim mismatch — `eta` dim 1 (= ", dims(eta)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(discrimination)[1] != n) reject("brm_ordinal_rng: dim mismatch — `discrimination` dim 1 (= ", dims(discrimination)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[1] != n) reject("brm_ordinal_rng: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `n` (= ", n, "), inferred from `anontok__1` dim 1. `n` sizes: `anontok__1` dim 1 (= ", anontok__1, "), `eta` dim 1 (= ", dims(eta)[1], "), `discrimination` dim 1 (= ", dims(discrimination)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
if (dims(threshold_effect)[2] != k) reject("brm_ordinal_rng: dim mismatch — `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 2 (= ", dims(threshold_effect)[2], ").");
array[n] int rv;
for(i in 1:n) {
rv[i] = brm_ordinal_rng(
eta[i],
thresholds,
discrimination[i],
structure,
link,
to_vector(threshold_effect[i, :])
);
}
return rv;
}
int brm_ordinal_rng(
real eta,
vector thresholds,
real discrimination,
int structure,
int link,
vector threshold_effect
) {
int k = dims(thresholds)[1];
if (dims(threshold_effect)[1] != k) reject("brm_ordinal_rng: dim mismatch — `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ") does not match `k` (= ", k, "), inferred from `thresholds` dim 1. `k` sizes: `thresholds` dim 1 (= ", dims(thresholds)[1], "), `threshold_effect` dim 1 (= ", dims(threshold_effect)[1], ").");
int K = (k + 1);
int rv = K;
if((structure == 1)) {
real u = uniform_rng(0.0, 1.0);
for(j in 1:k) {
if((rv == K)) {
real z_cumulative = (discrimination * (thresholds[j] - eta));
if((u <= brm_ordinal_cdf(z_cumulative | link))) {
rv += (j - rv);
}
}
}
} else {
for(j in 1:k) {
if((rv == K)) {
real z_stopping = (discrimination * ((thresholds[j] - eta) - threshold_effect[j]));
if((bernoulli_rng(brm_ordinal_cdf(z_stopping | link)) == 1)) {
rv += (j - rv);
}
}
}
}
return rv;
}
real brm_ordinal_cdf(
real z,
int link
) {
if((link == 1)) {
return inv_logit(z);
} else {
if((link == 2)) {
return Phi(z);
} else {
return (-expm1((-exp(z))));
}
}
}
}
data {
int x_n;
vector[x_n] x;
int choice_nonreference;
int choice_n;
array[choice_n] int choice;
int rating_thresholds_length;
int rating_n;
array[rating_n] int rating;
}
transformed data {
matrix[x_n, 2] X_choice_nested_arg1 = hcat(rep_vector(1.0, num_elements(x)), x);
int pop_choice_nested_arg1_n_covariates = 2;
matrix[x_n, 1] X_eta = hcat(x);
int pop_eta_n_covariates = 1;
matrix[num_elements(rating), rating_thresholds_length] rating_threshold_effect = rep_matrix(0.0, num_elements(rating), rating_thresholds_length);
}
parameters {
vector[(pop_choice_nested_arg1_n_covariates * choice_nonreference)] pop_choice_nested_arg1_beta_flat;
vector[pop_eta_n_covariates] pop_eta_beta_pop;
ordered[rating_thresholds_length] rating_thresholds;
}
transformed parameters {
matrix[pop_choice_nested_arg1_n_covariates, choice_nonreference] pop_choice_nested_arg1_beta_pop = to_matrix(
pop_choice_nested_arg1_beta_flat,
pop_choice_nested_arg1_n_covariates,
choice_nonreference
);
matrix[x_n, choice_nonreference] pop_choice_nested_arg1 = (X_choice_nested_arg1 * pop_choice_nested_arg1_beta_pop);
matrix[x_n, choice_nonreference] choice_nested_arg1 = pop_choice_nested_arg1;
matrix[(1 + choice_nonreference), x_n] choice_categorical_logits = (append_col(rep_vector(0.0, num_elements(choice)), choice_nested_arg1)');
vector[x_n] pop_eta = (X_eta * pop_eta_beta_pop);
vector[x_n] eta = pop_eta;
}
model {
pop_choice_nested_arg1_beta_flat ~ std_normal();
choice ~ categorical_logit(choice_categorical_logits);
pop_eta_beta_pop ~ normal([0]', [1]');
rating_thresholds ~ std_normal();
rating ~ brm_ordinal(eta, rating_thresholds, 1.0, 1, 2, rating_threshold_effect);
}
generated quantities {
vector[x_n] choice_likelihood = categorical_logit_lpmfs(choice, choice_categorical_logits);
array[x_n] int choice_gen = categorical_logit_int_rng(choice_n, choice_categorical_logits);
vector[num_elements(rating)] rating_likelihood = brm_ordinal_lpmfs(rating, eta, rating_thresholds, 1.0, 1, 2, rating_threshold_effect);
array[num_elements(rating)] int rating_gen = brm_ordinal_int_rng(rating_n, eta, rating_thresholds, 1.0, 1, 2, rating_threshold_effect);
}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: X_eta, choice_fit, choice_raw, rating_fit, rating_raw, x.
Model documentation:
- `pop_choice_nested_arg1`: Class-block population effects: one coefficient per design column and non-reference class.
Draws `beta_pop[1:ncoef, 1:nclass] ~ Normal(loc, scale)` and returns `X * beta_pop`, one
linear predictor column per non-reference class. `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 design column, shared by that column's classes.
- `pop_eta`: 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 = {"X_eta": {"dtype": "float64", "ndim": 2, "ragged": False}, "choice_fit": {"dtype": "object", "ndim": 1, "ragged": False}, "choice_raw": {"dtype": "object", "ndim": 1, "ragged": False}, "rating_fit": {"dtype": "int64", "ndim": 1, "ragged": False}, "rating_raw": {"dtype": "int64", "ndim": 1, "ragged": False}, "x": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "ppl_last_pop_choice_nested_arg1_beta_pop", "choice_nonreference", "ppl_first_pop_eta_beta_pop", "X_choice_nested_arg1", "X_eta", "choice", "_ppl_pw_choice_resp_lanes_1", "_ppl_pw_choice_resp_lanes_2", "_ppl_pw_choice_resp_lane_order", "rating", "_ppl_pw_rating_resp_lanes_1", "_ppl_pw_rating_resp_lanes_2", "_ppl_pw_rating_resp_lanes_3", "_ppl_pw_rating_resp_lane_order")
PREPARED = {"ppl_last_pop_choice_nested_arg1_beta_pop": {"dtype": "int64", "ndim": 0, "ragged": False}, "choice_nonreference": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_first_pop_eta_beta_pop": {"dtype": "int64", "ndim": 0, "ragged": False}, "X_choice_nested_arg1": {"dtype": "float64", "ndim": 2, "ragged": False}, "X_eta": {"dtype": "float64", "ndim": 2, "ragged": False}, "choice": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_choice_resp_lanes_1": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_choice_resp_lanes_2": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_choice_resp_lane_order": {"dtype": "int64", "ndim": 1, "ragged": False}, "rating": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_rating_resp_lanes_1": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_rating_resp_lanes_2": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_rating_resp_lanes_3": {"dtype": "int64", "ndim": 1, "ragged": False}, "_ppl_pw_rating_resp_lane_order": {"dtype": "int64", "ndim": 1, "ragged": False}}
UNTRANSLATED = {}
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_isequal_np(a, b):
# Julia's isequal on scalars: NaN equals NaN, -0.0 differs from 0.0, and
# missing (None) equals only missing.
if a is None or b is None:
return a is b
if a != a and b != b:
return True
if not bool(a == b):
return False
if isinstance(a, (int, float, np.number)) and isinstance(b, (int, float, np.number)) and a == 0:
return bool(np.signbit(a) == np.signbit(b))
return True
def _indices_np(values, level_values):
def cell(value, level_values_2):
found = None
for position, element in enumerate(level_values_2, 1):
matched = _rk_isequal_np(element, value)
if not isinstance(matched, (bool, np.bool_)):
raise TypeError("findfirst predicate must return Bool")
if matched:
found = position
break
plate_value = int(found)
return plate_value
indices = np.asarray([cell(element, level_values) for element in values], dtype=np.int64)
return indices
def _brm_sorted_labels_np_2(source):
labels = _rk_unique_np(source)
sorted_ = _rk_sort_np(labels)
return sorted_
def _brm_fit_levels_np_2(source):
value = _brm_sorted_labels_np_2(source)
levels = value
return levels
def _indices_np_2(values, level_values):
values = np.asarray(values)
level_values = np.asarray(level_values)
def cell(value, level_values_2):
found = None
for position, element in enumerate(level_values_2, 1):
matched = _rk_isequal_np(element, value)
if not isinstance(matched, (bool, np.bool_)):
raise TypeError("findfirst predicate must return Bool")
if matched:
found = position
break
plate_value = int(found)
return plate_value
indices = np.asarray([cell(element, level_values) for element in values], dtype=np.int64)
return indices
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 _rk_ordered_constrain(u, lo, hi):
# RKPPL ordered transform: y[1] = u[lo], y[i] = y[i - 1] + exp(u[lo + i - 1]).
v = u[lo - 1:hi]
return jnp.cumsum(jnp.concatenate([v[:1], jnp.exp(v[1:])]))
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")):
def ppl_pw_prior_beta_pop_cell(beta_pop_2):
log_scale = np.log(1.0)
standardized = (beta_pop_2 - 0.0) / jnp.where((beta_pop_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_pop_2 != 0.0 if 1.0 == 0 else False), 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] else jax.vmap(ppl_pw_prior_beta_pop_cell, in_axes=(0,))(beta_pop))
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 _function(location: ArrayLike, scale: ArrayLike, log_scale: ArrayLike, x: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `function` from its kernel plan."""
standardized = (x - location) / jnp.where((x == location if scale == 0 else False), 1.0, scale)
return standardized
def _rk_logerfc(x):
# log(erfc(x)) without overflow or cancellation (SpecialFunctions.logerfc):
# log(erfcx(x)) - x^2 for x > 0.
positive = x > 0
xp = jnp.where(positive, x, 1.0)
xn = jnp.where(positive, 0.0, x)
return jnp.where(positive, jnp.log(jsp.erfcx(xp)) - xp * xp, jnp.log(jsp.erfc(xn)))
def _normal_logcdf(z: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `_normal_logcdf` from its authored source."""
result = jnp.zeros_like(z)
def then_arm():
result_2 = _rk_logerfc(-z / np.sqrt(2.0)) - np.log(2.0)
return (None, jnp.asarray(result_2, dtype=jnp.float64))
def else_arm():
result_3 = jnp.log1p(-0.5 * jsp.erfc(z / np.sqrt(2.0)))
return (None, jnp.asarray(result_3, dtype=jnp.float64))
branch = jax.lax.cond(z < 0, then_arm, else_arm)
return branch[1]
def _function_2(standard_z: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `function` from its kernel plan."""
normal_logcdf = _normal_logcdf(standard_z, active)
standard_logcdf = normal_logcdf
return standard_logcdf
def _function_3(location: ArrayLike, scale: ArrayLike, log_scale: ArrayLike, x: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `function` from its kernel plan."""
standardized = (x - location) / jnp.where((x == location if scale == 0 else False), 1.0, scale)
return standardized
def _function_4(standard_z: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `function` from its kernel plan."""
normal_logcdf = _normal_logcdf(-standard_z, active)
standard_logccdf = normal_logcdf
return standard_logccdf
def _rk_log1mexp(x):
# log(1 - exp(x)) for x <= 0 (LogExpFunctions.log1mexp).
small = x < -0.6931471805599453
safe_small = jnp.where(small, x, -1.0)
safe_large = jnp.where(small, -1.0, x)
return jnp.where(small, jnp.log1p(-jnp.exp(safe_small)),
jnp.log(-jnp.expm1(safe_large)))
def brm_class_population_effects_density(
ppl_last_beta_pop: ArrayLike,
unconstrained: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Class-block population effects: one coefficient per design column and non-reference class.
Draws `beta_pop[1:ncoef, 1:nclass] ~ Normal(loc, scale)` and returns `X * beta_pop`, one
linear predictor column per non-reference class. `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 design column, shared by that column's classes.
"""
results = {}
if any(name in outputs for name in ("ppl_arrflat_beta_pop", "ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
ppl_arrflat_beta_pop = unconstrained[2:ppl_last_beta_pop]
if any(name in outputs for name in ("ppl_prior_beta_pop", "ppl_pw_prior_beta_pop")):
def ppl_pw_prior_beta_pop_cell(beta_pop):
log_scale = np.log(1.0)
standardized = (beta_pop - 0.0) / jnp.where((beta_pop == 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_pop != 0.0 if 1.0 == 0 else False), 0.0, log_scale)
return logpdf
ppl_pw_prior_beta_pop = (jnp.zeros(ppl_arrflat_beta_pop.shape[:1], dtype=jnp.float64) if 0 in ppl_arrflat_beta_pop.shape[:1] else jax.vmap(ppl_pw_prior_beta_pop_cell, in_axes=(0,))(ppl_arrflat_beta_pop))
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_arrflat_beta_pop" in outputs:
results["ppl_arrflat_beta_pop"] = ppl_arrflat_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
return results
def brm_class_population_effects(
X: ArrayLike,
beta_pop: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""Class-block population effects: one coefficient per design column and non-reference class.
Draws `beta_pop[1:ncoef, 1:nclass] ~ Normal(loc, scale)` and returns `X * beta_pop`, one
linear predictor column per non-reference class. `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 design column, shared by that column's classes.
"""
results = {}
if any(name in outputs for name in ("value",)):
value = X @ beta_pop
if "value" in outputs:
results["value"] = value
return results
def prepare_data(X_eta: ArrayLike, choice_fit: Any, choice_raw: Any, rating_fit: ArrayLike, rating_raw: ArrayLike, x: 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)`.
"""
X_eta = np.asarray(X_eta, dtype=np.float64)
choice_fit = np.asarray(choice_fit, dtype=object)
choice_raw = np.asarray(choice_raw, dtype=object)
rating_fit = np.asarray(rating_fit, dtype=np.int64)
rating_raw = np.asarray(rating_raw, dtype=np.int64)
x = np.asarray(x, dtype=np.float64)
value = _brm_fit_levels_np(choice_fit)
choice_fit_levels = value
value_2 = _indices_np(choice_raw, choice_fit_levels)
choice = np.asarray(value_2, dtype=np.int64)
X_choice_nested_arg1 = np.asarray(np.concatenate([np.ones((len(choice),), dtype=np.float64)[:, None], x[:, None]], axis=1), dtype=np.float64)
choice_nonreference = len(choice_fit_levels) - 1
value_3 = _brm_fit_levels_np_2(rating_fit)
rating_fit_levels = np.asarray(value_3, dtype=np.int64)
value_4 = _indices_np_2(rating_raw, rating_fit_levels)
rating = np.asarray(value_4, dtype=np.int64)
ppl_last_pop_choice_nested_arg1_beta_pop = 2 + 2 * choice_nonreference
ppl_first_pop_eta_beta_pop = ppl_last_pop_choice_nested_arg1_beta_pop + 1
def lane_conditions(lane_input_1):
return (bool(1 <= lane_input_1),)
lane_conditions_2 = np.asarray([lane_conditions(entry) for entry in choice], dtype=bool).reshape((-1, 1))
lanes = np.flatnonzero(lane_conditions_2[:, 0])
lanes_2 = np.flatnonzero(~lane_conditions_2[:, 0])
ppl_pw_choice_resp_lanes_1 = lanes
ppl_pw_choice_resp_lanes_2 = lanes_2
ppl_pw_choice_resp_lane_order = np.argsort(np.concatenate((lanes, lanes_2,)), kind="stable")
def lane_conditions_3(lane_input_1):
return (bool(lane_input_1 == 1), bool(lane_input_1 == 3),)
lane_conditions_4 = np.asarray([lane_conditions_3(entry_2) for entry_2 in rating], dtype=bool).reshape((-1, 2))
lanes_3 = np.flatnonzero(lane_conditions_4[:, 0])
lanes_4 = np.flatnonzero(~lane_conditions_4[:, 0] & lane_conditions_4[:, 1])
lanes_5 = np.flatnonzero(~lane_conditions_4[:, 0] & ~lane_conditions_4[:, 1])
ppl_pw_rating_resp_lanes_1 = lanes_3
ppl_pw_rating_resp_lanes_2 = lanes_4
ppl_pw_rating_resp_lanes_3 = lanes_5
ppl_pw_rating_resp_lane_order = np.argsort(np.concatenate((lanes_3, lanes_4, lanes_5,)), kind="stable")
return {"ppl_last_pop_choice_nested_arg1_beta_pop": StaticInt(ppl_last_pop_choice_nested_arg1_beta_pop), "choice_nonreference": StaticInt(choice_nonreference), "ppl_first_pop_eta_beta_pop": StaticInt(ppl_first_pop_eta_beta_pop), "X_choice_nested_arg1": np.asarray(X_choice_nested_arg1, dtype=np.float64), "X_eta": np.asarray(X_eta, dtype=np.float64), "choice": np.asarray(choice, dtype=np.int64), "_ppl_pw_choice_resp_lanes_1": np.asarray(ppl_pw_choice_resp_lanes_1, dtype=np.int64), "_ppl_pw_choice_resp_lanes_2": np.asarray(ppl_pw_choice_resp_lanes_2, dtype=np.int64), "_ppl_pw_choice_resp_lane_order": np.asarray(ppl_pw_choice_resp_lane_order, dtype=np.int64), "rating": np.asarray(rating, dtype=np.int64), "_ppl_pw_rating_resp_lanes_1": np.asarray(ppl_pw_rating_resp_lanes_1, dtype=np.int64), "_ppl_pw_rating_resp_lanes_2": np.asarray(ppl_pw_rating_resp_lanes_2, dtype=np.int64), "_ppl_pw_rating_resp_lanes_3": np.asarray(ppl_pw_rating_resp_lanes_3, dtype=np.int64), "_ppl_pw_rating_resp_lane_order": np.asarray(ppl_pw_rating_resp_lane_order, dtype=np.int64)}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
ppl_last_pop_choice_nested_arg1_beta_pop = prepared["ppl_last_pop_choice_nested_arg1_beta_pop"]
choice_nonreference = prepared["choice_nonreference"]
ppl_first_pop_eta_beta_pop = prepared["ppl_first_pop_eta_beta_pop"]
X_choice_nested_arg1 = prepared["X_choice_nested_arg1"]
X_eta = prepared["X_eta"]
choice = prepared["choice"]
_ppl_pw_choice_resp_lanes_1 = prepared["_ppl_pw_choice_resp_lanes_1"]
_ppl_pw_choice_resp_lanes_2 = prepared["_ppl_pw_choice_resp_lanes_2"]
_ppl_pw_choice_resp_lane_order = prepared["_ppl_pw_choice_resp_lane_order"]
rating = prepared["rating"]
_ppl_pw_rating_resp_lanes_1 = prepared["_ppl_pw_rating_resp_lanes_1"]
_ppl_pw_rating_resp_lanes_2 = prepared["_ppl_pw_rating_resp_lanes_2"]
_ppl_pw_rating_resp_lanes_3 = prepared["_ppl_pw_rating_resp_lanes_3"]
_ppl_pw_rating_resp_lane_order = prepared["_ppl_pw_rating_resp_lane_order"]
unconstrained = jnp.asarray(unconstrained)
X_choice_nested_arg1 = jnp.asarray(X_choice_nested_arg1)
X_eta = jnp.asarray(X_eta)
choice = jnp.asarray(choice)
_ppl_pw_choice_resp_lanes_1 = jnp.asarray(_ppl_pw_choice_resp_lanes_1)
_ppl_pw_choice_resp_lanes_2 = jnp.asarray(_ppl_pw_choice_resp_lanes_2)
_ppl_pw_choice_resp_lane_order = jnp.asarray(_ppl_pw_choice_resp_lane_order)
rating = jnp.asarray(rating)
_ppl_pw_rating_resp_lanes_1 = jnp.asarray(_ppl_pw_rating_resp_lanes_1)
_ppl_pw_rating_resp_lanes_2 = jnp.asarray(_ppl_pw_rating_resp_lanes_2)
_ppl_pw_rating_resp_lanes_3 = jnp.asarray(_ppl_pw_rating_resp_lanes_3)
_ppl_pw_rating_resp_lane_order = jnp.asarray(_ppl_pw_rating_resp_lane_order)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
prefix_stop = 2
if not (prefix_stop <= unconstrained.size):
raise ValueError("BoundsError: prefix exceeds array length")
ppl_vector_block_rating_thresholds = unconstrained[:max(prefix_stop, 0)]
rating_thresholds = _rk_ordered_constrain(ppl_vector_block_rating_thresholds, 1, 2)
if _entry in ("log_density", "log_jacobian"):
ppl_ordered_tail_rating_thresholds = unconstrained[1:2]
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
pop_eta_beta_pop = unconstrained[ppl_first_pop_eta_beta_pop - 1:ppl_first_pop_eta_beta_pop]
if _entry in ("log_density", "log_prior", "log_likelihood"):
pop_eta = brm_population_effects(
X=(X_eta if _entry in ("log_density", "log_likelihood") else None),
beta_pop=(pop_eta_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_likelihood"):
lane_entries = jnp.asarray(rating)[_ppl_pw_rating_resp_lanes_1]
lane_entries_2 = jnp.asarray(pop_eta["value"])[_ppl_pw_rating_resp_lanes_1]
def ppl_pw_rating_resp_cell(rating_2, eta, rating_thresholds_2):
if (1.0 > 0 if np.isfinite(1.0) else False):
x = 1.0 * (rating_thresholds_2[0] - eta)
log_scale = np.log(1.0)
def else_arm():
function = _function(0.0, 1.0, log_scale, x, jnp.logical_not((x == 0.0 if 1.0 == 0 else False)))
return function
logcdf_z = jax.lax.cond((x == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm)
def else_arm_3():
def else_arm_2():
function_2 = _function_2(logcdf_z, jnp.logical_and(jnp.logical_not(x == -jnp.inf), jnp.logical_not(x == jnp.inf)))
return function_2
return jax.lax.cond(x == jnp.inf, lambda: 0.0, else_arm_2)
value = jax.lax.cond(x == -jnp.inf, lambda: -jnp.inf, else_arm_3)
else:
value = -jnp.inf
ppl_density = value
return ppl_density
plate_part = (jnp.zeros(lane_entries.shape[:1], dtype=jnp.float64) if 0 in lane_entries.shape[:1] and lane_entries_2.shape[:1] == lane_entries.shape[:1] else jax.vmap(ppl_pw_rating_resp_cell, in_axes=(0, 0, None))(lane_entries, lane_entries_2, rating_thresholds))
lane_entries_3 = jnp.asarray(rating)[_ppl_pw_rating_resp_lanes_2]
lane_entries_4 = jnp.asarray(pop_eta["value"])[_ppl_pw_rating_resp_lanes_2]
def ppl_pw_rating_resp_cell_2(rating_2, eta, rating_thresholds_2):
if (1.0 > 0 if np.isfinite(1.0) else False):
x = 1.0 * (rating_thresholds_2[3 - 1 - 1] - eta)
log_scale = np.log(1.0)
def else_arm():
function_3 = _function_3(0.0, 1.0, log_scale, x, jnp.logical_not((x == 0.0 if 1.0 == 0 else False)))
return function_3
logccdf_z = jax.lax.cond((x == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm)
def else_arm_3():
def else_arm_2():
function_4 = _function_4(logccdf_z, jnp.logical_and(jnp.logical_not(x == jnp.inf), jnp.logical_not(x == -jnp.inf)))
return function_4
return jax.lax.cond(x == -jnp.inf, lambda: 0.0, else_arm_2)
value = jax.lax.cond(x == jnp.inf, lambda: -jnp.inf, else_arm_3)
else:
value = -jnp.inf
ppl_density = value
return ppl_density
plate_part_2 = (jnp.zeros(lane_entries_3.shape[:1], dtype=jnp.float64) if 0 in lane_entries_3.shape[:1] and lane_entries_4.shape[:1] == lane_entries_3.shape[:1] else jax.vmap(ppl_pw_rating_resp_cell_2, in_axes=(0, 0, None))(lane_entries_3, lane_entries_4, rating_thresholds))
lane_entries_5 = jnp.asarray(rating)[_ppl_pw_rating_resp_lanes_3]
lane_entries_6 = jnp.asarray(pop_eta["value"])[_ppl_pw_rating_resp_lanes_3]
def ppl_pw_rating_resp_cell_3(rating_2, eta, rating_thresholds_2):
if (1.0 > 0 if np.isfinite(1.0) else False):
def then_arm():
x = 1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta)
log_scale = np.log(1.0)
def else_arm():
function_3 = _function_3(0.0, 1.0, log_scale, x, jnp.logical_and(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, jnp.logical_not((x == 0.0 if 1.0 == 0 else False))))
return function_3
logccdf_z = jax.lax.cond((x == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm)
def else_arm_3():
def else_arm_2():
function_4 = _function_4(logccdf_z, jnp.logical_and(jnp.logical_and(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, jnp.logical_not(x == jnp.inf)), jnp.logical_not(x == -jnp.inf)))
return function_4
return jax.lax.cond(x == -jnp.inf, lambda: 0.0, else_arm_2)
x_2 = 1.0 * (rating_thresholds_2[rating_2 - 1] - eta)
log_scale_2 = np.log(1.0)
def else_arm_4():
function_3_2 = _function_3(0.0, 1.0, log_scale_2, x_2, jnp.logical_and(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, jnp.logical_not((x_2 == 0.0 if 1.0 == 0 else False))))
return function_3_2
logccdf_z_2 = jax.lax.cond((x_2 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_4)
def else_arm_6():
def else_arm_5():
function_4_2 = _function_4(logccdf_z_2, jnp.logical_and(jnp.logical_and(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, jnp.logical_not(x_2 == jnp.inf)), jnp.logical_not(x_2 == -jnp.inf)))
return function_4_2
return jax.lax.cond(x_2 == -jnp.inf, lambda: 0.0, else_arm_5)
x_3 = 1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta)
log_scale_3 = np.log(1.0)
def else_arm_7():
function_3_3 = _function_3(0.0, 1.0, log_scale_3, x_3, jnp.logical_and(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, jnp.logical_not((x_3 == 0.0 if 1.0 == 0 else False))))
return function_3_3
logccdf_z_3 = jax.lax.cond((x_3 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_7)
def else_arm_9():
def else_arm_8():
function_4_3 = _function_4(logccdf_z_3, jnp.logical_and(jnp.logical_and(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, jnp.logical_not(x_3 == jnp.inf)), jnp.logical_not(x_3 == -jnp.inf)))
return function_4_3
return jax.lax.cond(x_3 == -jnp.inf, lambda: 0.0, else_arm_8)
return jax.lax.cond(x == jnp.inf, lambda: -jnp.inf, else_arm_3) + jnp.log(-jnp.expm1(jax.lax.cond(x_2 == jnp.inf, lambda: -jnp.inf, else_arm_6) - jax.lax.cond(x_3 == jnp.inf, lambda: -jnp.inf, else_arm_9)))
def else_arm_26():
x_4 = 1.0 * (rating_thresholds_2[rating_2 - 1] - eta)
log_scale_4 = np.log(1.0)
def else_arm_10():
function = _function(0.0, 1.0, log_scale_4, x_4, jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not((x_4 == 0.0 if 1.0 == 0 else False))))
return function
logcdf_z = jax.lax.cond((x_4 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_10)
def else_arm_12():
def else_arm_11():
function_2 = _function_2(logcdf_z, jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(x_4 == -jnp.inf)), jnp.logical_not(x_4 == jnp.inf)))
return function_2
return jax.lax.cond(x_4 == jnp.inf, lambda: 0.0, else_arm_11)
x_5 = 1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta)
log_scale_5 = np.log(1.0)
def else_arm_13():
function_5 = _function(0.0, 1.0, log_scale_5, x_5, jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not((x_5 == 0.0 if 1.0 == 0 else False))))
return function_5
logcdf_z_2 = jax.lax.cond((x_5 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_13)
def else_arm_15():
def else_arm_14():
function_2_2 = _function_2(logcdf_z_2, jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(x_5 == -jnp.inf)), jnp.logical_not(x_5 == jnp.inf)))
return function_2_2
return jax.lax.cond(x_5 == jnp.inf, lambda: 0.0, else_arm_14)
def else_arm_25():
x_6 = 1.0 * (rating_thresholds_2[rating_2 - 1] - eta)
log_scale_6 = np.log(1.0)
def else_arm_16():
function_6 = _function(0.0, 1.0, log_scale_6, x_6, jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15))), jnp.logical_not((x_6 == 0.0 if 1.0 == 0 else False))))
return function_6
logcdf_z_3 = jax.lax.cond((x_6 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_16)
def else_arm_18():
def else_arm_17():
function_2_3 = _function_2(logcdf_z_3, jnp.logical_and(jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15))), jnp.logical_not(x_6 == -jnp.inf)), jnp.logical_not(x_6 == jnp.inf)))
return function_2_3
return jax.lax.cond(x_6 == jnp.inf, lambda: 0.0, else_arm_17)
x_7 = 1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta)
log_scale_7 = np.log(1.0)
def else_arm_19():
function_7 = _function(0.0, 1.0, log_scale_7, x_7, jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15))), jnp.logical_not((x_7 == 0.0 if 1.0 == 0 else False))))
return function_7
logcdf_z_4 = jax.lax.cond((x_7 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_19)
def else_arm_21():
def else_arm_20():
function_2_4 = _function_2(logcdf_z_4, jnp.logical_and(jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15))), jnp.logical_not(x_7 == -jnp.inf)), jnp.logical_not(x_7 == jnp.inf)))
return function_2_4
return jax.lax.cond(x_7 == jnp.inf, lambda: 0.0, else_arm_20)
x_8 = 1.0 * (rating_thresholds_2[rating_2 - 1] - eta)
log_scale_8 = np.log(1.0)
def else_arm_22():
function_8 = _function(0.0, 1.0, log_scale_8, x_8, jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15))), jnp.logical_not((x_8 == 0.0 if 1.0 == 0 else False))))
return function_8
logcdf_z_5 = jax.lax.cond((x_8 == 0.0 if 1.0 == 0 else False), lambda: 1.0 / 1.0, else_arm_22)
def else_arm_24():
def else_arm_23():
function_2_5 = _function_2(logcdf_z_5, jnp.logical_and(jnp.logical_and(jnp.logical_and(jnp.logical_not(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0), jnp.logical_not(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15))), jnp.logical_not(x_8 == -jnp.inf)), jnp.logical_not(x_8 == jnp.inf)))
return function_2_5
return jax.lax.cond(x_8 == jnp.inf, lambda: 0.0, else_arm_23)
return jax.lax.cond(x_6 == -jnp.inf, lambda: -jnp.inf, else_arm_18) + _rk_log1mexp(jax.lax.cond(x_7 == -jnp.inf, lambda: -jnp.inf, else_arm_21) - jax.lax.cond(x_8 == -jnp.inf, lambda: -jnp.inf, else_arm_24))
return jax.lax.cond(jax.lax.cond(x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_12) == jax.lax.cond(x_5 == -jnp.inf, lambda: -jnp.inf, else_arm_15), lambda: -jnp.inf, else_arm_25)
value = jax.lax.cond(1.0 * (rating_thresholds_2[rating_2 - 1 - 1] - eta) > 0, then_arm, else_arm_26)
else:
value = -jnp.inf
ppl_density = value
return ppl_density
plate_part_3 = (jnp.zeros(lane_entries_5.shape[:1], dtype=jnp.float64) if 0 in lane_entries_5.shape[:1] and lane_entries_6.shape[:1] == lane_entries_5.shape[:1] else jax.vmap(ppl_pw_rating_resp_cell_3, in_axes=(0, 0, None))(lane_entries_5, lane_entries_6, rating_thresholds))
ppl_pw_rating_resp = jnp.concatenate((plate_part, plate_part_2, plate_part_3,))[_ppl_pw_rating_resp_lane_order]
ppl_lik_rating_resp = jnp.sum(ppl_pw_rating_resp)
if _entry in ("log_density", "log_prior"):
def ppl_pw_prior_rating_thresholds_cell(rating_thresholds_2):
x_argument = 1.0 * rating_thresholds_2
log_scale = np.log(1.0)
standardized = (x_argument - 0.0) / jnp.where((x_argument == 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((x_argument != 0.0 if 1.0 == 0 else False), 0.0, log_scale)
return logpdf
ppl_pw_prior_rating_thresholds = (jnp.zeros(rating_thresholds.shape[:1], dtype=jnp.float64) if 0 in rating_thresholds.shape[:1] else jax.vmap(ppl_pw_prior_rating_thresholds_cell, in_axes=(0,))(rating_thresholds))
ppl_prior_rating_thresholds = jnp.sum(ppl_pw_prior_rating_thresholds)
if _entry in ("log_density", "log_jacobian"):
log_jacobian_2 = jnp.sum(ppl_ordered_tail_rating_thresholds)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
pop_choice_nested_arg1 = brm_class_population_effects_density(
ppl_last_beta_pop=(ppl_last_pop_choice_nested_arg1_beta_pop if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") 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_beta_pop", ("log_density", "log_prior", "log_likelihood", "constrain")),
("ppl_prior_beta_pop", ("log_density", "log_prior")),
("ppl_pw_prior_beta_pop", ("log_density", "log_prior")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_likelihood", "constrain"):
pop_choice_nested_arg1_beta_pop = jnp.reshape(pop_choice_nested_arg1["ppl_arrflat_beta_pop"], (2, choice_nonreference), order="F")
if _entry in ("log_density", "log_prior"):
prior = ppl_prior_rating_thresholds + pop_choice_nested_arg1["ppl_prior_beta_pop"] + pop_eta["ppl_prior_beta_pop"]
if _entry in ("log_density", "log_likelihood"):
pop_choice_nested_arg1_2 = brm_class_population_effects(
X=(X_choice_nested_arg1 if _entry in ("log_density", "log_likelihood") else None),
beta_pop=(pop_choice_nested_arg1_beta_pop 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
),
)
plate_argument = pop_choice_nested_arg1_2["value"]
def ppl_pw_choice_resp_cell(choice_2, ppl_c2):
def then_arm():
def _ppl_categorical_logit_ref_logpdf() -> jax.Array:
"""Compute `_ppl_categorical_logit_ref_logpdf` from its authored source."""
m = 0.0
def loop_body(j, carry):
(m_2,) = carry
m_3 = jnp.maximum(m_2, ppl_c2[j - 1])
return (m_3,)
carry_init = (jnp.asarray(m, dtype=jnp.float64),)
loop_carry = jax.lax.fori_loop(1, ppl_c2.shape[0] + 1, loop_body, carry_init) if 1 <= ppl_c2.shape[0] else carry_init
total = jnp.exp(-loop_carry[0])
def loop_body_2(j_2, carry_2):
(total_2,) = carry_2
total_3 = total_2 + jnp.exp(ppl_c2[j_2 - 1] - loop_carry[0])
return (total_3,)
carry_init_2 = (jnp.asarray(total, dtype=jnp.float64),)
loop_carry_2 = jax.lax.fori_loop(1, ppl_c2.shape[0] + 1, loop_body_2, carry_init_2) if 1 <= ppl_c2.shape[0] else carry_init_2
observed = jax.lax.cond(choice_2 == 1, lambda: 0.0, lambda: ppl_c2[choice_2 - 1 - 1])
return observed - (loop_carry[0] + jnp.log(loop_carry_2[0]))
ppl_categorical_logit_ref_logpdf = _ppl_categorical_logit_ref_logpdf()
return ppl_categorical_logit_ref_logpdf
ppl_density = jax.lax.cond(jnp.logical_and(1 <= choice_2, choice_2 <= ppl_c2.size + 1), then_arm, lambda: -jnp.inf)
return ppl_density
ppl_pw_choice_resp = (jnp.zeros(choice.shape[:1], dtype=jnp.float64) if 0 in choice.shape[:1] and plate_argument.shape[:1] == choice.shape[:1] else jax.vmap(ppl_pw_choice_resp_cell, in_axes=(0, 0))(choice, plate_argument))
ppl_lik_choice_resp = jnp.sum(ppl_pw_choice_resp)
likelihood = ppl_lik_choice_resp + ppl_lik_rating_resp
if _entry in ("log_density",):
posterior = prior + likelihood + log_jacobian_2
if not (unconstrained.size == ppl_first_pop_eta_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(likelihood, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(log_jacobian_2, dtype=jnp.float64)
if _entry == "constrain":
return {"rating_thresholds": jnp.asarray(rating_thresholds), "pop_choice_nested_arg1": {"beta_pop": jnp.asarray(pop_choice_nested_arg1_beta_pop)}, "pop_eta": {"beta_pop": jnp.asarray(pop_eta_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:
- `rating_thresholds`
- `pop_choice_nested_arg1.beta_pop`
- `pop_eta.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_first_pop_eta_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 {"rating_thresholds": {"start": 0, "stop": 2, "transform": "ordered", "dims": ()}, "pop_choice_nested_arg1.beta_pop": {"start": 2, "stop": int(prepared["ppl_last_pop_choice_nested_arg1_beta_pop"]), "transform": "identity", "dims": (2, int(prepared["choice_nonreference"]))}, "pop_eta.beta_pop": {"start": int(prepared["ppl_first_pop_eta_beta_pop"]) - 1, "stop": int(prepared["ppl_first_pop_eta_beta_pop"]), "transform": "identity", "dims": (1,)}}A rating known only up to a range of categories, such as "marked to severe" on a 0:4 scale, is coarsened evidence: y_min ~ coarsened(Ordinal(Cumulative(), ProbitLink(), eta); upper=y_max). Each row's response holds its lowest allowed category and upper its highest, both inclusive, so equal labels are an exact rating, and the row contributes the summed probability of its categories. Declare the levels on a CategoricalVector to keep a level that no row observed.
Observation mechanisms
Truncation conditions on being inside a sampling interval. Censoring records a limit in place of an unobserved value. An interval-censored response is the lower endpoint, and the likelihood is the probability of the interval (response, upper]. These are different observations of the same base law.
| Observation | Declaration | Predictive quantity |
|---|---|---|
| Selected positive values | y ~ truncated(Normal(mu, sigma); lower=0) | Truncated values |
| Detection limit | y ~ censored(Normal(mu, sigma); lower=lloq) | Values with the same clamping |
| Known interval | y ~ interval_censored(Normal(mu, sigma); upper=hi) | Uncoarsened values from the base law |
| Partly missing continuous values | mi(y) ~ Normal(mu, sigma) | A latent value for each missing row |
| Known relative precision | y ~ weighted(Normal(mu, sigma), aweights(w)) | Normal SD sigma / sqrt(w) |
| Replicated or powered density | y ~ weighted(Normal(mu, sigma), fweights(w)) | Base-law prediction; density multiplied by the weight |
The reference identifies supported base families. Response bounds may be data columns. interval_censored(x; upper=lloq) inside a predictor has a separate meaning: it imputes a censored covariate.
Mixtures and correlated outcomes
MixtureModel([Normal(mu1, sigma1), Normal(mu2, sigma2)], share) marginalizes component membership. Weights may be fixed, a declared Dirichlet simplex, or a valid row-dependent expression. The reference describes allowed component families. Stan can return membership probabilities as well as predictive draws; RK currently supplies the density, gradient and pointwise likelihood for this surface, but not mixture prediction.
For residual correlation, declare L ~ LKJCovarianceFactor(2; scale_prior=Exponential(1), shape=2) and observe [y1, y2] ~ MvNormalCholesky([mu1, mu2], L). This is a joint Gaussian observation per complete row. Non-Gaussian residual copulas and partially missing response vectors are outside that surface.
Continue to the Warfarin example for responses with different observation scales and a shared mechanistic model.