Skip to content

Arrays and loops ​

Represent vectors, matrices, unequal-length groups and sequential latent states without writing an unsupported model-level loop.

Continuous elementwise families also accept matrix-shaped parameters and observations. From v0.2.37, z ~ normal(M, 1.0) infers M's matrix shape; the typed form is z::matrix[R, C] ~ normal(M, 1.0). Every argument must be a scalar or a matrix of that shape.

Vectors and matrices ​

A numeric Julia vector binds as a Stan vector when the family expects real values; an integer count response retains its integer carrier. Matrix products use *, while .*, ./ and .+ request elementwise arithmetic.

julia
using StanBlocks
matrix_model = @slic (; X=[1.0 0.2; 1.0 0.5; 1.0 0.9], y=[0.1, 0.4, 0.8]) begin
    beta::vector[2] ~ normal(0, 1)
    mu = X * beta
    y ~ normal(mu, 1)
end
show(stdout, MIME"text/plain"(), [(name=o.name, type=o.type, shape=o.dims) for o in stan_descriptor(matrix_model).outputs]); println()
4-element Vector{@NamedTuple{name::Symbol, type::Symbol, shape::Tuple{Int64}}}:
 (name = :beta, type = :vector, shape = (2,))
 (name = :mu, type = :vector, shape = (3,))
 (name = :y_likelihood, type = :vector, shape = (3,))
 (name = :y_gen, type = :vector, shape = (3,))

An annotation states the carrier and its shape. It is not a declaration that can subsequently be filled by arbitrary indexed assignments in the model body. Use a whole-object expression, a function, or one of the annotated loops below.

Independent cells ​

@plate declares independent cells conditional on their shared inputs. An indexed sampling statement introduces one latent value per cell. The collected array can be used by an observation outside the loop.

julia
independent = @slic (; y=[0.2, -0.1, 0.4]) begin
    @plate for i in eachindex(y)
        theta[i] ~ normal(0, 1)
    end
    y ~ normal(theta, 1)
end
println(stan_code(independent))
functions {
// Return the normalized log probability for a single observation.
real normal_lpdfs(
    real args1,
    int args2,
    int args3
) {
    return normal_lpdf(args1 | args2, args3);
}
// Return one normalized log probability per observation, broadcasting distribution parameters elementwise.
vector normal_lpdfs(
    vector obs,
    vector loc,
    int scale
) {
    return jbroadcasted_normal_lpdfs(obs, loc, scale);
}
vector jbroadcasted_normal_lpdfs(
    vector x1,
    vector x2,
    int 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;
}
// 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,
    vector a,
    int b
) {
    int n = anontok__1;
    if((n == 0)) {
        vector[n] rv;
        return rv;
    } else {
        return to_vector(normal_rng(a, b));
    }
}
}
data {
    int y_n;
    vector[y_n] y;
}
transformed data {
}
parameters {
    vector[num_elements(y)] theta;
}
transformed parameters {
}
model {
    for(i in 1:num_elements(y)) {
        theta[i] ~ normal(0, 1);
    }
    y ~ normal(theta, 1);
}
generated quantities {
    vector[y_n] y_likelihood = normal_lpdfs(y, theta, 1);
    vector[y_n] y_gen = normal_vector_rng(y_n, theta, 1);
}

Within a cell, an indexed left-hand side is an output available after the loop. A fresh unindexed probability statement introduces a cell-local parameter. A fresh unindexed assignment is scratch work, not an output array. Do not read another cell's output from an independent plate.

Cells can also contain vectors or matrices. Fixed matrix dimensions retain their matrix carrier inside each cell; varying dimensions use flat storage with layout metadata. Read the descriptor's dims and segments when reconstructing values instead of inferring shapes from generated variable names. The do-block spelling plate(...) do ... end broadcasts a reusable submodel; partial pooling shows that form.

For several independent axes, use one annotated loop such as @plate for j in 1:J, s in 1:S and index outputs as x[j, s]. Collecting a plate(...) do result inside an annotated loop is not supported; from v0.2.37 the error names the multiple-axis form. Likewise, observe shared data outside a loop or index it by cell, rather than repeating the entire observation in every cell.

Unequal-length groups ​

Nested vectors preserve group boundaries. For a ragged observation, the pointwise log likelihood is one aggregate value per group, while predictive values use flat storage plus group-end metadata.

julia
ragged = @slic (; y=[[0.2, -0.1], [0.4]]) begin
    mu ~ normal(0, 1)
    y ~ normal(mu, 1)
end
show(stdout, MIME"text/plain"(), [(name=o.name, role=o.generative, groups=o.segments) for o in stan_descriptor(ragged).outputs]); println()
3-element Vector{NamedTuple{(:name, :role, :groups)}}:
 (name = :mu, role = :posterior, groups = nothing)
 (name = :y_gen, role = :draw, groups = [2, 3])
 (name = :y_likelihood, role = :pointwise_loglik, groups = [2, 3])

Choose integer nested vectors for count families and real nested vectors for continuous families. A group-level likelihood cannot in general be split into independent element contributions: a multivariate family may couple the entries of the group.

Sequential states ​

@scan gives a recurrence an explicit initial state. Its trailing loop may read earlier elements at fixed lags. The observation below reads the collected state outside the recurrence.

julia
series = @slic (; y=[0.2, -0.1, 0.4], T=3) begin
    phi ~ normal(0, 0.5)
    @scan begin
        state[1] ~ normal(0, 1)
        for t in 2:T
            state[t] ~ normal(phi * state[t-1], 1)
        end
    end
    y ~ normal(state, 1)
end
check = stanc_check(stan_code(series))
@assert check.ok check.output
show(stdout, MIME"text/plain"(), [(name=o.name, shape=o.dims) for o in stan_descriptor(series).outputs if o.kind == :parameter]); println()
2-element Vector{NamedTuple{(:name, :shape)}}:
 (name = :phi, shape = ())
 (name = :state, shape = (3,))

The initial statements and loop must fill every carried element exactly once; forward reads are not allowed. When the carried variable is itself observed, its predictive twin simulates a complete new trajectory, using earlier simulated values at the lagged positions. A one-step conditional prediction from observed history is a different operation.

The partial-pooling example uses independent cells; epidemic dynamics uses a deterministic ODE function when a numerical solver, rather than a latent recurrence, defines the states.