Skip to content

Models ​

Define a model, bind observations and inspect the roles of its inputs and outputs.

Definition and binding ​

A model declaration records probability statements and deterministic relations. Calling it with keyword arguments supplies data. The following declaration becomes a likelihood for the supplied observations, while mu remains unknown.

julia
using StanBlocks
const measurement = @slic begin
    mu ~ normal(0, 1)
    y ~ normal(mu, 1)
end
posterior = measurement(; y=[0.2, -0.1, 0.4])
descriptor = stan_descriptor(posterior)
show(stdout, MIME"text/plain"(), [(name=i.name, observed=i.observed) for i in descriptor.inputs if !i.derived && !i.inlined]); println()
1-element Vector{@NamedTuple{name::Symbol, observed::Bool}}:
 (name = :y, observed = 1)

Data binding is by name. Rebinding produces another model value; it does not edit the original declaration. Supply covariates and constants through these arguments as well. Ordinary numeric variables in the surrounding Julia module are not implicit model inputs.

Probability statements ​

The left side of ~ is an observation when it has bound data and a latent quantity otherwise. A deterministic assignment introduces a named value, not another sampling step. The descriptor reports the resulting output roles.

julia
derived = Base.merge(measurement, quote
    centered = mu - 0.5
end)(; y=[0.2, -0.1, 0.4])
show(stdout, MIME"text/plain"(), [(name=o.name, block=o.kind, meaning=o.generative) for o in stan_descriptor(derived).outputs]); println()
4-element Vector{@NamedTuple{name::Symbol, block::Symbol, meaning::Symbol}}:
 (name = :mu, block = :parameter, meaning = :posterior)
 (name = :y_likelihood, block = :generated_quantity, meaning = :pointwise_loglik)
 (name = :y_gen, block = :generated_quantity, meaning = :draw)
 (name = :centered, block = :generated_quantity, meaning = :derived)

A prior whose variable cannot affect any observation is generated from its random-number generator rather than retained as an inference parameter. Prediction explains this behavior when observations are omitted or marked for replay.

The top-level body accepts probability statements, whole-value assignments, submodel calls and a return value. Independent and sequential loops use @plate and @scan. Put other conditionals, loops and local mutation inside a Stan function.

Constraints ​

Distribution support and explicit bounds determine parameter constraints. A bound on a probability statement also truncates that probability density; it is not merely an instruction to a numerical optimizer. Here the scale has a half-normal prior, and the evaluated lower bound is visible in the descriptor.

julia
scaled = @slic (; y=[0.2, -0.1, 0.4]) begin
    mu ~ normal(0, 1)
    sigma ~ normal(0, 1; lower=0)
    y ~ normal(mu, sigma)
end
sigma_output = only(o for o in stan_descriptor(scaled).outputs if o.name == :sigma)
show(stdout, MIME"text/plain"(), (name=sigma_output.name, type=sigma_output.type, bounds=sigma_output.constraint_values)); println()
(name = :sigma, type = :real, bounds = (lower = 0,))

Use restricted only when the intended model needs a bounded kernel without its truncation normalizer. That distinction matters when a bound or the mass inside it depends on another unknown quantity. A parameter with flat() or a bare typed declaration has no proper prior; it needs an identifiable likelihood and an explicit modeling justification.

Annotations such as beta::vector[k] or L::cholesky_factor_corr[k] specify a Stan carrier when inference from the probability statement is insufficient. They belong to the model language; they do not require Julia types with those names to exist. Arrays and loops shows executable container forms.

Inspection ​

stan_code returns the complete program the compiler emits. Inspect it before choosing an inference method. stanc_check checks Stan's types and syntax; it does not prove that a distribution has the intended support or that a fit is informative.

julia
code = stan_code(scaled)
check = stanc_check(code)
@assert check.ok check.output
println(code)
functions {
// Return one normalized log probability per observation, broadcasting distribution parameters elementwise.
vector normal_lpdfs(
    vector obs,
    real loc,
    real scale
) {
    return jbroadcasted_normal_lpdfs(obs, loc, scale);
}
vector jbroadcasted_normal_lpdfs(
    vector x1,
    real x2,
    real x3
) {
    int n = dims(x1)[1];
    vector[n] rv;
    for(i in 1:n) {
        rv[i] = normal_lpdfs(broadcasted_getindex(x1, i), x2, x3);
    }
    return rv;
}
// Return the normalized log probability for a single observation.
real normal_lpdfs(
    real args1,
    real args2,
    real args3
) {
    return normal_lpdf(args1 | args2, args3);
}
// Read element i of a container used in elementwise broadcasting.
real broadcasted_getindex(vector x, int i) {
    return x[i];
}
// Draw independent values of the requested size, broadcasting scalar parameters and preserving the requested container type.
vector normal_vector_rng(
    int anontok__1,
    real a,
    real b
) {
    int n = anontok__1;
    if((n == 0)) {
        vector[n] rv;
        return rv;
    } else {
        return to_vector(normal_rng(rep_vector(a, n), b));
    }
}
}
data {
    int y_n;
    vector[y_n] y;
}
transformed data {
}
parameters {
    real mu;
    real<lower=0> sigma;
}
transformed parameters {
}
model {
    mu ~ normal(0, 1);
    sigma ~ normal(0, 1);
    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);
}

The golf example checks a bounded scale parameter's Stan density against an independently evaluated likelihood before interpreting its posterior.