Spatial and space-time fields
Share information between nearby observations, neighboring areas or related measurement channels. Choose a representation from the observation geometry and the predictions you need.
| Data | Term | Representation |
|---|---|---|
| Areas with known neighbors | car(area; edges=(from,to), type=:bym2) | Graph field plus independent area effects |
| Smooth continuous coordinates | hsgp(east,north; k=(kx,ky)) | Fixed Hilbert basis with kx*ky weights |
| Points evolving over time | gmrf((east,north),time; mesh=...) | Triangular-mesh Matérn field with OU evolution |
| Sparse irregular position–time reads | gmrf((east,north),time; neighbors=m) | Local Gaussian conditionals on the observed states |
| Irregular reads needing exact OU time covariance | gmrf((east,north),time; multiresolution=m) | Sparse spatial basis of shared OU paths |
Use a common planar distance unit. Longitude and latitude in degrees need a suitable projection before they represent distances in these terms.
Areal effects
ICAR shares information through adjacency. BYM2 adds independent area effects and estimates the structured variance share. The intercept carries the overall level; an exposure offset keeps the field on a relative-risk scale.
Area counts with a BYM2 field
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
log(rate) ~ 1 + offset(log_expected) + car(area; edges=(from, to), type=:bym2)
cases ~ Poisson(rate)
effect(rate, Intercept) ~ Normal(0, 1)
sd(rate, car(area)) ~ Normal(0, 0.5)
mixing(rate, car(area)) ~ Beta(2, 2)
end)((; area=["a", "b", "c", "d"], cases=[14, 23, 9, 18],
log_expected=log.([12., 20., 12., 20.]),
from=["a", "a", "b", "c"], to=["b", "c", "d", "d"]))SBBRMI with data keys = [:car_log_rate_area_comp_size, :car_log_rate_area_comp_start, :car_log_rate_area_inv_scale, :car_log_rate_area_n_nodes, :car_log_rate_area_n_struct, :car_log_rate_area_node1, :car_log_rate_area_node2, :car_log_rate_area_row_idx, :car_log_rate_area_struct_idx, :cases, :log_expected]
configured submodels:
_sb_car_bym2_configured_1 = Base.merge(BayesianRegressionModels._sb_car_bym2, quote
sigma ~ (StanBlocks.builtin.restricted)(normal, 0.0, 0.5; lower = 0.0)
rho ~ (StanBlocks.builtin.restricted)(beta, 2, 2; lower = 0.0, upper = 1.0)
end)
emitted @slic body:
begin
X_log_rate = hcat(rep_vector(1.0, num_elements(log_expected)))
pop_log_rate ~ _popefs_normal(; X = X_log_rate, beta_loc = [0], beta_scale = [1])
car_log_rate_area ~ _sb_car_bym2_configured_1(; n_struct = car_log_rate_area_n_struct, n_nodes = car_log_rate_area_n_nodes, node1 = car_log_rate_area_node1, node2 = car_log_rate_area_node2, comp_start = car_log_rate_area_comp_start, comp_size = car_log_rate_area_comp_size, struct_idx = car_log_rate_area_struct_idx, inv_scale = car_log_rate_area_inv_scale, row_idx = car_log_rate_area_row_idx)
log_rate = pop_log_rate + log_expected + car_log_rate_area
rate = exp(log_rate)
cases ~ poisson(rate)
end"""
Each value's position among the sorted levels `sorted_levels`, by binary search (`car` node labels).
"""
ReactiveKernels.@kernel(brm_sorted_positions(values, sorted_levels) = begin
positions = ReactiveKernels.plate(values) do value
BayesianRegressionModels._brm_sorted_position(sorted_levels, value)
end
return positions
end)
"""
An areal (`car`) effect in the BYM2 convolution.
Draws the scale `sigma`, the mixing weight `rho`, unstructured effects `theta ~ Normal(0, 1)`
and the ICAR field `phi ~ ICAR(node1, node2)` over the areas' adjacency, with a soft sum-to-zero per connected component. Islands read 0. Returns each row's area effect,
`sigma .* (sqrt.(rho .* inv_scale) .* phi_full .+ sqrt.(1 .- rho .* is_struct) .* theta)` at the row's area `area`.
"""
brm_car_bym2(node1, node2, struct_pos, area, comp_start, comp_size, inv_scale, is_struct) = begin
sigma ~ restricted(Normal(0.0, 0.5), 0.0, Inf)
rho ~ Beta(2.0, 2.0)
theta[axes(inv_scale, 1)] .~ Normal.(0, 1)
S = sum(comp_size)
phi[1:S] ~ ICAR(node1, node2)
cs = cumsum(vcat(0.0, phi))
phi_sums = cs[comp_start .+ comp_size] .- cs[comp_start]
phi_sums .~ Normal.(0.0, 0.001 .* comp_size)
phi_full = (vcat(phi, 0.0))[struct_pos]
effects = sigma .* (sqrt.(rho .* inv_scale) .* phi_full .+ sqrt.(1.0 .- rho .* is_struct) .* theta)
return effects[area]
end
begin
car_rate_area_area = brm_sorted_positions(area, car_rate_area_nodes)
car_rate_area ~ brm_car_bym2(car_rate_area_node1, car_rate_area_node2, car_rate_area_struct_pos, car_rate_area_area, car_rate_area_comp_start, car_rate_area_comp_size, car_rate_area_inv_scale, car_rate_area_is_struct)
rate_Intercept ~ Normal(0.0, 1.0)
log_rate = .+(rate_Intercept, log_expected, car_rate_area)
rate = exp.(log_rate)
cases .~ PoissonLog.(log_rate)
endfunctions {
matrix hcat(vector x) {
int n = dims(x)[1];
return to_matrix(x, n, 1);
}
real brm_icar_lpdf(
vector phi,
array[] int node1,
array[] int node2,
array[] int comp_start,
array[] int comp_size
) {
int E = dims(node1)[1];
int C = dims(comp_start)[1];
if (dims(node2)[1] != E) reject("brm_icar_lpdf: dim mismatch — `node2` dim 1 (= ", dims(node2)[1], ") does not match `E` (= ", E, "), inferred from `node1` dim 1. `E` sizes: `node1` dim 1 (= ", dims(node1)[1], "), `node2` dim 1 (= ", dims(node2)[1], ").");
if (dims(comp_size)[1] != C) reject("brm_icar_lpdf: dim mismatch — `comp_size` dim 1 (= ", dims(comp_size)[1], ") does not match `C` (= ", C, "), inferred from `comp_start` dim 1. `C` sizes: `comp_start` dim 1 (= ", dims(comp_start)[1], "), `comp_size` dim 1 (= ", dims(comp_size)[1], ").");
real lp = (-0.5 * dot_self((phi[node1] - phi[node2])));
for(c in 1:C) {
lp += normal_lpdf(sum(segment(phi, comp_start[c], comp_size[c])) | 0.0, (0.001 * comp_size[c]));
}
return lp;
}
vector car_bym2_effects(
real sigma,
real rho,
vector phi,
vector theta,
array[] int struct_idx,
vector inv_scale
) {
int N = dims(theta)[1];
if (dims(struct_idx)[1] != N) reject("car_bym2_effects: dim mismatch — `struct_idx` dim 1 (= ", dims(struct_idx)[1], ") does not match `N` (= ", N, "), inferred from `theta` dim 1. `N` sizes: `theta` dim 1 (= ", dims(theta)[1], "), `struct_idx` dim 1 (= ", dims(struct_idx)[1], "), `inv_scale` dim 1 (= ", dims(inv_scale)[1], ").");
if (dims(inv_scale)[1] != N) reject("car_bym2_effects: dim mismatch — `inv_scale` dim 1 (= ", dims(inv_scale)[1], ") does not match `N` (= ", N, "), inferred from `theta` dim 1. `N` sizes: `theta` dim 1 (= ", dims(theta)[1], "), `struct_idx` dim 1 (= ", dims(struct_idx)[1], "), `inv_scale` dim 1 (= ", dims(inv_scale)[1], ").");
vector[N] out;
for(k in 1:N) {
out[k] = (sqrt((1.0 - (rho * (struct_idx[k] > 0)))) * theta[k]);
if((struct_idx[k] > 0)) {
out[k] += (sqrt((rho * inv_scale[k])) * phi[struct_idx[k]]);
}
}
return (sigma * out);
}
vector car_rows(
vector effects,
array[] int row_idx
) {
int R = dims(row_idx)[1];
return effects[row_idx];
}
vector poisson_lpmfs(
array[] int obs,
vector lambda
) {
return jbroadcasted_poisson_lpmfs(obs, lambda);
}
vector jbroadcasted_poisson_lpmfs(
array[] int x1,
vector x2
) {
int n = dims(x1)[1];
vector[n] rv;
for(i in 1:n) {
rv[i] = poisson_lpmfs(broadcasted_getindex(x1, i), broadcasted_getindex(x2, i));
}
return rv;
}
real poisson_lpmfs(int args1, real args2) {
return poisson_lpmf(args1 | args2);
}
int broadcasted_getindex(array[] int x, int i) {
return x[i];
}
real broadcasted_getindex(vector x, int i) {
return x[i];
}
array[] int poisson_int_rng(
int anontok__1,
vector p
) {
int n = anontok__1;
return poisson_rng(p);
}
}
data {
int log_expected_n;
vector[log_expected_n] log_expected;
int car_log_rate_area_n_struct;
int car_log_rate_area_node1_n;
array[car_log_rate_area_node1_n] int car_log_rate_area_node1;
int car_log_rate_area_node2_n;
array[car_log_rate_area_node2_n] int car_log_rate_area_node2;
int car_log_rate_area_comp_start_n;
array[car_log_rate_area_comp_start_n] int car_log_rate_area_comp_start;
int car_log_rate_area_comp_size_n;
array[car_log_rate_area_comp_size_n] int car_log_rate_area_comp_size;
int car_log_rate_area_n_nodes;
int car_log_rate_area_inv_scale_n;
int car_log_rate_area_struct_idx_n;
array[car_log_rate_area_struct_idx_n] int car_log_rate_area_struct_idx;
vector[car_log_rate_area_inv_scale_n] car_log_rate_area_inv_scale;
int car_log_rate_area_row_idx_n;
array[car_log_rate_area_row_idx_n] int car_log_rate_area_row_idx;
int cases_n;
array[cases_n] int cases;
}
transformed data {
matrix[num_elements(log_expected), 1] X_log_rate = hcat(rep_vector(1.0, num_elements(log_expected)));
int pop_log_rate_n_covariates = 1;
}
parameters {
vector[pop_log_rate_n_covariates] pop_log_rate_beta_pop;
real<lower=0.0> car_log_rate_area_sigma;
real<lower=0.0, upper=1.0> car_log_rate_area_rho;
vector[car_log_rate_area_n_struct] car_log_rate_area_phi;
vector[car_log_rate_area_n_nodes] car_log_rate_area_theta;
}
transformed parameters {
vector[num_elements(log_expected)] pop_log_rate = (X_log_rate * pop_log_rate_beta_pop);
vector[car_log_rate_area_inv_scale_n] car_log_rate_area_effects = car_bym2_effects(
car_log_rate_area_sigma,
car_log_rate_area_rho,
car_log_rate_area_phi,
car_log_rate_area_theta,
car_log_rate_area_struct_idx,
car_log_rate_area_inv_scale
);
vector[car_log_rate_area_row_idx_n] car_log_rate_area = car_rows(car_log_rate_area_effects, car_log_rate_area_row_idx);
vector[num_elements(log_expected)] log_rate = (pop_log_rate + log_expected + car_log_rate_area);
vector[num_elements(log_expected)] rate = exp(log_rate);
}
model {
pop_log_rate_beta_pop ~ normal([0]', [1]');
car_log_rate_area_sigma ~ normal(0.0, 0.5);
car_log_rate_area_rho ~ beta(2, 2);
car_log_rate_area_phi ~ brm_icar(
car_log_rate_area_node1,
car_log_rate_area_node2,
car_log_rate_area_comp_start,
car_log_rate_area_comp_size
);
car_log_rate_area_theta ~ std_normal();
cases ~ poisson(rate);
}
generated quantities {
vector[cases_n] cases_likelihood = poisson_lpmfs(cases, rate);
array[cases_n] int cases_gen = poisson_int_rng(cases_n, rate);
}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
# prepare_data takes these data-only values from rk_bound_data(rk, source),
# because they have no Python translation (m.UNTRANSLATED):
# car_rate_area_area: keyword arguments to `sprint` have no JAX translation in recipe `__plate_value__
# = (sorted_levels, value) ->
# BayesianRegressionModels._brm_sorted_position(sorted_levels, value)`"""Generated by ReactiveKernelsPPL.jax_source from a built @rkppl program; do not edit.
Data: area, car_rate_area_comp_size, car_rate_area_comp_start, car_rate_area_inv_scale, car_rate_area_is_struct, car_rate_area_node1, car_rate_area_node2, car_rate_area_nodes, car_rate_area_struct_pos, cases, log_expected.
Model documentation:
- `car_rate_area`: An areal (`car`) effect in the BYM2 convolution.
Draws the scale `sigma`, the mixing weight `rho`, unstructured effects `theta ~ Normal(0, 1)`
and the ICAR field `phi ~ ICAR(node1, node2)` over the areas' adjacency, with a soft sum-to-zero per connected component. Islands read 0. Returns each row's area effect,
`sigma .* (sqrt.(rho .* inv_scale) .* phi_full .+ sqrt.(1 .- rho .* is_struct) .* theta)` at the row's area `area`.
"""
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 = {"area": {"dtype": "object", "ndim": 1, "ragged": False}, "car_rate_area_area": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_comp_size": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_comp_start": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_inv_scale": {"dtype": "float64", "ndim": 1, "ragged": False}, "car_rate_area_is_struct": {"dtype": "float64", "ndim": 1, "ragged": False}, "car_rate_area_node1": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_node2": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_nodes": {"dtype": "object", "ndim": 1, "ragged": False}, "car_rate_area_struct_pos": {"dtype": "int64", "ndim": 1, "ragged": False}, "cases": {"dtype": "int64", "ndim": 1, "ragged": False}, "log_expected": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "ppl_last_car_rate_area_theta", "ppl_first_car_rate_area_phi", "ppl_last_car_rate_area_phi", "_rkppl_index_1", "car_rate_area_comp_start", "car_rate_area_struct_pos", "car_rate_area_inv_scale", "car_rate_area_is_struct", "car_rate_area_area", "log_expected", "_ppl_yf_cases_resp", "_ppl_lfact_cases_resp", "car_rate_area_phi_sums_scale", "car_rate_area_node1", "ppl_prior_car_rate_area_phi_checked_node2", "ppl_axis1_car_rate_area_theta", "car_rate_area_S")
PREPARED = {"ppl_last_car_rate_area_theta": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_first_car_rate_area_phi": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_last_car_rate_area_phi": {"dtype": "int64", "ndim": 0, "ragged": False}, "_rkppl_index_1": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_comp_start": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_struct_pos": {"dtype": "int64", "ndim": 1, "ragged": False}, "car_rate_area_inv_scale": {"dtype": "float64", "ndim": 1, "ragged": False}, "car_rate_area_is_struct": {"dtype": "float64", "ndim": 1, "ragged": False}, "car_rate_area_area": {"dtype": "int64", "ndim": 1, "ragged": False}, "log_expected": {"dtype": "float64", "ndim": 1, "ragged": False}, "_ppl_yf_cases_resp": {"dtype": "float64", "ndim": 1, "ragged": False}, "_ppl_lfact_cases_resp": {"dtype": "float64", "ndim": 0, "ragged": False}, "car_rate_area_phi_sums_scale": {"dtype": "float64", "ndim": 1, "ragged": False}, "car_rate_area_node1": {"dtype": "int64", "ndim": 1, "ragged": False}, "ppl_prior_car_rate_area_phi_checked_node2": {"dtype": "int64", "ndim": 1, "ragged": False}, "ppl_axis1_car_rate_area_theta": {"dtype": "int64", "ndim": 0, "ragged": False}, "car_rate_area_S": {"dtype": "int64", "ndim": 0, "ragged": False}}
UNTRANSLATED = {"car_rate_area_area": "keyword arguments to `sprint` have no JAX translation in recipe `__plate_value__ = (sorted_levels, value) -> BayesianRegressionModels._brm_sorted_position(sorted_levels, value)`"}
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 _log_sigmoid(c1: ArrayLike, c2: ArrayLike, u: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `_rk_log_sigmoid` from its authored source."""
return jax.nn.log_sigmoid(u)
def _rk_log1mlogistic(x):
# log(1 - logistic(x)) (LogExpFunctions.log1mlogistic).
return jax.nn.log_sigmoid(-x)
def _log1m_sigmoid(c1: ArrayLike, c2: ArrayLike, u: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `_rk_log1m_sigmoid` from its authored source."""
return _rk_log1mlogistic(u)
def _rk_lgamma_correction(x):
# log(gamma(x)) - ((x - 0.5) * log(x) - x + 0.5 * log(2 pi)), for x >= 10:
# the Stirling series through x^-15.
z = 1.0 / (x * x)
return (1.0 / x) * (1.0 / 12 + z * (-1.0 / 360 + z * (1.0 / 1260 + z * (-1.0 / 1680
+ z * (1.0 / 1188 + z * (-691.0 / 360360 + z * (1.0 / 156 + z * (-3617.0 / 122400))))))))
def _rk_logbeta_np(a, b):
# SpecialFunctions.logbeta for positive arguments. With b the larger, a
# large b subtracts log(gamma(b)) - log(gamma(a + b)) in Stirling form,
# without cancellation.
a, b = np.minimum(a, b), np.maximum(a, b)
small = ssp.gammaln(a) + ssp.gammaln(b) - ssp.gammaln(a + b)
big = np.maximum(b, 10.0)
large = (ssp.gammaln(a) + _rk_lgamma_correction(big) - _rk_lgamma_correction(a + big)
- (a + big - 0.5) * np.log1p(a / big) - a * np.log(big) + a)
return np.where(b < 10, small, large)
def brm_car_bym2(
area: ArrayLike,
comp_start: ArrayLike,
inv_scale: ArrayLike,
is_struct: ArrayLike,
node1: ArrayLike,
phi: ArrayLike,
ppl_prior_phi_checked_node2: ArrayLike,
rho: ArrayLike,
rho_u: ArrayLike,
rkppl_index_1: ArrayLike,
sigma: ArrayLike,
struct_pos: ArrayLike,
theta: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""An areal (`car`) effect in the BYM2 convolution.
Draws the scale `sigma`, the mixing weight `rho`, unstructured effects `theta ~ Normal(0, 1)`
and the ICAR field `phi ~ ICAR(node1, node2)` over the areas' adjacency, with a soft sum-to-zero per connected component. Islands read 0. Returns each row's area effect,
`sigma .* (sqrt.(rho .* inv_scale) .* phi_full .+ sqrt.(1 .- rho .* is_struct) .* theta)` at the row's area `area`.
"""
results = {}
if any(name in outputs for name in ("phi_sums",)):
cs = jnp.cumsum(jnp.concatenate([jnp.atleast_1d(0.0), phi]))
if any(name in outputs for name in ("effects", "value")):
phi_full_gathered = jnp.concatenate([phi, jnp.atleast_1d(0.0)])
if any(name in outputs for name in ("phi_sums",)):
plate_argument = cs[rkppl_index_1 - 1]
plate_argument_2 = cs[comp_start - 1]
def phi_sums_cell(value, value_2):
plate_value = value - value_2
return plate_value
phi_sums = (jnp.zeros(plate_argument.shape[:1], dtype=jnp.float64) if 0 in plate_argument.shape[:1] and plate_argument_2.shape[:1] == plate_argument.shape[:1] else jax.vmap(phi_sums_cell, in_axes=(0, 0))(plate_argument, plate_argument_2))
if any(name in outputs for name in ("effects", "value")):
phi_full = phi_full_gathered[struct_pos - 1]
effects = sigma * (jnp.sqrt(rho * inv_scale) * phi_full + jnp.sqrt(1.0 - rho * is_struct) * theta)
if any(name in outputs for name in ("value",)):
value = effects[area - 1]
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_location", "ppl_prior_sigma_standard_logpdf")):
ppl_prior_sigma_location = 0.0
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_log_scale", "ppl_prior_sigma_scale", "ppl_prior_sigma_standard_logpdf")):
ppl_prior_sigma_scale = 0.5
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_log_scale")):
ppl_prior_sigma_log_scale = np.log(ppl_prior_sigma_scale)
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_standard_logpdf")):
ppl_prior_sigma_logpdf_z = (sigma - ppl_prior_sigma_location) / jnp.where((sigma == ppl_prior_sigma_location if ppl_prior_sigma_scale == 0 else False), 1.0, ppl_prior_sigma_scale)
ppl_prior_sigma_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_sigma_logpdf_z ** 2
if any(name in outputs for name in ("ppl_prior_sigma",)):
ppl_prior_sigma = ppl_prior_sigma_standard_logpdf - jnp.where((sigma != ppl_prior_sigma_location if ppl_prior_sigma_scale == 0 else False), 0.0, ppl_prior_sigma_log_scale)
if any(name in outputs for name in ("ppl_prior_rho", "ppl_prior_rho_a")):
ppl_prior_rho_a = 2.0
if any(name in outputs for name in ("ppl_prior_rho", "ppl_prior_rho_b")):
ppl_prior_rho_b = 2.0
if any(name in outputs for name in ("ppl_prior_rho",)):
def then_arm():
log_sigmoid = _log_sigmoid(1, 1, rho_u, (rho > 0) & (rho < 1))
log1m_sigmoid = _log1m_sigmoid(1, 1, rho_u, (rho > 0) & (rho < 1))
return (ppl_prior_rho_a - 1) * log_sigmoid + (ppl_prior_rho_b - 1) * log1m_sigmoid - _rk_logbeta_np(ppl_prior_rho_a, ppl_prior_rho_b)
ppl_prior_rho = jax.lax.cond((rho > 0) & (rho < 1), then_arm, lambda: -jnp.inf)
if any(name in outputs for name in ("ppl_prior_theta", "ppl_pw_prior_theta")):
def ppl_pw_prior_theta_cell(theta_2):
log_scale = np.log(1.0)
standardized = (theta_2 - 0.0) / jnp.where((theta_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((theta_2 != 0.0 if 1.0 == 0 else False), 0.0, log_scale)
return logpdf
ppl_pw_prior_theta = (jnp.zeros(theta.shape[:1], dtype=jnp.float64) if 0 in theta.shape[:1] else jax.vmap(ppl_pw_prior_theta_cell, in_axes=(0,))(theta))
if any(name in outputs for name in ("ppl_prior_theta",)):
ppl_prior_theta = jnp.sum(ppl_pw_prior_theta)
if any(name in outputs for name in ("ppl_prior_phi", "ppl_prior_phi_total")):
def ppl_prior_phi_squares_cell(i, j, phi_2):
difference = phi_2[i - 1] - phi_2[j - 1]
plate_value = difference * difference
return plate_value
ppl_prior_phi_squares = (jnp.zeros(node1.shape[:1], dtype=jnp.float64) if 0 in node1.shape[:1] and ppl_prior_phi_checked_node2.shape[:1] == node1.shape[:1] else jax.vmap(ppl_prior_phi_squares_cell, in_axes=(0, 0, None))(node1, ppl_prior_phi_checked_node2, phi))
ppl_prior_phi_total = jnp.sum(ppl_prior_phi_squares)
if any(name in outputs for name in ("ppl_prior_phi",)):
ppl_prior_phi = -0.5 * ppl_prior_phi_total
if "ppl_prior_phi" in outputs:
results["ppl_prior_phi"] = ppl_prior_phi
if "ppl_prior_rho" in outputs:
results["ppl_prior_rho"] = ppl_prior_rho
if "ppl_prior_sigma" in outputs:
results["ppl_prior_sigma"] = ppl_prior_sigma
if "ppl_prior_theta" in outputs:
results["ppl_prior_theta"] = ppl_prior_theta
if "ppl_pw_prior_theta" in outputs:
results["ppl_pw_prior_theta"] = ppl_pw_prior_theta
if "effects" in outputs:
results["effects"] = effects
if "phi_sums" in outputs:
results["phi_sums"] = phi_sums
if "ppl_prior_phi_total" in outputs:
results["ppl_prior_phi_total"] = ppl_prior_phi_total
if "ppl_prior_rho_a" in outputs:
results["ppl_prior_rho_a"] = ppl_prior_rho_a
if "ppl_prior_rho_b" in outputs:
results["ppl_prior_rho_b"] = ppl_prior_rho_b
if "ppl_prior_sigma_location" in outputs:
results["ppl_prior_sigma_location"] = ppl_prior_sigma_location
if "ppl_prior_sigma_log_scale" in outputs:
results["ppl_prior_sigma_log_scale"] = ppl_prior_sigma_log_scale
if "ppl_prior_sigma_scale" in outputs:
results["ppl_prior_sigma_scale"] = ppl_prior_sigma_scale
if "ppl_prior_sigma_standard_logpdf" in outputs:
results["ppl_prior_sigma_standard_logpdf"] = ppl_prior_sigma_standard_logpdf
if "value" in outputs:
results["value"] = value
return results
def prepare_data(area: Any, car_rate_area_area: ArrayLike, car_rate_area_comp_size: ArrayLike, car_rate_area_comp_start: ArrayLike, car_rate_area_inv_scale: ArrayLike, car_rate_area_is_struct: ArrayLike, car_rate_area_node1: ArrayLike, car_rate_area_node2: ArrayLike, car_rate_area_nodes: Any, car_rate_area_struct_pos: ArrayLike, cases: ArrayLike, log_expected: 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)`.
"""
area = np.asarray(area, dtype=object)
car_rate_area_area = np.asarray(car_rate_area_area, dtype=np.int64)
car_rate_area_comp_size = np.asarray(car_rate_area_comp_size, dtype=np.int64)
car_rate_area_comp_start = np.asarray(car_rate_area_comp_start, dtype=np.int64)
car_rate_area_inv_scale = np.asarray(car_rate_area_inv_scale, dtype=np.float64)
car_rate_area_is_struct = np.asarray(car_rate_area_is_struct, dtype=np.float64)
car_rate_area_node1 = np.asarray(car_rate_area_node1, dtype=np.int64)
car_rate_area_node2 = np.asarray(car_rate_area_node2, dtype=np.int64)
car_rate_area_nodes = np.asarray(car_rate_area_nodes, dtype=object)
car_rate_area_struct_pos = np.asarray(car_rate_area_struct_pos, dtype=np.int64)
cases = np.asarray(cases, dtype=np.int64)
log_expected = np.asarray(log_expected, dtype=np.float64)
rkppl_index_1 = np.asarray(car_rate_area_comp_start + car_rate_area_comp_size, dtype=np.int64)
car_rate_area_S = np.sum(car_rate_area_comp_size)
ppl_axis1_car_rate_area_theta = np.shape(car_rate_area_inv_scale)[0]
ppl_last_car_rate_area_theta = 3 + ppl_axis1_car_rate_area_theta
ppl_first_car_rate_area_phi = ppl_last_car_rate_area_theta + 1
ppl_last_car_rate_area_phi = ppl_first_car_rate_area_phi + (car_rate_area_S - 1)
car_rate_area_phi_sums_scale = 0.001 * car_rate_area_comp_size
ppl_yf_cases_resp = np.asarray(cases, dtype=np.float64)
ppl_lfact_cases_resp = np.sum(ssp.gammaln(ppl_yf_cases_resp + 1.0))
if len(car_rate_area_node2) == len(car_rate_area_node1):
value = car_rate_area_node2
else:
raise ValueError("node1 and node2 must list the same number of edges")
ppl_prior_car_rate_area_phi_checked_node2 = value
return {"ppl_last_car_rate_area_theta": StaticInt(ppl_last_car_rate_area_theta), "ppl_first_car_rate_area_phi": StaticInt(ppl_first_car_rate_area_phi), "ppl_last_car_rate_area_phi": StaticInt(ppl_last_car_rate_area_phi), "_rkppl_index_1": np.asarray(rkppl_index_1, dtype=np.int64), "car_rate_area_comp_start": np.asarray(car_rate_area_comp_start, dtype=np.int64), "car_rate_area_struct_pos": np.asarray(car_rate_area_struct_pos, dtype=np.int64), "car_rate_area_inv_scale": np.asarray(car_rate_area_inv_scale, dtype=np.float64), "car_rate_area_is_struct": np.asarray(car_rate_area_is_struct, dtype=np.float64), "car_rate_area_area": np.asarray(car_rate_area_area, dtype=np.int64), "log_expected": np.asarray(log_expected, dtype=np.float64), "_ppl_yf_cases_resp": np.asarray(ppl_yf_cases_resp, dtype=np.float64), "_ppl_lfact_cases_resp": ppl_lfact_cases_resp, "car_rate_area_phi_sums_scale": np.asarray(car_rate_area_phi_sums_scale, dtype=np.float64), "car_rate_area_node1": np.asarray(car_rate_area_node1, dtype=np.int64), "ppl_prior_car_rate_area_phi_checked_node2": np.asarray(ppl_prior_car_rate_area_phi_checked_node2, dtype=np.int64), "ppl_axis1_car_rate_area_theta": StaticInt(ppl_axis1_car_rate_area_theta), "car_rate_area_S": StaticInt(car_rate_area_S)}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
ppl_last_car_rate_area_theta = prepared["ppl_last_car_rate_area_theta"]
ppl_first_car_rate_area_phi = prepared["ppl_first_car_rate_area_phi"]
ppl_last_car_rate_area_phi = prepared["ppl_last_car_rate_area_phi"]
_rkppl_index_1 = prepared["_rkppl_index_1"]
car_rate_area_comp_start = prepared["car_rate_area_comp_start"]
car_rate_area_struct_pos = prepared["car_rate_area_struct_pos"]
car_rate_area_inv_scale = prepared["car_rate_area_inv_scale"]
car_rate_area_is_struct = prepared["car_rate_area_is_struct"]
car_rate_area_area = prepared["car_rate_area_area"]
log_expected = prepared["log_expected"]
_ppl_yf_cases_resp = prepared["_ppl_yf_cases_resp"]
_ppl_lfact_cases_resp = prepared["_ppl_lfact_cases_resp"]
car_rate_area_phi_sums_scale = prepared["car_rate_area_phi_sums_scale"]
car_rate_area_node1 = prepared["car_rate_area_node1"]
ppl_prior_car_rate_area_phi_checked_node2 = prepared["ppl_prior_car_rate_area_phi_checked_node2"]
ppl_axis1_car_rate_area_theta = prepared["ppl_axis1_car_rate_area_theta"]
car_rate_area_S = prepared["car_rate_area_S"]
unconstrained = jnp.asarray(unconstrained)
_rkppl_index_1 = jnp.asarray(_rkppl_index_1)
car_rate_area_comp_start = jnp.asarray(car_rate_area_comp_start)
car_rate_area_struct_pos = jnp.asarray(car_rate_area_struct_pos)
car_rate_area_inv_scale = jnp.asarray(car_rate_area_inv_scale)
car_rate_area_is_struct = jnp.asarray(car_rate_area_is_struct)
car_rate_area_area = jnp.asarray(car_rate_area_area)
log_expected = jnp.asarray(log_expected)
_ppl_yf_cases_resp = jnp.asarray(_ppl_yf_cases_resp)
car_rate_area_phi_sums_scale = jnp.asarray(car_rate_area_phi_sums_scale)
car_rate_area_node1 = jnp.asarray(car_rate_area_node1)
ppl_prior_car_rate_area_phi_checked_node2 = jnp.asarray(ppl_prior_car_rate_area_phi_checked_node2)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
ppl_fl_car_rate_area_sigma = unconstrained[0]
car_rate_area_sigma = jnp.exp(ppl_fl_car_rate_area_sigma)
u_argument = unconstrained[1]
constrain_2 = 1 / (1 + jnp.exp(-u_argument))
rate_Intercept = unconstrained[2]
car_rate_area_theta = unconstrained[3:ppl_last_car_rate_area_theta]
car_rate_area_phi = unconstrained[ppl_first_car_rate_area_phi - 1:ppl_last_car_rate_area_phi]
if _entry in ("log_density", "log_prior", "log_likelihood"):
car_rate_area = brm_car_bym2(
area=(car_rate_area_area if _entry in ("log_density", "log_likelihood") else None),
comp_start=(car_rate_area_comp_start if _entry in ("log_density", "log_prior") else None),
inv_scale=(car_rate_area_inv_scale if _entry in ("log_density", "log_likelihood") else None),
is_struct=(car_rate_area_is_struct if _entry in ("log_density", "log_likelihood") else None),
node1=(car_rate_area_node1 if _entry in ("log_density", "log_prior") else None),
phi=(car_rate_area_phi if _entry in ("log_density", "log_prior", "log_likelihood") else None),
ppl_prior_phi_checked_node2=(ppl_prior_car_rate_area_phi_checked_node2 if _entry in ("log_density", "log_prior") else None),
rho=(constrain_2 if _entry in ("log_density", "log_prior", "log_likelihood") else None),
rho_u=(u_argument if _entry in ("log_density", "log_prior", "log_likelihood") else None),
rkppl_index_1=(_rkppl_index_1 if _entry in ("log_density", "log_prior") else None),
sigma=(car_rate_area_sigma if _entry in ("log_density", "log_prior", "log_likelihood") else None),
struct_pos=(car_rate_area_struct_pos if _entry in ("log_density", "log_likelihood") else None),
theta=(car_rate_area_theta if _entry in ("log_density", "log_prior", "log_likelihood") else None),
outputs=tuple(
name for name, needed in (
("ppl_prior_phi", ("log_density", "log_prior")),
("ppl_prior_rho", ("log_density", "log_prior")),
("ppl_prior_sigma", ("log_density", "log_prior")),
("ppl_prior_theta", ("log_density", "log_prior")),
("ppl_pw_prior_theta", ("log_density", "log_prior")),
("effects", ("log_density", "log_likelihood")),
("phi_sums", ("log_density", "log_prior")),
("ppl_prior_phi_total", ("log_density", "log_prior")),
("ppl_prior_rho_a", ("log_density", "log_prior")),
("ppl_prior_rho_b", ("log_density", "log_prior")),
("ppl_prior_sigma_location", ("log_density", "log_prior")),
("ppl_prior_sigma_log_scale", ("log_density", "log_prior")),
("ppl_prior_sigma_scale", ("log_density", "log_prior")),
("ppl_prior_sigma_standard_logpdf", ("log_density", "log_prior")),
("value", ("log_density", "log_likelihood")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_likelihood"):
log_rate = rate_Intercept + log_expected + car_rate_area["value"]
ppl_lik_cases_resp = jnp.vdot(_ppl_yf_cases_resp, log_rate) - jnp.sum(jnp.exp(log_rate)) - _ppl_lfact_cases_resp
if _entry in ("log_density", "log_prior"):
ppl_prior_rate_Intercept_log_scale = np.log(1.0)
ppl_prior_rate_Intercept_standardized = (rate_Intercept - 0.0) / jnp.where((rate_Intercept == 0.0 if 1.0 == 0 else False), 1.0, 1.0)
ppl_prior_rate_Intercept_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_rate_Intercept_standardized ** 2
logpdf = ppl_prior_rate_Intercept_standard_logpdf - jnp.where((rate_Intercept != 0.0 if 1.0 == 0 else False), 0.0, ppl_prior_rate_Intercept_log_scale)
def ppl_pw_factor_car_rate_area_phi_sums_cell(car_rate_area_phi_sums, car_rate_area_phi_sums_scale_2):
scale_binding = 1.0 * car_rate_area_phi_sums_scale_2
x_argument = 1.0 * car_rate_area_phi_sums
log_scale = jnp.log(scale_binding)
standardized = (x_argument - 0.0) / jnp.where(jnp.logical_and(scale_binding == 0, x_argument == 0.0), 1.0, scale_binding)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf_2 = standard_logpdf - jnp.where(jnp.logical_and(scale_binding == 0, x_argument != 0.0), 0.0, log_scale)
return logpdf_2
ppl_pw_factor_car_rate_area_phi_sums = (jnp.zeros(car_rate_area["phi_sums"].shape[:1], dtype=jnp.float64) if 0 in car_rate_area["phi_sums"].shape[:1] and car_rate_area_phi_sums_scale.shape[:1] == car_rate_area["phi_sums"].shape[:1] else jax.vmap(ppl_pw_factor_car_rate_area_phi_sums_cell, in_axes=(0, 0))(car_rate_area["phi_sums"], car_rate_area_phi_sums_scale))
ppl_factor_car_rate_area_phi_sums = jnp.sum(ppl_pw_factor_car_rate_area_phi_sums)
prior = car_rate_area["ppl_prior_sigma"] + car_rate_area["ppl_prior_rho"] + logpdf + ppl_factor_car_rate_area_phi_sums + car_rate_area["ppl_prior_theta"] + car_rate_area["ppl_prior_phi"]
if _entry in ("log_density", "log_jacobian"):
u_argument_2 = unconstrained[1]
logjac = -jax.nn.softplus(-u_argument_2) - jax.nn.softplus(u_argument_2)
log_jacobian_2 = unconstrained[0] + logjac
if _entry in ("log_density",):
posterior = prior + ppl_lik_cases_resp + log_jacobian_2
if not (unconstrained.size == ppl_last_car_rate_area_phi):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
if _entry == "log_density":
return jnp.asarray(posterior, dtype=jnp.float64)
if _entry == "log_prior":
return jnp.asarray(prior, dtype=jnp.float64)
if _entry == "log_likelihood":
return jnp.asarray(ppl_lik_cases_resp, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(log_jacobian_2, dtype=jnp.float64)
if _entry == "constrain":
return {"car_rate_area": {"sigma": jnp.asarray(car_rate_area_sigma, dtype=jnp.float64), "rho": jnp.asarray(constrain_2, dtype=jnp.float64), "theta": jnp.asarray(car_rate_area_theta), "phi": jnp.asarray(car_rate_area_phi)}, "rate_Intercept": jnp.asarray(rate_Intercept, dtype=jnp.float64)}
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:
- `car_rate_area.sigma`
- `car_rate_area.rho`
- `rate_Intercept`
- `car_rate_area.theta`
- `car_rate_area.phi`
"""
return model("constrain", unconstrained, **prepared)
def dimension(prepared: dict) -> int:
"""The length of `unconstrained` for the data `prepared` (what `prepare_data` returned)."""
return int(prepared["ppl_last_car_rate_area_phi"])
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 {"car_rate_area.sigma": {"start": 0, "stop": 1, "transform": "floored", "dims": ()}, "car_rate_area.rho": {"start": 1, "stop": 2, "transform": "logistic", "dims": ()}, "rate_Intercept": {"start": 2, "stop": 3, "transform": "identity", "dims": ()}, "car_rate_area.theta": {"start": 3, "stop": int(prepared["ppl_last_car_rate_area_theta"]), "transform": "identity", "dims": (int(prepared["ppl_axis1_car_rate_area_theta"]),)}, "car_rate_area.phi": {"start": int(prepared["ppl_first_car_rate_area_phi"]) - 1, "stop": int(prepared["ppl_last_car_rate_area_phi"]), "transform": "identity", "dims": (int(prepared["car_rate_area_S"]),)}}List each undirected edge once. nodes=all_areas can preserve unobserved areas and islands. An island has an independent effect under BYM2 and zero spatial effect under ICAR. Replay keeps the fitted graph. Read rate directly: the declared log link already maps the predictor onto the count scale.
Smooth surfaces and channels
HSGP uses a squared-exponential covariance, smoother than the Matérn field below. iso=true shares a length across axes; iso=false gives each axis its own. by=channel allocates weights per channel, and cor=Omega correlates matching weights between channels.
Correlated channel surfaces
panes: brm|stanblocks|rkppl|stan|jax:3model = (@brm begin
mu ~ 0 + hsgp(east, north; k=(6, 6),
domain=((-25., 125.), (-25., 125.)), by=channel, cor=Omega)
y ~ Normal(mu, sigma)
Omega ~ LKJCholesky(2, 2)
sigma ~ Exponential(0.5)
sd(mu, hsgp(east, north)) ~ Exponential(1)
length_scale(mu, hsgp(east, north)) ~ truncated(LogNormal(log(25), 0.5);
lower=length_scale_floor, upper=300)
end)((; east=[10., 35., 70., 90., 15., 75.], north=[20., 80., 30., 70., 25., 65.],
channel=["a", "a", "a", "a", "b", "b"], y=[0.3, 0.8, -0.2, 0.4, 0.2, 0.5]))SBBRMI with data keys = [:Omega_n, :PHI_hsgp_east_north_by_channel, :channel_idx, :east, :n_channel, :n_terms_hsgpw_east_north_channel, :north, :omega2_hsgp_east_north_by_channel, :rho_lower_hsgp_east_north_by_channel, :y]
configured submodels:
_sb_hsgp_by_levelcor_configured_1 = Base.merge(BayesianRegressionModels._sb_hsgp_by_levelcor, quote
rho_iso ~ (StanBlocks.builtin.conditioning)(StanBlocks.builtin.lognormal, rho_lower, 300, 3.2188758248682006, 0.5; lower = fmax(0.0, rho_lower), upper = 300.0)
sigma ~ (StanBlocks.builtin.restricted)(exponential, 1.0 ./ 1.0; lower = 0.0)
end)
emitted @slic body:
begin
zflat_hsgpw_east_north_channel ~ std_normal(; n = n_channel * n_terms_hsgpw_east_north_channel)
b_hsgpw_east_north_channel = (to_matrix(zflat_hsgpw_east_north_channel, n_terms_hsgpw_east_north_channel, n_channel))'
Omega::cholesky_factor_corr[Omega_n] ~ lkj_corr_cholesky(2.0)
hsgp_east_north_by_channel ~ _sb_hsgp_by_levelcor_configured_1(; PHI = PHI_hsgp_east_north_by_channel, omega2 = omega2_hsgp_east_north_by_channel, rho_lower = rho_lower_hsgp_east_north_by_channel, beta = b_hsgpw_east_north_channel, group_idx = channel_idx, L_level = Omega)
mu = hsgp_east_north_by_channel
sigma ~ exponential(1.0 ./ 0.5)
y ~ normal(mu, sigma)
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)
"""
The Hilbert-space basis of an HSGP term at the rows.
Returns `(PHI, omega2)`: `PHI` holds one column per basis function, the Laplacian
eigenfunctions on the term's interval evaluated at each row's axes, and `omega2`
the matching squared frequencies, which the spectral density reads.
"""
ReactiveKernels.@kernel(brm_hsgp_basis_graph(axis_1, axis_2, modes, settings) = begin
B = prod(modes)
center_1 = settings[3]
width_1 = settings[4]
center_2 = settings[5]
width_2 = settings[6]
modes_1 = ReactiveKernels.plate(1:B) do b
return div(b - 1, 1) % modes[1] + 1
end
frequency_1 = ReactiveKernels.plate(modes_1) do mode
return ((mode * pi) / (2width_1)) ^ 2
end
modes_2 = ReactiveKernels.plate(1:B) do b
return div(b - 1, modes[1]) % modes[2] + 1
end
frequency_2 = ReactiveKernels.plate(modes_2) do mode
return ((mode * pi) / (2width_2)) ^ 2
end
widths = (width_1, width_2)
centers = (center_1, center_2)
omega2 = hcat(frequency_1, frequency_2)
basis_rows = ReactiveKernels.plate(axis_1, axis_2) do x_1, x_2
values = ReactiveKernels.plate(1:B) do b
return (sin(sqrt(omega2[b, 1]) * ((x_1 - centers[1]) + widths[1])) / sqrt(widths[1])) * (sin(sqrt(omega2[b, 2]) * ((x_2 - centers[2]) + widths[2])) / sqrt(widths[2]))
end
return values
end
PHI = if isempty(basis_rows)
zeros(0, B)
else
stack(basis_rows; dims = 1)
end
return (PHI, omega2)
end)
"""
The weight of each HSGP basis function: the square root of the covariance's
spectral density at its frequency, for the marginal scale `sigma` and length
scale `rho`.
"""
ReactiveKernels.@kernel(brm_hsgp_spectral_scales(axis_1, axis_2, modes, settings, sigma, rho) = begin
(PHI, omega2) = brm_hsgp_basis_graph(axis_1, axis_2, modes, settings)
weights = ReactiveKernels.plate(axes(omega2, 1)) do b
return (sigma * (rho * sqrt(2pi)) ^ (2 / 2)) * exp(-0.25 * (rho ^ 2 * omega2[b, 1] + rho ^ 2 * omega2[b, 2]))
end
return weights
end)
"""
An HSGP term's value at each row: the basis `PHI` times the basis weights `scales`
times the standardized coefficients `z`, each row reading its group's weights.
"""
ReactiveKernels.@kernel(brm_hsgp_spectral_graph(axis_1, axis_2, modes, settings, scales, z, group_index) = begin
(PHI, omega2) = brm_hsgp_basis_graph(axis_1, axis_2, modes, settings)
scaled_z = z .* transpose(scales)
rows = scaled_z[group_index, :]
value = vec(sum(PHI .* rows; dims = 2))
return value
end)
"""
An HSGP term with 2 groups whose length scale and marginal scale may vary by group.
Draws the length scale(s) `rho` and marginal scale(s) `sigma` with their
priors (and their group-level effects, when they have predictors), and the
standardized basis coefficients `z ~ Normal(0, 1)`. Each basis function is weighted
by the square root of the covariance's spectral density (`spectral_scale`); the term at
each row is its basis times the weighted coefficients of its group.
"""
brm_grouped_hsgp(axis_1, axis_2, modes, settings, group_index, L_level) = begin
rho ~ truncated(LogNormal(log.(25), 0.5), hsgp_east_north_rho_floor, 300)
sigma ~ Exponential(1)
z[1:2, 1:prod(modes)] .~ Normal.(0, 1)
z_level = L_level * z
spectral_scale = brm_hsgp_spectral_scales(axis_1, axis_2, modes, settings, sigma, rho)
value = brm_hsgp_spectral_graph(axis_1, axis_2, modes, settings, spectral_scale, z_level, group_index)
return value
end
begin
hsgp_east_north_group_index = brm_prepared_indices(channel, ["a", "b"])
hsgp_east_north_modes = copy(hsgp_east_north_modes_fit)
hsgp_east_north_settings = copy(hsgp_east_north_settings_fit)
hsgp_east_north_rho_floor = max(if hsgp_east_north_modes[1] == 1
0.0
else
((4 * hsgp_east_north_settings[4]) / pi) * sqrt(log(100.0) / (hsgp_east_north_modes[1] ^ 2 - 1))
end, if hsgp_east_north_modes[2] == 1
0.0
else
((4 * hsgp_east_north_settings[6]) / pi) * sqrt(log(100.0) / (hsgp_east_north_modes[2] ^ 2 - 1))
end)
hsgp_east_north ~ brm_grouped_hsgp(east, north, hsgp_east_north_modes, hsgp_east_north_settings, hsgp_east_north_group_index, Omega)
mu = hsgp_east_north
Omega ~ LKJCholesky(2, 2)
sigma ~ Exponential(0.5)
y .~ Normal.(mu, sigma)
endfunctions {
real conditioning_lognormal_lpdf(
real y,
real lo,
int hi,
real args1,
real args2
) {
array[1] real rv;
rv[1] = negative_infinity();
if((lo >= hi)) {
reject("truncated: lower bound must be less than upper bound");
} else {
if((y >= lo)) {
if((y <= hi)) {
rv[1] = (
lognormal_lpdf(y | args1, args2) -
log_diff_exp(lognormal_lcdf_stable(hi, args1, args2), lognormal_lcdf_stable(lo, args1, args2))
);
}
}
}
return rv[1];
}
real lognormal_lcdf_stable(
int y,
real mu,
real sigma
) {
return ((y <= 0) ? negative_infinity() : (is_inf(y) ? 0.0 : normal_lcdf_stable(log(y), mu, sigma)));
}
real normal_lcdf_stable(
real x,
real loc,
real scale
) {
return (is_inf(x) ? ((x < 0) ? negative_infinity() : 0.0) : ((((x - loc) / scale) < -35) ? std_normal_lcdf_tail(((x - loc) / scale)) : ((((x - loc) / scale) <= 0) ? (log(erfc(((-(x - loc)) / (scale * sqrt(2.0))))) - log(2.0)) : log1m((0.5 * erfc(((x - loc) / (scale * sqrt(2.0)))))))));
}
real std_normal_lcdf_tail(
real z
) {
return ((-0.5 * square(z)) + std_normal_scaled_lcdf_tail(z));
}
real std_normal_scaled_lcdf_tail(
real z
) {
real w = inv(square(z));
return (
((-log((-z))) - 0.9189385332046728) +
log1p((w * (-1 + (w * (3 + (w * (-15 + (w * (105 + (w * (-945 + (w * 10395))))))))))))
);
}
real lognormal_lcdf_stable(
real y,
real mu,
real sigma
) {
return ((y <= 0) ? negative_infinity() : (is_inf(y) ? 0.0 : normal_lcdf_stable(log(y), mu, sigma)));
}
vector brm_hsgp_sqrt_spd(
matrix omega2,
real sigma,
vector rho
) {
int m = dims(omega2)[1];
int d = dims(omega2)[2];
if (dims(rho)[1] != d) reject("brm_hsgp_sqrt_spd: dim mismatch — `rho` dim 1 (= ", dims(rho)[1], ") does not match `d` (= ", d, "), inferred from `omega2` dim 2. `d` sizes: `omega2` dim 2 (= ", dims(omega2)[2], "), `rho` dim 1 (= ", dims(rho)[1], ").");
vector[m] rv;
real scale = sigma;
for(axis in 1:d) {
scale *= sqrt((rho[axis] * 2.5066282746310002));
}
for(b in 1:m) {
real exponent = 0.0;
for(axis in 1:d) {
exponent += (rho[axis] * rho[axis] * omega2[b, axis]);
}
rv[b] = (scale * exp((-0.25 * exponent)));
}
return rv;
}
vector brm_hsgp_by_level_rows(
matrix PHI_by_level,
matrix W,
array[] int level_order,
array[] int level_sorted
) {
int n = dims(PHI_by_level)[1];
int m = dims(PHI_by_level)[2];
if (dims(level_order)[1] != n) reject("brm_hsgp_by_level_rows: dim mismatch — `level_order` dim 1 (= ", dims(level_order)[1], ") does not match `n` (= ", n, "), inferred from `PHI_by_level` dim 1. `n` sizes: `PHI_by_level` dim 1 (= ", dims(PHI_by_level)[1], "), `level_order` dim 1 (= ", dims(level_order)[1], "), `level_sorted` dim 1 (= ", dims(level_sorted)[1], ").");
if (dims(level_sorted)[1] != n) reject("brm_hsgp_by_level_rows: dim mismatch — `level_sorted` dim 1 (= ", dims(level_sorted)[1], ") does not match `n` (= ", n, "), inferred from `PHI_by_level` dim 1. `n` sizes: `PHI_by_level` dim 1 (= ", dims(PHI_by_level)[1], "), `level_order` dim 1 (= ", dims(level_order)[1], "), `level_sorted` dim 1 (= ", dims(level_sorted)[1], ").");
if (dims(W)[2] != m) reject("brm_hsgp_by_level_rows: dim mismatch — `W` dim 2 (= ", dims(W)[2], ") does not match `m` (= ", m, "), inferred from `PHI_by_level` dim 2. `m` sizes: `PHI_by_level` dim 2 (= ", dims(PHI_by_level)[2], "), `W` dim 2 (= ", dims(W)[2], ").");
vector[n] rv;
int first_row = 1;
while((first_row <= n)) {
int level = level_sorted[first_row];
int last_row = first_row;
while(((last_row < n) && (level_sorted[(last_row + 1)] == level))) {
last_row += 1;
}
rv[level_order[first_row:last_row]] = (PHI_by_level[first_row:last_row, :] * (W[level, :]'));
first_row = (last_row + 1);
}
return rv;
}
vector normal_lpdfs(
vector obs,
vector loc,
real scale
) {
return jbroadcasted_normal_lpdfs(obs, loc, scale);
}
vector jbroadcasted_normal_lpdfs(
vector x1,
vector x2,
real x3
) {
int n = dims(x1)[1];
vector[n] rv;
for(i in 1:n) {
rv[i] = normal_lpdfs(broadcasted_getindex(x1, i), broadcasted_getindex(x2, i), x3);
}
return rv;
}
real normal_lpdfs(
real args1,
real args2,
real args3
) {
return normal_lpdf(args1 | args2, args3);
}
real broadcasted_getindex(vector x, int i) {
return x[i];
}
vector normal_vector_rng(
int anontok__1,
vector a,
real b
) {
int n = anontok__1;
if((n == 0)) {
vector[n] rv;
return rv;
} else {
return to_vector(normal_rng(a, b));
}
}
}
data {
int n_channel;
int n_terms_hsgpw_east_north_channel;
int Omega_n;
int omega2_hsgp_east_north_by_channel_n;
int channel_idx_n;
array[channel_idx_n] int channel_idx;
int PHI_hsgp_east_north_by_channel_n;
int PHI_hsgp_east_north_by_channel_m;
matrix[PHI_hsgp_east_north_by_channel_m, PHI_hsgp_east_north_by_channel_n] PHI_hsgp_east_north_by_channel;
real rho_lower_hsgp_east_north_by_channel;
int omega2_hsgp_east_north_by_channel_m;
matrix[omega2_hsgp_east_north_by_channel_m, omega2_hsgp_east_north_by_channel_n] omega2_hsgp_east_north_by_channel;
int y_n;
vector[y_n] y;
}
transformed data {
int hsgp_east_north_by_channel_n_axes = omega2_hsgp_east_north_by_channel_n;
array[channel_idx_n] int hsgp_east_north_by_channel_level_order = sort_indices_asc(channel_idx);
matrix[channel_idx_n, PHI_hsgp_east_north_by_channel_n] hsgp_east_north_by_channel_PHI_by_level = PHI_hsgp_east_north_by_channel[hsgp_east_north_by_channel_level_order, :];
array[channel_idx_n] int hsgp_east_north_by_channel_level_sorted = channel_idx[hsgp_east_north_by_channel_level_order];
}
parameters {
vector[(n_channel * n_terms_hsgpw_east_north_channel)] zflat_hsgpw_east_north_channel;
cholesky_factor_corr[Omega_n] Omega;
real<lower=fmax(0.0, rho_lower_hsgp_east_north_by_channel), upper=300.0> hsgp_east_north_by_channel_rho_iso;
real<lower=0.0> hsgp_east_north_by_channel_sigma;
real<lower=0.0> sigma;
}
transformed parameters {
matrix[n_channel, n_terms_hsgpw_east_north_channel] b_hsgpw_east_north_channel = (to_matrix(zflat_hsgpw_east_north_channel, n_terms_hsgpw_east_north_channel, n_channel)');
matrix[Omega_n, n_terms_hsgpw_east_north_channel] hsgp_east_north_by_channel_beta_level = (Omega * b_hsgpw_east_north_channel);
vector[hsgp_east_north_by_channel_n_axes] hsgp_east_north_by_channel_rho = rep_vector(hsgp_east_north_by_channel_rho_iso, hsgp_east_north_by_channel_n_axes);
vector[omega2_hsgp_east_north_by_channel_m] hsgp_east_north_by_channel_sqrt_spd = brm_hsgp_sqrt_spd(
omega2_hsgp_east_north_by_channel,
hsgp_east_north_by_channel_sigma,
hsgp_east_north_by_channel_rho
);
matrix[Omega_n, omega2_hsgp_east_north_by_channel_m] hsgp_east_north_by_channel_beta_scaled = diag_post_multiply(hsgp_east_north_by_channel_beta_level, hsgp_east_north_by_channel_sqrt_spd);
vector[channel_idx_n] hsgp_east_north_by_channel = brm_hsgp_by_level_rows(
hsgp_east_north_by_channel_PHI_by_level,
hsgp_east_north_by_channel_beta_scaled,
hsgp_east_north_by_channel_level_order,
hsgp_east_north_by_channel_level_sorted
);
vector[channel_idx_n] mu = hsgp_east_north_by_channel;
}
model {
zflat_hsgpw_east_north_channel ~ std_normal();
Omega ~ lkj_corr_cholesky(2.0);
hsgp_east_north_by_channel_rho_iso ~ conditioning_lognormal(rho_lower_hsgp_east_north_by_channel, 300, 3.2188758248682006, 0.5);
hsgp_east_north_by_channel_sigma ~ exponential((1.0 ./ 1.0));
sigma ~ exponential((1.0 ./ 0.5));
y ~ normal(mu, sigma);
}
generated quantities {
vector[y_n] y_likelihood = normal_lpdfs(y, mu, sigma);
vector[y_n] y_gen = normal_vector_rng(y_n, mu, sigma);
}using ReactiveKernels, ReactiveKernelsPPL
rk = RKBRMI(model)
source = jax_source(rk.model, rk_bound_plan(rk))
write("model.py", source)
inputs = rk_bound_data(rk, source) # exactly the inputs prepare_data readsimport jax
import model as m
prepared = m.prepare_data(**inputs)
lp = m.log_density(u, **prepared) # u: unconstrained, length m.dimension(prepared)
lp = jax.jit(m.log_density)(u, **prepared) # one compiled function for every dataset of these shapes"""Generated by ReactiveKernelsPPL.jax_source from a built @rkppl program; do not edit.
Data: channel, east, hsgp_east_north_modes_fit, hsgp_east_north_settings_fit, north, y.
Model documentation:
- `hsgp_east_north`: An HSGP term with 2 groups whose length scale and marginal scale may vary by group.
Draws the length scale(s) `rho` and marginal scale(s) `sigma` with their
priors (and their group-level effects, when they have predictors), and the
standardized basis coefficients `z ~ Normal(0, 1)`. Each basis function is weighted
by the square root of the covariance's spectral density (`spectral_scale`); the term at
each row is its basis times the weighted coefficients of its group.
"""
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 = {"channel": {"dtype": "object", "ndim": 1, "ragged": False}, "east": {"dtype": "float64", "ndim": 1, "ragged": False}, "hsgp_east_north_modes_fit": {"dtype": "int64", "ndim": 1, "ragged": False}, "hsgp_east_north_settings_fit": {"dtype": "float64", "ndim": 1, "ragged": False}, "north": {"dtype": "float64", "ndim": 1, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}}
INPUTS = ("unconstrained", "hsgp_east_north_rho_floor", "ppl_last_hsgp_east_north_z", "ppl_axis2_hsgp_east_north_z", "_ppl_first_Omega", "plate_argument", "hsgp_east_north_spectral_scale_omega2", "hsgp_east_north_group_index", "hsgp_east_north_spectral_scale_PHI", "y", "ppl_prior_hsgp_east_north_rho_logcdf")
PREPARED = {"hsgp_east_north_rho_floor": {"dtype": "float64", "ndim": 0, "ragged": False}, "ppl_last_hsgp_east_north_z": {"dtype": "int64", "ndim": 0, "ragged": False}, "ppl_axis2_hsgp_east_north_z": {"dtype": "int64", "ndim": 0, "ragged": False}, "_ppl_first_Omega": {"dtype": "int64", "ndim": 0, "ragged": False}, "plate_argument": {"dtype": "int64", "ndim": 1, "ragged": False}, "hsgp_east_north_spectral_scale_omega2": {"dtype": "float64", "ndim": 2, "ragged": False}, "hsgp_east_north_group_index": {"dtype": "int64", "ndim": 1, "ragged": False}, "hsgp_east_north_spectral_scale_PHI": {"dtype": "float64", "ndim": 2, "ragged": False}, "y": {"dtype": "float64", "ndim": 1, "ragged": False}, "ppl_prior_hsgp_east_north_rho_logcdf": {"dtype": "float64", "ndim": 0, "ragged": False}}
UNTRANSLATED = {}
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 _standardized_np(location, scale, log_scale, x):
if scale == 0 and x == location:
value = 1.0
else:
value = scale
standardized = (x - location) / value
return standardized
def _rk_logerfc_np(x):
# log(erfc(x)) without overflow or cancellation (SpecialFunctions.logerfc):
# log(erfcx(x)) - x^2 for x > 0.
positive = x > 0
xp = np.where(positive, x, 1.0)
xn = np.where(positive, 0.0, x)
return np.where(positive, np.log(ssp.erfcx(xp)) - xp * xp, np.log(ssp.erfc(xn)))
def _normal_logcdf_np(z):
result = 0.0
if z < 0:
result = _rk_logerfc_np(-z / np.sqrt(2.0)) - np.log(2.0)
else:
result = np.log1p(-0.5 * ssp.erfc(z / np.sqrt(2.0)))
return result
def _standard_logcdf_np(standard_z):
value = _normal_logcdf_np(standard_z)
standard_logcdf = value
return standard_logcdf
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))
@jax.custom_jvp
def _rk_affine_logistic(x1, x2, x3):
return x1 + (x2 - x1) / (1 + jnp.exp(-x3))
def _affine_logistic_partials_1(x1, x2, x3):
return (x1 + (x2 - x1) / (1 + jnp.exp(-x3)), jnp.exp(-jax.nn.softplus(x3)))
def _affine_logistic_partials_2(x1, x2, x3):
return (x1 + (x2 - x1) / (1 + jnp.exp(-x3)), jnp.exp(-jax.nn.softplus(-x3)))
def _affine_logistic_partials_3(x1, x2, x3):
return (x1 + (x2 - x1) / (1 + jnp.exp(-x3)), jnp.exp(-jax.nn.softplus(x3)), jnp.exp(-jax.nn.softplus(-x3)))
def _affine_logistic_partials_4(x1, x2, x3):
return (x1 + (x2 - x1) / (1 + jnp.exp(-x3)), (x2 - x1) * jnp.exp(-jax.nn.softplus(-x3)) * jnp.exp(-jax.nn.softplus(x3)), jnp.exp(-jax.nn.softplus(x3)), jnp.exp(-jax.nn.softplus(-x3)))
def _affine_logistic_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 = _rk_affine_logistic(*primals)
return value, jnp.zeros_like(value)
if mask == 1:
values = _affine_logistic_partials_1(*primals)
return values[0], values[1] * tangents[0]
if mask == 2:
values = _affine_logistic_partials_2(*primals)
return values[0], values[1] * tangents[1]
if mask == 3:
values = _affine_logistic_partials_3(*primals)
return values[0], values[1] * tangents[0] + values[2] * tangents[1]
if mask == 4:
values = _affine_logistic_partials_4(*primals)
return values[0], values[1] * tangents[2]
if mask == 5:
values = _affine_logistic_partials_4(*primals)
return values[0], values[2] * tangents[0] + values[1] * tangents[2]
if mask == 6:
values = _affine_logistic_partials_4(*primals)
return values[0], values[3] * tangents[1] + values[1] * tangents[2]
if mask == 7:
values = _affine_logistic_partials_4(*primals)
return values[0], values[2] * tangents[0] + values[3] * tangents[1] + values[1] * tangents[2]
_rk_affine_logistic.defjvp(_affine_logistic_jvp, symbolic_zeros=True)
def _ppl_lkj_lower(z: ArrayLike, diagonal: ArrayLike, K: ArrayLike, P: ArrayLike) -> jax.Array:
"""Compute `_ppl_lkj_lower` from its authored source."""
out = jnp.zeros((K, K), dtype=jnp.float64)
out_2 = out.at[0, 0].set(1.0)
tuple_ = (1, 2, 1.0)
i = tuple_[0]
j = tuple_[1]
w = tuple_[2]
def loop_body(p, carry):
(i_2, j_2, out_3, w_2) = carry
out_4 = out_3.at[j_2 - 1, i_2 - 1].set(z[p - 1] * w_2)
w_3 = w_2 * jnp.sqrt(1 - z[p - 1] ** 2)
def then_arm():
i_3 = i_2 + 1
return (None, jnp.asarray(i_3, dtype=jnp.int64), jnp.asarray(j_2, dtype=jnp.int64), out_4, jnp.asarray(w_3, dtype=jnp.float64))
def else_arm():
out_5 = out_4.at[j_2 - 1, j_2 - 1].set(diagonal[j_2 - 1])
tuple__2 = (1, j_2 + 1, 1.0)
i_4 = tuple__2[0]
j_3 = tuple__2[1]
w_4 = tuple__2[2]
return (None, jnp.asarray(i_4, dtype=jnp.int64), jnp.asarray(j_3, dtype=jnp.int64), out_5, jnp.asarray(w_4, dtype=jnp.float64))
branch = jax.lax.cond(i_2 + 1 < j_2, then_arm, else_arm)
return (branch[1], branch[2], branch[3], branch[4])
carry_init = (jnp.asarray(i, dtype=jnp.int64), jnp.asarray(j, dtype=jnp.int64), out_2, jnp.asarray(w, dtype=jnp.float64))
loop_carry = jax.lax.fori_loop(1, P + 1, loop_body, carry_init) if 1 <= P else carry_init
return loop_carry[2]
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_logccdf = normal_logcdf
return standard_logccdf
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 _normal_logcdf_2(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_4(standard_z: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `function` from its kernel plan."""
normal_logcdf_2 = _normal_logcdf_2(-standard_z, active)
standard_logccdf = normal_logcdf_2
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 _function_5(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_6(standard_z: ArrayLike, active: ArrayLike) -> jax.Array:
"""Compute `function` from its kernel plan."""
normal_logcdf_2 = _normal_logcdf_2(standard_z, active)
standard_logcdf = normal_logcdf_2
return standard_logcdf
def _function_7(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_8(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 brm_grouped_hsgp_density(
ppl_last_z: ArrayLike,
ppl_prior_rho_logcdf: ArrayLike,
plate_argument: ArrayLike,
rho: ArrayLike,
rho_floor: ArrayLike,
sigma: ArrayLike,
unconstrained: ArrayLike,
value_omega2: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""An HSGP term with 2 groups whose length scale and marginal scale may vary by group.
Draws the length scale(s) `rho` and marginal scale(s) `sigma` with their
priors (and their group-level effects, when they have predictors), and the
standardized basis coefficients `z ~ Normal(0, 1)`. Each basis function is weighted
by the square root of the covariance's spectral density (`spectral_scale`); the term at
each row is its basis times the weighted coefficients of its group.
"""
results = {}
if any(name in outputs for name in ("ppl_arrflat_z", "ppl_prior_z", "ppl_pw_prior_z")):
ppl_arrflat_z = unconstrained[3:ppl_last_z]
if any(name in outputs for name in ("ppl_prior_rho", "ppl_prior_rho_logpdf", "rho_location")):
rho_location = jnp.log(25)
if any(name in outputs for name in ("spectral_scale",)):
def weights_cell(b, sigma_2, rho_2, omega2):
return_ = sigma_2 * (rho_2 * np.sqrt(2 * np.pi)) ** (2 / 2) * jnp.exp(-0.25 * (rho_2 ** 2 * omega2[b - 1, 0] + rho_2 ** 2 * omega2[b - 1, 1]))
return return_
spectral_scale = (jnp.zeros(plate_argument.shape[:1], dtype=jnp.float64) if 0 in plate_argument.shape[:1] else jax.vmap(weights_cell, in_axes=(0, None, None, None))(plate_argument, sigma, rho, value_omega2))
if any(name in outputs for name in ("ppl_prior_rho", "ppl_prior_rho_logpdf")):
ppl_prior_rho_logpdf_location = 1.0 * rho_location
ppl_prior_rho_logpdf_scale = 0.5
ppl_prior_rho_logpdf_log_scale = np.log(ppl_prior_rho_logpdf_scale)
ppl_prior_rho_logpdf_logpdf_log_x = jax.lax.cond(rho <= 0, lambda: -jnp.inf, lambda: jnp.log(rho))
ppl_prior_rho_logpdf_logpdf_jacobian = jnp.where(rho <= 0, 0.0, ppl_prior_rho_logpdf_logpdf_log_x)
ppl_prior_rho_logpdf_logpdf_logpdf_logpdf_z = (ppl_prior_rho_logpdf_logpdf_log_x - ppl_prior_rho_logpdf_location) / jnp.where((ppl_prior_rho_logpdf_logpdf_log_x == ppl_prior_rho_logpdf_location if ppl_prior_rho_logpdf_scale == 0 else False), 1.0, ppl_prior_rho_logpdf_scale)
ppl_prior_rho_logpdf_logpdf_logpdf_standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * ppl_prior_rho_logpdf_logpdf_logpdf_logpdf_z ** 2
ppl_prior_rho_logpdf_logpdf = ppl_prior_rho_logpdf_logpdf_logpdf_standard_logpdf - jnp.where((ppl_prior_rho_logpdf_logpdf_log_x != ppl_prior_rho_logpdf_location if ppl_prior_rho_logpdf_scale == 0 else False), 0.0, ppl_prior_rho_logpdf_log_scale)
ppl_prior_rho_logpdf = ppl_prior_rho_logpdf_logpdf - ppl_prior_rho_logpdf_logpdf_jacobian
if any(name in outputs for name in ("ppl_prior_rho",)):
def then_arm():
location = 1.0 * rho_location
x = 1.0 * rho_floor
log_scale = np.log(0.5)
logccdf_log_x = jax.lax.cond(x <= 0, lambda: -jnp.inf, lambda: jnp.log(x))
def else_arm():
function = _function(location, 0.5, log_scale, logccdf_log_x, jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not((logccdf_log_x == location if 0.5 == 0 else False))))
return function
logccdf_logccdf_z = jax.lax.cond((logccdf_log_x == location if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm)
def else_arm_3():
def else_arm_2():
function_2 = _function_2(logccdf_logccdf_z, jnp.logical_and(jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(logccdf_log_x == jnp.inf)), jnp.logical_not(logccdf_log_x == -jnp.inf)))
return function_2
return jax.lax.cond(logccdf_log_x == -jnp.inf, lambda: 0.0, else_arm_2)
location_2 = 1.0 * rho_location
log_scale_2 = np.log(0.5)
logccdf_log_x_2 = (-jnp.inf if 300.0 <= 0 else np.log(300.0))
def else_arm_4():
function_3 = _function_3(location_2, 0.5, log_scale_2, logccdf_log_x_2, jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not((logccdf_log_x_2 == location_2 if 0.5 == 0 else False))))
return function_3
logccdf_logccdf_z_2 = jax.lax.cond((logccdf_log_x_2 == location_2 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_4)
if logccdf_log_x_2 == jnp.inf:
value_2 = -jnp.inf
else:
if logccdf_log_x_2 == -jnp.inf:
value = 0.0
else:
function_4 = _function_4(logccdf_logccdf_z_2, ppl_prior_rho_logcdf > -np.log(2))
value = function_4
value_2 = value
def else_arm_12():
location_3 = 1.0 * rho_location
x_2 = 1.0 * rho_floor
log_scale_3 = np.log(0.5)
logccdf_log_x_3 = jax.lax.cond(x_2 <= 0, lambda: -jnp.inf, lambda: jnp.log(x_2))
def else_arm_5():
function_5 = _function(location_3, 0.5, log_scale_3, logccdf_log_x_3, jnp.logical_and(jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2)), jnp.logical_not((logccdf_log_x_3 == location_3 if 0.5 == 0 else False))))
return function_5
logccdf_logccdf_z_3 = jax.lax.cond((logccdf_log_x_3 == location_3 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_5)
def else_arm_7():
def else_arm_6():
function_2_2 = _function_2(logccdf_logccdf_z_3, jnp.logical_and(jnp.logical_and(jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2)), jnp.logical_not(logccdf_log_x_3 == jnp.inf)), jnp.logical_not(logccdf_log_x_3 == -jnp.inf)))
return function_2_2
return jax.lax.cond(logccdf_log_x_3 == -jnp.inf, lambda: 0.0, else_arm_6)
location_4 = 1.0 * rho_location
log_scale_4 = np.log(0.5)
logccdf_log_x_4 = (-jnp.inf if 300.0 <= 0 else np.log(300.0))
def else_arm_8():
function_3_2 = _function_3(location_4, 0.5, log_scale_4, logccdf_log_x_4, jnp.logical_and(jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2)), jnp.logical_not((logccdf_log_x_4 == location_4 if 0.5 == 0 else False))))
return function_3_2
logccdf_logccdf_z_4 = jax.lax.cond((logccdf_log_x_4 == location_4 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_8)
if logccdf_log_x_4 == jnp.inf:
value_4 = -jnp.inf
else:
if logccdf_log_x_4 == -jnp.inf:
value_3 = 0.0
else:
function_4_2 = _function_4(logccdf_logccdf_z_4, jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2)))
value_3 = function_4_2
value_4 = value_3
location_5 = 1.0 * rho_location
x_3 = 1.0 * rho_floor
log_scale_5 = np.log(0.5)
logccdf_log_x_5 = jax.lax.cond(x_3 <= 0, lambda: -jnp.inf, lambda: jnp.log(x_3))
def else_arm_9():
function_6 = _function(location_5, 0.5, log_scale_5, logccdf_log_x_5, jnp.logical_and(jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2)), jnp.logical_not((logccdf_log_x_5 == location_5 if 0.5 == 0 else False))))
return function_6
logccdf_logccdf_z_5 = jax.lax.cond((logccdf_log_x_5 == location_5 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_9)
def else_arm_11():
def else_arm_10():
function_2_3 = _function_2(logccdf_logccdf_z_5, jnp.logical_and(jnp.logical_and(jnp.logical_and(ppl_prior_rho_logcdf > -np.log(2), jnp.logical_not(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2)), jnp.logical_not(logccdf_log_x_5 == jnp.inf)), jnp.logical_not(logccdf_log_x_5 == -jnp.inf)))
return function_2_3
return jax.lax.cond(logccdf_log_x_5 == -jnp.inf, lambda: 0.0, else_arm_10)
return jax.lax.cond(logccdf_log_x_3 == jnp.inf, lambda: -jnp.inf, else_arm_7) + _rk_log1mexp(value_4 - jax.lax.cond(logccdf_log_x_5 == jnp.inf, lambda: -jnp.inf, else_arm_11))
return jax.lax.cond(jax.lax.cond(logccdf_log_x == jnp.inf, lambda: -jnp.inf, else_arm_3) == value_2, lambda: -jnp.inf, else_arm_12)
def else_arm_23():
location_6 = 1.0 * rho_location
log_scale_6 = np.log(0.5)
logcdf_log_x = (-jnp.inf if 300.0 <= 0 else np.log(300.0))
def else_arm_13():
function_5_2 = _function_5(location_6, 0.5, log_scale_6, logcdf_log_x, jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not((logcdf_log_x == location_6 if 0.5 == 0 else False))))
return function_5_2
logcdf_logcdf_z = jax.lax.cond((logcdf_log_x == location_6 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_13)
if logcdf_log_x == -jnp.inf:
value_6 = -jnp.inf
else:
if logcdf_log_x == jnp.inf:
value_5 = 0.0
else:
function_6_2 = _function_6(logcdf_logcdf_z, jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)))
value_5 = function_6_2
value_6 = value_5
location_7 = 1.0 * rho_location
x_4 = 1.0 * rho_floor
log_scale_7 = np.log(0.5)
logcdf_log_x_2 = jax.lax.cond(x_4 <= 0, lambda: -jnp.inf, lambda: jnp.log(x_4))
def else_arm_14():
function_7 = _function_7(location_7, 0.5, log_scale_7, logcdf_log_x_2, jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not((logcdf_log_x_2 == location_7 if 0.5 == 0 else False))))
return function_7
logcdf_logcdf_z_2 = jax.lax.cond((logcdf_log_x_2 == location_7 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_14)
def else_arm_16():
def else_arm_15():
function_8 = _function_8(logcdf_logcdf_z_2, jnp.logical_and(jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(logcdf_log_x_2 == -jnp.inf)), jnp.logical_not(logcdf_log_x_2 == jnp.inf)))
return function_8
return jax.lax.cond(logcdf_log_x_2 == jnp.inf, lambda: 0.0, else_arm_15)
def else_arm_22():
location_8 = 1.0 * rho_location
log_scale_8 = np.log(0.5)
logcdf_log_x_3 = (-jnp.inf if 300.0 <= 0 else np.log(300.0))
def else_arm_17():
function_5_3 = _function_5(location_8, 0.5, log_scale_8, logcdf_log_x_3, jnp.logical_and(jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16))), jnp.logical_not((logcdf_log_x_3 == location_8 if 0.5 == 0 else False))))
return function_5_3
logcdf_logcdf_z_3 = jax.lax.cond((logcdf_log_x_3 == location_8 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_17)
if logcdf_log_x_3 == -jnp.inf:
value_8 = -jnp.inf
else:
if logcdf_log_x_3 == jnp.inf:
value_7 = 0.0
else:
function_6_3 = _function_6(logcdf_logcdf_z_3, jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16))))
value_7 = function_6_3
value_8 = value_7
location_9 = 1.0 * rho_location
x_5 = 1.0 * rho_floor
log_scale_9 = np.log(0.5)
logcdf_log_x_4 = jax.lax.cond(x_5 <= 0, lambda: -jnp.inf, lambda: jnp.log(x_5))
def else_arm_18():
function_7_2 = _function_7(location_9, 0.5, log_scale_9, logcdf_log_x_4, jnp.logical_and(jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16))), jnp.logical_not((logcdf_log_x_4 == location_9 if 0.5 == 0 else False))))
return function_7_2
logcdf_logcdf_z_4 = jax.lax.cond((logcdf_log_x_4 == location_9 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_18)
def else_arm_20():
def else_arm_19():
function_8_2 = _function_8(logcdf_logcdf_z_4, jnp.logical_and(jnp.logical_and(jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16))), jnp.logical_not(logcdf_log_x_4 == -jnp.inf)), jnp.logical_not(logcdf_log_x_4 == jnp.inf)))
return function_8_2
return jax.lax.cond(logcdf_log_x_4 == jnp.inf, lambda: 0.0, else_arm_19)
location_10 = 1.0 * rho_location
log_scale_10 = np.log(0.5)
logcdf_log_x_5 = (-jnp.inf if 300.0 <= 0 else np.log(300.0))
def else_arm_21():
function_5_4 = _function_5(location_10, 0.5, log_scale_10, logcdf_log_x_5, jnp.logical_and(jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16))), jnp.logical_not((logcdf_log_x_5 == location_10 if 0.5 == 0 else False))))
return function_5_4
logcdf_logcdf_z_5 = jax.lax.cond((logcdf_log_x_5 == location_10 if 0.5 == 0 else False), lambda: 1.0 / 0.5, else_arm_21)
if logcdf_log_x_5 == -jnp.inf:
value_10 = -jnp.inf
else:
if logcdf_log_x_5 == jnp.inf:
value_9 = 0.0
else:
function_6_4 = _function_6(logcdf_logcdf_z_5, jnp.logical_and(jnp.logical_not(ppl_prior_rho_logcdf > -np.log(2)), jnp.logical_not(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16))))
value_9 = function_6_4
value_10 = value_9
return value_8 + _rk_log1mexp(jax.lax.cond(logcdf_log_x_4 == -jnp.inf, lambda: -jnp.inf, else_arm_20) - value_10)
return jax.lax.cond(value_6 == jax.lax.cond(logcdf_log_x_2 == -jnp.inf, lambda: -jnp.inf, else_arm_16), lambda: -jnp.inf, else_arm_22)
ppl_prior_rho = ppl_prior_rho_logpdf + -jax.lax.cond(ppl_prior_rho_logcdf > -np.log(2), then_arm, else_arm_23)
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_log_scale", "ppl_prior_sigma_scale")):
ppl_prior_sigma_scale = 1.0
if any(name in outputs for name in ("ppl_prior_sigma", "ppl_prior_sigma_log_scale")):
ppl_prior_sigma_log_scale = np.log(ppl_prior_sigma_scale)
if any(name in outputs for name in ("ppl_prior_sigma",)):
ppl_prior_sigma = jax.lax.cond(sigma < 0, lambda: -jnp.inf, lambda: -ppl_prior_sigma_log_scale - sigma / ppl_prior_sigma_scale)
if any(name in outputs for name in ("ppl_prior_z", "ppl_pw_prior_z")):
def ppl_pw_prior_z_cell(z):
log_scale_11 = np.log(1.0)
standardized = (z - 0.0) / jnp.where((z == 0.0 if 1.0 == 0 else False), 1.0, 1.0)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
logpdf = standard_logpdf - jnp.where((z != 0.0 if 1.0 == 0 else False), 0.0, log_scale_11)
return logpdf
ppl_pw_prior_z = (jnp.zeros(ppl_arrflat_z.shape[:1], dtype=jnp.float64) if 0 in ppl_arrflat_z.shape[:1] else jax.vmap(ppl_pw_prior_z_cell, in_axes=(0,))(ppl_arrflat_z))
if any(name in outputs for name in ("ppl_prior_z",)):
ppl_prior_z = jnp.sum(ppl_pw_prior_z)
if "ppl_arrflat_z" in outputs:
results["ppl_arrflat_z"] = ppl_arrflat_z
if "ppl_prior_rho" in outputs:
results["ppl_prior_rho"] = ppl_prior_rho
if "ppl_prior_rho_logpdf" in outputs:
results["ppl_prior_rho_logpdf"] = ppl_prior_rho_logpdf
if "ppl_prior_sigma" in outputs:
results["ppl_prior_sigma"] = ppl_prior_sigma
if "ppl_prior_z" in outputs:
results["ppl_prior_z"] = ppl_prior_z
if "ppl_pw_prior_z" in outputs:
results["ppl_pw_prior_z"] = ppl_pw_prior_z
if "ppl_prior_sigma_log_scale" in outputs:
results["ppl_prior_sigma_log_scale"] = ppl_prior_sigma_log_scale
if "ppl_prior_sigma_scale" in outputs:
results["ppl_prior_sigma_scale"] = ppl_prior_sigma_scale
if "rho_location" in outputs:
results["rho_location"] = rho_location
if "spectral_scale" in outputs:
results["spectral_scale"] = spectral_scale
return results
def brm_grouped_hsgp(
L_level: ArrayLike,
group_index: ArrayLike,
spectral_scale: ArrayLike,
value_PHI: ArrayLike,
z: ArrayLike,
*,
outputs: tuple[str, ...],
) -> dict:
"""An HSGP term with 2 groups whose length scale and marginal scale may vary by group.
Draws the length scale(s) `rho` and marginal scale(s) `sigma` with their
priors (and their group-level effects, when they have predictors), and the
standardized basis coefficients `z ~ Normal(0, 1)`. Each basis function is weighted
by the square root of the covariance's spectral density (`spectral_scale`); the term at
each row is its basis times the weighted coefficients of its group.
"""
results = {}
if any(name in outputs for name in ("value", "value_rows")):
z_level = L_level @ z
value_scaled_z = z_level * spectral_scale
value_rows = value_scaled_z[group_index - 1, :]
if any(name in outputs for name in ("value",)):
value = jnp.ravel(jnp.sum(value_PHI * value_rows, axis=2 - 1, keepdims=True), order="F")
if "value" in outputs:
results["value"] = value
if "value_rows" in outputs:
results["value_rows"] = value_rows
return results
def prepare_data(channel: Any, east: ArrayLike, hsgp_east_north_modes_fit: ArrayLike, hsgp_east_north_settings_fit: ArrayLike, north: 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)`.
"""
channel = np.asarray(channel, dtype=object)
east = np.asarray(east, dtype=np.float64)
hsgp_east_north_modes_fit = np.asarray(hsgp_east_north_modes_fit, dtype=np.int64)
hsgp_east_north_settings_fit = np.asarray(hsgp_east_north_settings_fit, dtype=np.float64)
north = np.asarray(north, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
value = _indices_np(channel, np.stack(["a", "b"]))
hsgp_east_north_group_index = np.asarray(value, dtype=np.int64)
hsgp_east_north_modes = np.asarray(hsgp_east_north_modes_fit.copy(), dtype=np.int64)
hsgp_east_north_settings = np.asarray(hsgp_east_north_settings_fit.copy(), dtype=np.float64)
if hsgp_east_north_modes[0] == 1:
value_2 = 0.0
else:
value_2 = 4 * hsgp_east_north_settings[3] / 3.141592653589793 * np.sqrt(np.log(100.0) / (hsgp_east_north_modes[0] ** 2 - 1))
if hsgp_east_north_modes[1] == 1:
value_3 = 0.0
else:
value_3 = 4 * hsgp_east_north_settings[5] / 3.141592653589793 * np.sqrt(np.log(100.0) / (hsgp_east_north_modes[1] ** 2 - 1))
hsgp_east_north_rho_floor = np.maximum(value_2, value_3)
ppl_axis2_hsgp_east_north_z = np.prod(hsgp_east_north_modes)
ppl_last_hsgp_east_north_z = 3 + 2 * ppl_axis2_hsgp_east_north_z
ppl_first_Omega = ppl_last_hsgp_east_north_z + 1
hsgp_east_north_rho_location = np.log(25)
hsgp_east_north_spectral_scale_B = np.prod(hsgp_east_north_modes)
hsgp_east_north_spectral_scale_center_1 = hsgp_east_north_settings[2]
hsgp_east_north_spectral_scale_width_1 = hsgp_east_north_settings[3]
hsgp_east_north_spectral_scale_center_2 = hsgp_east_north_settings[4]
hsgp_east_north_spectral_scale_width_2 = hsgp_east_north_settings[5]
plate_argument = np.arange(1, hsgp_east_north_spectral_scale_B + 1)
def cell(b, modes):
return_ = np.fmod((abs(b - 1) // abs(1) * (1 if (b - 1 >= 0) == (1 >= 0) else -1)), modes[0]) + 1
return return_
hsgp_east_north_spectral_scale_modes_1 = np.asarray([cell(element, hsgp_east_north_modes) for element in plate_argument], dtype=np.int64)
def cell_2(mode, width_1):
return_ = (mode * np.pi / (2 * width_1)) ** 2
return return_
hsgp_east_north_spectral_scale_frequency_1 = np.asarray([cell_2(element_2, hsgp_east_north_spectral_scale_width_1) for element_2 in hsgp_east_north_spectral_scale_modes_1], dtype=np.float64)
plate_argument_2 = np.arange(1, hsgp_east_north_spectral_scale_B + 1)
def cell_3(b, modes):
return_ = np.fmod((abs(b - 1) // abs(modes[0]) * (1 if (b - 1 >= 0) == (modes[0] >= 0) else -1)), modes[1]) + 1
return return_
hsgp_east_north_spectral_scale_modes_2 = np.asarray([cell_3(element_3, hsgp_east_north_modes) for element_3 in plate_argument_2], dtype=np.int64)
def cell_4(mode, width_2):
return_ = (mode * np.pi / (2 * width_2)) ** 2
return return_
hsgp_east_north_spectral_scale_frequency_2 = np.asarray([cell_4(element_4, hsgp_east_north_spectral_scale_width_2) for element_4 in hsgp_east_north_spectral_scale_modes_2], dtype=np.float64)
hsgp_east_north_spectral_scale_widths = (hsgp_east_north_spectral_scale_width_1, hsgp_east_north_spectral_scale_width_2)
hsgp_east_north_spectral_scale_centers = (hsgp_east_north_spectral_scale_center_1, hsgp_east_north_spectral_scale_center_2)
hsgp_east_north_spectral_scale_omega2 = np.concatenate([hsgp_east_north_spectral_scale_frequency_1[:, None], hsgp_east_north_spectral_scale_frequency_2[:, None]], axis=1)
def cell_5(x_1, x_2, B, omega2, centers, widths):
plate_argument_3 = np.arange(1, B + 1)
def cell_6(b, omega2_2, x_1_2, centers_2, widths_2, x_2_2):
return_ = np.sin(np.sqrt(omega2_2[b - 1, 0]) * (x_1_2 - centers_2[0] + widths_2[0])) / np.sqrt(widths_2[0]) * (np.sin(np.sqrt(omega2_2[b - 1, 1]) * (x_2_2 - centers_2[1] + widths_2[1])) / np.sqrt(widths_2[1]))
return return_
values = np.asarray([cell_6(element_5, omega2, x_1, centers, widths, x_2) for element_5 in plate_argument_3], dtype=np.float64)
return values
hsgp_east_north_spectral_scale_basis_rows = [cell_5(element_5, element_6, hsgp_east_north_spectral_scale_B, hsgp_east_north_spectral_scale_omega2, hsgp_east_north_spectral_scale_centers, hsgp_east_north_spectral_scale_widths) for element_5, element_6 in zip(east, north)]
if (len(hsgp_east_north_spectral_scale_basis_rows) == 0):
value_4 = np.zeros((0, hsgp_east_north_spectral_scale_B), dtype=np.float64)
else:
value_4 = np.stack(hsgp_east_north_spectral_scale_basis_rows, axis=0)
hsgp_east_north_spectral_scale_PHI = value_4
plate_argument_3 = np.arange(1, len(hsgp_east_north_spectral_scale_omega2) + 1)
location_binding = 1.0 * hsgp_east_north_rho_location
scale_binding = 0.5
x_argument = 1.0 * hsgp_east_north_rho_floor
ppl_prior_hsgp_east_north_rho_logcdf_log_scale = np.log(scale_binding)
if x_argument <= 0:
value_5 = -np.inf
else:
value_5 = np.log(x_argument)
ppl_prior_hsgp_east_north_rho_logcdf_logcdf_log_x = value_5
if scale_binding == 0 and ppl_prior_hsgp_east_north_rho_logcdf_logcdf_log_x == location_binding:
value_6 = 1.0 / scale_binding
else:
value_7 = _standardized_np(location_binding, scale_binding, ppl_prior_hsgp_east_north_rho_logcdf_log_scale, ppl_prior_hsgp_east_north_rho_logcdf_logcdf_log_x)
value_6 = value_7
ppl_prior_hsgp_east_north_rho_logcdf_logcdf_logcdf_z = value_6
if ppl_prior_hsgp_east_north_rho_logcdf_logcdf_log_x == -np.inf:
value_8 = -np.inf
else:
if ppl_prior_hsgp_east_north_rho_logcdf_logcdf_log_x == np.inf:
value_9 = 0.0
else:
value_10 = _standard_logcdf_np(ppl_prior_hsgp_east_north_rho_logcdf_logcdf_logcdf_z)
value_9 = value_10
value_8 = value_9
logcdf = value_8
return {"hsgp_east_north_rho_floor": hsgp_east_north_rho_floor, "ppl_last_hsgp_east_north_z": StaticInt(ppl_last_hsgp_east_north_z), "ppl_axis2_hsgp_east_north_z": StaticInt(ppl_axis2_hsgp_east_north_z), "_ppl_first_Omega": StaticInt(ppl_first_Omega), "plate_argument": np.asarray(plate_argument_3, dtype=np.int64), "hsgp_east_north_spectral_scale_omega2": np.asarray(hsgp_east_north_spectral_scale_omega2, dtype=np.float64), "hsgp_east_north_group_index": np.asarray(hsgp_east_north_group_index, dtype=np.int64), "hsgp_east_north_spectral_scale_PHI": np.asarray(hsgp_east_north_spectral_scale_PHI, dtype=np.float64), "y": np.asarray(y, dtype=np.float64), "ppl_prior_hsgp_east_north_rho_logcdf": logcdf}
def model(_entry: str, unconstrained: ArrayLike, **prepared: ArrayLike) -> Any:
"""Shared model computation. The generated entry wrappers select a static output."""
hsgp_east_north_rho_floor = prepared["hsgp_east_north_rho_floor"]
ppl_last_hsgp_east_north_z = prepared["ppl_last_hsgp_east_north_z"]
ppl_axis2_hsgp_east_north_z = prepared["ppl_axis2_hsgp_east_north_z"]
_ppl_first_Omega = prepared["_ppl_first_Omega"]
plate_argument = prepared["plate_argument"]
hsgp_east_north_spectral_scale_omega2 = prepared["hsgp_east_north_spectral_scale_omega2"]
hsgp_east_north_group_index = prepared["hsgp_east_north_group_index"]
hsgp_east_north_spectral_scale_PHI = prepared["hsgp_east_north_spectral_scale_PHI"]
y = prepared["y"]
ppl_prior_hsgp_east_north_rho_logcdf = prepared["ppl_prior_hsgp_east_north_rho_logcdf"]
unconstrained = jnp.asarray(unconstrained)
plate_argument = jnp.asarray(plate_argument)
hsgp_east_north_spectral_scale_omega2 = jnp.asarray(hsgp_east_north_spectral_scale_omega2)
hsgp_east_north_group_index = jnp.asarray(hsgp_east_north_group_index)
hsgp_east_north_spectral_scale_PHI = jnp.asarray(hsgp_east_north_spectral_scale_PHI)
y = jnp.asarray(y)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
ppl_int_hsgp_east_north_rho = unconstrained[0]
value = _rk_affine_logistic(jnp.maximum(hsgp_east_north_rho_floor, 0.0), 300.0, ppl_int_hsgp_east_north_rho)
hsgp_east_north_rho = value
u_argument = unconstrained[1]
constrain_2 = jnp.exp(u_argument)
u_argument_2 = unconstrained[2]
constrain_3 = jnp.exp(u_argument_2)
ppl_lkj_raw_Omega = unconstrained[_ppl_first_Omega - 1:_ppl_first_Omega]
ppl_lkj_partials_Omega = jnp.tanh(ppl_lkj_raw_Omega)
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
out = jnp.ones((2,), dtype=jnp.float64)
tuple_ = (1, 2, 1.0)
i = tuple_[0]
j = tuple_[1]
d = tuple_[2]
def loop_body(p, carry):
(d_2, i_2, j_2, out_2) = carry
d_3 = d_2 * jnp.sqrt(1 - ppl_lkj_partials_Omega[p - 1] ** 2)
def then_arm():
i_3 = i_2 + 1
return (None, jnp.asarray(d_3, dtype=jnp.float64), jnp.asarray(i_3, dtype=jnp.int64), jnp.asarray(j_2, dtype=jnp.int64), out_2)
def else_arm():
out_3 = out_2.at[j_2 - 1].set(d_3)
tuple__2 = (1, j_2 + 1, 1.0)
i_4 = tuple__2[0]
j_3 = tuple__2[1]
d_4 = tuple__2[2]
return (None, jnp.asarray(d_4, dtype=jnp.float64), jnp.asarray(i_4, dtype=jnp.int64), jnp.asarray(j_3, dtype=jnp.int64), out_3)
branch = jax.lax.cond(i_2 + 1 < j_2, then_arm, else_arm)
return (branch[1], branch[2], branch[3], branch[4])
loop_carry = jax.lax.fori_loop(1, 2, loop_body, (jnp.asarray(d, dtype=jnp.float64), jnp.asarray(i, dtype=jnp.int64), jnp.asarray(j, dtype=jnp.int64), out))
ppl_lkj_diagonal_Omega = loop_carry[3]
if _entry in ("log_density", "log_likelihood", "constrain"):
ppl_lkj_lower = _ppl_lkj_lower(ppl_lkj_partials_Omega, ppl_lkj_diagonal_Omega, 2, 1)
Omega = ppl_lkj_lower
if _entry in ("log_density", "log_jacobian"):
total = 0.0
tuple__2 = (1, 2)
i_2 = tuple__2[0]
j_2 = tuple__2[1]
def loop_body_2(p_2, carry_2):
(i_3, j_3, total_2) = carry_2
total_3 = total_2 + (j_3 - i_3 + 1) / 2 * jnp.log(1 - ppl_lkj_partials_Omega[p_2 - 1] ** 2)
tuple__3 = jax.lax.cond(i_3 + 1 < j_3, lambda: (i_3 + 1, j_3), lambda: (1, j_3 + 1))
i_4 = tuple__3[0]
j_4 = tuple__3[1]
return (i_4, j_4, total_3)
loop_carry_2 = jax.lax.fori_loop(1, 2, loop_body_2, (jnp.asarray(i_2, dtype=jnp.int64), jnp.asarray(j_2, dtype=jnp.int64), jnp.asarray(total, dtype=jnp.float64)))
ppl_lkj_logjac_Omega = loop_carry_2[2]
if _entry in ("log_density", "log_prior"):
ppl_prior_sigma_log_scale = np.log(0.5)
logpdf = jax.lax.cond(constrain_3 < 0, lambda: -jnp.inf, lambda: -ppl_prior_sigma_log_scale - constrain_3 / 0.5)
total_2 = -0.2876820724517809
def loop_body_3(i_3, carry_3):
(total_3,) = carry_3
total_4 = total_3 + ((2 - i_3) * jnp.log(ppl_lkj_diagonal_Omega[i_3 - 1]) + 2.0 * jnp.log(ppl_lkj_diagonal_Omega[i_3 - 1]))
return (total_4,)
loop_carry_3 = jax.lax.fori_loop(2, 3, loop_body_3, (jnp.asarray(total_2, dtype=jnp.float64),))
ppl_prior_Omega = loop_carry_3[0]
if _entry in ("log_density", "log_jacobian"):
u_argument_3 = unconstrained[1]
u_argument_4 = unconstrained[2]
log_jacobian_2 = jnp.log(300.0 - jnp.maximum(hsgp_east_north_rho_floor, 0.0)) - jax.nn.softplus(-unconstrained[0]) - jax.nn.softplus(unconstrained[0]) + u_argument_3 + u_argument_4 + ppl_lkj_logjac_Omega
if _entry in ("log_density", "log_prior", "log_likelihood", "constrain"):
hsgp_east_north = brm_grouped_hsgp_density(
ppl_last_z=(ppl_last_hsgp_east_north_z if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") else None),
ppl_prior_rho_logcdf=(ppl_prior_hsgp_east_north_rho_logcdf if _entry in ("log_density", "log_prior") else None),
plate_argument=(plate_argument if _entry in ("log_density", "log_likelihood") else None),
rho=(hsgp_east_north_rho if _entry in ("log_density", "log_prior", "log_likelihood") else None),
rho_floor=(hsgp_east_north_rho_floor if _entry in ("log_density", "log_prior", "log_likelihood") else None),
sigma=(constrain_2 if _entry in ("log_density", "log_prior", "log_likelihood") else None),
unconstrained=(unconstrained if _entry in ("log_density", "log_prior", "log_likelihood", "constrain") else None),
value_omega2=(hsgp_east_north_spectral_scale_omega2 if _entry in ("log_density", "log_likelihood") else None),
outputs=tuple(
name for name, needed in (
("ppl_arrflat_z", ("log_density", "log_prior", "log_likelihood", "constrain")),
("ppl_prior_rho", ("log_density", "log_prior")),
("ppl_prior_rho_logpdf", ("log_density", "log_prior")),
("ppl_prior_sigma", ("log_density", "log_prior")),
("ppl_prior_z", ("log_density", "log_prior")),
("ppl_pw_prior_z", ("log_density", "log_prior")),
("ppl_prior_sigma_log_scale", ("log_density", "log_prior")),
("ppl_prior_sigma_scale", ("log_density", "log_prior")),
("rho_location", ("log_density", "log_prior")),
("spectral_scale", ("log_density", "log_likelihood")),
)
if _entry in needed
),
)
if _entry in ("log_density", "log_likelihood", "constrain"):
hsgp_east_north_z = jnp.reshape(hsgp_east_north["ppl_arrflat_z"], (2, ppl_axis2_hsgp_east_north_z), order="F")
if _entry in ("log_density", "log_prior"):
prior = hsgp_east_north["ppl_prior_rho"] + hsgp_east_north["ppl_prior_sigma"] + logpdf + hsgp_east_north["ppl_prior_z"] + ppl_prior_Omega
if _entry in ("log_density", "log_likelihood"):
hsgp_east_north_2 = brm_grouped_hsgp(
L_level=(Omega if _entry in ("log_density", "log_likelihood") else None),
group_index=(hsgp_east_north_group_index if _entry in ("log_density", "log_likelihood") else None),
spectral_scale=(hsgp_east_north["spectral_scale"] if _entry in ("log_density", "log_likelihood") else None),
value_PHI=(hsgp_east_north_spectral_scale_PHI if _entry in ("log_density", "log_likelihood") else None),
z=(hsgp_east_north_z if _entry in ("log_density", "log_likelihood") else None),
outputs=tuple(
name for name, needed in (
("value", ("log_density", "log_likelihood")),
("value_rows", ("log_density", "log_likelihood")),
)
if _entry in needed
),
)
def ppl_pw_y_resp_cell(y_2, mu, sigma):
def then_arm():
log_scale = jnp.log(sigma)
standardized = (y_2 - mu) / jnp.where(jnp.logical_and(sigma == 0, y_2 == mu), 1.0, sigma)
standard_logpdf = -0.5 * np.log(2 * np.pi) - 0.5 * standardized ** 2
return standard_logpdf - jnp.where(jnp.logical_and(sigma == 0, y_2 != mu), 0.0, log_scale)
ppl_density = jax.lax.cond(sigma > 0, then_arm, lambda: -jnp.inf)
return ppl_density
ppl_pw_y_resp = (jnp.zeros(y.shape[:1], dtype=jnp.float64) if 0 in y.shape[:1] and hsgp_east_north_2["value"].shape[:1] == y.shape[:1] else jax.vmap(ppl_pw_y_resp_cell, in_axes=(0, 0, None))(y, hsgp_east_north_2["value"], constrain_3))
ppl_lik_y_resp = jnp.sum(ppl_pw_y_resp)
if _entry in ("log_density",):
posterior = prior + ppl_lik_y_resp + log_jacobian_2
if not (unconstrained.size == _ppl_first_Omega):
raise ValueError("[layout] packed length ≠ layout total: a packed point holds the coordinates of the binding whose layout packed it")
if _entry == "log_density":
return jnp.asarray(posterior, dtype=jnp.float64)
if _entry == "log_prior":
return jnp.asarray(prior, dtype=jnp.float64)
if _entry == "log_likelihood":
return jnp.asarray(ppl_lik_y_resp, dtype=jnp.float64)
if _entry == "log_jacobian":
return jnp.asarray(log_jacobian_2, dtype=jnp.float64)
if _entry == "constrain":
return {"hsgp_east_north": {"rho": jnp.asarray(hsgp_east_north_rho, dtype=jnp.float64), "sigma": jnp.asarray(constrain_2, dtype=jnp.float64), "z": jnp.asarray(hsgp_east_north_z)}, "sigma": jnp.asarray(constrain_3, dtype=jnp.float64), "Omega": jnp.asarray(Omega)}
def log_density(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log density a sampler targets at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`.
The sum of `log_prior`, `log_likelihood` and `log_jacobian`.
"""
return model("log_density", unconstrained, **prepared)
def log_prior(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log prior density of the constrained parameters at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_prior", unconstrained, **prepared)
def log_likelihood(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log likelihood of the observations at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_likelihood", unconstrained, **prepared)
def log_jacobian(unconstrained: ArrayLike, **prepared: ArrayLike) -> jax.Array:
"""The log Jacobian of the constraining transforms at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`."""
return model("log_jacobian", unconstrained, **prepared)
def constrain(unconstrained: ArrayLike, **prepared: ArrayLike) -> dict:
"""The constrained value of each parameter, and of each requested value, at `unconstrained`, the packed unconstrained parameters (length `dimension(prepared)`), for the data `prepare_data` returned: `f(u, **prepared)`. Returns a dict, a submodel's values nested under its name:
- `hsgp_east_north.rho`
- `hsgp_east_north.sigma`
- `sigma`
- `hsgp_east_north.z`
- `Omega`
"""
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_Omega"])
def parameters(prepared: dict) -> dict:
"""Each parameter's 0-based `start`/`stop` in `unconstrained`, its transform and dimensions,
for the data `prepared` (what `prepare_data` returned)."""
return {"hsgp_east_north.rho": {"start": 0, "stop": 1, "transform": "interval", "dims": ()}, "hsgp_east_north.sigma": {"start": 1, "stop": 2, "transform": "exp", "dims": ()}, "sigma": {"start": 2, "stop": 3, "transform": "exp", "dims": ()}, "hsgp_east_north.z": {"start": 3, "stop": int(prepared["ppl_last_hsgp_east_north_z"]), "transform": "identity", "dims": (2, int(prepared["ppl_axis2_hsgp_east_north_z"]))}, "Omega": {"start": int(prepared["_ppl_first_Omega"]) - 1, "stop": int(prepared["_ppl_first_Omega"]), "transform": "lkj", "dims": (2, 2)}}The lower bound keeps the length inside the fitted basis's approximation range. Increase k when shorter scales matter. For a grid, replay east, north and channel without y, then read the latent mu. Keep the grid inside the fitted domain; replay retains its basis and channel labels.
Matérn space and OU time
A mesh is a two-column vertex matrix and an integer cell matrix with three one-based vertex indices per triangle. The following small mesh illustrates the declaration; scientific fits need an appropriate boundary buffer and resolution.
Matérn space, OU time and correlated channels
panes: brm|stanblocks|rkppl|stan|jax:2model = (@brm begin
field ~ 0 + gmrf((east, north), time, channel;
mesh=(vertices=xy, cells=triangles), cor=Omega)
y ~ Normal(field, 0.2)
Omega ~ LKJCholesky(2, 2)
sd(field, gmrf((east, north), time, channel)) ~ Exponential(0.7)
length_scale(field, gmrf((east, north), time, channel), space) ~ LogNormal(log(0.4), 0.4)
length_scale(field, gmrf((east, north), time, channel), time) ~ LogNormal(log(1.7), 0.4)
end)((; east=[0.1, 0.9, 0.7, 0.3], north=[0.2, 0.4, 0.8, 0.5],
time=[0., 0.3, 0.3, 1.7], channel=["b", "a", "b", "a"], y=[0.2, -0.1, 0.3, 0.1],
xy=[0. 0.; 1. 0.; 1. 1.; 0. 1.; 0.5 0.5],
triangles=[1 2 5; 2 3 5; 3 4 5; 4 1 5]))SBBRMI with data keys = [:Omega_n, :east, :gmrf_field_east_north_time_channel_gptr, :gmrf_field_east_north_time_channel_grow, :gmrf_field_east_north_time_channel_gval, :gmrf_field_east_north_time_channel_index1, :gmrf_field_east_north_time_channel_index2, :gmrf_field_east_north_time_channel_index3, :gmrf_field_east_north_time_channel_lptr, :gmrf_field_east_north_time_channel_lrow, :gmrf_field_east_north_time_channel_mass, :gmrf_field_east_north_time_channel_n_field, :gmrf_field_east_north_time_channel_permutation, :gmrf_field_east_north_time_channel_previous_col, :gmrf_field_east_north_time_channel_previous_pos, :gmrf_field_east_north_time_channel_previous_ptr, :gmrf_field_east_north_time_channel_times, :gmrf_field_east_north_time_channel_weight1, :gmrf_field_east_north_time_channel_weight2, :gmrf_field_east_north_time_channel_weight3, :north, :time, :triangles, :xy, :y]
configured submodels:
_sb_gmrf_configured_1 = Base.merge(BayesianRegressionModels._sb_gmrf, quote
sigma ~ (StanBlocks.builtin.restricted)(exponential, 1.0 ./ 0.7; lower = 0.0)
spatial_length ~ (StanBlocks.builtin.restricted)(lognormal, -0.916290731874155, 0.4; lower = 0.0)
temporal_length ~ (StanBlocks.builtin.restricted)(lognormal, 0.5306282510621704, 0.4; lower = 0.0)
end)
emitted @slic body:
begin
Omega::cholesky_factor_corr[Omega_n] ~ lkj_corr_cholesky(2.0)
gmrf_field_east_north_time_channel ~ _sb_gmrf_configured_1(; L = Omega, n_field = gmrf_field_east_north_time_channel_n_field, times = gmrf_field_east_north_time_channel_times, permutation = gmrf_field_east_north_time_channel_permutation, mass = gmrf_field_east_north_time_channel_mass, gptr = gmrf_field_east_north_time_channel_gptr, grow = gmrf_field_east_north_time_channel_grow, gval = gmrf_field_east_north_time_channel_gval, lptr = gmrf_field_east_north_time_channel_lptr, lrow = gmrf_field_east_north_time_channel_lrow, previous_ptr = gmrf_field_east_north_time_channel_previous_ptr, previous_col = gmrf_field_east_north_time_channel_previous_col, previous_pos = gmrf_field_east_north_time_channel_previous_pos, index1 = gmrf_field_east_north_time_channel_index1, index2 = gmrf_field_east_north_time_channel_index2, index3 = gmrf_field_east_north_time_channel_index3, weight1 = gmrf_field_east_north_time_channel_weight1, weight2 = gmrf_field_east_north_time_channel_weight2, weight3 = gmrf_field_east_north_time_channel_weight3)
field = gmrf_field_east_north_time_channel
y ~ normal(field, 0.2)
end"""
A Gaussian Markov random field (`gmrf`) over a space-time mesh.
Draws the marginal scale `sigma`, the spatial length `spatial_length` and the
temporal length `temporal_length` from their priors, then the field
`field ~ #brm_callable_(spatial_length, temporal_length, …)` on the mesh `geometry`;
each row reads a weighted sum of three field states (its interpolation weights). Returns `sigma` times those reads, one value per row.
"""
brm_gmrf(geometry, rows, L) = begin
sigma ~ Exponential(0.7)
spatial_length ~ LogNormal(log.(0.4), 0.4)
temporal_length ~ LogNormal(log.(1.7), 0.4)
field[1:geometry.ncoordinates] ~ brm_value_function(spatial_length, temporal_length, L, geometry)
return sigma .* .+(rows.weight1 .* field[rows.index1], rows.weight2 .* field[rows.index2], rows.weight3 .* field[rows.index3])
end
begin
gmrf_field_east_north_time_channel_support = brm_gmrf_support(xy_fit[1], triangles_fit[1], time_fit, channel_fit)
gmrf_field_east_north_time_channel_rows = brm_gmrf_rows(gmrf_field_east_north_time_channel_support, east, north, time, channel)
gmrf_field_east_north_time_channel ~ brm_gmrf(gmrf_field_east_north_time_channel_support.geometry, gmrf_field_east_north_time_channel_rows, Omega)
field = gmrf_field_east_north_time_channel
Omega ~ LKJCholesky(2, 2)
y .~ Normal.(field, 0.2)
endfunctions {
real brm_gmrf_lpdf(
vector field,
real spatial_length,
real temporal_length,
matrix L,
vector times,
array[] int permutation,
vector mass,
array[] int gptr,
array[] int grow,
vector gval,
array[] int lptr,
array[] int lrow,
array[] int previous_ptr,
array[] int previous_col,
array[] int previous_pos
) {
int C = dims(L)[1];
int N = dims(permutation)[1];
int NP = dims(gptr)[1];
int NZ = dims(grow)[1];
int ND = dims(previous_col)[1];
if (dims(L)[2] != C) reject("brm_gmrf_lpdf: dim mismatch — `L` dim 2 (= ", dims(L)[2], ") does not match `C` (= ", C, "), inferred from `L` dim 1. `C` sizes: `L` dim 1 (= ", dims(L)[1], "), `L` dim 2 (= ", dims(L)[2], ").");
if (dims(mass)[1] != N) reject("brm_gmrf_lpdf: dim mismatch — `mass` dim 1 (= ", dims(mass)[1], ") does not match `N` (= ", N, "), inferred from `permutation` dim 1. `N` sizes: `permutation` dim 1 (= ", dims(permutation)[1], "), `mass` dim 1 (= ", dims(mass)[1], ").");
if (dims(lptr)[1] != NP) reject("brm_gmrf_lpdf: dim mismatch — `lptr` dim 1 (= ", dims(lptr)[1], ") does not match `NP` (= ", NP, "), inferred from `gptr` dim 1. `NP` sizes: `gptr` dim 1 (= ", dims(gptr)[1], "), `lptr` dim 1 (= ", dims(lptr)[1], "), `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ").");
if (dims(previous_ptr)[1] != NP) reject("brm_gmrf_lpdf: dim mismatch — `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ") does not match `NP` (= ", NP, "), inferred from `gptr` dim 1. `NP` sizes: `gptr` dim 1 (= ", dims(gptr)[1], "), `lptr` dim 1 (= ", dims(lptr)[1], "), `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ").");
if (dims(gval)[1] != NZ) reject("brm_gmrf_lpdf: dim mismatch — `gval` dim 1 (= ", dims(gval)[1], ") does not match `NZ` (= ", NZ, "), inferred from `grow` dim 1. `NZ` sizes: `grow` dim 1 (= ", dims(grow)[1], "), `gval` dim 1 (= ", dims(gval)[1], ").");
if (dims(previous_pos)[1] != ND) reject("brm_gmrf_lpdf: dim mismatch — `previous_pos` dim 1 (= ", dims(previous_pos)[1], ") does not match `ND` (= ", ND, "), inferred from `previous_col` dim 1. `ND` sizes: `previous_col` dim 1 (= ", dims(previous_col)[1], "), `previous_pos` dim 1 (= ", dims(previous_pos)[1], ").");
return brm_gmrf_logdensity(
field,
spatial_length,
temporal_length,
L,
times,
permutation,
mass,
gptr,
grow,
gval,
lptr,
lrow,
previous_ptr,
previous_col,
previous_pos
);
}
real brm_gmrf_logdensity(
vector field,
real spatial_length,
real temporal_length,
matrix L,
vector times,
array[] int permutation,
vector mass,
array[] int gptr,
array[] int grow,
vector gval,
array[] int lptr,
array[] int lrow,
array[] int previous_ptr,
array[] int previous_col,
array[] int previous_pos
) {
int D = dims(field)[1];
int C = dims(L)[1];
int T = dims(times)[1];
int N = dims(permutation)[1];
int NP = dims(gptr)[1];
int NZ = dims(grow)[1];
int ND = dims(previous_col)[1];
if (dims(L)[2] != C) reject("brm_gmrf_logdensity: dim mismatch — `L` dim 2 (= ", dims(L)[2], ") does not match `C` (= ", C, "), inferred from `L` dim 1. `C` sizes: `L` dim 1 (= ", dims(L)[1], "), `L` dim 2 (= ", dims(L)[2], ").");
if (dims(mass)[1] != N) reject("brm_gmrf_logdensity: dim mismatch — `mass` dim 1 (= ", dims(mass)[1], ") does not match `N` (= ", N, "), inferred from `permutation` dim 1. `N` sizes: `permutation` dim 1 (= ", dims(permutation)[1], "), `mass` dim 1 (= ", dims(mass)[1], ").");
if (dims(lptr)[1] != NP) reject("brm_gmrf_logdensity: dim mismatch — `lptr` dim 1 (= ", dims(lptr)[1], ") does not match `NP` (= ", NP, "), inferred from `gptr` dim 1. `NP` sizes: `gptr` dim 1 (= ", dims(gptr)[1], "), `lptr` dim 1 (= ", dims(lptr)[1], "), `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ").");
if (dims(previous_ptr)[1] != NP) reject("brm_gmrf_logdensity: dim mismatch — `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ") does not match `NP` (= ", NP, "), inferred from `gptr` dim 1. `NP` sizes: `gptr` dim 1 (= ", dims(gptr)[1], "), `lptr` dim 1 (= ", dims(lptr)[1], "), `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ").");
if (dims(gval)[1] != NZ) reject("brm_gmrf_logdensity: dim mismatch — `gval` dim 1 (= ", dims(gval)[1], ") does not match `NZ` (= ", NZ, "), inferred from `grow` dim 1. `NZ` sizes: `grow` dim 1 (= ", dims(grow)[1], "), `gval` dim 1 (= ", dims(gval)[1], ").");
if (dims(previous_pos)[1] != ND) reject("brm_gmrf_logdensity: dim mismatch — `previous_pos` dim 1 (= ", dims(previous_pos)[1], ") does not match `ND` (= ", ND, "), inferred from `previous_col` dim 1. `ND` sizes: `previous_col` dim 1 (= ", dims(previous_col)[1], "), `previous_pos` dim 1 (= ", dims(previous_pos)[1], ").");
vector[(dims(mass)[1] + dims(lrow)[1])] factor = brm_gmrf_factor(
(1.0 / spatial_length),
(spatial_length / 2.0),
mass,
gptr,
grow,
gval,
lptr,
lrow,
previous_ptr,
previous_col,
previous_pos
);
real logdet_space = (((2.0 * sum(log(segment(factor, 1, N)))) - sum(log(mass))) - (N * log((2.0 * 3.141592653589793))));
real lp = (((T * C * logdet_space) / 2.0) - ((D * log((2.0 * 3.141592653589793))) / 2.0));
for(c in 1:C) {
lp -= (N * T * log(L[c, c]));
}
matrix[N, C] residual;
for(t in 1:T) {
real a = ((t == 1) ? 0.0 : exp(((-(times[t] - times[(t - 1)])) / temporal_length)));
real variance = ((t == 1) ? 1.0 : (-expm1(((-2.0 * (times[t] - times[(t - 1)])) / temporal_length))));
for(c in 1:C) {
for(i in 1:N) {
int index = (permutation[i] + (N * ((c - 1) + (C * (t - 1)))));
real z = field[index];
if((t > 1)) {
z -= (a * field[(index - (N * C))]);
}
for(k in 1:(c - 1)) {
z -= (residual[i, k] * L[c, k]);
}
residual[i, c] = (z / L[c, c]);
}
}
real quadratic = 0.0;
for(c in 1:C) {
for(i in 1:N) {
real stiffness = 0.0;
for(p in gptr[i]:(gptr[(i + 1)] - 1)) {
stiffness += (gval[p] * residual[grow[p], c]);
}
real z = ((mass[i] * (residual[i, c] / spatial_length)) + ((spatial_length / 2.0) * stiffness));
quadratic += square((z / (sqrt((4.0 * 3.141592653589793 * mass[i])) * sqrt(variance))));
}
}
lp -= (quadratic + ((N * C * log(variance)) / 2.0));
}
return lp;
}
vector brm_gmrf_factor(
real mass_scale,
real stiffness_scale,
vector mass,
array[] int gptr,
array[] int grow,
vector gval,
array[] int lptr,
array[] int lrow,
array[] int previous_ptr,
array[] int previous_col,
array[] int previous_pos
) {
int N = dims(mass)[1];
int NP = dims(gptr)[1];
int NZ = dims(grow)[1];
int NL = dims(lrow)[1];
int ND = dims(previous_col)[1];
if (dims(lptr)[1] != NP) reject("brm_gmrf_factor: dim mismatch — `lptr` dim 1 (= ", dims(lptr)[1], ") does not match `NP` (= ", NP, "), inferred from `gptr` dim 1. `NP` sizes: `gptr` dim 1 (= ", dims(gptr)[1], "), `lptr` dim 1 (= ", dims(lptr)[1], "), `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ").");
if (dims(previous_ptr)[1] != NP) reject("brm_gmrf_factor: dim mismatch — `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ") does not match `NP` (= ", NP, "), inferred from `gptr` dim 1. `NP` sizes: `gptr` dim 1 (= ", dims(gptr)[1], "), `lptr` dim 1 (= ", dims(lptr)[1], "), `previous_ptr` dim 1 (= ", dims(previous_ptr)[1], ").");
if (dims(gval)[1] != NZ) reject("brm_gmrf_factor: dim mismatch — `gval` dim 1 (= ", dims(gval)[1], ") does not match `NZ` (= ", NZ, "), inferred from `grow` dim 1. `NZ` sizes: `grow` dim 1 (= ", dims(grow)[1], "), `gval` dim 1 (= ", dims(gval)[1], ").");
if (dims(previous_pos)[1] != ND) reject("brm_gmrf_factor: dim mismatch — `previous_pos` dim 1 (= ", dims(previous_pos)[1], ") does not match `ND` (= ", ND, "), inferred from `previous_col` dim 1. `ND` sizes: `previous_col` dim 1 (= ", dims(previous_col)[1], "), `previous_pos` dim 1 (= ", dims(previous_pos)[1], ").");
vector[NL] ldl_values = rep_vector(0.0, NL);
vector[N] diagonal = rep_vector(0.0, N);
vector[N] work = rep_vector(0.0, N);
for(j in 1:N) {
for(p in lptr[j]:(lptr[(j + 1)] - 1)) {
work[lrow[p]] = 0.0;
}
for(p in gptr[j]:(gptr[(j + 1)] - 1)) {
if((grow[p] >= j)) {
work[grow[p]] = (stiffness_scale * gval[p]);
}
}
work[j] += (mass_scale * mass[j]);
for(q in previous_ptr[j]:(previous_ptr[(j + 1)] - 1)) {
int k = previous_col[q];
int start = previous_pos[q];
real v = (ldl_values[start] * diagonal[k]);
for(p in start:(lptr[(k + 1)] - 1)) {
work[lrow[p]] -= (ldl_values[p] * v);
}
}
diagonal[j] = work[j];
ldl_values[lptr[j]] = 1.0;
for(p in (lptr[j] + 1):(lptr[(j + 1)] - 1)) {
ldl_values[p] = (work[lrow[p]] / diagonal[j]);
}
}
return append_row(diagonal, ldl_values);
}
vector brm_gmrf_rows(
real sigma,
vector field,
array[] int index1,
array[] int index2,
array[] int index3,
vector weight1,
vector weight2,
vector weight3
) {
int R = dims(index1)[1];
if (dims(index2)[1] != R) reject("brm_gmrf_rows: dim mismatch — `index2` dim 1 (= ", dims(index2)[1], ") does not match `R` (= ", R, "), inferred from `index1` dim 1. `R` sizes: `index1` dim 1 (= ", dims(index1)[1], "), `index2` dim 1 (= ", dims(index2)[1], "), `index3` dim 1 (= ", dims(index3)[1], "), `weight1` dim 1 (= ", dims(weight1)[1], "), `weight2` dim 1 (= ", dims(weight2)[1], "), `weight3` dim 1 (= ", dims(weight3)[1], ").");
if (dims(index3)[1] != R) reject("brm_gmrf_rows: dim mismatch — `index3` dim 1 (= ", dims(index3)[1], ") does not match `R` (= ", R, "), inferred from `index1` dim 1. `R` sizes: `index1` dim 1 (= ", dims(index1)[1], "), `index2` dim 1 (= ", dims(index2)[1], "), `index3` dim 1 (= ", dims(index3)[1], "), `weight1` dim 1 (= ", dims(weight1)[1], "), `weight2` dim 1 (= ", dims(weight2)[1], "), `weight3` dim 1 (= ", dims(weight3)[1], ").");
if (dims(weight1)[1] != R) reject("brm_gmrf_rows: dim mismatch — `weight1` dim 1 (= ", dims(weight1)[1], ") does not match `R` (= ", R, "), inferred from `index1` dim 1. `R` sizes: `index1` dim 1 (= ", dims(index1)[1], "), `index2` dim 1 (= ", dims(index2)[1], "), `index3` dim 1 (= ", dims(index3)[1], "), `weight1` dim 1 (= ", dims(weight1)[1], "), `weight2` dim 1 (= ", dims(weight2)[1], "), `weight3` dim 1 (= ", dims(weight3)[1], ").");
if (dims(weight2)[1] != R) reject("brm_gmrf_rows: dim mismatch — `weight2` dim 1 (= ", dims(weight2)[1], ") does not match `R` (= ", R, "), inferred from `index1` dim 1. `R` sizes: `index1` dim 1 (= ", dims(index1)[1], "), `index2` dim 1 (= ", dims(index2)[1], "), `index3` dim 1 (= ", dims(index3)[1], "), `weight1` dim 1 (= ", dims(weight1)[1], "), `weight2` dim 1 (= ", dims(weight2)[1], "), `weight3` dim 1 (= ", dims(weight3)[1], ").");
if (dims(weight3)[1] != R) reject("brm_gmrf_rows: dim mismatch — `weight3` dim 1 (= ", dims(weight3)[1], ") does not match `R` (= ", R, "), inferred from `index1` dim 1. `R` sizes: `index1` dim 1 (= ", dims(index1)[1], "), `index2` dim 1 (= ", dims(index2)[1], "), `index3` dim 1 (= ", dims(index3)[1], "), `weight1` dim 1 (= ", dims(weight1)[1], "), `weight2` dim 1 (= ", dims(weight2)[1], "), `weight3` dim 1 (= ", dims(weight3)[1], ").");
return (sigma * ((weight1 .* field[index1]) + (weight2 .* field[index2]) + (weight3 .* field[index3])));
}
vector normal_lpdfs(
vector obs,
vector loc,
real scale
) {
return jbroadcasted_normal_lpdfs(obs, loc, scale);
}
vector jbroadcasted_normal_lpdfs(
vector x1,
vector x2,
real x3
) {
int n = dims(x1)[1];
vector[n] rv;
for(i in 1:n) {
rv[i] = normal_lpdfs(broadcasted_getindex(x1, i), broadcasted_getindex(x2, i), x3);
}
return rv;
}
real normal_lpdfs(
real args1,
real args2,
real args3
) {
return normal_lpdf(args1 | args2, args3);
}
real broadcasted_getindex(vector x, int i) {
return x[i];
}
vector normal_vector_rng(
int anontok__1,
vector a,
real b
) {
int n = anontok__1;
if((n == 0)) {
vector[n] rv;
return rv;
} else {
return to_vector(normal_rng(a, b));
}
}
}
data {
int Omega_n;
int gmrf_field_east_north_time_channel_n_field;
int gmrf_field_east_north_time_channel_times_n;
vector[gmrf_field_east_north_time_channel_times_n] gmrf_field_east_north_time_channel_times;
int gmrf_field_east_north_time_channel_permutation_n;
array[gmrf_field_east_north_time_channel_permutation_n] int gmrf_field_east_north_time_channel_permutation;
int gmrf_field_east_north_time_channel_mass_n;
vector[gmrf_field_east_north_time_channel_mass_n] gmrf_field_east_north_time_channel_mass;
int gmrf_field_east_north_time_channel_gptr_n;
array[gmrf_field_east_north_time_channel_gptr_n] int gmrf_field_east_north_time_channel_gptr;
int gmrf_field_east_north_time_channel_grow_n;
array[gmrf_field_east_north_time_channel_grow_n] int gmrf_field_east_north_time_channel_grow;
int gmrf_field_east_north_time_channel_gval_n;
vector[gmrf_field_east_north_time_channel_gval_n] gmrf_field_east_north_time_channel_gval;
int gmrf_field_east_north_time_channel_lptr_n;
array[gmrf_field_east_north_time_channel_lptr_n] int gmrf_field_east_north_time_channel_lptr;
int gmrf_field_east_north_time_channel_lrow_n;
array[gmrf_field_east_north_time_channel_lrow_n] int gmrf_field_east_north_time_channel_lrow;
int gmrf_field_east_north_time_channel_previous_ptr_n;
array[gmrf_field_east_north_time_channel_previous_ptr_n] int gmrf_field_east_north_time_channel_previous_ptr;
int gmrf_field_east_north_time_channel_previous_col_n;
array[gmrf_field_east_north_time_channel_previous_col_n] int gmrf_field_east_north_time_channel_previous_col;
int gmrf_field_east_north_time_channel_previous_pos_n;
array[gmrf_field_east_north_time_channel_previous_pos_n] int gmrf_field_east_north_time_channel_previous_pos;
int gmrf_field_east_north_time_channel_weight3_n;
int gmrf_field_east_north_time_channel_index1_n;
array[gmrf_field_east_north_time_channel_index1_n] int gmrf_field_east_north_time_channel_index1;
int gmrf_field_east_north_time_channel_index2_n;
array[gmrf_field_east_north_time_channel_index2_n] int gmrf_field_east_north_time_channel_index2;
int gmrf_field_east_north_time_channel_index3_n;
array[gmrf_field_east_north_time_channel_index3_n] int gmrf_field_east_north_time_channel_index3;
int gmrf_field_east_north_time_channel_weight1_n;
vector[gmrf_field_east_north_time_channel_weight1_n] gmrf_field_east_north_time_channel_weight1;
int gmrf_field_east_north_time_channel_weight2_n;
vector[gmrf_field_east_north_time_channel_weight2_n] gmrf_field_east_north_time_channel_weight2;
vector[gmrf_field_east_north_time_channel_weight3_n] gmrf_field_east_north_time_channel_weight3;
int y_n;
vector[y_n] y;
}
transformed data {
}
parameters {
cholesky_factor_corr[Omega_n] Omega;
real<lower=0.0> gmrf_field_east_north_time_channel_sigma;
real<lower=0.0> gmrf_field_east_north_time_channel_spatial_length;
real<lower=0.0> gmrf_field_east_north_time_channel_temporal_length;
vector[gmrf_field_east_north_time_channel_n_field] gmrf_field_east_north_time_channel_field;
}
transformed parameters {
vector[gmrf_field_east_north_time_channel_weight3_n] gmrf_field_east_north_time_channel = brm_gmrf_rows(
gmrf_field_east_north_time_channel_sigma,
gmrf_field_east_north_time_channel_field,
gmrf_field_east_north_time_channel_index1,
gmrf_field_east_north_time_channel_index2,
gmrf_field_east_north_time_channel_index3,
gmrf_field_east_north_time_channel_weight1,
gmrf_field_east_north_time_channel_weight2,
gmrf_field_east_north_time_channel_weight3
);
vector[gmrf_field_east_north_time_channel_weight3_n] field = gmrf_field_east_north_time_channel;
}
model {
Omega ~ lkj_corr_cholesky(2.0);
gmrf_field_east_north_time_channel_sigma ~ exponential((1.0 ./ 0.7));
gmrf_field_east_north_time_channel_spatial_length ~ lognormal(-0.916290731874155, 0.4);
gmrf_field_east_north_time_channel_temporal_length ~ lognormal(0.5306282510621704, 0.4);
gmrf_field_east_north_time_channel_field ~ brm_gmrf(
gmrf_field_east_north_time_channel_spatial_length,
gmrf_field_east_north_time_channel_temporal_length,
Omega,
gmrf_field_east_north_time_channel_times,
gmrf_field_east_north_time_channel_permutation,
gmrf_field_east_north_time_channel_mass,
gmrf_field_east_north_time_channel_gptr,
gmrf_field_east_north_time_channel_grow,
gmrf_field_east_north_time_channel_gval,
gmrf_field_east_north_time_channel_lptr,
gmrf_field_east_north_time_channel_lrow,
gmrf_field_east_north_time_channel_previous_ptr,
gmrf_field_east_north_time_channel_previous_col,
gmrf_field_east_north_time_channel_previous_pos
);
y ~ normal(field, 0.2);
}
generated quantities {
vector[y_n] y_likelihood = normal_lpdfs(y, field, 0.2);
vector[y_n] y_gen = normal_vector_rng(y_n, field, 0.2);
}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 readsThis model has no JAX module yet.
JAXEmissionError: a range whose length depends on data has no JAX translation (its stop needs a static limit, its start and step must be static, or its ends entries of integer arrays of the prepared data) in recipe `##plate_argument#603649017482000017 = (geometry, j) -> geometry.previous_ptr[j]:geometry.previous_ptr[j + 1] - 1`The term directly contributes the field, without an extra population coefficient. Omit channel for a single field; omit cor for independent channels. cor may also name a known correlation matrix. Replace a supported term prior by = value to fix that quantity.
| Quantity | Interpretation | Units |
|---|---|---|
sd | Nominal continuum marginal SD | Predictor units |
Spatial length_scale | Matérn ν=1 length ell_s; practical range is 2ell_s | Coordinate units |
Temporal length_scale | OU correlation time ell_t; a gap of ell_t has correlation exp(-1) | Time units |
All three default to LogNormal(0,1). Finite-mesh marginal variances depend on boundary and resolution, so its SD is a continuum parameter, not a promise of identical vertex variances. The normalized field density includes the hyperparameter-dependent determinants.
Representation and prediction
| Representation | State and replay boundary |
|---|---|
| Mesh | Vertices × fitted times × channels; three barycentric reads per observation. New coordinates may lie inside the mesh, but frozen replay requires fitted times and channels. |
neighbors=m | Local conditionals on distinct observed position–time states. Spatial and temporal covariance are approximated. Frozen replay keeps that support. |
multiresolution=m | Sparse normalized spatial basis with exact OU temporal covariance and marginal SD. Basis paths use their readers' time unions; frozen replay keeps positions and times. |
For neighbors, brm_gmrf_predict can evaluate new points. Without an RNG it returns conditional means; pass an RNG to include conditional new-point variation. These draws have pointwise conditional laws and do not supply the joint covariance needed for uncertainty in spatial totals. Observation noise is added only when predicting measurements.
The figure isolates the OU temporal factor at one location and channel, computed directly as exp(-gap / ell_t). It shows how a fixed prior correlation time changes dependence; it is not a posterior reconstruction.
{"spec":"{\"$schema\":\"https://vega.github.io/schema/vega-lite/v5.json\",\"_aov\":{\"legendInteraction\":\"highlight\"},\"_aovLegend\":{\"dimmed\":true,\"filtered\":false,\"opacity\":null,\"params\":[\"legend_selection\"],\"transform\":[]},\"config\":{\"axis\":{\"labelLimit\":0},\"header\":{\"labelLimit\":0},\"legend\":{\"labelLimit\":0}},\"data\":{\"values\":[{\"correlation\":1.0,\"gap\":0.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.9048374180359595,\"gap\":0.05,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.8187307530779818,\"gap\":0.1,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.7408182206817179,\"gap\":0.15,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.6703200460356393,\"gap\":0.2,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.6065306597126334,\"gap\":0.25,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.5488116360940265,\"gap\":0.3,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.4965853037914095,\"gap\":0.35,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.44932896411722156,\"gap\":0.4,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.4065696597405991,\"gap\":0.45,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.36787944117144233,\"gap\":0.5,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.33287108369807955,\"gap\":0.55,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.30119421191220214,\"gap\":0.6,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.2725317930340126,\"gap\":0.65,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.2465969639416065,\"gap\":0.7,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.22313016014842982,\"gap\":0.75,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.20189651799465538,\"gap\":0.8,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.18268352405273466,\"gap\":0.85,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.16529888822158653,\"gap\":0.9,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.14956861922263506,\"gap\":0.95,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.1353352832366127,\"gap\":1.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.1224564282529819,\"gap\":1.05,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.11080315836233387,\"gap\":1.1,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.10025884372280375,\"gap\":1.15,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.09071795328941251,\"gap\":1.2,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0820849986238988,\"gap\":1.25,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.07427357821433388,\"gap\":1.3,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.06720551273974976,\"gap\":1.35,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.06081006262521797,\"gap\":1.4,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.05502322005640723,\"gap\":1.45,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.049787068367863944,\"gap\":1.5,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0450492023935578,\"gap\":1.55,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.04076220397836621,\"gap\":1.6,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.036883167401240015,\"gap\":1.65,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.03337326996032608,\"gap\":1.7,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0301973834223185,\"gap\":1.75,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.02732372244729256,\"gap\":1.8,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.024723526470339388,\"gap\":1.85,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0223707718561656,\"gap\":1.9,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.02024191144580439,\"gap\":1.95,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.01831563888873418,\"gap\":2.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.016572675401761255,\"gap\":2.05,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.014995576820477703,\"gap\":2.1,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.013568559012200934,\"gap\":2.15,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.012277339903068436,\"gap\":2.2,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.011108996538242306,\"gap\":2.25,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.010051835744633586,\"gap\":2.3,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.009095277101695816,\"gap\":2.35,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00822974704902003,\"gap\":2.4,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.007446583070924338,\"gap\":2.45,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.006737946999085467,\"gap\":2.5,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.006096746565515638,\"gap\":2.55,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0055165644207607716,\"gap\":2.6,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.004991593906910217,\"gap\":2.65,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.004516580942612666,\"gap\":2.7,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.004086771438464067,\"gap\":2.75,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.003697863716482932,\"gap\":2.8,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.003345965457471272,\"gap\":2.85,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0030275547453758153,\"gap\":2.9,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0027394448187683684,\"gap\":2.95,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0024787521766663585,\"gap\":3.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0022428677194858034,\"gap\":3.05,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.002029430636295734,\"gap\":3.1,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0018363047770289071,\"gap\":3.15,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.001661557273173934,\"gap\":3.2,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0015034391929775724,\"gap\":3.25,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0013603680375478939,\"gap\":3.3,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.001230911902673481,\"gap\":3.35,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0011137751478448032,\"gap\":3.4,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0010077854290485105,\"gap\":3.45,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0009118819655545162,\"gap\":3.5,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0008251049232659046,\"gap\":3.55,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0007465858083766792,\"gap\":3.6,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0006755387751938444,\"gap\":3.65,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0006112527611295723,\"gap\":3.7,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0005530843701478336,\"gap\":3.75,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0005004514334406108,\"gap\":3.8,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00045282718288679695,\"gap\":3.85,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00040973497897978675,\"gap\":3.9,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0003707435404590882,\"gap\":3.95,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00033546262790251185,\"gap\":4.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0003035391380788668,\"gap\":4.05,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00027465356997214254,\"gap\":4.1,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00024851682710795185,\"gap\":4.15,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0002248673241788482,\"gap\":4.2,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00020346836901064417,\"gap\":4.25,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0001841057936675792,\"gap\":4.3,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00016658581098763354,\"gap\":4.35,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0001507330750954765,\"gap\":4.4,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.0001363889264820114,\"gap\":4.45,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00012340980408667956,\"gap\":4.5,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00011166580849011478,\"gap\":4.55,\"length\":\"ell_t = 0.5\"},{\"correlation\":0.00010103940183709342,\"gap\":4.6,\"length\":\"ell_t = 0.5\"},{\"correlation\":9.142423147817327e-5,\"gap\":4.65,\"length\":\"ell_t = 0.5\"},{\"correlation\":8.272406555663223e-5,\"gap\":4.7,\"length\":\"ell_t = 0.5\"},{\"correlation\":7.48518298877006e-5,\"gap\":4.75,\"length\":\"ell_t = 0.5\"},{\"correlation\":6.77287364908539e-5,\"gap\":4.8,\"length\":\"ell_t = 0.5\"},{\"correlation\":6.128349505322213e-5,\"gap\":4.85,\"length\":\"ell_t = 0.5\"},{\"correlation\":5.5451599432176945e-5,\"gap\":4.9,\"length\":\"ell_t = 0.5\"},{\"correlation\":5.017468205617528e-5,\"gap\":4.95,\"length\":\"ell_t = 0.5\"},{\"correlation\":4.5399929762484854e-5,\"gap\":5.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":4.1079555225300724e-5,\"gap\":5.05,\"length\":\"ell_t = 0.5\"},{\"correlation\":3.7170318684126734e-5,\"gap\":5.1,\"length\":\"ell_t = 0.5\"},{\"correlation\":3.363309518571897e-5,\"gap\":5.15,\"length\":\"ell_t = 0.5\"},{\"correlation\":3.0432483008403625e-5,\"gap\":5.2,\"length\":\"ell_t = 0.5\"},{\"correlation\":2.7536449349747158e-5,\"gap\":5.25,\"length\":\"ell_t = 0.5\"},{\"correlation\":2.4916009731503204e-5,\"gap\":5.3,\"length\":\"ell_t = 0.5\"},{\"correlation\":2.254493791321221e-5,\"gap\":5.35,\"length\":\"ell_t = 0.5\"},{\"correlation\":2.0399503411171922e-5,\"gap\":5.4,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.8458233995780558e-5,\"gap\":5.45,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.670170079024566e-5,\"gap\":5.5,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.5112323819855033e-5,\"gap\":5.55,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.3674196065680964e-5,\"gap\":5.6,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.2372924261788221e-5,\"gap\":5.65,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.119548484259094e-5,\"gap\":5.7,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.013009359863071e-5,\"gap\":5.75,\"length\":\"ell_t = 0.5\"},{\"correlation\":9.166087736247617e-6,\"gap\":5.8,\"length\":\"ell_t = 0.5\"},{\"correlation\":8.29381916075737e-6,\"gap\":5.85,\"length\":\"ell_t = 0.5\"},{\"correlation\":7.504557915076858e-6,\"gap\":5.9,\"length\":\"ell_t = 0.5\"},{\"correlation\":6.79040480737947e-6,\"gap\":5.95,\"length\":\"ell_t = 0.5\"},{\"correlation\":6.14421235332821e-6,\"gap\":6.0,\"length\":\"ell_t = 0.5\"},{\"correlation\":1.0,\"gap\":0.0,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.9753099120283326,\"gap\":0.05,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.951229424500714,\"gap\":0.1,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.9277434863285529,\"gap\":0.15,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.9048374180359595,\"gap\":0.2,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.8824969025845955,\"gap\":0.25,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.8607079764250578,\"gap\":0.3,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.8394570207692074,\"gap\":0.35,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.8187307530779818,\"gap\":0.4,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.7985162187593771,\"gap\":0.45,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.7788007830714049,\"gap\":0.5,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.7595721232249685,\"gap\":0.55,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.7408182206817179,\"gap\":0.6,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.7225273536420722,\"gap\":0.65,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.7046880897187134,\"gap\":0.7,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.6872892787909722,\"gap\":0.75,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.6703200460356393,\"gap\":0.8,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.6537697851298473,\"gap\":0.85,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.6376281516217733,\"gap\":0.9,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.6218850564650201,\"gap\":0.95,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.6065306597126334,\"gap\":1.0,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.5915553643668151,\"gap\":1.05,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.5769498103804866,\"gap\":1.1,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.5627048688069557,\"gap\":1.15,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.5488116360940265,\"gap\":1.2,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.5352614285189903,\"gap\":1.25,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.522045776761016,\"gap\":1.3,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.5091564206075492,\"gap\":1.35,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.4965853037914095,\"gap\":1.4,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.48432456895536247,\"gap\":1.45,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.4723665527410147,\"gap\":1.5,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.4607037809989658,\"gap\":1.55,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.44932896411722156,\"gap\":1.6,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.43823499246494924,\"gap\":1.65,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.4274149319487267,\"gap\":1.7,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.4168620196785084,\"gap\":1.75,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.4065696597405991,\"gap\":1.8,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.39653141907499284,\"gap\":1.85,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.38674102345450123,\"gap\":1.9,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.37719235356315695,\"gap\":1.95,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.36787944117144233,\"gap\":2.0,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.3587964654059516,\"gap\":2.05,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.3499377491111553,\"gap\":2.1,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.3412977553009937,\"gap\":2.15,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.33287108369807955,\"gap\":2.2,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.32465246735834974,\"gap\":2.25,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.3166367693790533,\"gap\":2.3,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.30881897968801986,\"gap\":2.35,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.30119421191220214,\"gap\":2.4,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.29375770032353277,\"gap\":2.45,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.2865047968601901,\"gap\":2.5,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.27943096822140734,\"gap\":2.55,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.2725317930340126,\"gap\":2.6,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.2658029590889266,\"gap\":2.65,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.2592402606458915,\"gap\":2.7,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.25283959580474646,\"gap\":2.75,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.2465969639416065,\"gap\":2.8,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.24050846320834213,\"gap\":2.85,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.23457028809379765,\"gap\":2.9,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.22877872704522242,\"gap\":2.95,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.22313016014842982,\"gap\":3.0,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.2176210568652329,\"gap\":3.05,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.21224797382674304,\"gap\":3.1,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.20700755268115265,\"gap\":3.15,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.20189651799465538,\"gap\":3.2,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.19691167520419406,\"gap\":3.25,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.19204990862075413,\"gap\":3.3,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.18730817948195702,\"gap\":3.35,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.18268352405273466,\"gap\":3.4,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1781730517728984,\"gap\":3.45,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.17377394345044514,\"gap\":3.5,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1694834494994701,\"gap\":3.55,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.16529888822158653,\"gap\":3.6,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.16121764412977677,\"gap\":3.65,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1572371663136276,\"gap\":3.7,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.15335496684492847,\"gap\":3.75,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.14956861922263506,\"gap\":3.8,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.14587575685622736,\"gap\":3.85,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1422740715865136,\"gap\":3.9,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.13876131224295524,\"gap\":3.95,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1353352832366127,\"gap\":4.0,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.13199384318783022,\"gap\":4.05,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.12873490358780423,\"gap\":4.1,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1255564274931972,\"gap\":4.15,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1224564282529819,\"gap\":4.2,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.11943296826671962,\"gap\":4.25,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.11648415777349697,\"gap\":4.3,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.11360815367076377,\"gap\":4.35,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.11080315836233387,\"gap\":4.4,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.10806741863482926,\"gap\":4.45,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.10539922456186433,\"gap\":4.5,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.1027969084352864,\"gap\":4.55,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.10025884372280375,\"gap\":4.6,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.09778344405135005,\"gap\":4.65,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.09536916221554961,\"gap\":4.7,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.09301448921066349,\"gap\":4.75,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.09071795328941251,\"gap\":4.8,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.08847811904208731,\"gap\":4.85,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.0862935864993705,\"gap\":4.9,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.08416299025731036,\"gap\":4.95,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.0820849986238988,\"gap\":5.0,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.08005831278672054,\"gap\":5.05,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.07808166600115317,\"gap\":5.1,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.07615382279861033,\"gap\":5.15,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.07427357821433388,\"gap\":5.2,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.07243975703425146,\"gap\":5.25,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.0706512130604296,\"gap\":5.3,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.06890682839466258,\"gap\":5.35,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.06720551273974976,\"gap\":5.4,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.06554620271802433,\"gap\":5.45,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.06392786120670757,\"gap\":5.5,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.06234947668967343,\"gap\":5.55,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.06081006262521797,\"gap\":5.6,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.05930865682943872,\"gap\":5.65,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.057844320874838456,\"gap\":5.7,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.05641613950377735,\"gap\":5.75,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.05502322005640723,\"gap\":5.8,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.053664691912730135,\"gap\":5.85,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.05233970594843238,\"gap\":5.9,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.051047434004154395,\"gap\":5.95,\"length\":\"ell_t = 2.0\"},{\"correlation\":0.049787068367863944,\"gap\":6.0,\"length\":\"ell_t = 2.0\"}]},\"encoding\":{\"color\":{\"field\":\"length\",\"scale\":{\"domain\":[\"ell_t = 0.5\",\"ell_t = 2.0\"],\"range\":[\"#2a78d6\",\"#eb6834\"]},\"title\":\"OU correlation time\",\"type\":\"nominal\"},\"opacity\":{\"condition\":{\"test\":{\"and\":[{\"or\":[\"!isValid(datum[\\\"length\\\"])\",{\"empty\":true,\"param\":\"legend_selection\"}]}]},\"value\":1},\"value\":0.15},\"tooltip\":[{\"field\":\"gap\",\"type\":\"quantitative\"},{\"field\":\"correlation\",\"type\":\"quantitative\"},{\"field\":\"length\",\"type\":\"nominal\"}],\"x\":{\"field\":\"gap\",\"scale\":{\"zero\":false},\"title\":\"Time gap\",\"type\":\"quantitative\"},\"y\":{\"field\":\"correlation\",\"scale\":{\"zero\":false},\"title\":\"Prior temporal correlation\",\"type\":\"quantitative\"}},\"height\":260,\"mark\":\"line\",\"params\":[{\"bind\":\"scales\",\"name\":\"grid\",\"select\":{\"encodings\":[\"x\",\"y\"],\"type\":\"interval\"}},{\"bind\":\"legend\",\"name\":\"legend_selection\",\"select\":{\"fields\":[\"length\"],\"type\":\"point\"}}],\"width\":500,\"description\":\"Prior OU temporal correlation at one location and channel, with fixed correlation times 0.5 (blue) and 2 (orange). At a gap equal to its correlation time, each curve equals exp(-1). These curves are computed during the build, without fitting data.\"}","caption":"Prior OU temporal correlation at one location and channel, with fixed correlation times 0.5 (blue) and 2 (orange). At a gap equal to its correlation time, each curve equals exp(-1). These curves are computed during the build, without fitting data.","alt":"Prior OU temporal correlation at one location and channel, with fixed correlation times 0.5 (blue) and 2 (orange). At a gap equal to its correlation time, each curve equals exp(-1). These curves are computed during the build, without fitting data."}All representations support full-model MCMC on RK and Stan. RK mesh fields may live in independent plate cells; the cell predictor must be 0 + gmrf, and shared channel correlation belongs outside the cell. Neighbor fields do not use that plate or embedded-Laplace surface. field_states=:units lets supported field states become SVI units; see the SVI example. Embedded Laplace is an explicit mesh integration choice. Large operator solves use a fixed-probe determinant estimate, so even a Gaussian integral can be approximate. Check the solver and probe settings against the accuracy needed for the fit. The representation notes retain the precision derivations and synthetic benchmark protocols.
Continue to the spatial-fields example for a fitted station field with its diagnostics and maps. For a continuous-time latent process fitted to discrete observations, continue to the state-space example.