Skip to content

Composition ​

Reuse a probabilistic component inside another model and change one assumption without maintaining another complete program.

Submodels ​

An anonymous @slic block receives inputs by keyword and can return a value. At a call site, ~ includes the component's parameter and density statements; the returned value becomes the caller's left-hand side.

julia
using StanBlocks
const standardized_effect = @slic begin
    z ~ normal(0, 1)
    return location + scale * z
end
const regression = @slic begin
    slope ~ standardized_effect(; location=0.0, scale=1.0)
    y ~ normal(slope * x, 1)
end
model = regression(; x=[-1.0, 0.0, 1.0], y=[-0.8, 0.1, 1.2])
show(stdout, MIME"text/plain"(), [(name=o.name, block=o.kind) for o in stan_descriptor(model).outputs]); println()
4-element Vector{@NamedTuple{name::Symbol, block::Symbol}}:
 (name = :slope_z, block = :parameter)
 (name = :slope, block = :transformed_parameter)
 (name = :y_likelihood, block = :generated_quantity)
 (name = :y_gen, block = :generated_quantity)

The returned slope is a deterministic transformation of the component's standard-normal parameter. Its internal parameter receives a namespace from the receiving name, so using the component twice introduces two sets of latent quantities. Shared inputs are passed explicitly at both call sites.

A named submodel can instead declare positional inputs. Its body still defines a probabilistic component, rather than a deterministic Stan function.

julia
@slic offset_effect(location::real) = begin
    deviation ~ normal(0, 1)
    return location + deviation
end
positional = @slic (; y=[0.2, -0.1]) begin
    mu ~ offset_effect(0.5)
    y ~ normal(mu, 1)
end
println(stan_code(positional))
functions {
// Return one normalized log probability per observation, broadcasting distribution parameters elementwise.
vector normal_lpdfs(
    vector obs,
    real loc,
    int scale
) {
    return jbroadcasted_normal_lpdfs(obs, loc, scale);
}
vector jbroadcasted_normal_lpdfs(
    vector x1,
    real x2,
    int 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,
    int 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,
    int 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_deviation;
}
transformed parameters {
    real mu = (0.5 + mu_deviation);
}
model {
    mu_deviation ~ normal(0, 1);
    y ~ normal(mu, 1);
}
generated quantities {
    vector[y_n] y_likelihood = normal_lpdfs(y, mu, 1);
    vector[y_n] y_gen = normal_vector_rng(y_n, mu, 1);
}

Use a module-level const binding for a reusable component that should retain its identity. Definitions in another module retain their defining scope; import the component into the caller and supply its inputs through the call.

A component may also bind its own observed data with @slic (; obs=values). From v0.2.37, calling it as s ~ component() observes those values under the scoped name s_obs, with the usual predictive and likelihood outputs. This also covers partly-missing vectors and observations indexed by an annotated loop inside the component. An outer plate cannot repeat that whole observation in every cell: observe it outside that plate or index the data by cell.

Replacement ​

Base.merge with a quoted statement replaces the declaration with the same left-hand-side name. Here the observation family changes while the slope's component and prior remain shared.

julia
robust_regression = Base.merge(regression, quote
    y ~ student_t(4, slope * x, 1)
end)
robust = robust_regression(; x=[-1.0, 0.0, 1.0], y=[-0.8, 0.1, 1.2])
println(stan_code(robust))
functions {
// Return one normalized log probability per observation, broadcasting distribution parameters elementwise.
vector student_t_lpdfs(
    vector obs,
    int nu,
    vector loc,
    int scale
) {
    return jbroadcasted_student_t_lpdfs(obs, nu, loc, scale);
}
vector jbroadcasted_student_t_lpdfs(
    vector x1,
    int x2,
    vector x3,
    int x4
) {
    int n = dims(x1)[1];
    vector[n] rv;
    for(i in 1:n) {
        rv[i] = student_t_lpdfs(broadcasted_getindex(x1, i), x2, broadcasted_getindex(x3, i), x4);
    }
    return rv;
}
// Return the normalized log probability for a single observation.
real student_t_lpdfs(
    real args1,
    int args2,
    real args3,
    int args4
) {
    return student_t_lpdf(args1 | args2, args3, args4);
}
// 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 student_t_vector_rng(
    int anontok__1,
    int nu,
    vector a,
    int b
) {
    int n = anontok__1;
    if((n == 0)) {
        vector[n] rv;
        return rv;
    } else {
        return to_vector(student_t_rng(nu, a, b));
    }
}
}
data {
    int y_n;
    vector[y_n] y;
    int x_n;
    vector[x_n] x;
}
transformed data {
}
parameters {
    real slope_z;
}
transformed parameters {
    real slope = (0.0 + (1.0 * slope_z));
}
model {
    slope_z ~ normal(0, 1);
    y ~ student_t(4, (slope * x), 1);
}
generated quantities {
    vector[y_n] y_likelihood = student_t_lpdfs(y, 4, (slope * x), 1);
    vector[y_n] y_gen = student_t_vector_rng(y_n, 4, (slope * x), 1);
}

This is a structural change to the model. It differs from binding observations, which retains the probability statement and uses the supplied value in its density. Replacing a latent declaration with a fixed value instead removes that declaration from the model.

julia
fixed = Base.merge(regression, (; slope=0.8))(; x=[-1.0, 0.0, 1.0], y=[-0.8, 0.1, 1.2])
show(stdout, MIME"text/plain"(), [o.name for o in stan_descriptor(fixed).outputs if o.kind == :parameter]); println()
Symbol[]

The empty parameter list is the intended result: the fixed slope no longer introduces its component's standard-normal parameter. A fixed value remains an input to the observation density.

Composition does not choose a parameterization or establish identifiability. Compare the statistical assumptions and their predictive consequences, rather than treating two generated programs as evidence of equivalent inference. Partial pooling uses one school component across independent cells and verifies the resulting joint density.