Skip to content

Public API ​

Declaring models ​

Build a model from a declaration and bind its data. See Model syntax.

BayesianRegressionModels.@brm Macro
julia
@brm formula_block
@brm df formula_block

Parse a brms-style formula block into a BRMI (BRM Intermediate).

The one-argument form returns a function model(df) -> BRMI (the model name is gensym-ed). The two-argument form bakes df in and returns the BRMI directly. Inside formula_block, each line is one of:

  • lhs ~ rhs — a sampling statement (likelihood or linear predictor).

  • (x, y, z) ~ rhs — broadcast one RHS over several sampling LHSs, sugar for repeating the ~ row once per name. Each slot takes one ordinary sampling LHS; [y1, y2] ~ ... stays the joint multivariate response.

  • lhs = rhs — a literal binding (named intermediate).

  • @plate for i in eachindex(x) ... end — a group-local kernel cell. Reads such as x[i] are sliced per group, result[i] = ... declares a model-scope output, and bare assignments remain cell locals.

  • rows = groups(event_subject => subject) — a model-scope binding: for each entry of subject, the indices of event_subject that hold it. A @plate for i in … cell reads a vector at them, x[rows[i]], and observes y[rows[i]] ~ …; @plate for p in groups(g; order = t) iterates the groups of g itself (see groups).

  • effect(lp, coefficient) ~ Normal(location, scale) — an SBBRMI population-coefficient prior override.

  • sd(lp, ID[, coefficient]) ~ Exponential(scale) and cor(:, ID) ~ LKJCholesky(K, eta) — priors for a shared |ID| random-effect block; a block written without an ID is addressed by its grouping column (sd(lp, g), cor(lp, g), see effect).

Multiple ~ lines produce a multi-response / distributional model. Inside an observed family's argument expression, nested @brm(expr) is the explicit opt-in for a coefficient-bearing predictor formula. Unmarked family arguments remain ordinary expressions.

julia
brmi = @brm df begin
    y ~ Normal(loc, err)
    loc ~ 1 + age + (1 | subj)
    err ~ Exponential(1)
end

The resulting BRMI feeds either backend: SBBRMI(brmi) (StanBlocks → Stan) or RKBRMI(brmi) (ReactiveKernels → RKPPL).

source
BayesianRegressionModels.@getproperty Macro
julia
@getproperty obj.field

Expands to hasproperty(obj, :field) ? obj.field : :field — used by the @brm df-baked path to fall back from "column from the dataframe" to "bare symbol" without erroring on missing columns.

source
BayesianRegressionModels.@n Macro
julia
@n lhs = rhs

Lower a parsed-formula LHS into a NamedColumn binding. Used internally by @brm; not normally called by hand.

source
BayesianRegressionModels.@x Macro
julia
@x expr

Lower a parsed-formula RHS into the column-type tree (ExprColumn / NamedColumn). Used internally by @brm; not normally called by hand.

source
BayesianRegressionModels.AbstractColumn Type
julia
AbstractColumn

Supertype of every column-shape token the @brm parser produces. Subtypes include MissingColumn, DataColumn, NamedColumn, ExprColumn, MultiMembershipTerm, and LikelihoodColumn.

Backend dispatchers (_sb_emit!, the RK emitter, the introspection walkers) branch on this hierarchy rather than on Symbol tags.

source
BayesianRegressionModels.BRMBuilder Type
julia
BRMBuilder

What @brm begin … end returns when no data is given: a model builder. Call it on a data frame, builder(df), to get the BRMI; every API that takes a builder (brm_descriptor(builder, df), generative_plan(builder, df), …) accepts it unchanged. It keeps the authored source, so a model can be inspected and composed before any data exists:

  • brm_columns(builder) lists the data columns the model reads;

  • merge(a, b, …) concatenates the fragments' sources into one builder;

  • structure_of(builder) and priors_of(builder) split the source into the model and its prior-address statements, each a builder;

  • show(builder) prints the source.

brm(expr; mod) returns the same builder for a source Expr without evaluating code, so a model family can be assembled from interpolated Expr fragments at run time, in a precompile workload or from code compiled before the family existed.

source
BayesianRegressionModels.BRMComponent Type
julia
@brm function name(inputs...)
    # BRM declarations, local to each call
    return value
end

A reusable BRM component with explicit inputs and a returned value. Embed it with value ~ name(inputs...). Each call owns its declarations; its arguments refer to the parent's values. Both StanBlocks and ReactiveKernels lower the same component through their native submodel scopes.

A component may return several named values as a named tuple, return (; recovery, decay = exp(log_decay)). The parent then reads each one as a property of the call, kin.recovery, with its own row axis; the call's priors and correlations remain one scope.

The short definition @brm model(df) = begin … end retains its existing meaning: a data-to-model builder.

source
BayesianRegressionModels.BRMI Type
julia
BRMI(; ops...)
BRMI(operations::NamedTuple)

BRM Intermediate — the parsed formula. operations is a NamedTuple mapping each LHS name to its NamedColumn. The two backends SBBRMI and RKBRMI walk this representation.

A BRMI is what @brm ultimately returns (either directly, when df is baked in, or by calling the gensym'd model function on a dataframe). Introspect via outcomes / linear_predictors / predictors / grouping_factors / dependencies / data_columns.

source
BayesianRegressionModels.Data Type
julia
Data(df)

Wrapper that exposes every column of the underlying DataFrame as a NamedColumn over a DataColumn. Used by @brm to lift df columns into the formula's column-type universe.

source
BayesianRegressionModels.DataColumn Type
julia
DataColumn(vec)

Wraps an observed vector from the dataframe. Surfaces as the leaf of a NamedColumn for any data-backed predictor or response.

source
BayesianRegressionModels.ExprColumn Type
julia
ExprColumn(f, args...; kwargs...)

Represents an f(args...; kwargs...) formula RHS — the leaves the @brm parser builds for every :call Expr (e.g. Normal(loc, err), 1 + a + (1|g), mo(c)). Access via getf / getargs / getkwargs / getop.

Construction runs _check_term_kwargs so a term can reject a retired keyword at the @brm call site rather than in the backend.

Only the function is a type parameter, so methods dispatch on the term (ExprColumn{typeof(hsgp)}). The arguments and keywords are not: as parameters they spelled the whole expression tree below a node in its type, and through NamedColumn references the trees of every value it reads, so a large model's columns had types of hundreds of kilobytes and its build and planning compiled each method that touches them once per tree (about ten minutes on a 479-statement model, snag rkbrmi-start-up-8ed0a306).

source
BayesianRegressionModels.LikelihoodColumn Type
julia
LikelihoodColumn(parent, rhs)

Pairs an observed-response parent (NamedColumn over a DataColumn) with its distributional rhs.

source
BayesianRegressionModels.MaybeData Type
julia
MaybeData(df)

Like Data, but for columns that may not be present in the dataframe. Missing columns surface as NamedColumn wrapping a MissingColumn — i.e. a parameter to be sampled rather than observed.

source
BayesianRegressionModels.MissingColumn Type
julia
MissingColumn()

LHS marker for response columns that aren't in the dataframe — the backend treats them as parameters rather than observations.

source
BayesianRegressionModels.NamedColumn Type
julia
NamedColumn(name, parent)

Assigns a formula-local symbol name to its parent column. Every lhs ~ rhs and lhs = rhs line produces a NamedColumn keyed by lhs. Access via name / parent.

The parent's type is not a type parameter: a reference to a named value holds its whole definition, so a parameter would spell that definition's expression tree in the type of every column that reads the name, and every method that touches such a column would compile once per tree (see ExprColumn).

source
BayesianRegressionModels.brm Function
julia
brm(source::Expr; mod::Module) -> BRMBuilder
brm(source::AbstractString; mod::Module) -> BRMBuilder
brm(df, source; mod::Module) -> BRMI

The model builder of a @brm block given as a value, without evaluating code. brm(source; mod) returns the BRMBuilder that @brm begin … end written in module mod returns; brm(df, source; mod) builds it on df. Names the block reads that are not formula names (distribution and term constructors, user functions, the inputs of name = constant(expr) that are not data fields) resolve as globals of mod. A local value enters the block by interpolation, $value, as in any Expr.

julia
covariates = (:weight, :age)
rhs = Expr(:call, :+, 1, covariates..., :((1 | p | subject)))
model = brm(quote
    log_CL ~ $rhs
    sigma ~ Exponential(1)
    conc ~ Normal(log_CL, sigma)
end; mod=@__MODULE__)
fit = SBBRMI(model(df); mod=@__MODULE__)

No method is defined and no code is compiled for the model, so a builder can be made at run time, in a precompile workload, or from code compiled before the model existed, and merge of builders is brm of their joined sources. A named function definition, f(df) = begin … end, is not a builder value: write that with @brm.

source
BayesianRegressionModels.brm_components Function
julia
brm_components(model::BRMI)
brm_components(builder::BRMBuilder, data)
brm_components(component::BRMComponent)

Discover recursively included BRM component calls from the authored model. Each record contains path (the call's logical scope), definition (the shared BRMComponent object), source (a copy of its authored function expression), scope (its defining module), and call (a copied call expression, without bound data values). Repeated calls have separate paths and share their definition identity. For a component definition itself, the first record has path () and no call. No backend compilation or manually maintained source registry is required.

source
BayesianRegressionModels.getargs Function
julia
getargs(x::ExprColumn) -> Tuple
getargs(x::ExprColumn, n) -> Tuple

The positional args of an ExprColumn. The two-arg form asserts length == n. Plus helpers for +-flattening: getargs(+, x::ExprColumn{typeof(+)}) returns the summands; getargs(+, x) wraps non-+ shapes as a 1-tuple.

source
BayesianRegressionModels.getf Function
julia
getf(x::ExprColumn) -> F

The callable head of an ExprColumn — e.g. Normal, +, ~, assign, mo. Sole dispatch tag for backend emitters.

source
BayesianRegressionModels.getkwargs Function
julia
getkwargs(x::ExprColumn) -> NamedTuple

The keyword args of an ExprColumn. E.g. hsgp(x; k=20, c=1.5) exposes (; k=20, c=1.5).

source
BayesianRegressionModels.getop Function
julia
getop(x) -> Symbol_or_Function

Symbolic operator name for an ExprColumn: :|| for the doublepipe marker, :(=) for assign, otherwise falls through to getf. Used by the HTML renderer to print formula RHS with the original operator surface.

source
BayesianRegressionModels.maybedata Function
julia
maybedata(df) -> MaybeData

Convenience constructor for MaybeData. Used by @brm to surface response-side names that may be data (observed) or parameters (sampled).

source
BayesianRegressionModels.name Function
julia
name(x::NamedColumn) -> Symbol

Return the formula-local name assigned to x (i.e. the LHS of the ~ / = line that produced it).

source

Fitting ​

Choose a backend, construct an inference problem and retain fitted state. See Backends and Adaptive centering.

BayesianRegressionModels.AbstractAdaptiveCenteringBlock Type
julia
AbstractAdaptiveCenteringBlock

Supertype of the random-effect blocks adaptive_centering_blocks returns: AdaptiveCenteringBlock for a block whose marginal scales are sampled coordinates, R2D2AdaptiveCenteringBlock for one whose scales an R2D2 prior derives. Both carry ranef, target_c, effects and cholesky_free with the same meaning, and _adaptive_block_cholesky(x, block) rebuilds diag(tau) * L for either.

source
BayesianRegressionModels.AdaptiveCenteringBlock Type
julia
AdaptiveCenteringBlock

The unconstrained-coordinate description needed to adapt one ordinary random-effect block without parsing generated Stan.

  • ranef is BRM's emitted RanefBlock.

  • target_c is the parametrization of the compiled model: 0.0 for BRM's standardised z emission and 1.0 for a centered_groups= emission.

  • effects[k,g] indexes term k, group g in the compiled model's unconstrained vector.

  • cholesky_free indexes Stan's K(K-1)/2 unconstrained values for a correlated block's cholesky_factor_corr[K] L; it is empty at K=1.

  • log_scales indexes the unconstrained values underlying the positive scale: tau for a correlated emission, log_scale for the (1 | g) fast path, or one stratum's column of the sampled tau_s_tau for a stratum of a gr(g, by=b) block.

Construct with adaptive_centering_blocks. Indices are resolved by name against the caller-supplied unconstrained-name vector; no ordering of the whole parameter vector is assumed.

source
BayesianRegressionModels.BRMCoordinatePair Type
julia
BRMCoordinatePair

One sampled coordinate shared by an RKBRMI and an SBBRMI of the same BRMI:

  • address — the semantic address both backends agree on, e.g. (; kind=:population, predictor=:mu, coefficient=:x) or (; kind=:ranef_z, group=:subject, id=:effect, level=3, margin=(:mu, :x)), or a Student-t block's per-level weight (; kind=:ranef_mixing, …, level=3);

  • rk / stan — the RK layout coordinate name and the Stan unconstrained parameter name;

  • rk_declaration / rk_index — the RK declaration's complete scope path (e.g. pop_mu.beta_pop) and the element of its constrained value that the coordinate parameterizes;

  • relation — how the constrained values correspond: :identity (equal), :exp (the RK value is exp of the Stan value, e.g. a random-intercept scale against Stan's log_scale), :cholesky (a correlation-factor coordinate; the whole factors are compared, see brm_check_coordinate_transport), :simplex (one free coordinate of a simplex block; see below), :centered (one standardized draw of a centered random-effect block; see below), or :shares (one coordinate of a T::shares(total) cell latent: the same coordinate on both sides, whose latent's values are compared cell by cell), or :grouped_shares (one coordinate of the grouped entries of a mi(x)::shares(total, rows) completion: the same coordinate on both sides, whose missing entries are compared), or :completion (one standardized draw z of a non-centered missing-value completion against the Stan entry s = location + scale * z of the same position; see below), :bounded_completion (the same support-unconstrained coordinate on both sides, with the computed value compared: lower + exp(z), or the support transform of a non-centered completion law with no location and scale), or :car_separated (one coordinate of a car(...) field lowered by its unit border separator, RKBRMI(brmi; car_units): a shared or unit draw on RK against one area of Stan's field; see below);

  • stan_value — the Stan constrained parameter name holding the physical value this coordinate parameterizes. It equals stan except inside a Stan array of vectors, whose unconstrained values BridgeStan stores array-major while param_unc_names lists the same block first-index-fastest, so the name at a position can belong to another element.

In the :identity, :exp, :cholesky, :shares, :grouped_shares and :bounded_completion relations the two UNCONSTRAINED values are equal, so those coordinates move by a permutation. A :simplex block has the same physical simplex on both sides but different free coordinates: RK samples stick-breaking fractions σ(u[j] + log(K-j)), while Stan samples the inverse isometric log-ratio transform. Its j-th RK and Stan coordinates are paired only as block positions; the block moves through the nonlinear map recorded in BRMCoordinateTransport.simplexes. A :centered pair joins RK's standardized draw z of one (level, margin) with the effect b of the same (level, margin) that a centered SB block (centered_groups) samples. At each point b = diag(tau) * L * z per level (times sqrt(w) of the level's mixing weight for a Student-t block), with that point's scales tau, correlation factor L and weights, so the block moves through the map recorded in BRMCoordinateTransport.centered. A :completion pair joins RK's standardized draw z of one missing entry (RKBRMI(brmi; completions = :noncentered)) with Stan's unconstrained entry of the same position, s = location + scale * z at that point's location and scale (the value under Normal, its log under LogNormal), so the part moves through the map recorded in BRMCoordinateTransport.completions. A :car_separated pair joins one of RK's standardized draws of a separated field (its shared draws w, then each unit's draws z_u) with one area of Stan's field phi (graph order), as block positions only: the whole field moves through the exact linear map the separation defines, phi = vcat((F w)[x_phi], phi_I_1, …)[restore] with each unit's interior from its draws and shared values (t.fields).

source
BayesianRegressionModels.BRMCoordinateTransport Type
julia
BRMCoordinateTransport

The validated coordinate correspondence returned by brm_coordinate_transport. rk_names and stan_names are the two complete coordinate lists, pairs holds one BRMCoordinatePair per coordinate in RK order, and permutation matches positions: stan_names[i] is paired with rk_names[permutation[i]]. correlations lists each paired correlation factor (rk_declaration, stan_carrier, dimension K) for the whole-factor physical check. A random-effect factor also carries its group, id and ordered predictor/coefficient margins; one stratum's factor of a stratified gr(g, by = b) block adds by, the stratum label, its slice rk_index of the RK declaration and its index stan_index into the Stan carrier's array. A factor declared by a submodel provider carries its target and declaration.

simplexes lists each :simplex block: its semantic address, rk_declaration, stan_carrier, simplex length K, and the block's rk_positions / stan_positions (the K-1 free coordinates, in element order). logdensity_offset is the constant -sum(log(K) / 2 for each simplex): at transported points the RK log density equals Stan's normalized log density with Jacobian (propto=false, jacobian=true) plus this offset, because the two simplex transforms' log-Jacobians are sum(log, x) and sum(log, x) + log(K)/2.

centered lists each centered SB random-effect block: its group, id, ordered margins, SB binding and effect carrier stan_carrier, margin count K, level count G, the RK coordinates of its scales (rk_scales, one per sampled margin scale_margins, log scales), of its correlation factor (rk_cholesky, empty for K == 1 or a known correlation) and, for a Student-t block, of its mixing weights (rk_mixing, one per SB level, log weights; empty otherwise), the known values (known_scales, nothing at a sampled margin, and the known Cholesky factor known_L or nothing; sd(...) = value, cor(:, ID) = R, which enter the map as constants), and the K × G matrices rk / stan of standardized-draw and effect coordinates by (margin, SB level), with their positions (scale_positions, cholesky_positions, mixing_positions, rk_positions, stan_positions). stan_values names each effect's constrained Stan value. The block's density offset depends on the point: at transported points the RK log density equals Stan's plus logdensity_offset plus G * log(det(diag(tau) * L)) per centered block (plus K/2 * sum(log, w) for a Student-t block), the log-Jacobian of z -> b; use brm_stan_logdensity_to_rk. Reading logdensity_offset from a transport with a centered block is an error naming that function.

completions lists each standardized missing-value completion part (an RKBRMI(brmi; completions = :noncentered) completion, or the free entries of its mi(x)::shares(total, rows)): its target column, RK draw declaration rk_declaration, SB entries stan_carrier, law (Normal or LogNormal), the scoped RK names of its location, scale and value, and its RK draws rk / SB entries stan with their positions. At each point SB's unconstrained entries are s = location .+ scale .* z (the values under Normal, their logs under LogNormal) with that point's location and scale, which RK computes and may read any coordinate; at transported points the RK log density equals Stan's plus the log-Jacobian sum(log, scale) over the part's entries.

fields lists each car(...) field lowered by its unit border separator (RKBRMI(brmi; car_units)): its address, area column area, RK declaration rk_declaration and field value value, its separation, and the RK coordinates rk (the shared coordinates, then each unit's draws) and Stan field entries stan (graph order) with their positions. Points move through the separation's linear map and its inverse, gradients through its transpose; the map's log-Jacobian is constant and in logdensity_offset, which adds, per field, -(n/2) log(2π) + Σ_c (log(0.001 n_c) + log(2π)/2) over its components of n_c areas, n its unit draws and components with a separator (RK's draws and component totals are standard normals whose unit terms cancel the differences' densities, Stan's field the unnormalized ICAR with a normalized Normal(0, 0.001 n_c) per component sum).

With no simplex, centered block, standardized completion or separated field, stan_u == rk_u[permutation] for points and gradients alike (brm_rk_to_stan, brm_stan_to_rk) and logdensity_offset == 0. Otherwise points and gradients move differently: use brm_rk_point_to_stan, brm_stan_point_to_rk, brm_stan_gradient_to_rk and brm_stan_logdensity_to_rk.

source
BayesianRegressionModels.BRMCoordinateTransportError Type
julia
BRMCoordinateTransportError <: Exception

A known boundary of the semantic brm_coordinate_transport. reason is :unsupported_coverage when the semantic inventory does not cover the model, or :parameterization_mismatch when a known correspondence is not one of the transport's relations (for example, exact-total blocks or a reordered correlation factor). message::String retains the diagnostic rendered by showerror.

Neither reason returns a partial map or permits a matched timing comparison. Other failures, including invalid inputs and failed physical checks, propagate normally; do not classify arbitrary exceptions as missing transport coverage.

source
BayesianRegressionModels.BRMCutFamily Type
julia
BRMCutFamily

The downstream conditionals of a cut posterior, one per upstream draw, on one compiled RK program (from brm_cut_family).

  • targets[k]: a LogDensityProblems target (density and gradient) in the downstream coordinates names, conditional on upstream draw k.

  • upstream[:, k]: that draw, in the upstream fit's unconstrained coordinates upstream_names.

  • starts[k], features[k]: a start point for target k, and the draw's coordinates as a vector a family sampler can compare conditionals by.

  • joint_names: the joint model's coordinates, when the family can place its draws there (nothing otherwise).

source
BayesianRegressionModels.BRMFilter Type
julia
BRMFilter

An RK-only finite-state filter. state exposes the conditional particle clouds, fixed-parameter masses, predictive log score, accumulated log normalizer and bounded diagnostics. The filter retains its compiled target and finite state, not its original RKBRMI, training rows or consumed stream.

Treat the target, state and returned arrays as read-only. Each successful step returns a new filter; a failed step leaves its input usable.

source
BayesianRegressionModels.BRMFilterSMC Type
julia
BRMFilterSMC

Bounded-window parameter learning over an authored finite-state filter. Construct with brm_filter(completed_smc_fit; learn=true, ...), or with a brm_smc_carry(fit; parameters=:filter, inputs=...) calibration and a model. The native parameter ensemble, conditional state clouds and bounded window live in state. The calibration retains no historical latent coordinates. state.positions contains unconstrained member columns and state.parameter_mass their normalized weights. state.records is the bounded window; state.history reports ESS, replenishment and proposal diagnostics. Accumulate each step's latest replenished flag to count lifetime events; summing bounded history counts only its retained steps.

Window boundaries replace the posterior with independent Gaussian parameter marginals and a weighted state pool. This assumed-density approximation loses parameter correlations and parameter–state dependence; it is not exact full-history SMC². Treat all fields as read-only.

source
BayesianRegressionModels.BRMFittedState Type
julia
BRMFittedState

The frozen preprocessing of a fitted RKBRMI, without its training rows: what brm_fitted_state returns. It holds

  • fitted: the values the emitted program computes from its fit-role inputs (center/zscale/standardize means and SDs, group level sets, HSGP intervals, …), by the name the program reads them under, as RKPPL's frozen_values record (fitted.values). The record also holds the element type and size of each fit-role input, never its values;

  • fitted_reads and fit_twins: the fit-role inputs each fitted value is fitted from, and the data column each fit-role input copies, so a replay that resamples a grouping refits that grouping's values from its own data;

  • fits: the fits the planner computes in Julia (factor and mo level sets, spline fits), keyed by what they fit;

  • constants: the name = constant(expr) values;

  • scalars: numeric scalar data inputs, including prior arguments and inputs of constant(...), and the data arrays only a prior reads. Omitted fields take these fitted values; a supplied prior argument must equal its fitted value, literal or read by name in the program;

  • declaration: the authored model (show(brm_source(rk))), which a replay's model must repeat;

  • program: the fit's emitted program, which a replay must reproduce. A statement an earlier BRM wrote in another form of the same program (macro calls with their places, a ragged join's columns as trailing arguments) is read in this BRM's form (_rk_stored_statement), so the state replays unless its program changed otherwise;

  • coordinates: the names of the fit's unconstrained coordinates;

  • columns: the element type of each data column of the fit (a scalar's type);

  • responses: the responses the fit conditions on;

  • held_out: the fit's response hold-outs.

Level sets include the group labels of the fitted subjects; means, SDs, level sets and basis fits are summaries of the training data, never its rows. It round-trips through Serialization.

source
BayesianRegressionModels.BRMLaplacePlan Type
julia
BRMLaplacePlan

Which latent terms of a model brm_laplace_problem integrates, from brm_laplace_plan. plan.terms holds one entry per latent term (random-effect block, cdar walk, car field or declared vector): its declaration, grouping, kind, class (:integrated, :gated, :sampled or :never), reason, whether it is admitted (integrated by the problem), and for a gated term its importance_ess ((; min, median, below, blocks, draws)) or nothing. plan.ess_floor is the floor, a fraction of draws. Pass a plan as brm_laplace_problem(rk; integrate = plan) to integrate exactly its admitted terms; brm_laplace_plan's integrate and sample override the classes. A generated plan retains its preparation: applying it to the same rk with the same ad_backend copies the prepared workspaces without preparing the observations again, including when only some candidate terms are admitted. Each returned problem has independent mutable state. Keep the backend's inputs unchanged while using the plan; another backend or AD configuration is prepared afresh. This is an in-process reuse contract: diagnostic exports and reconstructed plans do not retain a portable cache of compiled factors.

source
BayesianRegressionModels.BRMLaplaceProblem Type
julia
BRMLaplaceProblem
brm_laplace_problem(backend::RKBRMI; ad_backend, subject_group=nothing,
    nested_groups=NamedTuple(), shared_groups=(), unit_partition=:subjects, tol=1e-24, maxiter=200,
    structured=:auto, integrate=nothing, max_cell_width=128,
    solver=:auto, matrixfree=MatrixFreeLaplace(), progress=nothing)

Integrate every unit's standardized random effects out of an RK-lowered model by a Laplace approximation at their conditional mode, leaving the population coordinates for HMC. The units, and which coordinates are their random effects, are the partition of brm_nlme_view; every other packed coordinate (population coefficients, scalars, shared latents and the random-effect scales and correlation factors) is a population coordinate.

The returned problem implements the LogDensityProblems interface (order 1) over the population coordinates, in packed order (problem.names). Its log density is the Laplace approximation of the model's marginal log posterior density in those unconstrained coordinates, exact when the model is Gaussian in the random effects and exact determinant algebra is selected (see solver below). Each evaluation finds every unit's mode by continuation from the prior: it starts the effects at their prior's mode and follows each unit's mode while the likelihood's weight rises from 0 to 1 in 10 stages (one stage for a sparse component or structured unit whose density is known to be log-concave). Each stage uses Newton's method with a per-unit backtracking line search, until every unit's Newton decrement gᵀ(−H)⁻¹g is at most tol, or stops shrinking at rounding level. The log determinant moves with the modes to first order; the standardized draws' N(0, I) prior makes −H ≥ I for log-concave likelihoods, so the default tol keeps the modes to about 1e-12. The gradient comes from the implicit-function theorem with third-derivative contractions of the model density.

Two kinds of population point have log density -Inf, which a sampler treats as a divergent step, as at the extreme points a diverging warm-up trajectory reaches:

  • the model's density, gradient or unit Hessians overflow during the mode search, so that no finite Newton step exists (the full model's density there is not finite either); problem.nonfinite counts them;

  • a stage of the mode search has not converged after maxiter Newton steps (default 200), as when a start lies far up an exponential's slope, where Newton gains about one unit per step; problem.unconverged counts them, and a warning names the point, the unit and its last decrements. At a point a sampler would accept this marks a defect.

A mode search must not depend on preceding evaluations: in a non-concave conditional density, a warm start can select a different local maximum and change the target. Continuation from the prior defines a single-mode approximation at the mode connected to the prior's mode, which changes only where that mode ceases to exist; the marginal can jump there. problem.folds counts evaluations whose followed mode needed a modified Newton step after the first stage. This does not sum over multiple conditional modes or guarantee a global maximum.

A problem holds the last result and prepared AD workspaces as mutable state: use one per chain (deepcopy gives a copy its own prepared AD workspaces). A call at the same population point as the last mode search (bit for bit), such as an optimizer's value and then gradient at one point, reuses that search instead of repeating it, and returns what a new search would; the counters above count it once. A copy starts without it.

When every likelihood term's parameters depend on its unit's random effects only through linear predictors (Poisson-log, Bernoulli/binomial-logit, negative-binomial with log mean and log shape, Normal; unweighted, uncensored, flat groupings), the problem is a BRMStructuredLaplaceProblem: each unit's mode is its own Newton search on its own rows from closed-form per-row derivatives, and the gradient is one reverse sweep of the likelihood parameters. Otherwise it is a BRMLaplaceProblem, which differentiates the whole model. structured=true requires the first (refusing with the reason), false forces the second.

A BRMLaplaceProblem assembles the units' Hessians from η Hessian-vector products and its gradient from third-order contractions, each one pass over the whole model. By default it takes one of each per within-unit position, so their number follows the largest unit. With unit_partition = :connected, a unit can join many subjects through a few effects they all read (one site's effect read with every path through the site), and it then takes one product per color of a star coloring of its likelihood cells' structural supports, and two contractions per color: their number follows the effects one cell couples, not the unit's size. It falls back to positions where they are fewer.

Declared independent Gaussian vectors can also be named by declaration, e.g. integrate = (:field,) for field[1:n] .~ Normal.(mean, scale). Their means and scales can depend on outer coordinates; each element retains its authored coordinate and prior. Width screening applies to the whole vector.

integrate = :auto chooses the latent terms itself (brm_laplace_plan with its defaults): every term only Normal rows read, and every term read by counts, binomial rows or @plate cells whose per-block importance diagnostic admits it. integrate = plan takes a BRMLaplacePlan as given; the problem's plan field holds the plan it was built from. With integrate, progress reports the preparation through Treebars as in brm_laplace_plan.

integrate = :g or integrate = (:g, :h, …) instead integrates every level of the named grouping columns' latent blocks by one sparse Laplace, whatever their nesting: random-effect blocks over the grouping, cdar(step; by=g) walks (their standardized innovations) and car(g; edges) fields over an area column (ICAR values under their graph precision, BYM2's iid parts too; the default lowering, not car_units). Groupings may be crossed, nested with any number of levels per parent, or cut across the NLME units. The problem is then a BRMSparseLaplaceProblem over every other coordinate, the latent draws of the other groupings included. A field's per-component soft sum-to-zero stays out of the sparse factor (Woodbury); every component must be read by some row. Every observation is a regression response of one of the structured problem's four families, whose rows it shares, or sits in a @plate cell. A cell is one term over the coordinates it reads, its gradient, Hessian block and third derivatives by Enzyme over that selection (ReactiveKernelsPPL's compact-cell AD), which needs the Enzyme dogfood line from 7a886d9. The integrated effects' negative Hessian I + Cᵀ W C (with the cells' blocks added) has sparse local structure; each group of integrated effects that share likelihood terms (a unit, or the units a crossed grouping joins) takes its own Newton steps, backtracking and stop. subject_group, nested_groups, shared_groups and structured describe the per-unit Laplace and do not apply with it.

For the integrate path, solver=:auto keeps exact algebra on components of at most matrixfree.exact_limit coordinates (default 256) and uses operator solves and approximate determinants on larger components. solver=:exact retains the sparse Cholesky/augmented-factor implementation, while solver=:matrixfree forces operator algebra. MatrixFreeLaplace configures fixed probes, numerical tolerances and iteration caps. The large-component gradient differentiates the reported finite determinant approximation, including its dependence on the conditional mode. Probes and policy stay fixed throughout a prepared target's use and copies. problem.algebra.diagnostics reports per-component determinant probe MCSE; this is not a bound on the error of Laplace integration. Operator curvature checks cover Krylov search directions; they do not certify global positive definiteness. Failed capped linear solves raise an error.

subject_group, nested_groups and shared_groups are those of brm_nlme_view; the shared latents (a block over a grouping in shared_groups, a car(...) field) are population coordinates. Refused, with BRMNLMEViewError: everything brm_nlme_model refuses, including Student-t random-effect blocks.

source
BayesianRegressionModels.BRMNLMEConditionalProblem Type
julia
BRMNLMEConditionalProblem
brm_nlme_conditional_problem(map::BRMNLMEJointMap, start;
    backend=map.sb, ad_backend)

Condition one backend's full target on the fixed coordinates of start, a value returned by brm_nlme_joint_start for the same map. The returned problem implements the LogDensityProblems interface over the free coordinates only: the standardized subject draws, including one block per nested unit. A non-centered completion's unit draws are free coordinates too: RK's standardized draws x.z_mis in the RK frame, the entries x_y_mis Stan samples in the Stan frame. Population coefficients, scalar parameters, shared latent coordinates and the random-effect scales and correlation factors stay at start.

backend selects the evaluated target and its coordinate frame:

  • map.sb (default): map.stan_problem, the exact compiled Stan model, in Stan unconstrained order. No ad_backend is taken.

  • map.rk: rk_logdensity_problem(map.rk; ad_backend), the ReactiveKernels program of the same BRMI, in RK packed order. ad_backend is a DifferentiationInterface backend such as reverse-mode AutoEnzyme.

The log density at a free point x is the target's log density at the start point with the free coordinates replaced by x; it differs from the conditional posterior of the subject draws only by a constant. The gradient, and the Hessian when the target provides one, are the target's restricted to the free coordinates. Each evaluation builds a fresh full point. deepcopy gives an RK copy its own prepared automatic-differentiation workspace and a Stan copy its own native model instance. WarmupHMC's multi-chain scalar-density entry copies the problem once per chain.

Fields:

  • map, backend — the joint map and the selected backend.

  • target — the evaluated full LogDensityProblems target.

  • point — the complete start point in the target's frame.

  • free, fixed — the target's indices of the free and fixed coordinates.

  • names — the target's names of the free coordinates, in problem order.

  • subjects, margins — for each free coordinate, its subject label and the view's (; block, predictor, coefficient, level) margin record.

  • position — the initial free point, point[free].

Construction checks that start has this map's dimension, names and fixed/free partition, that its recorded values equal start.stan, that the point passes the physical RK/Stan coordinate check, and that the target's log density there is finite. A map without subject draws, or without fixed coordinates, is refused. No caller input is mutated. Use brm_nlme_conditional_point for complete points in the target's frame and brm_nlme_joint_values(problem, x) for the NLME values of a free point; sample the unconditioned model with map.stan_problem and start.stan instead.

source
BayesianRegressionModels.BRMNLMEJointMap Type
julia
BRMNLMEJointMap
brm_nlme_joint_map(rk::RKBRMI, sb::SBBRMI; path, subject_group=nothing,
                   nested_groups=NamedTuple(), shared_groups=(), unit_partition=:subjects, kwargs...)

Prepare a bridge from natural subject effects and an NLME covariance to the complete unconstrained coordinates of a compiled BridgeStan model. BRM compiles sb itself at path, so the returned stan_problem is the exact target whose coordinates are converted. Pass that problem to the sampler. Both backends must lower the same BRMI instance. The NLME view must cover every RK coordinate, and the semantic RK/Stan transport must pair every coordinate on both sides. Models with several groupings require the same explicit subject ownership arguments (subject_group, nested_groups, shared_groups) as brm_nlme_view. Shared latent variables may arrive in the fitted population vector or in an explicit full packed shared_point from the RK model. Non-centered completions read as unit draws (RKBRMI(brmi; completions = :noncentered)) are covered: the transport moves their draws to the entries Stan samples. Student-t mixing weights, centered Stan random effects, and other incomplete pairings are refused rather than silently initialized.

source
BayesianRegressionModels.BRMNLMEUnitProblem Type
julia
BRMNLMEUnitProblem

One unit's conditional posterior given fixed population values, returned by brm_nlme_unit_problem. Its coordinates are the unit's standardized random effects z (η = C z, C the lower Cholesky factor of the unit's Ω block), and its log density is -|z|²/2 - d/2 log 2π + loglik_i(θ, σ, C z), which is the RK model's density in those coordinates up to the population terms, which are held fixed. It implements LogDensityProblems with a gradient (first order), so any sampler can run it, one unit at a time or in parallel.

Fields: model, subject (the unit's position in model.view.levels), theta, sigma and factor (C).

source
BayesianRegressionModels.BRMNLMEView Type
julia
BRMNLMEView

The nonlinear-mixed-effects partition of one RKBRMI, returned by brm_nlme_view. All positions index the backend's packed unconstrained coordinate vector (coordinates, in packed order).

  • group — the subject grouping column; levels[i] is subject i's label, in the RK level order.

  • role[c] — :population (population coefficients, categorical contrasts, monotonic simplexes, ordinal thresholds and vector parameters), :shared_latent (sampled coordinates shared by the units: HSGP components, missing-value completions, submodels (a function-style component call's sampled locals other than its random-effect blocks, which are read as model-scope blocks), the sampled scales of a block with a known correlation, car(...) fields (only their separator draws, scale and mixing share when lowered with car_units), the latents a @plate cell declares and the sampled locals of a component called in a cell, and every coordinate of a random-effect block over a grouping in shared_groups; a grouped HSGP or cdar walk whose levels are the units shares only its hyperparameters), :scalar (other sampled scalars such as residual scales), :subject_scale / :subject_correlation (the random-effect scales and Cholesky correlation factors, i.e. Ω), or :subject_effect / :subject_mixing (subject subject[c]'s standardized draw or Student-t mixing weight).

  • subject_coordinates[i] — subject i's compact block of standardized draws. Flat models share one order; nested models add one instance per nested level owned by this subject.

  • block_margins[k] — (; block, predictor, coefficient) for position k of each random-effect family (coefficient === :mixing for a mixing weight). block is (; group, id, predictor): the grouping column, the |ID|, and, for a block without an ID, the predictor that owns it (nothing otherwise).

  • family_sizes[f] and subject_families[i] — each covariance family's dimension and the ordered family IDs for subject i's block instances.

  • families[f] — (; block, record, stratum, size, scales, factor, fixed): family f's block identity, its coordinate record, its stratum (the position of the by level for a stratified gr(g, by=b) block, nothing otherwise), its dimension, the packed positions of its scales (margin order) and of its LKJ correlation factor (empty for K = 1), and its fixed covariance (nothing when estimated). A stratified block has one family per stratum; each level's block belongs to its stratum's family, and its block identity carries stratum (the by level). A non-centered completion (RKBRMI(brmi; completions=:noncentered)) whose rows lie on the grouping axis or read it through data-indexed gathers is one family of size 1 with covariance fixed at 1: each missing cell is an instance of it in the subject owning its row, with role :subject_effect (its block identity carries completion=true). The grouped entries of a non-centered mi(x)::shares(total, rows) completion are one more such family (its block identity also carries shares=true): each coordinate of a group, K - 1 for a group of K missing entries, is an instance in the subject owning the group's rows, and the group's observed term (RKBRMI's completions) belongs to that subject. Bounded free entries use the same Gaussian family and observe their transformed law minus the Gaussian density, preserving the exact full density. A grouped HSGP hsgp(x; by=g) without cor= whose levels are the units (g is the subject grouping, a nested grouping, or a column whose labels are subjects) is one family whose size is its number of basis functions, with covariance fixed at the identity: each level's standardized weights are an instance of it in the subject owning the level (its block identity carries hsgp, the term's declaration). Each (1 | g) effect of a hyper-predicted amplitude or length scale (log(sd(hsgp(x))) ~ 1 + (1 | g)) is an estimated family of size 1 over the same units. A walk cdar(step; by=g, cor=C) whose groups are units in the same sense, and whose cor= couples only groups of one subject, is one family whose size is its number of steps, with covariance fixed at the identity: each group's standardized innovations are an instance of it in the subject owning the group (its block identity carries cdar, the term's declaration; the margins are cdar(step)[s] for each step value s). Its marginal SD and persistence are :shared_latent. A car(...) field lowered with RKBRMI(brmi; car_units) over the subject labels has a family of size 1 fixed at 1 for its interior draws, each draw an instance in the subject that is its unit, and for a BYM2 field one more for each area's iid part (block identity car, the term's declaration, and part, :draw or :iid; margin car(area)[part], level the draw's or area's position).

  • subject_margins[i] — the compact coordinates' family margin and grouping level labels for subject i.

  • mu_references — one (; predictor, coefficient, link, population, subject, design, eta_scale) per population coefficient that can be absorbed into a subject margin. population is the coefficient's packed position, subject the margin's position in a flat subject block, and design[i] its multiplier for subject i. eta_scale is the margin's known SD (1 for a sampled margin): the effect is eta_scale times η, so η absorbs design[i] / eta_scale. Nested models currently expose no such references.

  • rows[i] — the rows of the grouping column that belong to subject i.

  • nested_groups, shared_groups — the groupings the caller named as owned by a unit and as crossed with the units.

  • unit_partition — :subjects (default) or :connected. In connected mode, levels[i] is the tuple of scientific subject labels in inference unit i; subject_coordinates, subject_families, subject_margins and rows are indexed by inference unit. Every original covariance-family instance remains.

  • subject_levels, subject_unit, unit_members, subject_ranges — original scientific labels, their unit IDs, each unit's original subject indices, and each original subject's range inside its unit's compact effect vector. coordinate_subject[c] retains the original owner of packed coordinate c; subject[c] is its inference-unit owner. Zero means shared in both maps.

  • factor_supports — in connected mode, structural packed-coordinate supports per observation cell, keyed by observation name. A support is a vector of indices or :whole; it includes dormant branches and zero coefficients. These supports determine connectivity and retain individual-cell sparsity.

Subject draws are standardized (η = diag(scale) L z, z ~ N(0, I)): the subject block holds z, and Ω is read through the scale and correlation coordinates. Because the map from z to η is linear given Ω, Laplace and FOCE objectives agree in either coordinate system.

source
BayesianRegressionModels.BRMNLMEViewError Type
julia
BRMNLMEViewError <: Exception

A model that has no nonlinear-mixed-effects reading in brm_nlme_view: no subject-level random effects, a grouping named in neither nested_groups nor shared_groups, a unit-owned grouping that couples its levels (gr(...; cor=...)), an mm(...) block, a unit-owned Student-t block that holds known values, or a coordinate the semantic inventory does not cover. A stratified gr(g, by=b) block is read as one covariance family per stratum; a block with a known correlation, or whose every value is known, as one family of fixed identity covariance; and a block with known scales under a sampled correlation as one family that holds those margins' SDs. message names the offending declaration or coordinates.

source
BayesianRegressionModels.BRMSMCCarriedReference Type
julia
BRMSMCCarriedReference

A data-only posterior summary for new-window SMC: RKPPL's owned normalized Gaussian reference plus BRM's frozen preprocessing and source identity. It holds no old window, particle cloud, compiled target or AD workspace. Construct it with brm_smc_carry, and treat its contents as read-only.

source
BayesianRegressionModels.BRMSMCFit Type
julia
BRMSMCFit

An RK-only SMC fit, including its frozen training template, current backend and RKPPL state. For a prepared embedded-Laplace fit, template and backend are Laplace problems; the particle rows follow backend.names. state.positions contains unconstrained draws as columns; state.weights contains normalized weights. A completed fit has state.temperature == 1. Inspect state.history for ESS before resampling, ancestry and mutation diagnostics; equal final weights do not prove mixing.

Keep model code, bound data and the returned arrays read-only. Continue a partial fit with brm_smc_fit, and assimilate cumulative data with brm_smc_update.

source
BayesianRegressionModels.BRMSMCWindowFit Type
julia
BRMSMCWindowFit

An SMC bridge for one new window under a carried posterior approximation. backend contains this window, previous contains only the carried summary, and state is the producer's particle state. Continue a partial bridge with brm_smc_fit. Once complete, call brm_smc_carry to discard this window before assimilating the next one.

With coordinates=:auto, particle rows contain only the old coordinates needed by this window and the new coordinates it introduces. The backend's layout still describes the full current model. Omitted old coordinates are retained through their conditional Gaussian in the carried summary. Use brm_smc_coordinates to inspect the coordinate mapping and brm_smc_recover to recover a full joint draw from a compact position.

state.log_normalizer estimates this window's predictive normalizer under the carried prior, not exact full-history evidence.

source
BayesianRegressionModels.BRMSVILaplaceState Type
julia
BRMSVILaplaceState

Data-only checkpoint for brm_svi_fit(...; laplace=GaussianBlockLaplace()). It retains frozen preprocessing, a fixed-rank common Gaussian factor, small conditional blocks keyed by coordinate or unit identity, and the last global VI factor for initialization. It contains no observations or compiled queries. Resume with brm_svi_fit(state, builder(new_window); ...).

Projection preserves selected block moments approximately and drops residual cross-block dependence. New units initially have zero common-factor loading; fixed-rank continuation cannot preserve every new cross-unit dependence. The checkpoint retains unit_partition and uses format 2. Connected units must retain all their members in the same order across windows.

source
BayesianRegressionModels.BRMSVINonfiniteError Type
julia
BRMSVINonfiniteError

Thrown by brm_svi_fit and brm_svi_resume when an iteration evaluates the target to a non-finite value or gradient at its Monte Carlo draws. It is raised after the draws are evaluated and before the iteration changes the variational factors or the optimizer. iteration is the iteration that failed, one past the last completed one. terms lists every non-finite term in batch order, each a named tuple with:

  • term: :global for the global prior term, :unit for a unit's term;

  • unit: the unit's index, 0 for the global term;

  • quantities: what was not finite, for example :value_plus, :global_gradient_minus or :unit_gradient_plus (a unit is evaluated at the antithetic pair of draws, plus and minus; the global term has :value and :global_gradient);

  • coordinates: the names of the packed coordinates whose gradient entries were not finite;

  • draw_finite: whether the point the term was evaluated at was finite;

  • points: the packed point(s) the term was evaluated at, in the order of coordinate_names(rk.model.layout), as the columns of a fit's draws: plus and minus for a unit (under unit_curvature = :orthogonal, the pair that failed), draw for the global term. A coordinate the term does not read holds the value the fit holds for it there: the model's start, or a field state's draw of this iteration. Evaluating the model's density and gradient at a point replays the term's evaluation, so a consumer can look for the cause in its own model;

  • largest: the term's coordinate of largest magnitude across points, among the globals and the unit's own, as (; coordinate, value) (nothing for a term with no coordinates). Magnitude alone says little: a level well placed at 80 outranks an intercept ten prior sds out;

  • furthest: the globals of the failing point furthest from their own priors, at most three, furthest first, each (; coordinate, value, prior_sds): the distance from the mean of the prior's Gaussian projection in its sds, the sd the SVI sd bound multiplies. A global whose prior reads other coordinates is not measured;

  • probe: which coordinates carry the failure, found by swapping one coordinate at a time between the failing point and a finite reference, (; reference, repairs, breaks). reference is the pair's other draw (:plus or :minus) when that one is finite, otherwise :mean, the pair's mean (a unit) or the global factor's mean (the global term); repairs names the coordinates whose reference value alone makes the failing point finite, breaks those whose failing value alone makes the reference fail. A unit's swaps evaluate the model's own unit term at packed points. nothing when the reference is not finite either.

The run in memory is not a checkpoint after this error, because its random stream has advanced. Continue from the last checkpoint save received. A continuation repeats the run's random stream exactly, so resuming that checkpoint with unchanged controls reaches the same evaluation again.

source
BayesianRegressionModels.BRMSVIOptimizerState Type
julia
BRMSVIOptimizerState
brm_svi_optimizer_checkpoint(fit)

The state of a brm_svi_fit run after a completed iteration, for continuing the same optimization with brm_svi_resume, in this or another process. For the minibatch engine it holds the raw variational factors (also while polishing, next to the running average the result reports), the global Adam moments and step count, the random stream, the iteration, the ELBO trace, window statistics and bounded parameter-iterate histories of the stopping rule, and the polishing state, the weighted sampler, per-unit visits, cached entropy, lazy-average counters and structured-unit Adam moments. For laplace=GaussianBlockLaplace() it holds the global factor, Adam, the ELBO so far, the averaging window of global iterates, the random stream and a separate draw_rng, and the call counts and numerical records. Both hold the optimizer controls, the streaming carry of a window fit, and the identity of the target (the emitted program and callables, the bound data and frozen preprocessing, the packed coordinates, which mi(...) completions are non-centered, the subject groupings and coordinate ownership, and the fixed shared values). It holds no observations, compiled model or AD workspace. Its size is that of the variational factors (twice while polishing; plus the averaging window for GaussianBlockLaplace) plus at most 512 observations per monitored moment and one ELBO value per iteration so far; a run keeps no history of checkpoints.

brm_svi_optimizer_checkpoint(fit) copies the state from the result of a brm_svi_fit or brm_svi_resume; the save argument of those functions receives such copies while they run. Persist it with Julia Serialization to a trusted file; loading it needs the same Julia, package and model code versions. Write it atomically, so that an abrupt termination leaves the last complete checkpoint in place:

julia
using Serialization
function save_checkpoint(path, state)
    temporary = path * ".partial"
    open(io -> serialize(io, state), temporary, "w")
    mv(temporary, path; force=true)
end

A checkpoint written by BRM 0.2.237 or earlier still resumes. One taken while polishing keeps, for the iterates it had averaged, the narrower average of dense units' precision those versions returned; later iterates are averaged in covariance.

The streaming carry brm_svi_checkpoint is a different object: it continues on a new, disjoint window and holds no optimizer state.

source
BayesianRegressionModels.BRMSVIStart Type
julia
BRMSVIStart

A factor-level start for brm_svi_fit, from brm_svi_combine: the means and mean-field standard deviations of the global coordinates it informs, keyed by semantic coordinate identity, with the precision of each block of them that is correlated (globals.correlated, positions into globals.keys and a dense precision), the unit factors (mean and precision) keyed by unit label and semantic identity, the identity of the model it was combined for, and receipt, which says where every number came from. It holds no data and no compiled model, so it serializes like a BRMSVIState (with the same package versions). Pass it as brm_svi_fit(x; start): it sets where the fit's factors start and is not a prior.

source
BayesianRegressionModels.BRMSVIState Type
julia
BRMSVIState
brm_svi_checkpoint(fit)

Data-only streaming state: the global Gaussian, unit Gaussians keyed by subject label, semantic coordinate identities and frozen BRMFittedState preprocessing. It holds neither observations nor a compiled model or AD workspace. Serialize this state to resume with brm_svi_fit(state, builder(new_data); ...) in another process. Recreate custom model functions in that process before loading it. Format 1 dense-unit states remain supported. Format 2 also stores local diagonal-plus-low-rank factors directly, without dense matrices or optimizer moments. Coordinate reordering preserves their covariance exactly. This carries a fitted approximation into a new, disjoint window; it holds no optimizer state. An interrupted optimization of the same model and data continues from brm_svi_optimizer_checkpoint instead.

The checkpoint retains unit_partition. Connected continuation accepts complete unchanged units and wholly new units; a retained subject whose component or member order changes is refused before optimization. New checkpoints use format 3 and require the same package versions when serialized.

source
BayesianRegressionModels.BRMSparseLaplaceProblem Type
julia
BRMSparseLaplaceProblem

The Laplace of a regression-shaped RK model with every level of chosen groupings' random-effect blocks, cdar walks and car fields integrated by one sparse Laplace; see brm_laplace_problem's integrate. Same interface as BRMStructuredLaplaceProblem: LogDensityProblems order 1 over names (packed positions population), brm_laplace_draws, and the counters nonfinite, unconverged and folds, plus nonfinite_gradient (gradients that are not finite although the log density is; a warning names the first nonfinite term) and search (the last evaluation's Newton steps, shifted steps per stage, largest shift, refused full steps, final decrement and stop reason per component). integrate names the integrated groupings, integrated their draws' packed positions, components the groups of integrated draws that share likelihood terms.

source
BayesianRegressionModels.BRMStructuredLaplaceProblem Type
julia
BRMStructuredLaplaceProblem

The per-unit Laplace of a regression-shaped RK model, built on its rows; see brm_laplace_problem. Same interface as BRMLaplaceProblem: LogDensityProblems order 1 over names (packed positions population), brm_laplace_draws, and the counters nonfinite, unconverged and folds.

source
BayesianRegressionModels.GaussianBlockLaplace Type
julia
GaussianBlockLaplace(; trace_probes=8, logdet_probes=8,
    averaging_window=200, mode_tolerance=1e-8,
    mode_krylovdim=128, trace_krylovdim=128, correction_krylovdim=64,
    logdet_krylovdim=32, draw_krylovdim=32, draw_solve_krylovdim=64,
    carry_draws=128, carry_rank=8, carry_shrinkage=.01)

Opt in with brm_svi_fit(model; laplace=GaussianBlockLaplace(), ...). Jointly integrate the certified Gaussian population coefficients, unit effects and shared HSGP weights conditional on the remaining variational globals. The initial supported likelihood is Gaussian with an affine mean and a scale independent of the integrated coordinates. Unsupported expressions are refused from their model plan. This is conditional integration inside VI.

Each update evaluates the entire current window. Krylov bases and probe counts have fixed caps; an exhausted numerical budget raises an error. Trace and log-determinant probes add Monte Carlo error, distinct from iterative error. Rounding is a third error: about eps(Float64)*cond(H)*d in a log-determinant probe for a d-coordinate conditional precision H, which the recorded logdet_quadrature_width does not include. A precision too ill-conditioned to factor in double precision, possible from about cond(H)=1e16, raises an error. Optimization runs the declared max_iterations at fixed lr_global and returns the mean of its final averaging_window parameter iterates. Completing that budget does not establish convergence or posterior accuracy.

The checkpoint projects the first carry_draws joint draws into a common factor of fixed carry_rank plus residual blocks of at most 16 coordinates. Unit conditional moments reduce projection noise. Positive carry_shrinkage regularizes the residual covariance toward an explicit numerical reference. This projection adds approximation error and drops residual cross-block dependence. At least carry_draws joint draws are generated even when ndraws requests fewer returned draws. Continue on a disjoint window with brm_svi_fit(previous, builder(new_window)).

source
BayesianRegressionModels.LearnedCentering Type
julia
LearnedCentering(; start=0.5, step=0.05, delay=true)

The default on a fresh brm_svi_fit: learned partial centering with one control c ∈ (0, 1) per eligible cell, optimized jointly with the variational factors by the ELBO (the VIP of Gorinova, Moore and Hoffman, 2020). c = 0 is the non-centred coordinate and c = 1 the centred one: a random effect located at its population predictor and, in a correlated block, at its conditional mean given the block's earlier margins; an authored Gaussian vector element at its law's mean, when that law's mean or scale reads an estimated coordinate (a constant law, such as Normal(0, 1), leaves nothing to learn and is coupled instead). Controls start at start (grouped HSGP weights at min(start, 0.1)); step is the Adam step size of the controls' logits, taken whenever their unit is in the batch.

With delay=true (the default) a fresh fit explores with its cells in their packed coordinates first, the plain factorization, until exploration's ELBO test first reads flat (the trend test that ends exploration; its drift gate aside). Then each cell's control starts at start, each unit's factor is carried into its learned coordinates at the global factor's mean, and exploration goes on, its stopping test reading only the windows since. Grouped HSGP weights are not deferred: their controls learn from the first iteration. delay=false learns every control from the first iteration. Pass centering=nothing for the plain factorization. Streaming and optimizer continuation retain the saved policy.

source
BayesianRegressionModels.LinearCoupling Type
julia
LinearCoupling(; step=0.5)

The default on a fresh brm_svi_fit and streaming update: every unit's variational factor is conditional on the globals, with a mean linear in the global factor's draw, z_i = M_i + V_i ζ + U_i⁻ᵀ ε_i for ζ the global draw's standard normals at the globals the unit's term reads (and the global factor's rank part), on the unit's coordinates that learned centering does not centre (@plate cell latents among them; a centred cell follows the globals through its own map). Fresh fits hold V_i at zero during exploration, then learn it when the unit is in the batch during settling and polishing. Its scaled natural-gradient step has size step (about step / 2k of the way to its quadratic fixed point per visit, for k coupling noise components), with a mean-point gradient baseline that removes noise from unsettled unit means. It keeps the dependence between a population value and the units that the data pin only together, whatever the model's authoring, which independent factors lose. The global factor's and the units' entropies are unchanged by it. A streaming checkpoint carries each unit's prior conditional on the globals it was coupled to. Pass coupling=nothing for independent global and unit factors. Optimizer continuation keeps the saved activation and baseline policies; checkpoints predating these controls retain immediate updates without the baseline.

source
BayesianRegressionModels.MatrixFreeLaplace Type
julia
MatrixFreeLaplace(; exact_limit=1024, probes=8, seed=20261102,
    solve_tolerance=1e-10, solve_maxiter=512,
    preconditioner_memory=32, preconditioner_ridge=0.01, control_variate=true)

Numerical policy for brm_laplace_problem(...; solver=:auto). Components above exact_limit use preconditioned CG and a fixed Rademacher trace approximation of log. solver=:exact retains sparse factorization; solver=:matrixfree forces the operator path. Seeds, probes and iteration caps are fixed for a prepared target.

Every large component has a reference P = C*C', prepared once and fixed during target evaluations, at zero latent coordinates and zero population coordinates (a problem with a gmrf field: at its population prior medians). A component that is exactly one gmrf field uses that field's time-block reference (src/gmrf_preconditioner.jl), which sees the data's curvature. Any other component uses a bounded-fill LDL with preconditioner_memory extra factor entries per column and relative diagonal ridge preconditioner_ridge; reduction cliques are not expanded to build it. The reference transforms the determinant and its derivative together; it does not regularize the model's precision. Set preconditioner_memory=nothing to use no reference: diagonal Newton solves and an untransformed determinant.

The determinant is the reference's exact log determinant plus the mean over the probes r of r' log(A) r, A = C^-1 H C^-T (without a reference, A = H). Each r takes one Lanczos recurrence, A V = V T + β v e', stopped when the solve of A x = r it implies reaches solve_tolerance. On that space r' log(A) r = ‖r‖² e₁' log(T) e₁, and the determinant's sensitivity to H is ‖r‖² V G V' in the same coordinates, G being the derivative of log at T in the direction e₁e₁'. No quadrature enters. Probe error and solve error are distinct; neither is an exact determinant certificate, and increasing dimension does not increase the work caps or guarantee accuracy. Lanczos checks curvature in its own directions; this is not a proof of global positive definiteness for a nonconcave conditional density. A recurrence retains its basis while its probe runs, so that probe's memory is the iteration count times the coordinates.

Fixed probes leave noise in the gradient that does not shrink relative to the posterior as a field grows. With control_variate=true a field whose reference decouples its channels (one channel included) also rebuilds that reference at each point and estimates only the difference from it (src/gmrf_tracked_reference.jl). This costs about twice as much per probe and cuts the noise several times over. The value and its gradient stay one fixed-probe function and its exact derivative.

source
BayesianRegressionModels.R2D2AdaptiveCenteringBlock Type
julia
R2D2AdaptiveCenteringBlock

A random-effect block whose marginal scales are not raw log-scale coordinates, described for adaptive partial centering: an R2D2-scaled block (ranef_intercept_r2d2, ranef_correlated_r2d2, ranef_correlated_draws_r2d2), or a known-value block that holds some scales or its correlation at known values (sd(...) = value, cor(:, ID) = R). ranef, target_c, effects and cholesky_free mean exactly what they mean on AdaptiveCenteringBlock. There is no log_scales coordinate vector: scales[k] is the compiled log-scale of term k as a function of the unconstrained vector — the model's own R2, Dirichlet share and reference/total scale coordinates, a known block's sampled scale coordinate, a bounded ordinary scale's declared transform, or a known scale's constant. Those coordinates are read, never transformed. A known correlation is the constant Cholesky factor cholesky_known (empty when the block samples L), and cholesky_free is then empty.

A Student-t block (ranef(:, ID) ~ TDist(nu)) is described in this form too: mixing[g] indexes level g's mixing weight w[g] (its unconstrained value is log w[g]), and level g's factor is sqrt(w[g]) * diag(tau) * L. The weights are read, never transformed. mixing is empty for a Gaussian block.

Construct with adaptive_centering_blocks.

source
BayesianRegressionModels.RKBRMI Type
julia
RKBRMI(brmi; held_out=(), completions=:centered, car_units=nothing)
RKBRMI(brmi, plan, built)

A BRMI lowered to the ReactiveKernels backend. plan is the strict, RK-independent structural plan; model is the executable thin-layer program provided by BayesianRegressionModelsReactiveKernelsExt when ReactiveKernels is loaded. Implemented only by that extension; the generic here lets the core validate and materialise plans without loading RK. held_out selects a strict subset of response names whose likelihoods are withheld. Authored priors and sampled coordinates remain in the program. completions parametrizes the mi(...) completions of a model: :centered samples each missing value under its law; :noncentered samples one standard-normal draw z per missing value. A Normal(location, scale) value is location + scale * z (its exp for LogNormal); any other continuous univariate law's value is its support transform of the draw (lower + exp(z) above a lower bound, upper - exp(z) below an upper one, a scaled logistic on an interval, z itself on the real line, the coordinate the centred lowering samples), and each entry observes the exact density remainder logpdf(law, x) + log|T'(z)| - log N(z; 0, 1) in :pointwise. A collection of mi sources (completions = (:x,)) non-centers those completions only. All are the same model. A non-centered completion whose rows lie on the subject grouping axis is a unit draw of brm_nlme_view (two-stage, SVI, Laplace and the NLME estimators) instead of a shared latent. A centred completion whose law reads the units' draws is refused there, since its density would then be a prior term reading them; the fits that take a @brm model lower exactly such completions non-centered themselves. An mi(y) response that nothing else reads lowers to the regression plan, which samples none of its missing entries, so it lowers the same way under every spelling. brm_coordinate_transport pairs the non-centered draws with Stan's centred entries. reprocess keeps the backend's parametrization. The grouped entries of mi(x)::shares(total, rows) take :noncentered under any law: their coordinates (the centred ones, which the transport pairs with Stan's) are standard-normal draws, and each group observes the rest of their density, the law at its entries and the shares' log-Jacobian less the draws' standard-normal density. The density is the centred one; :pointwise holds those group terms as the observation of a placeholder per group. The entries of no group are non-centered like any other completion's. car_units samples car(...) fields by their unit border separator: unit labels row-aligned with a field's rows (the name of a column the model reads, or the labels themselves) give each area the unit of its rows. One such entry labels every field; fields on different row sets each take their own, keyed by their area column (car_units = (area = :units, area_b = :units_b)), and a field without an entry keeps the default lowering. The separator holds the areas of no unit or of several units and, on each border between two units, the border areas of the side with fewer of them. Given the separator values and each unit's sum over its interior areas (per connected component), the units' interiors are independent Gaussians, so the field is sampled as standard-normal draws: shared ones for those values (<field>.w) and, per unit k, ones for its interior (<field>.z_k). This is the default lowering's field and density, up to a constant Jacobian, soft sum-to-zero included; a component inside one unit is all that unit's draws. brm_nlme_view then reads the interior draws (and a BYM2 field's per-area iid part) as unit draws, so θ holds the separator values and the sums instead of one coordinate per area. Each unit's interior, and the shared values, are mapped through sparse Cholesky factors, linear in the graph's edges. reprocess keeps the fit's separation on a frozen replay and lowers a rebuild with the same car_units columns; brm_coordinate_transport maps a separated field to SBBRMI's field through the separation's exact linear map.

The three-argument constructor wraps an existing artifact build without planning, translation, emitted-definition evaluation or kernel construction. Pass the original brmi, artifact.plan from emit_rk_artifact(brmi; held_out, case_id), and that artifact's built = build_kernel(rk_translate_artifact(artifact)). The wrapper retains these exact values; the caller must preserve their common provenance and held_out selection. Retain the bound program separately for queries. This constructor supports coordinate transport and its physical check on that existing build.

brm_source returns the brmi passed to either constructor; parent(backend) is that model after prior-address resolution.

A backend translates its emitted program (definition module and lowering) and binds its data once, on first use; every query reads that one binding. reprocess replays share the fit's translated program and bind only their own data.

source
BayesianRegressionModels.S2ZEffectBlock Type

Fitted design, prior and coordinate identities for one S2Z block.

population is the sampled theta (the population coefficients with the block means integrated in), recovered the block means μ and coefficients the conventional population coefficients theta - B μ, both recovered in generated quantities, indexed like population_columns. effects are the conventional per-level effects r + μ.

source
BayesianRegressionModels.SBBRMI Type
julia
SBBRMI(brmi::BRMI; mod=@__MODULE__, cv_groups=Set{Symbol}(),
       centered_groups=Set{Symbol}(), total_groups=(),
       s2z_groups=(), s2z_rho=nothing, s2z_coordinates=:contrasts,
       held_out=()) -> SBBRMI

StanBlocks backend: walks brmi, emits a StanBlocks.SlicModel, and materialises the data dict. Pass mod if you're constructing the model from a module other than BayesianRegressionModels so SLIC's symbol resolver finds your locally-defined submodels.

Random-effect blocks use the standard (non-centered) parametrization by default. For groupings whose blocks the data identify strongly or unevenly, use S2Z (s2z_groups, s2z_rho, below) with WarmupHMC adaptive centering (adaptive_centering_problem).

total_groups requests exact total coefficients instead (default (), none). total_groups=:auto integrates matching population coefficients into group totals when the exact Gaussian conditional construction is available: one grouping structure per predictor, independent random-effect margins, and Normal, Flat, or Student-t population priors (Student-t uses its exact Gaussian scale mixture), whose arguments read only numbers and data; those values enter the program as data. Unmatched fixed effects and offset(...) terms remain explicit summands. Original population coefficients and deviations are recovered in generated quantities; inspect total_effect_blocks. Naming a group explicitly requires every block of that group to be eligible and errors otherwise, naming each predictor whose block would stay conventional and why. total_groups=[:g => [:b]] (or :g => :b) requests only b's block on g; entries mix, as in [:subject, :g => [:b, :c]]. :auto keeps the whole model conventional when any block must stay conventional. Scale priors may be any supported family on the positive half-line, or one of them truncated at zero with no upper bound. Correlated, crossed, stratified, multi-membership and R2D2 blocks are never totals.

s2z_groups is an opt-in collection of grouping-factor names (default (), disabled) emitted in the posterior-preserving sum-to-zero parameterization: J-1 free orthonormal contrast coordinates per coefficient with a fixed projected partial map, exact Gaussian marginalization of the omitted block means into the sampled population coefficients theta, and generated recovery quantities. s2z_rho is required whenever s2z_groups is nonempty (no public default yet): a scalar in [0,1], one weight per coefficient, or a J-by-K matrix (0 = noncentered contrasts, 1 = centered), applied to every S2Z predictor; or predictor => weights pairs, one per S2Z predictor, when predictors on the grouping need different weights, e.g. s2z_rho = [:mu => [1, 1, 1, 0], :sigma => 1.0]. Pairs must name every sampled S2Z predictor and no other. WarmupHMC's adaptive_centering_problem adapts the weights online, starting from these. First scope is scalar independent blocks with J >= 2, fully matched population design and Flat/Normal population priors, one S2Z grouping per predictor; anything else errors loudly. The predictor's other groupings (crossed, nested or |ID|) and direct terms (hsgp, categorical blocks, ...) stay ordinary terms. Inspect s2z_effect_blocks. S2Z groups are excluded from totals and cannot overlap centered_groups or cv_groups. S2Z applies to the blocks an observed likelihood reaches: a predictor that none reaches (its response omitted from the data, for example) keeps its block of the grouping conventional, re-drawn in generated quantities, while the grouping stays S2Z on every other predictor.

s2z_coordinates=:groups instead samples J group coordinates per coefficient: independent s_j ~ N(0, tau^(2c_j)) cells with deviations tau * (w - mean(w)), w = s ./ tau.^c. The extra dimension mean(w) is an independent auxiliary that leaves the posterior unchanged. There s2z_rho is each group's power-interpolation centeredness c (default 0), and every group is one scalar cell for adaptive_centering_problem.

Deprecated

:groups is unrequested and unvalidated, kept working only pending further exploration/research; prefer the default :contrasts.

cv_groups is an opt-in set of grouping-factor names (e.g. [:subject]) whose per-group random effect should be emitted with cv-contagious sizing – the std-normal draw is sized from maximum(<g>_idx) instead of the standalone data scalar n_<g>, so marking the group index with maybecv(:<g>_idx) at trace time flips that RE to a generated-quantities population re-draw (leave-all-out / out-of-sample). This is used when generating a CV model artifact; the default (empty cv_groups) sizes the same submodel from n_<g> and leaves the RE a fitted parameter. There are no separate _cv submodels — the size expression passed at the call site is the entire difference. Plain (… | g) ranefs and cross-formula (… |ID| g) buckets are both supported; stratified gr(g, by=b) errors if opted-in.

centered_groups is an opt-in set of grouping-factor names whose per-group random effect should be emitted in the centered parameterization – the per-group effect itself is the sampled parameter, with the covariance as its prior (bc ~ multi_normal_cholesky(0, diag_pre_multiply(tau, L))). Naming a group here explicitly selects conventional centered deviations and excludes it from automatic totals. Other conventional blocks use noncentered draws. Plain (… | g) ranefs and (… |ID| g) buckets are supported; stratified gr(g, by=b) is not.

The two sets are mutually exclusive per group: a centered block's sampled parameter is the per-group effect itself, and no available spelling of that can carry a cv taint in its size, so SBBRMI rejects a group named in both rather than silently emitting an in-sample block. Note also that centered and non-centered emissions use different unconstrained coordinates, so fitted draws are not interchangeable between them.

held_out names one response or a collection of responses — a strict subset. Holding out every observation is refused: there would be nothing to fit, and held-out likelihoods are not the prior mechanism. Each named observation is emitted through StanBlocks' cv activity analysis, the given-a-fit transformation: its likelihood is removed while its predictive draw remains in generated quantities, and every parameter it reads — even one only it reads — stays a parameter, so a fit's draws supply them. It is not a fit that ignores the response: to not condition on a response (say a PK-only fit of a joint PK/QT model), omit its column from the data instead, and everything no remaining likelihood reaches moves to generated quantities. Names resolve against both top-level responses and data-backed observations inside kernel(...) cells. For prior draws, keep the model identical and omit the response column from the data — the program lowers to generated quantities automatically.

held_out takes no per-row masks. To fit on some rows of a response, build the model on those rows only and predict or score the others by replaying the fit's draws onto the full data with reprocess.

Formula statements sd(:, ID) ~ Exponential(scale) and cor(:, ID) ~ LKJCholesky(K, eta) configure a shared |ID| block. An SD statement can instead select one emitted margin with sd(predictor, ID, coefficient), or every margin one predictor contributes with sd(predictor, ID). See ranefcoefnames for the authoritative ordered addresses. A block written without an ID, (… | g) or (… || g), is addressed by its grouping column instead (sd(:, g), sd(lp, g, x), cor(lp, g)); it then lowers as the generated |lp__g| block (the k-th || term as |lp__g__nocor__k|), and that ID is what this backend's parent, its descriptor and brm_start show. Omitted statements retain historical defaults; Julia's Exponential scale is converted to Stan's rate.

Use stan_code to extract the transpiled Stan source. For sampling, load StanLogDensityProblems + BridgeStan and wrap the emitted SlicModel in a StanProblem.

julia
brmi  = @brm df (y ~ 1 + a + (1|g))
sbbrmi = SBBRMI(brmi)
src   = stan_code(sbbrmi)
source
BayesianRegressionModels.adaptive_centering_blocks Function
julia
adaptive_centering_blocks(model, unc_names) -> Vector{AbstractAdaptiveCenteringBlock}

Describe every random-effect block in model for adaptive partial centering: an AdaptiveCenteringBlock for each block whose marginal scales are sampled, and an R2D2AdaptiveCenteringBlock for each block whose scales an R2D2 prior derives or that holds a scale or its correlation at a known value. model is an SBBRMI or GenerativePlan, and unc_names is the compiled model's unconstrained parameter-name vector (for example BridgeStan's param_unc_names).

The result supports both BRM endpoints: the default noncentered emission is the compiled target c=0, while SBBRMI(...; centered_groups=...) is target c=1. Every intermediate source uses the triangular term-wise map

u[k] = c[k] * sum(C[k,l] * z[l] for l < k) + C[k,k]^c[k] * z[k]

with C = diag(tau) * L. At K=1, this reduces to u = s^c * z with s = exp(log_scale) and no Cholesky coordinates. Consequently c=0 is the literal standardised draw and c=1 is the literal model-scale effect. adaptive_centering_problem additionally centres the cells of a block compiled non-centred on their predictor's population coefficient where one matches (u[k] gains c[k] * beta[k], so c=1 is the level's total); that location is not part of this metadata, and adaptive_centering_controls reports it per cell.

R2D2 blocks use the same map; only tau differs. It is not a coordinate but the emitted model's own derived scale — ref * sqrt(phi[j] * R2 / (1 - R2)) for sd(...) ~ r2d2(...) (block-wide, per-margin ICC, or joint include=), with a free half-normal for a margin a partial ICC statement leaves unaddressed, and sqrt((1 - R2) * tau_bsv^2) for the whole-predictor effect(lp, :) ~ r2d2(...) form — re-derived from the R2, Dirichlet share and reference/total scale coordinates on every evaluation. Those coordinates are read, never transformed. A reference scale must be a positive constant, data scalar, or lower=0 parameter (or a product, quotient, square root or literal power of them); anything else raises naming the block and the expression.

Known-value blocks (sd(...) = value, cor(:, ID) = R) use the same map under either emission and are returned as R2D2AdaptiveCenteringBlocks too: a known SD is a constant log-scale, a sampled SD of the same block its <binding>_tau (or <binding>_tau_free) coordinate, and a known correlation the constant Cholesky factor cholesky_known, with no Cholesky coordinates. When every scale and the correlation are known, every control of the block is a fixed per-coordinate rescaling of the compiled draw, so it cannot change the sampling geometry under an adapted diagonal metric.

Student-t blocks (ranef(:, ID) ~ TDist(nu)), with sampled, configured or known scales and either emission, are R2D2AdaptiveCenteringBlocks whose level g has the factor C_g = sqrt(w[g]) * diag(tau) * L, with w[g] the block's mixing weight. The same map then reads C_g in place of C, so c=0 is the emitted standardised draw and c=1 the level's effect b[g]. The weights are read, never transformed.

A stratified gr(g, by=b) block samples one tau, L frame per stratum of b, and each group reads its own stratum's frame. It is returned as one AdaptiveCenteringBlock per stratum, in stratum order: the stratum's tau and L coordinates over the effects of its groups. Each such block keeps the stratified block's binding, group and by, and its ranef.levels are the stratum's groups in block order, as brm_ranef_draws lists them. Intercept-only (1 | mm(...)) blocks adapt through the ordinary scalar path (their downstream gather is linear); an mm block with any slope term, including a slope-only (0 + x | mm(...)), shares the ordinary correlated emission and adapts with it.

A block emitted in generated quantities (RanefBlock.generated: no observed likelihood reaches it, for example because its response is omitted) has no sampler coordinate: Stan re-draws its effects, so it has nothing to adapt and is skipped, as transport_draws and population_draws skip it. Its scale or correlation parameters, if they remain sampled, stay untouched coordinates of the wrapped density.

Correlated cdar(step; by=group, cor=C) walks are not ordinary random-effect blocks either; they have their own metadata contract in _adaptive_cdar_centering_blocks and join the online plan through the WarmupHMC extension exactly like the ungrouped-HSGP companion below.

source
julia
adaptive_centering_blocks(rk::RKBRMI, unc_names=<the RK layout names>)

The random-effect blocks of an RKBRMI for adaptive partial centring, with indices that are positions of rk_logdensity_problem(rk; ad_backend)'s unconstrained vector. Every block is compiled non-centred (target_c = 0): effects[k, g] is the standardized draw of term k, level g, and cholesky_free its correlation factor's free coordinates. ranef.binding is the block's RK draws declaration (b_g of b_g.z.1.1), ranef.levels its grouping's levels in RK's row order of z.

A Gaussian block whose scales are each sampled as exp of a coordinate (a zero lower bound, unbounded above) is an AdaptiveCenteringBlock: log_scales are those coordinates. Every other covered block is an R2D2AdaptiveCenteringBlock, as on SBBRMI: term k's log scale is a function of the unconstrained vector that reads, never transforms, its inputs:

  • a bounded scale (Uniform(a, b), truncated(...; lower, upper)) is the log of its RK constrained value, lo + exp(u) or lo + (hi - lo) * logistic(u);

  • a known scale (sd(lp, g[, coefficient]) = value) is the constant log(value), and a known correlation (cor(:, g) = R) the constant factor cholesky_known, with no Cholesky coordinates;

  • a Student-t block (ranef(:, g) ~ TDist(nu)) scales level g's factor by sqrt(w[g]), its mixing weight, read through mixing[g] (the coordinate <draws>.w.<g>, log w[g]).

A stratified gr(g, by=b) block is one block per stratum of b, in RK's stratum order: each holds the stratum's groups and reads the stratum's own scales and factor, as adaptive_centering_blocks does for an SBBRMI. Covered groupings: one grouping column or a shared |ID| bucket's joint columns, scalar or correlated, || blocks included.

A block whose levels are correlated (gr(g; cor=...)) raises, as on SBBRMI. HSGP basis weights, car, cdar and gmrf fields, cell latents and completions are not random-effect blocks and are not returned here; the wrapper adapts HSGP basis weights, grouped HSGP level cells under hsgp_levels = true, and car and cdar cells under fields = true, as cells of their own (adaptive_centering_cells).

source
BayesianRegressionModels.adaptive_centering_cells Function
julia
adaptive_centering_cells(rk::RKBRMI, unc_names=<the RK layout names>; hsgp=true, hsgp_levels=false, fields=false) -> (; blocks, cells)
adaptive_centering_cells(model, unc_names) -> (; blocks, cells)

The cells adaptive_centering_problem adapts for model (an RKBRMI, SBBRMI or GenerativePlan): its random-effect cells, its HSGP basis-weight cells (an RKBRMI's unless hsgp = false), grouped HSGP level cells (an RKBRMI's under hsgp_levels = true), exact totals and S2Z cells (SBBRMI only), and its areal car field cells and cdar walk cells (an RKBRMI's under fields = true), each set as its wrapper adapts it, described as plain data: numbers, symbols, strings, nothing, vectors and named tuples. Indices are positions of the unconstrained vector unc_names names: for an RKBRMI, by default, rk_logdensity_problem(rk)'s layout; for an SBBRMI, BridgeStan's param_unc_names. Together the rows define the wrapper's map exactly (below), so a caller outside BRM can rebuild it without BRM internals. Reading them needs no WarmupHMC and builds no wrapper.

cells[p], in the wrapper's cell order (the order of centeredness, adaptive_centering_controls and checkpoints: random-effect cells of ordinary blocks, then of derived-scale blocks, each containing blocks first, then level, then term; then HSGP basis cells; then HSGP level cells; then exact totals; then S2Z cells; then car cells; then cdar cells). A random-effect cell (family = :ranef) has:

  • cell (== p), family (:ranef), block (its row in blocks), binding, group, level (the level's label) and level_index, term (its margin's declared position), margin ((; predictor, coefficient), or nothing when the block has no margin labels);

  • effect, the coordinate of the cell's compiled value, and name, its name;

  • conditioning: the cells of the same level's earlier terms, in term order;

  • location: coefficient, the coordinate of the population coefficient the cell is centred on (0 for none); factors, the coordinates of the factor(f) levels holding its level; containers, the cells of the coarser groupings holding its level, coarsest first, every one earlier than p.

An HSGP cell (family = :hsgp, one per basis weight: term by term, a grouped by = g term level by level, then basis by basis) has cell, family, block, binding (the predictor), margin ((; predictor, coefficient), the coefficient being the term), level (nothing) and level_index (the level's position in the grouping's level order, 1 for an ungrouped term), term (the basis function), effect, name, target (the weight's compiled frame: 0 on an RKBRMI; an SBBRMI term may compile each basis at its own centeredness), scale = (; spectrum, sigma, length_scales, omega2, harmonic) and location = (;). spectrum is :exp_quad or :periodic; sigma and each of length_scales are (; coordinate, lower, upper), coordinate == 0 marking a known value (lower == upper); omega2 holds the basis function's squared frequency per axis (:exp_quad), and harmonic its harmonic (:periodic).

A car cell (family = :car, one per area; an :icar field's cells in its emitted phi order, a :bym2 field's in sorted area order) has cell, family, block, binding (the predictor), margin ((; predictor, coefficient), the coefficient being the term), level (the area's label) and level_index, term (1 for an :icar area's phi, 2 for a :bym2 area's theta), effect, name, scale = (; sigma, rho, share) (sigma and rho each (; coordinate, lower, upper); rho.coordinate == 0 for :icar) and location = (; intercept, phi, log_inv_scale).

A cdar cell (family = :cdar, one per group × step innovation, group fastest) has cell, family, block, binding, margin, level (nothing), level_index (the group), term (the innovation's position), effect, name, scale = (; sigma, rho, cdiag, step) and location = (;).

blocks[b] of a random-effect block: block, family (:ranef), binding, group, id, by, levels, n_terms, n_levels, margins (per term), target (the compiled frame's control: 0 for a block emitted non-centred, every RKBRMI block; 1 for an SBBRMI block in centered_groups), log_scales[k] (term k's log scale as atoms (; constant, linear, unit, simplex, bounded); an ordinary block's is the single linear atom 1.0 * x[i] of its scale coordinate), correlation ((; free, cpc): the coordinates of Stan's cholesky_factor_corr free values, or the constant canonical partial correlations of a known correlation; both empty for one term) and mixing (per level, the coordinate of a Student-t level's log w, or empty). An HSGP block (one per term, per level of a grouped term): block, family (:hsgp), kind = :basis, binding (the predictor), term, level_index, n_basis, spectrum and target (per basis function). A car block: block, family (:car), binding (the predictor), term, type (:icar or :bym2), areas, target (0). A cdar block: block, family (:cdar), binding, term, n_groups, n_steps, target (0).

A grouped HSGP level block has family = :hsgp, kind = :levels, binding, term, group, levels, n_levels, n_basis, target = 0 and correlation = (; kind, free, cpc): kind is :none, :parameter, or :data. Its cells follow basis, then level order. Each has cell, family, block, binding, group, margin, level, level_index, term (the basis), effect, name, target = 0, conditioning (the earlier levels' cell ids within this basis), location = (;), and scale = (; spectrum=:exp_quad, sigma, length_scales, rho_floor, omega2). Each hyperparameter is either (; kind=:bounded, coordinate, lower, upper) as above, or (; kind=:log_predictor, intercept, sd, z), whose log value is x[intercept] + constrain(sd) * x[z]. An intercept coordinate of 0 omits the intercept; sd.coordinate == 0 omits the level effect. sd has the ordinary (; coordinate, lower, upper) form. A predicted length scale is floored at rho_floor after exponentiation.

Exact totals and S2Z cells have family = :scalar, cell, block, effect, name, their own target, scale = (; log_coordinate) (the raw log-scale coordinate), and binding, group, margin, level, term all nothing. Each exact-total column has one block (; block, family=:scalar, kind=:total, target=1, cells, design, log_scale): cells are its cell ids in group order, design is a vector of its linearly independent design columns (each a vector in that same order), and log_scale is its log-scale coordinate. Its cells' level_index is the row of that design and location = (; kind=:least_squares). S2Z cells form one block (; block, family=:scalar, kind=:s2z, cells, target) with target a vector, and location = (; constant=0) per cell. They follow block, coefficient, then contrast or group order; level_index is their position in this S2Z block. Contrast coordinates require compiled endpoint frames (0 or 1 per coefficient); the existing deprecated group coordinates accept any compiled frame.

The map

Read x as the sampler's unconstrained vector and map cells in order; a coordinate no cell names passes through unchanged. For cell p (block b, term k, level g, control c, target t):

  • log τ_i = constant + Σ weight * x[coordinate] (linear atoms) + Σ (log_weight * log σ(x[i]) + log1m_weight * log(1 - σ(x[i]))) (unit; σ the logistic) + Σ weight * log(simplex_constrain(x[coordinates])[entry]) (simplex; transform names the simplex transform: :stan, Stan's isometric log-ratio and softmax, for an SBBRMI; :stick_breaking, ReactiveKernelsPPL's, for an RKBRMI's R2D2 shares, whose N coordinates u give break fractions z_i = σ(u_i + log(N + 1 - i)), entry j ≤ N the value z_j * Π_{i<j} (1 - z_i) and entry N + 1 the remaining stick) + Σ weight * log(lower + (upper - lower) * σ(x[i])) (bounded; log(exp(x[i]) + lower) when upper is infinite);

  • L is Stan's cholesky_factor_corr of the canonical partial correlations tanh(x[free[j]]) (or cpc[j]), row i holding j = (i-1)(i-2)/2 + 1, …; C = r_g * diag(τ) * L with r_g = exp(x[mixing[g]] / 2) (1 without mixing), and s = C[k, k];

  • the earlier terms' innovations ζ_l = (y_l - t * loc_l) / s_l^t over conditioning (y_l their compiled values; ζ_l = y_l when t = 0), and m = Σ_l C[k, l] * ζ_l;

  • loc = m + x[coefficient] + Σ x[factors] + Σ_a e_a, a containing cell a's effect e_a = s_a * y_a in a block with target = 0 and y_a otherwise;

  • the compiled value y = t * loc + (x[effect] - c * loc) * s^(t - c), and the log-Jacobian adds (t - c) * log s.

An HSGP cell is centred on 0 at its spectral scale s: with target t, the compiled value y = x[effect] * s^(t - c), and the log-Jacobian adds (t - c) * log s. Write σ and ρ_j for the constrained sigma and length_scales[j] (below; a known value is its lower), and ℓ = log σ + Σ_a (log(ρ_a * sqrt(2π)) / 2 - ρ_a^2 * omega2[a] / 4) over the axes a of omega2 for :exp_quad (ρ_a = ρ_1 for every axis when length_scales holds one), or ℓ = log σ + (log 2 + log(besselix(harmonic, 1 / ρ_1^2))) / 2 for :periodic (besselix(ν, z) = I_ν(z) * exp(-z), the scaled modified Bessel function). Then log s = ℓ while ℓ > -110, and -150 + log(1 + exp(ℓ + 150)) below, a smooth floor that keeps s^(t - c) a normal Float64 at every control.

For grouped HSGP level cells, use that spectral formula with the level's hyperparameters. Rebuild the level correlation's Cholesky factor L as for random effects (L = I for kind = :none). At level g let C[g, :] = exp(ℓ_floored) * L[g, :], s = C[g, g] and loc = Σ_l C[g, l] * y[conditioning[l].effect] over earlier levels of this basis. Then y[effect] = (x[effect] - c * loc) * s^(-c) and the log-Jacobian adds -c * log s. All level targets are 0.

Map an exact-total column together. Form W from the block's design columns, a_j = exp((1 - c_j) * x[log_scale]) and A = Diagonal(a). With x_col the column's effect coordinates, solve loc = W * ((W' * A * W) \ (W' * A * x_col)), then y_col = loc + A * (x_col - loc). Its log-Jacobian is sum(log, a) + logdet(W'W) - logdet(W'AW). An empty design gives loc = 0 and both log determinants 0. These cells are coupled within the column; their location is not a constant prior mean. For S2Z cells, independently, y[effect] = x[effect] * exp((target - c) * x[scale.log_coordinate]), with log-Jacobian (target - c) * x[scale.log_coordinate].

A car or cdar cell is a scalar cell with target 0: with its location loc and scale s, y = (x[effect] - c * loc) * s^(-c) and the log-Jacobian adds -c * log s. Write σ = constrain(x[sigma.coordinate]) and ρ = constrain(x[rho.coordinate]), where constrain(v) = lower + exp(v) for an infinite upper and lower + (upper - lower) * σ(v) otherwise:

  • car: log s = log σ + share * log(1 - ρ) / 2, and loc is x[intercept] (0 when intercept == 0) plus, when phi != 0, σ * sqrt(ρ * exp(log_inv_scale)) * x[phi];

  • cdar: loc = 0 and log s = log σ + log(cdiag) / 2 + log(v) / 2 with the walk's spread v = (1 - ρ^(2 step)) / (1 - ρ^2), or v = step where 1 - ρ^2 <= 1e-12.

The HSGP, scalar and field scale coordinates are not rewritten by any cell.

Where s leaves Float64's normal range BRM sums log s as log τ_k, the logs of the stick factors of row k and log r_g, which is finite wherever the coordinates are. ranef_order = :learned permutes, at restarting windows, the order of a correlated block's terms within a level; these rows describe the declared order, the default.

Under an RKBRMI's default hsgp_levels = false, grouped level terms keep their emitted frame and have no cells. Exact totals or S2Z cells beside cdar walks raise, as their wrapper does. Blocks the wrapper does not build raise as in adaptive_centering_blocks.

source
BayesianRegressionModels.adaptive_centering_controls Function
julia
adaptive_centering_controls(adaptive, model; unc_names=nothing) -> Vector{NamedTuple}

One row per adaptive cell of adaptive, the wrapper adaptive_centering_problem returned for model, in the wrapper's pair order (the order centeredness and checkpoints use). Every row has

  • cell, the pair number; index and name, its unconstrained coordinate;

  • family: :ranef (ordinary or R2D2 random-effect cell), :hsgp (basis weight), :scalar (exact total or S2Z contrast), :car (areal field cell) or :cdar (walk cell);

  • c, the current source control, and target, the compiled frame's.

Random-effect rows also carry binding, group, margin (its (; predictor, coefficient), as brm_ranef_draws labels it), level, term (the margin's declared position in its block), rank, its position in the group's current triangular order (term itself under ranef_order=:declared, the learned position under ranef_order=:learned), and location, the unconstrained name of the population coefficient the cell is centred on (so its c=1 coordinate is the level's total), or nothing for a cell centred on 0 (see adaptive_centering_problem). HSGP and cdar rows carry binding, margin = (; predictor, coefficient=term) and term (the basis or walk cell); a grouped HSGP mapped across its levels also carries group, level (the level's label) and rank (its position in the basis column's triangular map). Car rows carry binding, margin, level (the area's label) and term: 1 for an :icar area's structured phi cell, 2 for a :bym2 area's unstructured theta cell. Fields that do not apply are nothing.

Read it after warm-up from the same object the sampler adapted, for example a single-chain adaptive_warmup_mcmc run; samplers that copy their density per chain leave the passed object at its initial controls (warmuphmc-use §5c). Pass unc_names when adaptive does not wrap a BridgeStan model.

source
BayesianRegressionModels.adaptive_centering_problem Function
julia
adaptive_centering_problem(model, problem, ad_backend; kwargs...)

Wrap a BRM problem in WarmupHMC's strictly-online adaptive-centering transform. Compiled models use BRM's WarmupHMC extension.

source
BayesianRegressionModels.brm_check_coordinate_transport Function
julia
brm_check_coordinate_transport(t, rk::RKBRMI, stan_model, u_rk; atol=1e-10, rtol=1e-10)

Confirm at the RK unconstrained point u_rk that both backends describe the same physical parameter point: every paired constrained value agrees under its relation, every correlation factor agrees as a whole matrix, including its structurally fixed unit diagonal norm and zero upper triangle, every simplex agrees as a whole vector of K elements, every centered block's Stan effects equal diag(tau) * L * z computed from RK's own constrained scales, correlation factor and standardized draws (times sqrt(w) of the level's own mixing weight for a Student-t block), and every standardized completion's Stan entries equal the values RK's own graph computes from its draws, and every separated car(...) field's Stan areas equal the field RK's own graph computes from its draws. The Stan point is brm_rk_point_to_stan(t, u_rk). stan_model is the compiled BridgeStan.StanModel whose param_unc_names built t. Returns (; pairs::Int, factors::Int, simplexes::Int, centered::Int, completions::Int, fields::Int, max_error::Float64): pairs counts checked elements outside correlation factors, simplexes, centered blocks and standardized completions, factors counts whole correlation matrices, simplexes whole simplexes, centered whole centered blocks (all K × G effects), completions whole standardized completion parts (all entries), fields whole separated car(...) fields (all areas), and max_error is the largest absolute physical difference over these elements and every matrix, simplex, effect and entry. Every comparison must meet atol + rtol * max(abs(rk_value), abs(stan_value)). Any disagreement is an error naming the coordinate. Densities and gradients are not compared here.

source
BayesianRegressionModels.brm_coordinate_transport Function
julia
brm_coordinate_transport(rk::RKBRMI, sb::SBBRMI, stan_names) -> BRMCoordinateTransport

Pair every sampled coordinate of rk (its built layout's coordinate_names) with exactly one unconstrained Stan coordinate of sb. stan_names is the compiled model's BridgeStan.param_unc_names(model), in its order. Both backends must come from the same BRMI.

The correspondence is semantic. Population coefficients pair by predictor and coefficient label; categorical coefficients by their fitted level; scalar parameters by their authored name; random-effect blocks by grouping column and |ID|, with scales by margin, standardized draws by (grouping level, margin) and correlation-factor coordinates in Stan's packing. A grouped levels × margins RK draw matrix therefore reaches Stan's flat margin + K(level - 1) vector through the level and margin labels, never through matching dimensions.

Covered in this version: scalar parameters, vector parameters (a response's OrderedLogistic cutpoints and Ordinal cumulative or stopping-ratio thresholds, element by element under the shared ordered or unconstrained transform, and authored Dirichlet simplexes as :simplex blocks; all keep their declaration name on both backends), Ordinal per-threshold coefficients by (stage, term), ordinary-prior population coefficients (including shared-design and separate categorical blocks), plain random-effect blocks ((1 | g), (0 + x | g), (1 + x | g), (… | id | g)) with sampled scales, non-centered or centered on the SB side (see below), stratified blocks gr(g, by = b) (each stratum's scales by margin and its correlation factor, by the b level; the standardized draws by (level of g, margin)), ungrouped HSGP terms (isotropic or per-axis length scales, marginal scale and basis weights, paired by their formula axes and parameter roles), grouped HSGP terms hsgp(x...; by = g) (the length scale and amplitude, or a hyper-predicted one's intercept, level-effect scale and level effects by level label; a multigroup((x, y)) term's own spatial scale; the standardized weights by level label and basis function, or by inducing point and basis function for cor = multigroup((x, y), …); a level correlation cor = Omega and the declared inputs of multigroup pair as their own declarations), monotonic mo/mo1 terms (the coefficient as a population coefficient, the increments as a :simplex block), and the declarations a downstream submodel provider scopes under its target (_rk_submodel_rhs! / _sb_submodel_rhs!). A plain or stratified random-effect block declared inside a function-style component call (kin ~ kinetics(x, unit) with (1 | p | unit) in its body) pairs as at model scope, by that call's own grouping levels and margins: RK kin.<block>.z with Stan kin_<block>_z_flat, its semantic addresses carrying scope = (:kin,) (a tuple path for nested calls), so repeated calls over equal labels stay apart. A provider declaration <target>.<path> pairs with the sampled SB output that the same <target> declaration owns under StanBlocks' submodel name <target>_<path> (path segments joined by _), element by element; a simplex declaration pairs as a :simplex block and an LKJ Cholesky factor as a correlation factor. Name both providers' declarations identically for this pairing. Missing-value completions pair RK <column>.y_mis.<i> with Stan <column>_y_mis.<i> when the completed column feeds a downstream likelihood. A completion RK samples non-centered (RKBRMI(brmi; completions = :noncentered), a Normal or LogNormal law, and the free entries of mi(x)::shares(total, rows)) samples standard normal draws <column>.z_mis.<i> (<column>.z_free.<i>) where Stan samples the entries <column>_y_mis.<i> (<column>_y_free.<i>): each draw pairs with the entry of the same position as a :completion pair, and the part moves through s = location .+ scale .* z on Stan's unconstrained entries, with the location and scale RK computes at the point (t.completions); they may read any coordinate. A car(...) field pairs its scale and mixing share as scalars and its structured and unstructured parts area by area; lowered by its unit border separator (RKBRMI(brmi; car_units)), its shared and unit draws pair with Stan's areas as block positions (:car_separated), and the field moves through the separation's exact linear map (t.fields). Any coordinate outside that coverage — on either side — is an error naming it; there is no partial transport. An SBBRMI built with exact total-effect blocks has no sampled counterpart for the absorbed coordinates; build it with total_groups=() for this comparison.

A block in centered_groups samples the effects b themselves, with diag(tau) * L as their covariance factor, while RK samples standardized draws z. Its effects pair with RK's draws by (level, margin) as :centered pairs, its scales and correlation factor pair as for a non-centered block, and the block moves through the exact per-point map b = diag(tau) * L * z, using that point's tau and L (t.centered). A centered Student-t block's mixing weights pair by level label as for a non-centered one, and its map is b = sqrt(w) * diag(tau) * L * z per level. Its SB margins must be in RK's margin order.

Every non-simplex, non-centered, non-completion pair has equal unconstrained values on both sides, and the log-Jacobian of each backend's transform is evaluated at the same physical point. Without simplex, centered or completion blocks, points and gradients move by the same permutation (brm_rk_to_stan, brm_stan_to_rk). With them, use brm_rk_point_to_stan, brm_stan_point_to_rk and brm_stan_gradient_to_rk, and move the Stan density with brm_stan_logdensity_to_rk. Confirm the physical agreement at concrete points with brm_check_coordinate_transport.

For an already retained artifact build, use RKBRMI(brmi, artifact.plan, built) with the original brmi, artifact plan and built = build_kernel(bound). That constructor wraps the exact values without translating or building again. Use the same held_out selection for both backends. Known coverage boundaries and incompatible parameterizations throw BRMCoordinateTransportError with distinct reason values; other failures propagate normally.

source
BayesianRegressionModels.brm_cut_family Function
julia
brm_cut_family(joint::RKBRMI, upstream::RKBRMI, U; ad_backend, start=nothing)
brm_cut_family(inputs, downstream::RKBRMI, data, upstream::RKBRMI, U;
               ad_backend, joint=nothing, start=nothing)

One downstream conditional per upstream draw U[:, k]: the columns of U are draws in upstream's unconstrained coordinates (rk_restore_draws order), for example the posterior positions of a fit of upstream.

Coordinate cut (the default). upstream is joint's model on the data without the downstream responses, so the declarations it samples are the upstream part (an omitted response is not conditioned on, and what no remaining likelihood reaches leaves the sampler). Each conditional is joint with those declarations pinned at draw k: the downstream coordinates of joint, with density equal to joint's up to a per-draw constant. RK folds what depends only on the pinned values into constants of that draw's kernel. A declaration only partly upstream (a shared (… | p | g) block whose margins split across the stages) is refused.

Explicit cut. For a joint model whose efficient computation fuses what the cut separates, downstream is a model of stage 2 alone that reads the declared stage-1 outputs as data, built once on its data. Draw k's conditional is downstream on merge(data, inputs(U[:, k])): inputs takes the upstream draw (a vector in upstream's unconstrained coordinates) and returns the stage-2 columns, and may spend any compute preparing them. Preprocessing stays frozen at downstream's own data, as reprocess freezes it. inputs may be a tuple of upstream value names instead, such as (:conc,): each draw then binds those graph values of upstream under the same names. Pass the joint model as joint= to place the draws in its coordinates: every joint coordinate must be an upstream or a downstream coordinate of the same name.

ad_backend is the gradient backend of the targets, as in rk_logdensity_problem. start is every target's start point in the downstream coordinates (default zeros).

source
BayesianRegressionModels.brm_cut_fit Function
julia
brm_cut_fit(sampler, family::BRMCutFamily) -> NamedTuple

Sample every conditional of family with sampler(targets, starts, features), which returns one coordinates × draws matrix per target (a family sampler, or independent fits), and place the draws:

  • downstream[k]: target k's draws in family.names;

  • joint: when the family knows the joint model, its coordinates × draws matrix; every column takes its upstream coordinates from the draw its conditional was built on, family.upstream[:, source[j]];

  • joint_names, source.

source
BayesianRegressionModels.brm_cut_point Function
julia
brm_cut_point(U) -> Matrix

The poor cut's upstream point: the coordinate-wise median of the upstream draws (the columns of U) in their unconstrained coordinates, as a one-column matrix to build a one-conditional family on.

source
BayesianRegressionModels.brm_cut_propagate Function
julia
brm_cut_propagate(fit, family::BRMCutFamily, U; rng=Random.default_rng()) -> NamedTuple

The poor cut's draws. family has one conditional, at the upstream point (brm_cut_point(U)), and fit = brm_cut_fit(sampler, family) its downstream draws. Each upstream draw U[:, k] is paired with downstream draw σ(k), a draw without replacement while the fit has enough draws, and placed in the joint coordinates: joint (joint coordinates × size(U, 2)), joint_names, and pairing (σ).

source
BayesianRegressionModels.brm_execute Function
julia
brm_execute(d::BRMDescriptor, name::Symbol, args...; kwargs...)

Run a derived operation.

julia
brm_execute(d, :transpile)                       # the Stan source
prob = brm_execute(d, :fit)                      # a BridgeStan-backed StanProblem
brm_execute(d, :predict; problem=prob, draws=theta_unc, seed=1234)
brm_execute(d, :replay, new_df)                  # a NEW BRMDescriptor

:stan-origin operations forward to StanBlocks' stan_execute (data keywords re-bind inputs; :predict requires draws and seed). :brm-origin operations take the new dataframe positionally and return a new descriptor. For prior draws, build the descriptor with the response column omitted and sample the :instantiate problem (fixed_param); there is no separate prior operation. Unknown names fail closed via brm_operation.

source
BayesianRegressionModels.brm_filter Function
julia
brm_filter(model; parameters=nothing, ensemble=nothing, weights=nothing,
    inputs=(), groups=(;), drifting=(), rng=Xoshiro(), particles=1000,
    history_limit=32)
brm_filter(fit::Union{BRMSMCFit,BRMSMCWindowFit}; learn=false, kwargs...)

Initialize filtering before the first authored time slice of a BRMI or RKBRMI. Load ReactiveKernels, ReactiveKernelsPPL and SequentialMonteCarlo. Recurrences and observation laws come from the model's captured RKPPL source; preprocessing remains frozen at its training values.

Supply a calibrated constrained parameter named tuple/dict, an unconstrained coordinate vector, or an ensemble of such points. RKPPL selects only static parameters, excluding historical latent seeds, innovations and trajectories. An SMC fit supplies its completed posterior particles and weights. particles is the number of conditional state particles per parameter member. A fixed ensemble can lose parameter diversity. With learn=true, the completed fit instead initializes a BRMFilterSMC through its selected static Gaussian summary. This route adds members, window_length, ess_fraction, options and boundary controls for bounded-window replenishment and rejuvenation. Its Gaussian/state-pool approximation is documented on BRMFilterSMC.

inputs names the per-step covariate ports. groups fixes the authored plate axis, and drifting names sampled carried states with an explicit authored parameter transition. No parameter jitter is introduced automatically.

Initialization is cold even when parameters came from a posterior. To continue after its training history, warm the states with brm_filter_stream(filter, training_records; condition_state_only=true); this preserves calibrated parameter masses and does not count that likelihood again. A joint checkpoint resumes directly without warm-up.

The initial RKPPL implementation supports scalar Float64 carries, bounded literal lags and one fixed group plate. It refuses whole-history reductions, growing state and unsupported trajectory transformations. The explicit Xoshiro RNG is copied. Opaque callables must themselves have bounded work and storage.

source
BayesianRegressionModels.brm_filter_checkpoint Function
julia
brm_filter_checkpoint(filter::BRMFilter)
brm_filter_resume(model::Union{BRMI,RKBRMI}, checkpoint)

Copy a data-only checkpoint, including the finite state, RNG, bounded history and preparation configuration. Restore against the same authored model and frozen preprocessing, explicitly rebuilt after restart. Neither training rows nor compiled functions are saved. Resume checks model/preprocessing identity and RKPPL's configuration, package-version and state-shape checks.

Use Julia Serialization only with trusted checkpoints. File writing and atomic replacement belong to the caller. Exact continuation requires the same code, Julia/package versions and fixed model inputs.

source
BayesianRegressionModels.brm_filter_step Function
julia
brm_filter_step(filter::BRMFilter, observation::NamedTuple;
    inputs=(;), groups=nothing, condition_state_only=false)

Advance one time slice. The new state's predictive_logscore scores the observation before conditioning; log_normalizer accumulates scores from ordinary steps. State-only warm-up preserves both the accumulated normalizer and calibrated parameter masses. Missing observations advance the state without conditioning. A selected group advances on its own clock; omitted groups do not advance. Mixed global/group recurrences require synchronous slices. Group-indexed arrays retain their original positions.

source
BayesianRegressionModels.brm_filter_stream Function
julia
brm_filter_stream(filter::BRMFilter, records; steps=typemax(Int),
    condition_state_only=false, progress=nothing, stop=filter->false)

Consume records (observation=(;y=...), inputs=(;x=...), groups=nothing); inputs and groups can be omitted. Check cooperative interruption and stop before requesting each record, and return after the last completed step. Use an Iterators.Stateful iterator to resume consumption of a live stream. An ordinary filter retains no records or iterator. For BRMFilterSMC, the producer retains at most window_length records for rejuvenation; condition_state_only=true requires an ordinary filter first, then transfer through boundary.

source
BayesianRegressionModels.brm_filter_tune Function
julia
brm_filter_tune(fit; rng, init, inputs=(), groups=(;), boundary=nothing, ...)
brm_filter_tune(calibration, model; rng, init, ...)

Tune an independent fixed NUTS proposal for filter parameter learning, using RKPPL's tune_filter_smc. init is in the selected static unconstrained frame. Pass the resulting schedule as SMCOptions(tuning=schedule) to brm_filter. Only the reference is differentiated; particle resampling is not. The final temperature's kernel stays fixed throughout the stream, including boundaries.

source
BayesianRegressionModels.brm_fitted_state Function
julia
brm_fitted_state(rk::RKBRMI) -> BRMFittedState

Export the frozen preprocessing of the fitted model rk as a BRMFittedState that holds no training rows. A model is exported only when every value its program fits from the training data is a fitted value the state holds. Otherwise the error names the statement that still reads a training column, and that model is replayed with reprocess on the training fit instead.

source
BayesianRegressionModels.brm_laplace_mode Function
julia
brm_laplace_mode(target; init=nothing, iterations=1000, g_abstol=1e-6)
    -> (; draws, diagnostics)

The mode of the embedded-Laplace marginal of target, any problem brm_laplace_problem returns: the population point that maximizes its log density, by L-BFGS (Optim) with a backtracking line search on the problem's own value and gradient, from init (population coordinates, in target.names order) or, by default, the population coordinates' prior medians. It is a point fit: the mode of the marginal over the population, the integrated effects at their conditional modes there. It never puts a Gaussian over the population.

draws is one complete RK packed point (coordinates × 1, the shape of brm_laplace_draws): the population coordinates at the mode and every integrated effect at its conditional mode. diagnostics holds the log density there (value), whether L-BFGS converged (converged; a warning names a run that did not), its iterations, the gradient's norm (gradient_norm) and how many evaluations scored -Inf (nonfinite).

Needs Optim loaded (using WarmupHMC loads it through Pathfinder).

source
BayesianRegressionModels.brm_laplace_plan Function
julia
brm_laplace_plan(rk::RKBRMI; ad_backend, integrate = :auto, sample = (),
    ess_floor = 0.5, draws = 200, at = nothing, rng = Random.Xoshiro(20261031),
    max_cell_width = 128, solver=:auto, matrixfree=MatrixFreeLaplace())
    -> BRMLaplacePlan

Sort rk's latent terms for the sparse Laplace (BRMLaplacePlan):

Declared independent Gaussian vectors, such as field[1:n] .~ Normal.(mean, scale), participate in automatic planning and can be named in integrate or sample by their declaration. Each element is a diagnostic block; width screening keeps or samples the whole vector. Fixed or outer-dependent means and scales retain the authored prior and its derivatives. A term supplying another Gaussian law's parameters stays sampled. Constrained, non-Gaussian and correlated vector priors are never admitted. Derived Normal observations stay sampled automatically because their dependence on the vector can be nonlinear; name the vector in integrate to opt in.

  • integrated: every row reading the term is recognized as affine Normal, with scale fixed conditional on the sampled coordinates. Its Laplace is exact with exact determinant algebra;

  • gated: recognized affine log-Poisson, logit-binomial/Bernoulli, or log-NegativeBinomial2 rows with shape fixed conditional on the sampled coordinates. These have log-concave conditionals. The term is integrated where its per-block importance diagnostic admits it. That diagnostic proposes each block (one level of the term, one area of a field) from the Gaussian of the Laplace's precision restricted to it, given the rest at the mode, and weighs it by the exact density of the terms and prior pieces that touch it. A term is admitted when no block's importance ESS falls below ess_floor × draws. The diagnostic is measured at the population point at (default: the population coordinates' prior medians; a whole packed point is taken too);

  • never: the term moves a shape or dispersion, or is a Student-t, stratified or car_units block, which the sparse Laplace does not integrate;

  • sampled: named in sample, gated and not admitted, or read by arbitrary @plate cells/model-value observations without a structural log-concavity guarantee. This conservative rule also declines linear cells whose algebra has not been recognized. The reason identifies the relevant observations.

Automatic selection requires the recognized structure at every outer point; a good local ESS or a positive mode Hessian cannot establish it. Log-concavity does not guarantee an accurate Gaussian approximation. The local diagnostic checks only the chosen point and one block at a time, so passing it does not certify joint tails or accuracy elsewhere. Scale and shape may still depend on sampled outer parameters. The selected partition stays fixed in the target.

Before preparing derivatives, max_cell_width (a finite positive integer, default 128) bounds the integrated footprint of each ordinary observation cell, or each summand/direct outer block of a recognized sum. Cells are visited in observation-name/cell order. An overwide cell samples the whole unforced term contributing the most coordinates, breaking ties by declaration order, and updates every cell that reads that term. Correlated margins stay together. Forced terms are never silently sampled: an unresolved conflict raises with the observation, cell, width and bound. All likelihoods and priors remain. plan.width_events reports those choices; integrated_dimension and sampled_dimension report the final packed dimensions. A plan with no admitted terms supplies the full model's density and gradient through the same workflow.

integrate = (names…) and sample = (names…) override the classes by declaration or grouping. Naming a supported term in integrate explicitly opts in even without a concavity guarantee and bypasses the ESS gate, including cells, model-value observations and terms on shape or dispersion. The caller must assess that approximation; the automatic guarantee does not extend to the joint conditional containing such forced terms. A Student-t, stratified or car_units term cannot be forced (the sparse Laplace does not integrate it). ess_floor = 0.5 and draws = 200 are defaults, not measured thresholds; the plan reports each gated term's importance ESS so a reader can judge.

solver and matrixfree select the conditional algebra as in brm_laplace_problem. The plan retains that policy when applied to a target or replanned by brm_ladder_fit; explicit target keywords override it.

progress reports the plan through Treebars: a Treebars node, under which the plan builds its own, or a backend symbol such as :state. Each observation gets a node, and each ordinary cell group a node naming its Hessian block's size while Enzyme compiles it, so the node's time shows where preparation goes.

source
BayesianRegressionModels.brm_nlme_conditional_point Function
julia
brm_nlme_conditional_point(problem::BRMNLMEConditionalProblem, x)

Return the complete point of problem.target for the free point x: problem.point with problem.free replaced by x, in the target's frame (Stan unconstrained order for map.sb, RK packed order for map.rk). A matrix whose columns are free draws, as WarmupHMC returns them, gives one complete point per column. The result is fresh; x is not mutated.

source
BayesianRegressionModels.brm_nlme_estimates Function
julia
brm_nlme_estimates(m::BRMNLMEModel, θ, σ, Ω[, ebes])
brm_nlme_estimates(m::BRMNLMEModel, result[, ebes])

Read an NLME point of m in the model's own names and natural units. θ and σ are m's unconstrained vectors (m.theta, m.sigma order) and Ω the natural-effect covariance: one block-diagonal matrix for a flat model, one matrix per family for a nested one. With NLMEEstimation loaded, result may be a FOCE(I) or SAEM result; a FOCE(I) result carries its own EBEs. ebes is an empirical_bayes / posthoc result for m.

Returns (; point, eta):

  • point — one named tuple keyed by the model's identifiers:

    • a predictor's population coefficients under the predictor's name, one entry per coefficient address (point.log_CL.weight for effect(log_CL, weight)), on the scale the formula gives them. A categorical column is one entry of level => value pairs, one per non-reference level, as brm_start takes it;

    • a sampled scalar under its name, constrained (point.sigma, not its log);

    • a random-effect block under its |ID| (point.pk), or var"<predictor>|<group>" for a block without one, as (; group, margins, covariance, sd, cor) on the η scale; a block whose every scale and whose correlation are known (sd(...) = value, cor(:, ID) = R) as (; group, margins, known = true, covariance, sd, cor) with its known values (its η are its standardized draws, under a covariance held at the identity, and its effects diag(sd) L η); a block with some known values adds known_sd (each margin's known SD, nothing at a sampled one) and known_cor = true as they apply, with covariance, sd and cor in natural units (a known margin's η is its effect over its known SD; a known correlation's η are its standardized draws, its effects diag(sd) L η); a stratified gr(g, by=b) block as (; group, by, margins, strata), whose strata pairs each level of b with its stratum's (; covariance, sd, cor). A block over a grouping in shared_groups (its coordinates are θ) adds crossed = true and effects, one level => effects pair per level of the grouping: the block's effect on its margins, as the model adds it to the rows;

    • other — the constrained values of estimated or fixed declarations that have no BRM address (shared HSGP and imputation latents, simplexes, thresholds), under their program names; empty when there are none.

  • eta — nothing without ebes; otherwise (; subjects, names, values): the subjects' grouping levels, the margin names of NLMEEstimation.parameter_names(m).eta, and the natural EBEs in m's native shape (one column, or one compact vector, per subject).

Predictor names, scalar names and block keys share one namespace; a model in which two coincide is refused. No input is mutated.

source
BayesianRegressionModels.brm_nlme_fit Function
julia
brm_nlme_fit(x, estimator; start=nothing, inits=nothing, ebes=true,
    ad_backend=nothing, shared_point=nothing, subject_group=nothing,
    nested_groups=NamedTuple(), shared_groups=(), unit_partition=nothing,
    progress=nothing, kwargs...)

Fit an NLME model through the RK backend with one of NLMEEstimation's own estimators and read the result in the model's names and natural units. Requires NLMEEstimation and Enzyme to be loaded.

  • x — a @brm model (BRMI), its RKBRMI, or a prepared BRMNLMEModel. For a BRMI or RKBRMI the model is prepared with ad_backend (default reverse-mode AutoEnzyme) and the shared_point, subject_group, nested_groups, shared_groups and unit_partition of brm_nlme_model; passing those to a prepared model is refused. A BRMI is lowered centred, except the mi(...) completions whose law reads the units' draws, which are lowered non-centered (RKBRMI(brmi; completions = (:x,))) so their density belongs to their units' conditionals, and the grouped entries of mi(x)::shares(total, rows); an RKBRMI with such a completion centred is refused by brm_nlme_view.

  • estimator — NLMEEstimation.saem, NLMEEstimation.focei, or NLMEEstimation.empirical_bayes (equivalently posthoc, which estimates the subject effects at the start's population values). kwargs pass through to it (rng, options, kernel, subjects, method, …); FOCE without interaction is focei with FOCEOptions(interaction=false).

  • start — nothing for the prior-median start of brm_nlme_start(m), a full RK packed point u for brm_nlme_start(m, u), a start returned by brm_nlme_start, or NLMEEstimation's own start: a NamedTuple (; theta, sigma, omega) with optional eta (one column, or compact vector, per subject) and the subjects that eta belongs to, as grouping levels the way brm_nlme_start reports them (all of the model's without it), or an NLMEEstimation saem or focei result, which starts from its population point and warm-starts from its subjects' final SAEM states or FOCE(I) EBEs. Ω is derived from omega. The start's subject effects are matched to the estimator's subjects by subject; a caller's η0 replaces them, and a subject the start has none for needs one.

  • inits — initial values keyed by prior address, as brm_start takes them; every coordinate they do not address keeps its prior-median start. Give either start or inits.

  • ebes — after saem, run empirical_bayes at the fitted population point (warm-started from SAEM's final subject states) so the result reports EBEs. SAEM's own eta are chain states, not EBEs. true uses empirical_bayes's defaults, false skips the pass, and a NamedTuple of empirical_bayes keywords tunes it (ebes=(; options=EBEOptions(maxiter=20), require_convergence=false)); subjects and η0 come from the SAEM result and are refused there. focei always returns its EBEs and empirical_bayes is the pass itself, so for them ebes is ignored and keywords are refused.

  • progress — report the whole fit through Treebars: a Treebars node, under which the call builds a BRM NLME fit node, or a backend symbol such as :state that starts a new root. Its phases are Lower to ReactiveKernels, Prepare NLME model (the steps of brm_nlme_model), Starting point, Estimate (<estimator>) holding the estimator's own node, and after saem Posthoc EBEs holding empirical_bayes's node; a stage x has already passed shows as reused. An interrupt requested on that node or an ancestor (Treebars.request_interrupt!) raises Treebars.ProgressInterrupted when the next preparation phase starts; once the estimator runs it honours the interrupt as NLMEEstimation documents (an interrupted saem returns its last completed iteration with interrupted = true), and the EBE pass is then skipped, returning ebes = nothing. nothing (the default) reports nothing.

Returns (; estimates, result, ebes, start, model): estimates as brm_nlme_estimates returns them, NLMEEstimation's raw result, the EBE result used (or nothing), the start, and the prepared model.

source
BayesianRegressionModels.brm_nlme_joint_start Function
julia
brm_nlme_joint_start(map::BRMNLMEJointMap;
    theta, sigma, omega, eta, subjects, shared_point=nothing)

Convert one NLME estimate into the same model's complete BridgeStan init_positions. theta and sigma are the NLME model's unconstrained vectors. For a flat model, omega is its natural-effect covariance matrix, eta[:, j] is the natural effect of subjects[j], and covariance between independent blocks must be zero. For a nested model, omega[f] is one covariance matrix per family and eta[j] is the compact effect vector for subjects[j]. Subjects may be reordered, but every model level must occur exactly once. If the NLME model estimated shared latent coordinates, pass its complete theta vector in the model's packed order, including those coordinates. For a fit that held them fixed, pass the shorter population theta and the same full packed shared_point supplied to brm_nlme_model. Only the shared entries of that point are copied. The two forms cannot be combined.

Returns (; stan, fixed, free, checked). stan is the full unconstrained vector. fixed names and indexes the population, scalar, shared and covariance coordinates; free names and indexes standardized subject coordinates. Both sets include their values and partition the full vector. checked is BRM's physical RK/Stan coordinate comparison. The function also inverts the constructed point and checks the supplied theta, sigma, omega, eta and shared values. No caller input is mutated.

source
BayesianRegressionModels.brm_nlme_joint_values Function
julia
brm_nlme_joint_values(map::BRMNLMEJointMap, stan_u)

Read a complete Stan unconstrained point back as (; theta, sigma, omega, eta, subjects, shared). theta contains ordinary population coordinates; shared contains the names and unconstrained values of shared latent coordinates in RK order, whether they were fitted or fixed. omega is the covariance matrix of natural effects (a known margin's η is its effect over its known SD); columns of eta follow subjects in the NLME view's grouping-level order. The inverse uses the validated semantic transport and the actual RK constrained scale/correlation values.

source
julia
brm_nlme_joint_values(problem::BRMNLMEConditionalProblem, x)

Read the free point x of a conditional problem back as (; theta, sigma, omega, eta, subjects, shared), exactly as brm_nlme_joint_values(problem.map, stan_u) reads the corresponding complete Stan point, whichever backend problem evaluates.

source
BayesianRegressionModels.brm_nlme_loglikelihood Function
julia
brm_nlme_loglikelihood(m::BRMNLMEModel, i, θ, σ, η_i) -> Float64

One subject's conditional log-likelihood from its observation cells: its plate cells, its rows of flat grouped responses and its observed values of completed covariates. The work depends on those cells' observations, not on other subjects. Models whose observations have no subject cells use brm_nlme_loglikelihoods instead.

source
BayesianRegressionModels.brm_nlme_loglikelihood_and_gradient Function
julia
brm_nlme_loglikelihood_and_gradient(m::BRMNLMEModel, i, θ, σ, η_i)

Return one subject's conditional log-likelihood and its η_i gradient. RK's compact partition sampler evaluates all that subject's cells in one fused call and differentiates only the subject's own effects: θ and σ are held fixed, so no derivative flows through the values they share with other units.

source
BayesianRegressionModels.brm_nlme_loglikelihoods Function
julia
brm_nlme_loglikelihoods(m::BRMNLMEModel, θ, σ, H) -> Vector{Float64}

Every subject's conditional log-likelihood log p(y_i | θ, σ, η_i), with η_i = H[:, i] for a flat model or η_i = H[i] for a nested model, from one evaluation of the model. See BRMNLMEModel for the coordinates.

source
BayesianRegressionModels.brm_nlme_loglikelihoods_and_gradients Function
julia
brm_nlme_loglikelihoods_and_gradients(m::BRMNLMEModel, θ, σ, H) -> (values, G)

brm_nlme_loglikelihoods together with each subject's η gradient, in the same matrix or vector-of-vectors shape as H, from one reverse sweep that also retains the pointwise densities. Subjects are conditionally independent, so the joint gradient restricted to subject i's block is its conditional gradient once the standard-normal draw prior is removed.

source
BayesianRegressionModels.brm_nlme_model Function
julia
brm_nlme_model(backend::RKBRMI; ad_backend, observation_ad_backend=nothing,
    shared_point=nothing, subject_group=nothing,
    nested_groups=NamedTuple(), shared_groups=(), unit_partition=:subjects,
    progress=nothing) -> BRMNLMEModel

Prepare an RK-lowered population model for NLME estimators: its brm_nlme_view partition, the backend's sampler query retaining its pointwise densities (first-order, reverse-mode Enzyme: ad_backend must be AutoEnzyme(; mode=Enzyme.Reverse)), a reverse-over-forward sampler HVP query, its pointwise densities, and the subject attribution of every observed density.

The sampler query is prepared the first time it is used: by the lockstep gradients (brm_nlme_loglikelihoods_and_gradients) and by the per-unit Laplace. So is the HVP query: by the dense η Hessian blocks (NLMEEstimation.conditional_loglikelihood_hessian_blocks) and by the per-unit Laplace. A fit that reads neither (minibatch SVI, the per-subject unit problems) compiles neither. With ReactiveKernels before 0.1.12 its preparation holds 8n² bytes for the n packed coordinates (n one-hot basis vectors of length n), 200 GB at 158,343 coordinates; from 0.1.12 it is linear in n. No step of the preparation copies the model per thread.

observation_ad_backend selects the forward-mode backend for Gaussian moment Jacobians. With the NLMEEstimation/Enzyme extension loaded, an AutoEnzyme reverse backend automatically selects Enzyme forward mode. Other callers can pass a forward backend explicitly.

Shared sampled coordinates enter θ by default and can therefore be estimated jointly with ordinary population parameters. To hold them fixed, pass shared_point, a full RK packed unconstrained point. Only its shared entries are used. The model's θ positions and names make the chosen fit mode explicit.

Pass the same subject_group, nested_groups, shared_groups and unit_partition as for brm_nlme_view when the model has several groupings. With nested effects its NLME layout has one shared covariance family per random-effect declaration and one compact η vector per subject; the blocks over shared_groups are shared latents in θ (or fixed by shared_point).

With unit_partition=:connected, individual structural cell supports join likelihood-linked subjects before attribution. Every likelihood, gradient and subset then uses complete inference units; the view retains original subject labels and slices. The attribution description below applies to the default :subjects policy. Both policies retain strict locality validation.

Each pointwise density belongs to one subject. A density on the subject column's rows (a flat grouped response, a completed covariate's observed values, a group term of mi(x)::shares, a plate cell joining those rows) belongs to the subject of its rows. Any other observation, on rows of its own (a fragment's rows read through an index, exp(log_f[f_obs]), or joined by a plate over the fragment's own groups), has its densities' subjects measured on the pointwise query: moving the η blocks of halves of the subjects, 2⌈log₂ n⌉ evaluations for n subjects. A density that reads no subject's η counts toward the first subject.

When every observed density belongs to one subject's cells, the model prepares one compiled observation partition per unit label. Each unit value or gradient runs all its cells in one pass. RK's strict locality check refuses a value that cannot be computed at the requested rows, naming its producer. BRM checks the structural packed-coordinate footprints against its unit ownership before returning the model, including for value-only use.

One compact partition sampler is prepared on first gradient use. For nested models, value-only cell footprint kernels supply the individual supports whose cliques form each unit's sparse η Hessian pattern. These supports include both arms of branches and zero-weight coordinates; no numerical probes or gradient pruning determine the structure. Retained conditional captures can still have conservative supports; a structural read of another unit's effect is refused.

Calls from several tasks. One-unit calls can come from several tasks at once: brm_nlme_loglikelihood, brm_nlme_loglikelihood_and_gradient, the NLMEEstimation protocol's per-subject methods, and brm_nlme_unit_problem densities. NLMEEstimation's WarmupHMCNUTS(threads = true) makes such calls. Each call takes an evaluator of its own. The first evaluator is the model's own partition query and sampler. Further ones are prepared when calls first overlap, at most one per Julia thread, each with its own partition query, compact sampler and work points. Overlapping calls therefore run in parallel instead of waiting for each other. A unit's value and gradient are the same bit for bit whichever evaluator computes them. Overlapping calls need Enzyme's concurrent-GC repair (Enzyme dogfood from 72d5d25). Without it the first call that would need a second evaluator raises a BRMNLMEViewError. Batched calls run on the calling task.

progress reports the preparation through Treebars: pass a Treebars node and the call builds a Prepare NLME model node under it, with one phase per step (subject partition, pointwise sampler, observation attribution, η Hessian-vector product, Gaussian observations, subject cells, population prior; a step the model does not need is skipped), or a backend symbol such as :state to start a new root. An interrupt requested on that node or an ancestor (Treebars.request_interrupt!) raises Treebars.ProgressInterrupted when the next step starts. nothing (the default) reports nothing.

Refuses (BRMNLMEViewError) everything brm_nlme_view refuses, Student-t random-effect blocks (the estimators own a Gaussian η prior), and observed densities that cannot be attributed under the selected policy. In default :subjects mode, a plate cell joining rows of several subjects, and a measured density that reads several subjects' η (the message names them), is not finite at the measuring point, or changes with some of the moves but not all.

Numerical attribution alone cannot detect every piecewise-constant dependence. For models with subject cells, the subsequent structural ownership check also includes dormant branches and refuses a partition that reads another subject's effects before returning the model.

source
BayesianRegressionModels.brm_nlme_start Function
julia
brm_nlme_start(m::BRMNLMEModel)
brm_nlme_start(m::BRMNLMEModel, u::AbstractVector)
brm_nlme_start(m::BRMNLMEModel, map::BRMNLMEJointMap, stan_u::AbstractVector)
brm_nlme_start(m::BRMNLMEModel, inits::NamedTuple; base=m.unit)

Read one complete point of the same model as NLMEEstimation starting values for m. u is a full RK packed unconstrained point of m.backend's layout. stan_u is a full unconstrained point of map.stan_problem; map must come from the same BRMI instance and NLME partition as m, and its validated semantic transport converts stan_u to RK coordinates first. inits are initial values keyed by prior address, as brm_start takes them; the point is brm_start(m.backend, inits; base), whose default base is m's unit point (zero subject effects, and the fixed values of a fixed-shared model). Requires NLMEEstimation to be loaded.

Without a point, the start is the model's prior medians: every population coefficient, sampled scalar and random-effect scale starts at the median of the prior law the model declares for it (laws whose arguments name another scalar use that scalar's own median), the random-effect correlations at the identity, and every subject effect at zero. A coordinate whose law has no median (Flat(), or an argument without a value) and every other estimated coordinate (shared latents, simplexes, thresholds) keeps the zero unconstrained value. The result adds start_source = (; prior_median, zero), the packed names of the θ, σ and random-effect scale coordinates in each group.

Returns a named tuple:

  • theta, sigma — m's unconstrained θ and σ, read at their positions in the point. When m estimates shared latent coordinates, θ includes them in packed order.

  • omega — NLMEEstimation's log-Cholesky covariance vector ω for nlme_layout(m), the value saem, focei and empirical_bayes take.

  • omega_matrix — the natural covariance diag(scale) L Lᵀ diag(scale) at the point: one block-diagonal matrix for a flat model, one matrix per random-effect family for a nested model.

  • eta — natural subject effects diag(scale) L z, in m's native shape: a neta × nsubjects matrix, or one compact vector per subject for a nested model. Pass it as η0.

  • subjects — the grouping levels, in the subject order of eta and m.

  • names — (; theta, sigma, eta) coordinate names, as NLMEEstimation.parameter_names(m) reports them.

  • theta_roles — :population or :shared_latent for each θ entry.

  • shared — (; names, values, estimated) for the shared latent coordinates: estimated is true when they are part of θ. A model built with shared_point fixes them, and then the point's shared values must equal that model's fixed values exactly; a different point is refused.

  • loglikelihoods — each subject's conditional log-likelihood at the start.

  • population_logprior — the authored population priors in NLME coordinates.

  • max_error — the largest difference between BRM's covariance coordinates in the point and those mapped back from omega.

Every covariance block must be positive definite, and the conditional likelihoods and population prior must be finite. No input is mutated.

source
BayesianRegressionModels.brm_nlme_unit_eta Function
julia
brm_nlme_unit_eta(p::BRMNLMEUnitProblem, z) -> Vector

The unit's natural random effects η = C z at its standardized point z.

source
BayesianRegressionModels.brm_nlme_unit_problem Function
julia
brm_nlme_unit_problem(m::BRMNLMEModel, i, θ, σ, Ω) -> BRMNLMEUnitProblem

Unit i's conditional posterior at fixed population values θ, σ and Ω: Ω is the natural-effect covariance as brm_nlme_estimates takes it, one matrix for a flat model or one per covariance family for a nested one. The unit is evaluated on its own observation cells (see brm_nlme_model), so its cost does not grow with the number of units. A flat model whose observations have no subject cells is refused with the reason. A nested model without subject cells is accepted, but its unit gradient evaluates the whole model (brm_nlme_loglikelihoods_and_gradients), at a cost that grows with the number of units.

source
BayesianRegressionModels.brm_nlme_view Function
julia
brm_nlme_view(backend::RKBRMI; subject_group=nothing,
              nested_groups=NamedTuple(), shared_groups=(),
              unit_partition=:subjects) -> BRMNLMEView

Read the nonlinear-mixed-effects partition of an RK-lowered model: population coordinates, subject-level covariance coordinates, other scalars, and one compact random-effect block per subject. For several grouping columns, supply the top-level subject_group and name every other grouping once: in nested_groups, a NamedTuple mapping each nested grouping to its parent subject labels, row-aligned with the grouping (every nested level must belong to exactly one subject), or in shared_groups, a tuple of groupings crossed with the subjects. The parent labels are the name of a column the model reads (nested_groups = (g = :region,)) or the labels themselves, a vector (nested_groups = (g = data.g_region,)): the backend keeps only the columns its formulas read, so a column no formula reads is passed as a vector. Every coordinate of a random-effect block over a shared grouping (its standardized draws, scales, correlation factor and Student-t mixing weights, for any block form) is a :shared_latent, and so is a grouped hsgp(x; by = g) or a cdar(step; by = g) walk with g in shared_groups. nested_groups may also name the by grouping of a cdar or grouped hsgp term that no random effect uses, so that its levels are units. A random-effect block declared inside a function-style component call (kin ~ f(subject), with (1 | pk | subject) in f's body) is read as the same block at model scope over the column the call passes for the grouping input: that column is one of the model's groupings, named as subject_group, in nested_groups or in shared_groups like any other, and the block's |ID| and margins carry the call's path (kin.pk, predictor kin.CL), as its coordinates do (kin.b_pk_subject.z). Nested calls compose their paths. The call's other sampled locals, its population coefficients included, are :shared_latent, and so is a block whose grouping input is passed an expression rather than a column, or whose call reads other levels of the column than the model does. A car(...) field is shared, since its edges couple its areas, unless the backend was lowered by the field's unit border separator with the subject labels (RKBRMI(brmi; car_units = :subject)): then only its separator draws, scale and mixing share are shared, and each subject's interior draws (and a BYM2 field's iid part of each of its areas) are that subject's unit draws. The grouped entries of mi(x)::shares(total, rows) are unit draws of the subject owning each group's rows when the backend is non-centered (RKBRMI(brmi; completions = :noncentered)); centred they are refused, since their density reads the law and with it the units' draws. So is the centred completion of any mi(x) whose law reads the units' draws, and a submodel's sampled declaration whose law reads them: each unit's conditional would omit that prior term while the lockstep gradient carries it. Lowered non-centered, such a completion's missing entries are unit draws observing their law's density in their unit's conditional; the fits that take a @brm model (brm_nlme_fit, brm_two_stage_fit, brm_svi_fit) lower exactly those completions non-centered themselves. A latent a @plate cell declares (x ~ Normal(loc[i], s), brm-use kernel.md), and the sampled locals of a component called in a cell, are :shared_latent coordinates, read as the entries of a top-level vector x[1:n] .~ Law are: their authored law stays in the population prior, they enter θ (or are fixed by shared_point), and brm_svi_fit gives each cell's coordinates to the unit whose cells read them (a latent under a transformed law, such as LogNormal, stays global until ReactiveKernels reads its constrained block per cell). A cell latent whose law reads a value the model computes per cell (m[i]) is refused by name with the same model's rewrite. A declaration of zero length, such as the coefficient block of a single-level treatment-coded factor, owns no coordinate and is not a refusal. See BRMNLMEView.

unit_partition=:subjects keeps the scientific subjects as inference units. With :connected, structural likelihood-cell supports join subjects that a cell reads together, transitively. Shared coordinates do not join units. The model, priors and scientific subject labels are preserved; estimator indices refer to whole connected units. Merged units use compact ragged effects and retain every original covariance-family instance. This policy does not expand the coordinate inventory or remove the structural refusals below.

Refuses with BRMNLMEViewError when the model has no such reading: no random effects over the subjects, a grouping named in neither nested_groups nor shared_groups (the message names it), a subject-owned grouping that couples its levels, a subject-owned Student-t block that holds known values, a car(...) field lowered with car_units that are not the subjects, a centred mi(x)::shares(total, rows) completion or one with a group whose missing entries lie on rows of several subjects, or any coordinate the semantic inventory does not cover.

Known values on a subject-owned Gaussian block (sd(...) = value, cor(:, ID) = R) stay in the model as inputs, and NLMEEstimation's FixedOmega holds what they fix. Known scales under a sampled correlation are one family that holds those margins' SDs at 1: a known margin's η is its effect over its known SD, and the free SDs and the correlation are estimated. A block with a known correlation, or whose every value is known, is one family held at the identity: its standardized draws are η, and any sampled scale is a :shared_latent.

source
BayesianRegressionModels.brm_rk_point_to_stan Function
julia
brm_rk_point_to_stan(t::BRMCoordinateTransport, u_rk) -> Vector
brm_stan_point_to_rk(t::BRMCoordinateTransport, u_stan) -> Vector

Move an unconstrained POINT between the RK and Stan coordinate frames. Paired coordinates move by t.permutation; each t.simplexes block goes through the physical simplex, from RK's stick-breaking coordinates to Stan's isometric log-ratio coordinates or back; each t.centered block's standardized draws z become the effects b = diag(tau) * L * z per level, or back, with the point's own scales tau and correlation factor L; each t.completions part's standardized draws z become Stan's entries s = location .+ scale .* z, or back, with the location and scale RK computes at that point; each t.fields field's draws become Stan's field through its separation's linear map, or back through its inverse. The two functions are inverses and both describe the same physical parameter point. They equal brm_rk_to_stan / brm_stan_to_rk for a transport without simplex, centered or completion blocks. Neither mutates its input. Use brm_stan_gradient_to_rk for gradients and brm_stan_logdensity_to_rk for log densities.

source
BayesianRegressionModels.brm_rk_to_stan Function
julia
brm_rk_to_stan(t::BRMCoordinateTransport, v) -> Vector
brm_stan_to_rk(t::BRMCoordinateTransport, v) -> Vector

Move an unconstrained point, or a gradient with respect to it, between the RK and Stan coordinate orders of a transport without simplex or centered blocks. Both are the same permutation: each pair has equal unconstrained values, so a Stan gradient maps back to RK order exactly as the point does. A transport with simplex or centered blocks refuses both, since its points and gradients move differently; use brm_rk_point_to_stan, brm_stan_point_to_rk and brm_stan_gradient_to_rk. Neither function mutates v.

source
BayesianRegressionModels.brm_smc_carry Function
julia
brm_smc_carry(fit::Union{BRMSMCFit,BRMSMCWindowFit}; scale=nothing, basis=nothing,
    parameters=nothing, inputs=(), max_reflections=16, maxiter=100,
    progress=nothing)
brm_smc_carry(model::Union{BRMI,RKBRMI}; reference, ad_backend=AutoEnzyme())

Summarize a completed posterior with RKPPL's carry_smc, retaining BRM's fitted preprocessing without training rows. For a complete-frame cloud, the default reference has its weighted mean and marginal standard deviations. A selective window updates its compact marginal and combines it with the old inactive conditional to produce a full joint Gaussian summary. A supplied portable WarmupHMC scale_data record defines the Gaussian covariance; the caller must calibrate it as a posterior approximation. A mutation/proposal scale alone does not guarantee posterior moments. No dense covariance or mutation-kernel adaptation is performed here.

Use basis=:fit to ask RKPPL to fit bounded correlation directions and moments from the completed weighted cloud through WarmupHMC's public fitter. max_reflections and maxiter bound the fit, and progress is forwarded to the producer. The owned carried.posterior.fit_diagnostics reports reflections, iterations, residuals, convergence and effective sample size. Finite budgets can still discard covariance; convergence does not certify posterior accuracy. The fitted reference is used by subsequent windows, without adapting this completed run's production kernel.

Use basis=smc_reference(schedule).scale to ask RKPPL to fit the completed cloud's weighted variances along an independently learned orientation. This retains its bounded reflection directions and recalibrates their magnitudes, without forming a dense covariance. Cross-covariances in that basis are discarded, so its orientation must still be adequate for the posterior. basis and an explicit scale are mutually exclusive.

For a finite-state filter, use parameters=:filter and name any per-step covariate inputs. RKPPL selects the authored static parameters and retains their native constrained transforms, discarding historical latent coordinates. This calibration is consumed by brm_filter(carried, model; ...); it cannot initialize a full-frame window bridge. With basis=:fit, fitting uses only the selected static cloud. Any supplied scale or portable basis must describe the selected coordinates. A slice of a full correlated scale generally is not the marginal Gaussian scale of those coordinates.

The model form instead carries an explicitly supplied normalized posterior approximation calibrated for this model and data. smc_reference(schedule) from reference=:pilot is an importance/proposal reference, not a fitted posterior covariance; do not carry it as a posterior-moment summary without separate calibration. An external reference's location and scale are copied without retaining its observations, queries or draws.

This is an assumed-density approximation. It is exact only for a Gaussian posterior with matching moments, with additional Monte Carlo error when those moments come from a finite cloud. A diagonal reference discards correlations.

Pass the result and a newly bound declaration to brm_smc_update(carried, builder(new_window); rng, particles, options, ...). Only new, nonoverlapping observations belong in each window. By default the same source, coordinates and fitted preprocessing must apply. Selective growing windows opt in with coordinates=:auto; see brm_smc_update.

source
BayesianRegressionModels.brm_smc_checkpoint Function
julia
brm_smc_checkpoint(fit::BRMSMCFit)
brm_smc_resume(template::RKBRMI, checkpoint;
    data=nothing, previous_data=nothing, nthreads=nothing,
    ad_backend=AutoEnzyme(mode=Enzyme.Reverse))
brm_smc_resume(laplace_problem, checkpoint;
    current=laplace_problem, previous=nothing, nthreads=nothing,
    ad_backend=AutoEnzyme(mode=Enzyme.Reverse))

Create a data-only checkpoint or restore it against an explicitly rebuilt original training template. Persist the checkpoint with Julia Serialization to a trusted file. It contains particle state and identity checks, not training data, compiled targets or AD caches. Retain the model code and all required data.

For a checkpoint after a data update, data supplies the current cumulative data and previous_data supplies the previous posterior's data. Omit previous_data when that posterior is the original training fit. Resume checks the training template, current and previous bindings, and RKPPL's program, layout and endpoint-density checks. It restores without advancing; continue with brm_smc_fit. Exact replay requires the same Julia/package versions, model code, data and configuration. File writing and atomic replacement belong to the caller.

The checkpoint keeps the worker cap options.nthreads it was written with. nthreads=n (ReactiveKernelsPPL 0.1.100) replaces only that cap, for example nthreads=Threads.nthreads() after moving to a process with more threads; the workers used stay bounded by the available Julia threads and the particle count. Particle positions, weights, temperatures and the normalizer do not depend on it; per-worker sums in the stage diagnostics and the recorded worker count do. The window-checkpoint method brm_smc_resume(model::BRMI, checkpoint) takes the same keyword.

A Laplace checkpoint requires explicitly reconstructed equivalent problems: current is the cumulative endpoint and previous the previous endpoint (defaults to the training template for the first update). Approximation and solver settings, data, coordinates and preprocessing must match. No problem, factory or mutable solver workspace is stored in the checkpoint.

source
BayesianRegressionModels.brm_smc_rescore Function
julia
brm_smc_rescore(template::RKBRMI, checkpoint;
    data=nothing, previous_data=nothing, rtol=1e-10,
    ad_backend=AutoEnzyme(mode=Enzyme.Reverse))
brm_smc_rescore(model::BRMI, checkpoint;
    rtol=1e-10, ad_backend=AutoEnzyme(mode=Enzyme.Reverse))
brm_smc_rescore(laplace_problem, checkpoint;
    current=laplace_problem, previous=nothing, rtol=1e-10,
    ad_backend=AutoEnzyme(mode=Enzyme.Reverse))

Recompute a checkpoint's saved endpoint scores on the current host, explicitly accepting only floating-point drift within rtol * max(abs(saved_score), 1) per score. Requires ReactiveKernelsPPL 0.1.156. All version, model, data, coordinate and checkpoint-state checks still apply. The reconstruction arguments match brm_smc_resume, including cumulative updates, carried-reference windows and embedded Laplace problems.

Returns a new checkpoint without changing the input. Each call appends a record to checkpoint.state.rescored with changed, max_abs, max_rel, rtol and codegen. Save this returned checkpoint, then pass it to brm_smc_resume on the same host. Resume itself remains exact; it never rescores automatically. This is not a version migration and does not rescore tuning-pilot checkpoints.

source
BayesianRegressionModels.brm_smc_compare Function
julia
brm_smc_compare(fits::BRMSMCFit...)
brm_smc_runs(model; seeds, particles=1000, reference=nothing,
    options=SMCOptions(), ad_backend=AutoEnzyme(mode=Enzyme.Reverse), progress=nothing)

Compare two or more completed fits of the same model, data and, for updates, the same previous posterior; fits of different identities, or fits that have not reached temperature one, are refused by name. Nothing is fitted or reweighted: the comparison summarizes the retained clouds. Per unconstrained coordinate (names) it returns each run's weighted mean and SD (runs), the pooled mean and the root mean within-run variance (pooled_mean, pooled_sd), the largest difference between run means in pooled-SD units (mean_difference), the smallest and largest run SD in pooled-SD units (sd_ratio_min, sd_ratio_max), and the coordinate with the largest mean difference (worst). log_normalizer holds the runs' evidence estimates with their mean and sample SD. Each run also reports its surviving initial lineages, this bridge's stage count, and the evaluations and divergences summed over its retained history, which history_limit may have truncated.

These are descriptive agreement statistics between independent runs, not Monte Carlo standard errors and not an acceptance gate: close agreement does not prove the runs explored the posterior, and disagreement localizes which coordinates to inspect. brm_smc_runs fits one bridge per integer seed with the same settings as brm_smc_fit, in sequence, and returns (; fits, comparison).

source
BayesianRegressionModels.brm_smc_coordinates Function
julia
brm_smc_coordinates(fit::BRMSMCWindowFit)

Inspect an initialized or completed selective window's compact, current-model and full-joint coordinate mapping through RKPPL's smc_window_coordinates. Particle rows use the compact order; brm_smc_recover uses the joint order. Requires a fit initialized with coordinates=:auto.

source
BayesianRegressionModels.brm_smc_fit Function
julia
brm_smc_fit(model; rng=Xoshiro(), particles=1000, reference=nothing,
    options=SMCOptions(), ad_backend=AutoEnzyme(mode=Enzyme.Reverse),
    stages=typemax(Int), progress=nothing)
brm_smc_fit(fit::BRMSMCFit; stages=typemax(Int), progress=nothing)

Fit a BRMI, RKBRMI or prepared RK-backed brm_laplace_problem through RKPPL's adaptive SMC bridge, or continue a partial fit. Load ReactiveKernels, ReactiveKernelsPPL, SequentialMonteCarlo, WarmupHMC, Enzyme, ADTypes and DifferentiationInterface. The model is evaluated with its full prior, likelihood and unconstrained-coordinate Jacobian.

For an embedded-Laplace problem, the supplied marginal gradient is consumed directly, without differentiating through its mode search. Generic, structured, sparse and zero-integration targets are supported (RKPPL 0.1.57+). Each sampler execution, pilot and mutation worker owns independent mutable problem workspaces. ad_backend prepares the reference; the supplied problem already owns its target-gradient implementation. Complete a finished marginal cloud with brm_laplace_draws(fit; conditional, rng), retaining its returned weights. The normalizer is for the approximate marginal, and conditional completion does not correct that outer approximation.

reference is RKPPL's SMCReference(location, scale): a normalized Gaussian in unconstrained coordinates. scale accepts a vector of diagonal scales or a portable WarmupHMC.scale_data(L) record. The default is standard Normal or the exact reference retained by options.tuning. These are reference draws, not model-prior draws. Its actual density is included in the importance ratio. options is RKPPL's SMCOptions; mutation uses fixed NUTS, with diagonal scales or metric=WarmupHMC.scale_data(L). With options.tuning=brm_smc_tune(...), its settings vary between stages according to the precomputed schedule; they stay fixed during each stage. History retains the selected kernel, evaluation count, mean acceptance and mean squared unconstrained movement. These diagnostics do not prove adequate exploration. The explicit Random.Xoshiro is copied, not advanced.

stages bounds the number of complete bridge stages in this call (zero only initializes). progress accepts the usual BRM Treebars node or backend symbol. An interrupt returns the last completed stage; resume the returned fit. No other backend is fitted by this entry point.

Numerical failures propagate ReactiveKernelsPPL.SMCNonfiniteError (RKPPL 0.1.37+), with owned position and optional gradient vectors, value, quantity, endpoint and temperature. Its compact display does not replace the complete numerical fields. NaN/+Inf densities and nonfinite gradients at finite density fail fast; -Inf still denotes points outside support. A failed continuation leaves the input fit and its RNG unchanged, so it can be inspected or checkpointed. This exception also propagates from brm_smc_update.

source
BayesianRegressionModels.brm_smc_recover Function
julia
brm_smc_recover(fit::BRMSMCWindowFit, compact_position; rng=Xoshiro())

Recover one full joint unconstrained position from a selective window's compact position. Selected coordinates keep their supplied values; omitted old coordinates are drawn from their carried conditional Gaussian. The result follows the joint order of brm_smc_coordinates. Recovery does not add full-width particles to the fit. A supplied compact position must have the order and length of a column of fit.state.positions.

Works for an initialized or completed coordinates=:auto window. To obtain a posterior draw, use a completed fit and select a compact particle according to fit.state.weights before recovery.

source
BayesianRegressionModels.brm_smc_tune Function
julia
brm_smc_tune(model; rng, init, reference=nothing,
    temperatures=nothing, pilot_steps=64, pilot=nothing,
    max_reflections=nothing, recording_target=nothing, pilot_evaluations=nothing,
    reference_inflation=nothing, grid_start=nothing, progress=nothing, callback=nothing,
    checkpoint_dir=nothing, resume=false, overwrite=false,
    options=SMCOptions(), ad_backend=AutoEnzyme(mode=Enzyme.Reverse))
brm_smc_tune(completed_fit::BRMSMCFit, cumulative_data; rng, init,
    temperatures=nothing, pilot_steps=64, pilot=nothing,
    max_reflections=nothing, recording_target=nothing, pilot_evaluations=nothing,
    grid_start=nothing, progress=nothing, callback=nothing, checkpoint_dir=nothing,
    resume=false, overwrite=false,
    options=SMCOptions())

Prepare bridge-specific independent pilots before running production particles. A completed call returns RKPPL's SMCTuningSchedule; pass it to SMCOptions(tuning=schedule) in brm_smc_fit or brm_smc_update. Load the same packages as for fitting. Both explicit rng::Xoshiro and unconstrained init are copied; choose them independently of the production cloud, including the retained cloud of a completed fit. BRM never derives pilot inputs from fitted particles. model may be a prepared Laplace problem; for its updates pass the prepared cumulative target in place of cumulative_data, as in brm_smc_update.

The default pilot=:continuous adapts diagonal scales and step size at each supplied temperature; pilot_steps counts transitions per knot. pilot=:adaptive uses WarmupHMC's adaptive warmup and retains the active portable scale together with its paired step size; pilot_steps is its retained-draw floor. Optional max_reflections and recording_target control geometry and the recording pool; pilot_evaluations sets the initial work window, not a hard total-work budget. nothing leaves these controls and pilot at RKPPL's defaults. Pilot draws are discarded; retained pilot evaluation counts exclude initialization and the first step-size search.

Pilots run one after another by default (grid_start=nothing, RKPPL's :sequential): each grid pilot starts at the previous knot's final position, and no thread count shortens tuning. With pilot=:adaptive, grid_start=:independent (ReactiveKernelsPPL 0.1.100) starts every grid pilot at its own copy of init and runs up to options.nthreads of them at once, capped by the available Julia threads and the unfinished knots. The reference pilot still finishes first. Knot seeds are reserved in grid order, so the completed schedule is the same for every worker count, but it generally differs from the sequential schedule. The continuous pilot is sequential only. Keep grid_start unchanged when resuming a tuning checkpoint; options.nthreads may change there.

Production uses the nearest frozen temperature knot, with ties selecting the higher knot. temperatures must increase strictly from zero to one; nothing uses RKPPL's default grid. Include small positive knots for bridges that change rapidly near zero; a generic default need not resolve a particular model's curvature. options supplies the starting kernel and production move/depth settings and must not already contain a schedule. Pilot draws are not posterior samples.

For an initial fit, the normalized reference defaults to standard Normal and stays fixed. With pilot=:adaptive, reference=:pilot, a separate full-target pilot first estimates the reference mean and, from RKPPL 0.1.47, the spread of its retained draws in the learned basis multiplied by reference_inflation (RKPPL's default is 2; nothing leaves that default; 1 uses the uninflated moments); that normalized Gaussian is then frozen before temperature-grid tuning and production. The scale is stored as copied plain data, with no dense metric. Cross-covariances in the learned basis are discarded, and inflation does not guarantee posterior coverage: compare independent runs (brm_smc_compare) and read each stage's reference_sd beside its coordinate_sd. Omit reference in the subsequent fit to use the schedule's exact reference; an explicit conflicting reference rejects. For an update, supply the complete cumulative data. The original preprocessing is frozen and the previous posterior is the source; there is no initial-reference argument. Schedules belong to their exact endpoints and cannot silently transfer to new data. Checkpoints retain the schedule without rerunning its pilots on resume. The production temperature rule remains adaptive; this does not establish exactly unbiased evidence at finite particle counts.

With pilot=:adaptive, progress accepts a Treebars parent and reports nested tuning, current pilot and sampler progress. callback(snapshot, boundary) can return literal true to stop at :init, :window or :pilot boundaries. The scalar snapshot describes phase (:reference or :grid), knot, temperature, boundary, completed_knots, window, retained_draws and evaluations. A stop before completion returns RKPPL's SMCTuningPartial, including when no draw exists yet; it cannot tune production. A stop after the last completed pilot returns the ready schedule. These boundaries are cooperative: initialization or one window can exceed a wall-clock deadline.

checkpoint_dir atomically retains tuning_latest.jls before callbacks. Resume with the original model/data/preprocessing and tuning keywords using either resume=partial (also after trusted Serialization round-trip) or checkpoint_dir=dir, resume=true. Use this same method for initial, prepared Laplace, cumulative-update and carried-window targets; retain the same previous fit/carry and coordinate selection for updates. BRM supplies endpoint identities; RKPPL validates those, configuration and versions, skips completed pilots and restores the active sampler and RNG. The required rng is ignored on resume. Supply callback/progress afresh. Inputs and supplied partials remain unchanged. A fresh process rebuilds the model as usual, including models whose laws are bound in the generated RK program module (such as gmrf(...) fields); this needs ReactiveKernelsPPL 0.1.98 or later. Checkpoints written with an earlier ReactiveKernelsPPL are not migrated: resume them with their original versions or write a new initialization checkpoint.

Fresh calls refuse an existing tuning checkpoint unless overwrite=true; overwrite cannot accompany resume. Only the latest outer checkpoint is kept and progress/history retention is bounded, but active sampler draws can grow. Completed pilots retain summaries, not draws. A process failure loses work since the last boundary; without a directory, only an orderly stop yields recoverable work. Keep Julia/package versions, code, data and configuration unchanged and deserialize only trusted files. Production brm_smc_checkpoint is separate: it retains an already-completed schedule, not an unfinished pilot.

source
BayesianRegressionModels.brm_smc_update Function
julia
brm_smc_update(fit::BRMSMCFit, cumulative_data;
    options=fit.state.options, stages=typemax(Int), progress=nothing)

Update a completed fit to the posterior for cumulative_data, which must contain the complete data intended for the new posterior, not just the new rows. Replays the original training template with frozen preprocessing and the same coordinates. New group levels and incompatible layouts are refused.

For a Laplace fit, pass a prepared next problem in place of cumulative_data. Build it with brm_laplace_problem(reprocess(training_rk, cumulative_data); ...) using the same integration, engine, tolerance and iteration limit. BRM checks those controls, ordered coordinates and frozen preprocessing before bridging.

The bridge is from the previous posterior to the new posterior: the prior and Jacobian occur once. Both histories are evaluated after parameter moves, including deterministic recurrences. This is sequential parameter inference with full-history replay, not constant-cost streaming or latent-state filtering. Returns a new fit; its input remains usable. A partial update is continued with brm_smc_fit, not by starting another update.

If the completed fit used tuning, its schedule belongs to the old bridge and the default options rejects. Supply a new brm_smc_tune(fit, cumulative_data; rng, init, ...) schedule in SMCOptions(tuning=...), or explicitly choose untuned SMCOptions().

source
BayesianRegressionModels.brm_stan_gradient_to_rk Function
julia
brm_stan_gradient_to_rk(t::BRMCoordinateTransport, u_rk, stan_gradient) -> Vector

Pull back the gradient of Stan's normalized log density with Jacobian (propto=false, jacobian=true), taken at brm_rk_point_to_stan(t, u_rk), to RK's coordinates at u_rk; the result is RK's log-density gradient. Paired coordinates move by t.permutation; a simplex block multiplies by the transpose of the exact Jacobian of its stick-breaking-to-log-ratio map, whose log-Jacobian difference is the constant t.logdensity_offset. A centered block multiplies by the transpose of the Jacobian of z -> b, which also moves its scale and correlation coordinates, and adds the gradient of that map's log-Jacobian (see brm_stan_logdensity_to_rk). A standardized completion's entries s = location .+ scale .* z pull back to scale .* g on its draws and, through the location and scale, to every coordinate they read (a reverse-mode Enzyme pullback of RK's values, which needs Enzyme loaded), plus the gradient of the log-Jacobian sum(log, scale). A separated car(...) field multiplies by the transpose of its linear map, whose log-Jacobian is in the constant t.logdensity_offset. Neither input is mutated.

source
BayesianRegressionModels.brm_stan_logdensity_to_rk Function
julia
brm_stan_logdensity_to_rk(t::BRMCoordinateTransport, u_rk, stan_value) -> Real

RK's log density at u_rk, from Stan's normalized log density with Jacobian (propto=false, jacobian=true) stan_value at brm_rk_point_to_stan(t, u_rk): stan_value + t.logdensity_offset (the constant simplex offset) plus, for each centered block, the log-Jacobian G * log(det(diag(tau) * L)) of its map z -> b over its G levels at u_rk (plus K/2 * sum(log, w) over a Student-t block's mixing weights), and, for each standardized completion, the log-Jacobian sum(log, scale) of its map z -> location .+ scale .* z over its entries at u_rk. Works for every transport; without centered blocks or standardized completions it equals stan_value + t.logdensity_offset.

source
BayesianRegressionModels.brm_start Function
julia
brm_start(rk::RKBRMI, inits::NamedTuple; base, term_inits=(), component_inits=()) -> Vector{Float64}
brm_start(sb::SBBRMI, stan_model, inits::NamedTuple; base, term_inits=(), component_inits=()) -> Vector{Float64}

Build a complete unconstrained starting point from initial values keyed by the model's prior addresses. The RK method returns a packed point of rk's layout, the value rk_logdensity_problem and brm_nlme_start take. The Stan method returns a point of the compiled stan_model (a BridgeStan.StanModel compiled from sb, e.g. stan_instantiate(sb; path).model), the value a sampler takes as its initial position.

inits keys are resolved against the model:

  • lp = (; Intercept = 1.2, x = 0.3) sets population coefficients of linear predictor lp, on its link scale (effect(lp, Intercept), effect(lp, x)). Use the public predictor name: CL for log(CL) ~ 1 + x. A categorical predictor column takes level-keyed pairs, lp = (; arm = ["b" => 0.4, "c" => -0.1]), one per non-reference level. The first categorical term of an intercept-free predictor (0 + arm, 0 + factor(g)) is coded as cell means and has no reference level: every level is a coefficient, lp = (; arm = ["a" => 1.1, "b" => 0.4, ...]).

  • ID = Σ sets the scales and correlation of the shared (… | ID | g) block from the covariance matrix Σ of its natural effects. Rows and columns follow ranefcoefnames(brmi, ID). ID = (; sd, cor) sets either part: sd is one positive value per margin (or one for all) and cor a correlation matrix in the same order.

  • ID = (; sd, cor, effects) also places the block's groups: effects = ["a" => 1.2, "b" => -0.4, …] gives each listed level its effect, one number for a one-margin block and one vector in ranefcoefnames order otherwise. An effect is what the level adds to each margin's linear predictor, on its link scale: the effects that brm_ranef_draws reads back. The block's draws are solved for under its scales and correlation as given (or at base), and a Student-t block's mixing weights at base, so each listed group starts at its own value instead of the population value. Unlisted levels keep their coordinates at base: their standardized draws, or their effects in a centred block.

  • A stratified (… | ID | gr(g, by = b)) block has its own scales and correlation in each stratum (level of b). sd, cor and ID = Σ set every stratum; stratum => value pairs set the listed ones, sd = ["small" => 0.4, "large" => [0.6, 0.2]] (one value for all margins, or one per margin), cor = ["small" => C], ID = ["small" => Σ]. Unlisted strata keep their values at base. Each listed level's effects hold under its own stratum's scales and correlation.

  • name = value sets a scalar parameter (sigma ~ Exponential(1)), vector parameter (cutpoints, a Dirichlet simplex), or matrix parameter on its constrained scale. For L ~ LKJCholesky(K, eta), give the lower Cholesky factor, e.g. L = [1.0 0.0; 0.3 sqrt(0.91)], not a correlation matrix. A matrix must have the parameter's exact shape.

  • name = values sets a latent declared in a @plate cell (log_T ~ Normal(loc, s)) on its constrained scale: one flat vector, cell after cell, or one vector per cell when its length varies by cell (one number per cell for a scalar latent). Both backends take both forms and give the same physical point.

term_inits sets formula terms' own parameters with quoted prior addresses:

julia
term_inits = [:(sd(mu, cdar(year))) => 0.02, :(ar(mu, cdar(year))) => 0.6]
u = brm_start(sb, stan_model, (; mu=(; Intercept=0.0)); term_inits)

Addresses are parsed, never evaluated. They follow the prior grammar's wildcards, components (sd(mu, t2(x, z), rr)) and literal keyword qualifiers. Values are on the natural constrained scale. Scalars broadcast over a vector-valued parameter; supplied vectors must have its exact size. Simplexes require positive entries summing to one. Known values may only be restated consistently. A predicted hyperparameter must be initialized through its predictor, since it has no independent sampled carrier.

component_inits sets sampled parameters local to reusable component calls:

julia
component_inits = [:left => (; a=0.7, z=[-0.2, 0.4]),
                   (:nested, :inner) => (; a=0.9)]
u = brm_start(rk, (; sigma=0.6); component_inits)

A scope is the full tuple of authored call targets, or a target symbol when it identifies exactly one call. Each NamedTuple uses that call's local parameter names and constrained scalar or array values of the exact shape. Positive and bounded scalars, simplexes and correlation Cholesky factors use their physical values. A key naming one of the call's own linear predictors or |ID| blocks takes the inits grammar above, resolved in the call: rise = (; Intercept = log(1/6)) sets effect(rise, Intercept) on the link scale, and rates = (; sd, cor, effects) or rates = Σ sets the call's shared block, with effects keyed by the call's own levels:

julia
component_inits = [:left => (; rise=(; Intercept=log(1/6)),
                       rates=(; sd=[0.3, 0.5], cor=[1 0.4; 0.4 1],
                              effects=["a" => [0.1, -0.2]]))]

Unknown, ambiguous or duplicate scopes, computed values, wrong shapes and invalid constraints are rejected. RK initialization uses its native layout and needs no compiled Stan model. An unconditioned RKBRMI (every response omitted) samples nothing: its start is the empty point, and an addressed value is refused because no coordinate holds it.

base=:prior_median fills unaddressed scalar-prior parameters from finite medians within their effective bounds, including fitted length-scale floors. This includes scalar parameters, population coefficients and |ID| block scales recursively inside components, with the inputs bound separately at each call. Explicit inits, term_inits and component_inits take precedence. Structured latent blocks (cell latents, innovations, ordered vectors, correlation factors, simplexes and joint shrinkage coordinates) keep the valid neutral coordinates of the zero base; these are not called multivariate medians. An unsupported scalar median requires an explicit value or a numeric base. This deterministic operation does not optimize or sample. brm_start(sb, stan_model, (;); base=:prior_median) returns a reusable vector. It does not change the no-inits method, which computes a start from data.

Every other coordinate keeps the constrained value it has at base, a full unconstrained point of the same backend (default all zeros: coefficients 0, scales 1, identity correlations, standardized random effects 0). A random base gives Stan-style random starting values for the unaddressed rest. The natural random effects are zero whenever their standardized draws are zero, whatever scale and correlation are set.

On an SBBRMI with exact total-coefficient blocks, a coefficient the block absorbed has no sampled coordinate: its value places every group's total at its population value A β — with group-level predictors in the block, the group's own A (W[g,:] .* β) — plus the group's effect given through the |ID| the block absorbed ((; effects), the deviation of the total), with the block's unaddressed absorbed coefficients and effects at 0. Such an |ID| keeps its address: ID = Σ or (; sd) sets the block's total scale, the SD of each group's total around A β, which is the margin's between-group SD. An |ID| that a sum-to-zero block (s2z_groups) claimed keeps its address the same way: (; sd) sets the block's scale tau, and (; effects), which must list every level, sets the levels' deviations from their mean μ. A coefficient a sum-to-zero block absorbed, or effects given for it, set the block's sampled population coefficient theta = β + B μ, with μ the mean of the given effects (zero without) and an unaddressed coefficient at 0.

An |ID| block whose margins are partly integrated out of the model (an omitted response) samples only its active margins; their scales, correlation and effects are the corresponding parts of the given values.

Unknown addresses, ambiguous names, wrong shapes and values outside a parameter's support are errors. The result is checked: constraining it reproduces every addressed value. No input is mutated.

source
BayesianRegressionModels.brm_svi_centeredness Function
julia
brm_svi_centeredness(fit, controls) -> Vector{Float64}

A learned-centering SVI fit's controls as the centeredness vector of adaptive_centering_problem, in the order of controls, the rows adaptive_centering_controls reports for that wrapper: each random-effect row whose grouping, margin and level a fit cell shares takes that cell's c; every other row keeps its current c. WarmupHMC then adapts from there. The wrapper locates a cell at its matched population coefficient (and containing terms), where SVI locates it at all its mu-referenced coefficients, so the controls are a start, not the same parametrization.

source
BayesianRegressionModels.brm_svi_combine Function
julia
brm_svi_combine(x, slices; exclude=(), rng=Random.Xoshiro(1), prior_pairs=16,
    prior_iterations=150, joint_limit=4096, ad_backend=nothing,
    shared_point=nothing, subject_group=nothing, nested_groups=NamedTuple(),
    shared_groups=(), unit_partition=nothing, global_coordinates=nothing,
    progress=nothing) -> BRMSVIStart

Combine brm_svi_fit fits of one declaration on slices of the data into a factor-level start for the fit of x, the same declaration on all of it: one sweep of expectation propagation on partitioned data (Vehtari et al. 2020, JMLR 21(17)) in the variational form of partitioned VI (Ashman et al. 2022, arXiv:2202.12275). Pass the result as brm_svi_fit(x; start).

  • x — the full model, as brm_svi_fit takes it, with the same preparation keywords. Pass a prepared BRMNLMEModel to prepare its minibatch target once for this call and the fit.

  • slices — the slices' fit results or their brm_svi_checkpoint states (a streaming carry's state included). Each slice is the same declaration with the same groupings, bound to a subset of the rows, and each unit's rows lie in one slice (units nested in the slices, such as stations in regions). Its preprocessing must equal x's except the level tables of the unit grouping, nested groupings, and shared groupings whose levels reach the coordinates only through their random-effect draws: a fitted transform (standardize, constant) fitted on a slice's rows is refused, so bind such a slice with RKBRMI(builder(slice_data), brm_fitted_state(full); resample_groups=(unit_grouping,)). A state from an older BRM is refused; take brm_svi_checkpoint of the fit again.

Coordinates match across bindings by semantic identity: a random-effect draw of the units, a nested or a shared grouping by its block, margin and level label; any other coordinate by its packed name, so a global model-scope vector must mean the same entry in every slice (one frame for a field's basis, for example). A unit's packed-name coordinate matches only that unit's factor in a slice, since an entry of a vector indexed by the units sits at another position in another binding; where the names differ it keeps the default.

Centered fits and checkpoints are accepted. Their unit factors are Gaussian conditional on the globals: each is mapped to packed coordinates at the global mean when that unit was last fitted, using its saved affine maps, before the usual slice carry. receipt.centering records projection=:conditional_at_saved_global_mean and which slices were centered. This start does not retain the dependence of a unit's packed coordinates on global uncertainty. Dense factors preserve all conditional covariance. As with plain factor starts, a structured unit starts from marginal SDs with zero rank loadings. Its centering transform preserves residual marginal variances, projecting residual correlations. An older centered checkpoint without affine maps can still stream or resume. To combine it, checkpoint its original live fresh fit again, or stream a new window covering the units with missing maps.

  • Global coordinates combine as a product of Gaussian sites in unconstrained coordinates, P = P₀ + Σ_s (P_s − P₀) and P m = P₀ m₀ + Σ_s (P_s m_s − P₀ m₀), with the prior counted once. (m₀, P₀) is the diagonal Gaussian projection of the global prior (the factor a fit on no data reaches, from prior_iterations natural-gradient steps on prior_pairs antithetic draws of rng); a flat prior has P₀ = 0. A slice contributes a site only where its data reaches the coordinate (an observation reads it, or a prior of a reached coordinate does); a slice holding a global inside one of its units contributes that unit factor's marginal. P_s is the inverse of the slice factor's covariance over the coordinates it reaches, so a LowRankGlobal slice's rank part enters as correlation: a ridge in a slice (a direction its data leaves to the prior, such as a level two coefficients share) stays wide in its site, and the product lands where the slices' ridges cross, which a coordinate-by-coordinate product cannot find. MeanFieldGlobal slices hold no correlation, so their sites are diagonal; fit the slices with LowRankGlobal(r), r at least the number of such directions, where they disagree. A joint site holds the coordinates a slice narrows (a marginal variance below 0.8 of the prior projection's) or carries along a ridge (below 1.2, with at least 0.8 of it in the rank part); a rank row on a coordinate the slice leaves at its prior is noise, so there the coordinate has a marginal site where it is narrower than the prior and none otherwise. A site's directions wider than the prior's projection are dropped and counted. The product is dense in the coordinates in joint sites; above joint_limit of them (or at 0) the globals combine coordinate by coordinate through their marginal variances, and they do the same if a joint mean leaves the range that supports it: from the lowest to the highest of 3 sds around each counted site's mean and the prior's. Slices can contradict each other by thousands of their own sds, on a coordinate each pins by itself. A plain product would hold that coordinate as narrow as the narrowest slice, where few of them put it, and through small correlations move coordinates no slice informs. So the slices are read as random effects, as in a random-effects meta-analysis, in either product: where Cochran's Q says the slices that pin a coordinate contradict (at 0.999, allowing for sds a quarter of the posterior's, as SVI's can be), their between-slice variance (a Paule-Mandel estimate, receipt.globals.heterogeneity) is added to the sites' variance, and the coordinate sits among the slices, starting no narrower than the product says and no wider than a cold fit's default 0.1. A slice pins a coordinate if it narrows it and the rank part does not carry it, or if its marginal variance is below 0.01 of the prior projection's; a ridge's marginals say little about their coordinates, so ridges that cross keep it at 0. The start keeps the product's precision (globals.correlated) where it is not diagonal; its σ is the mean-field part, 1/√P_kk. A LowRankGlobal(r) fit from it starts its rank part on the r directions in which that precision is widest relative to σ, and MeanFieldGlobal fits start at σ.

  • Coordinates left out (exclude). A global coordinate whose meaning depends on the slice's domain is no estimate of the full model's: a spatial field's amplitude fitted on one region measures the field's variation inside that region, so slices that partition space all put it low. spread and the between-slice variance compare the slices with each other, so neither can see a bias they share, and the product starts it among them. exclude names such coordinates, and each takes no site and starts as a coordinate no slice informs: at the full model's default start (the prior-median point, with the fit's global_scale), exactly as if every slice had left it uninformed, a joint site included (its marginal over the other coordinates). Draws are carried to that default where it is one of their hyperparameters. A name (a Symbol or String) selects that coordinate and every coordinate under it: exclude=[:natural_field] leaves out natural_field.amplitude and every natural_field.z.*; a function of a name selects where it returns true. A selection of nothing, or a name of no global coordinate, is refused. receipt.globals.excluded marks them, and informed still counts their slices' sites.

  • Draws are carried to the combined hyperparameters. A random-effect draw z is standardized: its level's effect is A z, A = √w diag(τ) L, and a margin's total adds the population coefficients its block absorbs: those the NLME view mu-references into the units' block (mu ~ 1 + x + (1 + x | unit): the intercept and x), and otherwise a coefficient whose own column a shared grouping's block repeats ((gain, offset) ~ 1 + (1 | ID | device): each intercept), so that every total moves once. A slice's data informs those effects and totals, not z, and a copied z under the combined τ means another effect (a slice that fitted a small τ holds large z). So each slice's factor over a level's draws is first carried by z_s = C z_c + d, C = A_s⁻¹ A_c, d = A_s⁻¹ δ (A_s at the slice's own scales, correlation and coefficients, A_c at the combined ones, δ the change of the absorbed coefficients times their design), which keeps the effects and totals. A shared level that is a global coordinate has its sites (each draw's marginal) carried before they multiply, per level, after the other globals; the level's product precision joins globals.correlated when the carry correlates its draws. One that only a single unit reads is that unit's coordinate and is carried with it.

  • Units take their slice's factor (mean and precision, or the marginal of the coordinates the slice holds), carried as a site: the factor is the draws' N(0, I) prior times the site of the unit's data, and the site moves with the map while the prior is applied once, Λ' = Cᵀ(Λ − I)C + I, Λ'M' = Cᵀ(ΛM − (Λ − I)d). A unit whose data pins its effects keeps its totals; one with little data moves to the combined population. Where the map would make a negative site (a slice factor wider than the prior) indefinite, the negative part is dropped; failing that, the factor is carried as a plain change of variables. A unit coordinate with factors in two slices is refused: overlapping slices are not combined. Draws of a level-correlated block, of a family with a fixed covariance (completions, grouped HSGP weights) and other unit coordinates are copied as they are. A slice unit's diagonal-plus-low-rank factor enters through its precision; in the fit, a unit above unit_dense_limit takes the start's mean and marginal sds, its rank part starting at zero. Units that are connected components (unit_partition=:connected), whose members change between bindings, are refused.

The combination is a start: the fit's target is the full model. SVI's global factors are narrower than the posterior, so the product of many slices' sites starts the globals narrower still; the fit's optimizer widens them. SVI is a local optimizer, so the start can decide which optimum the fit reaches: a coordinate the slices bias the same way (a domain-dependent scale) can hold the fit in an optimum where other coordinates (the units' effects) carry what it should, even at a higher ELBO than a cold fit's. Compare the fit with a cold one on held-out data, not only by its ELBO.

receipt reports, per global coordinate of x (receipt.globals, aligned with coordinates): informed, how many slices had a site; clamped, how many of those were dropped; spread, the largest distance of a slice's mean from the combined mean in that slice's standard deviations (NaN below two sites; for a carried draw, both in the combined hyperparameters), with spread_slice naming that slice, so a large value marks slices that disagree on that coordinate's marginal (along a ridge they may still agree jointly); carried, whether its sites were carried (a shared level's draw); joint, how the globals combined (:joint, :diagonal when no slice has a rank part, :limit above joint_limit; :indefinite when the joint product was not positive definite and :outlying when one of its means left the range above, where the coordinate-by-coordinate one was used); heterogeneity, the between-slice variance added to that coordinate's sites; outlying, which coordinates' joint means left that range; excluded, which coordinates exclude left out; and the prior projection's prior_mean and prior_sd (Inf where flat). clamped counts dropped site directions, each at the coordinate it weighs most. receipt.slice_rank lists each slice's global rank. receipt.units counts the units copied whole and carried (some draws carried), and lists the partial and cold (in no slice) labels, the dropped ones (a negative site part dropped), the mapped ones (carried as a change of variables) and the uncarried ones (whose own density at the combined globals is clearly better, by over half a nat per draw, with their slice's draws as they were); receipt.prior records the projection's draws and its flat coordinates.

source
BayesianRegressionModels.brm_svi_fit Function
julia
brm_svi_fit([save,] x; laplace=nothing, batch_size=32, rng=Random.default_rng(),
    family=MeanFieldGlobal(), unit_sampling=nothing, ndraws=1000, start=nothing, inits=nothing,
    ad_backend=nothing, shared_point=nothing, subject_group=nothing,
    nested_groups=NamedTuple(), shared_groups=(), unit_partition=nothing,
    global_coordinates=nothing, progress=nothing, stationarity=true,
    stop_after=nothing, checkpoint_every=nothing, threads=nothing,
    kwargs...) -> (; draws, coordinates, diagnostics)

Minibatch stochastic variational inference for a model whose subjects are conditionally independent given the population (the subjects of brm_nlme_view), over the RK backend's packed unconstrained coordinates. Each iteration evaluates batch_size subjects, each at an antithetic pair of draws through their own observation cells, and scales them to all subjects, so its cost follows the batch size, not the number of subjects.

With laplace=GaussianBlockLaplace(), jointly integrate certified Gaussian coefficients, unit effects and shared fields inside the variational target. This opt-in evaluates the entire current window, uses a fixed update budget with convergence unassessed, and returns a correlated BRMSVILaplaceState through brm_svi_checkpoint. See GaussianBlockLaplace for eligibility, numerical limits and the additional carry approximation. The minibatch controls and per-subject factors below describe laplace=nothing.

  • x — a @brm model (BRMI), its RKBRMI, or a prepared BRMNLMEModel. For a BRMI or RKBRMI the model is prepared with ad_backend (default reverse-mode AutoEnzyme, which needs Enzyme loaded), shared_point, subject_group, nested_groups and shared_groups, as brm_nlme_model takes them; a nested model passes subject_group and nested_groups, a model with a grouping crossed with the subjects shared_groups. A BRMI's mi(...) completions whose law reads the units' draws are lowered non-centered, as by brm_nlme_fit. Every observation must belong to one subject's cells: a cell of a @plate for over the subjects or over their rows, or a row of a flat-row response grouped by the subjects.

  • family — the global factor: MeanFieldGlobal() (diagonal) or LowRankGlobal(r) (diagonal plus rank r).

  • centering — fresh fits default to LearnedCentering, jointly learning each supported unit cell's coordinates and variational factor. This includes unit-owned Gaussian random effects, Gaussian vector elements and grouped HSGP weights. By default (LearnedCentering(; delay=true)) a fresh fit explores with its cells, grouped HSGP weights excepted, in their packed coordinates first and centres them once exploration's ELBO test first reads flat, then explores on; diagnostics.centering.activation_window names that window (0 for delay=false or a fit with nothing to defer, nothing if it never came). diagnostics.centering reports the cells and eligibility exclusions, authored @plate cell latents among them (the plan reads no location or scale for them). Pass centering=nothing for packed unit coordinates. Streaming updates and optimizer resume inherit the saved policy, including an older plain fit's. A factor-level start is a fresh fit; its unit Gaussians are transported into the newly selected coordinates.

  • coupling — fresh fits and streaming updates default to LinearCoupling: every unit's factor is conditional on the globals, its mean linear in the global factor's standard-normal draw at the globals the unit's term reads, learned with the fit, on the unit coordinates learned centering does not centre (@plate cell latents among them). Fresh runs hold the coupling at zero during exploration and learn it in settling and polishing, using a mean-point gradient baseline to reduce update noise. It keeps the dependence between a population value and units the data pin only together, which independent factors lose: their population intervals then shrink to the noise over all rows. diagnostics.coupling reports each unit's coupled rows and globals (positions in its block and in diagnostics.globals), its coupling matrix and its conditional and marginal sds. The unit factors in diagnostics.q are the conditionals at the global mean, which factor-level starts and brm_svi_combine read; a streaming checkpoint carries each unit's prior conditional on its coupled globals. Pass coupling=nothing for independent global and unit factors. Optimizer resume keeps the saved policy.

  • unit_dense_limit — units with at most this many coordinates use a dense Gaussian and natural-gradient updates (default 64, allowed 0:256).

  • unit_curvature — how a dense unit's step estimates its curvature. :orthogonal (default): on each visit the unit is evaluated at d mutually orthogonal antithetic pairs of draws from its factor (2d gradient evaluations for d coordinates; a randomly rotated spherical-radial cubature rule), whose Stein estimate is its whole expected curvature, exact when the unit's term is quadratic in its coordinates, and the step defaults to unit_step = 1. The step reads the estimate's positive part, which on a quadratic term is all of it: on a saturating term the estimate is mostly noise with nearly symmetric eigenvalues until the unit's stiff directions are resolved, and its negative part would shrink the factor's precision far below the target's curvature. :pair: one antithetic pair (2 evaluations) and its rank-one estimate's positive part, with unit_step = 0.1, BRM 0.2.242's step; a unit of tens of coordinates then needs far more visits to settle than a minibatch run gives it, and the hyperparameters follow its unsettled factor. Structured units (above unit_dense_limit) are unaffected: they evaluate one pair, and unit_step defaults to 0.1 for them either way. Larger units use a diagonal-plus-low-rank covariance with unit_rank columns (default 8, allowed 0:32, clipped to the unit dimension). Rank zero gives a diagonal factor. Their reparameterized ELBO gradients use Adam with posterior-scale preconditioning and bounded relative steps. Polishing averages their log scales and loadings; dense units average covariances. diagnostics.unit_families reports each unit's family, dimension and rank. A streaming update preserves existing units' families and ranks; these controls apply to new units. The factor restriction changes the approximation, not the model density.

  • unit_reoptimize — k, default 0 (off). Each batch unit on the orthogonal design first takes k whole natural-gradient steps at the iteration's draw of the globals, before the gradient the globals step on is formed, so that gradient reads every batch unit near its conditional optimum given that draw (structured stochastic VI, Hoffman and Blei 2015). It is for a ridge between a global and every unit, where the data pin only a combination such as an intercept plus each unit's effect: with the units' factors lagging each global move, the global means crawl along the ridge under every schedule, and re-optimized units follow them. On a unit Gaussian given the globals one step reaches the optimum. Each step costs the unit's 2d evaluations again (counted in unit_gradient_calls). It needs unit_curvature = :orthogonal; units on the single pair and structured units are not re-optimized.

  • sparse_globals — how the globals few units read (expected readers per batch below one: a window's boundary state, a read-pair gmrf field state, a separator; diagnostics.sparse_globals lists them) take their step. :sites, the default, steps each on one diagonal site per reader, measured with the reader's coordinates held at its factor. :collapsed gives each reader one joint site over all the sparse globals it reads with its own coordinates integrated out (the Schur complement of the curvature the orthogonal design estimates, plus 2k unit evaluations for its k sparse globals). The sparse globals take a joint Gaussian factor whose sparse precision is the global term's curvature plus the summed sites. Each iteration takes one sparse-Cholesky Newton step for its mean; the same factor supplies draws, entropy and marginal sds by selected inversion. Polished results average means and marginal log scales, retaining the correlations of the last joint precision factor. Readers stay coupled to their sparse globals, with their slope from the same curvature. Where the data pin a sparse global only together with its readers' coordinates (a slow field beside fast window states, a boundary beside a window's path), the default crawls along that ridge. With fixed hyperparameters and Gaussian terms, each sparse-global solve gives exact means and marginal sds once every dense orthogonal-design reader has supplied its site. The readers' own factors still take their bounded local steps and can need further visits. A unit without a whole curvature (a structured unit, or unit_curvature = :pair) gives a joint site conditional on its factor. It refuses learned centering whose cells read a sparse global as a location or scale, and laplace.

  • separator — defaults to :auto in explicitly connected mode and :none otherwise. Automatic promotion uses bounded structural trials if a unit exceeds max_unit_coordinates=4096 or max_unit_work=1_000_000, with at most max_promoted_coordinates=128 extra globals including block closure. separator=:none retains explicit global_coordinates promotion. Prior, transform and partition-axis blocks remain intact. Inspect diagnostics.separator for selected blocks, reasons and whether budgets were achieved; the heuristic cannot promise an optimal cut or satisfy every budget. Changing ownership changes the variational approximation, never the model density.

  • cell_units — where connected mode puts likelihood cells that read no subject's effect. :components, its default, gives them inference units of their own, appended after the subjects' units, so a batch subsamples them: cells reading a common ordinary coordinate that no subject's cell reads share a unit, transitively, and cells with no such coordinate are grouped into about √m units of √m cells. A coordinate that joins nearly all of them, such as a shared population mean, joins them into one unit until it is promoted through global_coordinates or separator. :first_unit keeps them all in the first unit and counts unit work without rows, as earlier versions did, and is the only choice with unit_partition=:subjects. Splitting these cells changes the variational factorization and adds gradient variance from subsampling them, never the density. Checkpoints keep the layout they were made with.

  • unit_sampling — defaults to :work in explicitly connected mode and :uniform otherwise. :uniform selects distinct units with weight N/B; :work makes B draws with replacement, with probabilities pᵢ = (1/N + wᵢ/sum(w))/2. The structural work proxy wᵢ counts local coordinates, structural reads in the unit's likelihood/prior factors and the rows of its vector-valued observation cells; it is not measured runtime. All-zero work gives uniform probabilities. Repeated selections share one antithetic evaluation and one local update, with multiplicity retained in the global density and gradient weight countᵢ/(B*pᵢ). Every unit has positive probability. This changes the visit schedule and estimator variance; it does not guarantee faster convergence.

  • Inference ownership follows structural likelihood and authored-prior supports, including dormant branches and zero coefficients. Ordinary sampled coordinates read by only one unit join that unit; shared and prior-only coordinates stay global. Joint prior and transform blocks stay together. Each authored prior and Jacobian is counted once, including gradients through global hyperparameters. Scientific NLME roles are unchanged.

  • global_coordinates — packed coordinate indices or names to keep global. Promotion closes over joint blocks and dependent priors. It can include standardized subject effects. In connected mode the observation partition is rebuilt after promotion; the scientific model view stays unchanged. Diagnostics expose globals, units, unit_levels and owner (zero for globals or fixed coordinates, otherwise the unit index).

  • field_states — how a read-pair field (gmrf(...; neighbors=m)) is held. :global (default) gives each state its own global Gaussian factor. :units puts a state read by one unit into that unit's factor, next to its effects, so its cost and storage follow the unit's reads, and a state read by several units stays global. It reads the field's lengths from the globals, and has no streaming form. A mesh gmrf is refused either way: one factor per mesh state collapses the learned lengths.

  • start / inits — where the global and unit means start: BRM's prior-median starting point by default, a full RK packed point start, or values keyed by prior address as brm_start takes them. Declarations without a recorded median, including ordinary model-scope vectors, retain the packed unit point; entries not supplied in inits retain that default point. start may instead be a factor-level start: a BRMSVIStart from brm_svi_combine, or fits or states of the same declaration on slices of the data (a vector, or one), combined as brm_svi_combine does with its defaults. It sets the mean and scale of every global and the factor of every unit it holds, matched by semantic coordinate identity; the rest keeps the default start, the global rank part starts at zero and Adam's moments start fresh. It is a start, not a prior: the target is unchanged. diagnostics.start holds its receipt, with applied counting the globals and units it started (nothing for any other start).

  • progress — a Treebars node or backend symbol: one BRM SVI fit node with the phases Lower to ReactiveKernels, Prepare NLME model, Minibatch target (the unit partition gradient and the start), Stochastic optimization (its message names the window, iteration and ELBO) and Draws from q. An interrupt raises Treebars.ProgressInterrupted at the next window.

  • threads — how many tasks evaluate a batch's subjects and step their factors, capped at the batch size. Each further task prepares its own copy of the compact cell samplers before the first iteration, which costs time and retained memory. The default is Threads.nthreads(), or 1 on an Enzyme without the concurrent-GC repair, which refuses an explicit threads above one. The result does not depend on it: the draws come from the one rng in batch order and the subjects' results are summed in batch order, so a run and its checkpoints are the same to the last bit at any threads, and brm_svi_resume can continue at another. The fit holds BLAS at one thread while it optimizes and draws, and restores it afterwards. Not with laplace=GaussianBlockLaplace(), whose updates evaluate the whole window.

  • Optimizer controls: max_iterations, lr_global (Adam on the globals while exploring, in the coordinates' own units), unit_step (the subjects' natural-gradient step, by default 1 under unit_curvature = :orthogonal and 0.1 under :pair; a step that would change a subject's precision more than 2.5-fold along some direction, or move its mean more than one sd of its factor, is shortened for that subject. A structured unit's Adam takes it as the step size of its mean and log scales, by default 0.1 under either curvature, and its rank part steps a tenth as far; a value you pass applies to both families), polish_lr (Adam on the globals while settling and polishing, as a fraction of each global's current scale), window, patience, min_windows, trend_windows, stationarity, settle_windows, polish_windows, global_scale and unit_scale (initial factor scales). The run explores at constant steps until the trimmed ELBO has not risen detectably over patience windows (after at least min_windows) and its least-squares slope over the last trend_windows windows (default 4 patience + 1; 0 turns this off, the rule of BRM 0.2.263 and earlier when stationarity=false) is not above twice its standard error (read both with and without the first patience windows, which climb from the start), settles at the constant scale-relative step until the two-window test and the iterate check below pass on settling's own history, then polishes for polish_windows windows with decaying steps and returns the average of the polished iterates.

  • stationarity=true requires stable parameter iterates before certifying convergence. Exploration may reduce its step on an ELBO plateau while moments still move; this is a step change, not a convergence certificate. It does not reduce it while a global still drifts steadily: when the ELBO test passes, exploration goes on unless some recent window of the globals' mean and marginal log sd iterates reads split-Rhat at most 1.5 (a steady drift reads about 2), because settling's scale-relative step cannot finish such a move. This drift gate never holds exploration past half of max_iterations; diagnostics.stationarity.exploration.drift reports its last reading, the windows it held and whether the half-budget cap ended it. It is off with settle_windows=0 and in checkpoints written before it existed. A fit that ends without converging warns, naming the globals still moving. The check reads every global and unit mean and marginal log sd, plus learned centering controls and linear coupling coefficients. Unit marginal scales include the coupling's variance. Each block needs at least 200 actual updates and rank-normalized/folded split-Rhat at most 1.1 in one of up to five recent windows. Bulk effective sample size is reported separately; it does not gate the phase change. These are diagnostics of the optimizer iterates, not posterior draws. Histories retain at most 512 samples per moment by doubling their thinning interval; unit clocks advance only when selected. Storage is linear in the number of moments, up to 8 KiB per mean/scale coordinate, plus 4 KiB per centering or coupling coefficient. Checks become less frequent as a phase grows and use bounded coordinate chunks. Histories restart at settling. settle_windows=nothing (default) lets settling use the remaining max_iterations budget; with stationarity=false it retains the old cap of 100 windows. An explicit nonnegative settle_windows caps the phase. Reaching that cap still starts polishing, but returns converged=false unless its tests passed. Once settling has begun, the overall iteration budget also reserves the final polish_windows for averaging, with converged=false and status :max_iterations if the tests have not passed. This stays inside max_iterations; a short remaining budget uses only its remaining updates, and a non-round limit includes its last partial window. No budget fallback ends exploration before its ELBO tests pass; the drift gate's half-budget cap only releases one that already passed them. settle_windows=0 skips settling and requires the iterate check to pass during exploration before averaging starts. stationarity=false uses the ELBO-only rule, as does a resumed checkpoint written before this control existed. Stability does not establish global optimality or posterior accuracy, and can miss drift below its resolution.

  • sd_bound (default 2), a stopgap: after every global step, a global whose prior reads no other coordinate has its marginal sd under q held at most sd_bound times the sd of its prior's Gaussian projection, so a global whose gradient is mostly noise cannot random-walk wide and overflow the density. It treats the symptom, not the optimizer's blindness to the prior under that noise, and it holds q too narrow where a posterior is wider than the bound. A fit that ends with a global at its bound warns and names it (diagnostics.sd_bound); sd_bound=nothing turns the bound off. A resumed checkpoint keeps its own factor, 2 for one written before sd_bound existed.

  • Interruptible runs: stop_after ends this call after that many iterations (the run continues with brm_svi_resume on the same model and data; the stopping rule and step-size schedule are unaffected). An optional first argument save (a function, so a do block works) receives a BRMSVIOptimizerState after every iteration that is a multiple of checkpoint_every (default: once per window), when this call stops, and before an interrupt propagates. With laplace=GaussianBlockLaplace() the default is every 50 updates, and the interrupt is checked every 50 updates.

  • Watching a running fit: snapshot is a function, or a file path that the run rewrites atomically so it always holds the latest complete snapshot. It receives a detached copy of the current approximation and diagnostics, without the call returning and without decoding a checkpoint, after every iteration that is a multiple of snapshot_every (default: once per window, or every 50 updates with laplace=GaussianBlockLaplace()), when this call stops, and before an interrupt propagates. snapshot_draws adds that many draws (default none); each snapshot costs drawing them plus a copy of the factors. The run is the same to the last bit whether it is observed or not: draws come from a copy of the random stream, and a snapshot's q and draws equal those of a result stopped at its iteration. A snapshot is one named tuple of plain arrays, so a saved one loads without BRM or the model:

    • status: :running while the call continues. Only the boundary where the call ends says more: :converged, :max_iterations, :stopped (stop_after was reached; the run can continue), :settle_limit (polishing completed after settling reached its cap without passing), or :interrupted.

    • iteration, max_iterations, seconds (since optimization started in this call), threads, format, and model_identity, which names the emitted program, bound data and packed coordinates.

    • phase: :exploring, :settling or :polishing; for GaussianBlockLaplace, :fixed_budget. stages and, for the minibatch engine, stationarity, as in diagnostics.

    • q: μ, ρ, Β, M, Λ and U, as in diagnostics.q. q_kind says what it is: :raw_iterate, :polished_average (the Polyak–Ruppert average, averaged_iterations of them, 0 at the iteration polishing starts) or, for GaussianBlockLaplace, :window_average. A unit above unit_dense_limit appears in Λ and U as (; family=:diagonal_lowrank, ρ, Β), its covariance being Diagonal(exp.(2ρ)) + Β * Β', so that no BRM type is needed to read it.

    • coordinates, levels, globals and units: q.μ[k] is coordinate coordinates[globals[k]], q.M[i][k] is coordinate coordinates[units[i][k]], of unit levels[i].

    • elbo_windows (the mean ELBO per completed window; for GaussianBlockLaplace per 50 updates), elbo (the last iteration's value, nothing before the first). Without GaussianBlockLaplace also elbo_windows_trimmed, which the stopping rule reads, and clipped_steps, as in diagnostics.

    • draws: coordinates × snapshot_draws, as the result's draws.

    BRM keeps no snapshot: the size of one is that of q and draws plus two numbers per window (one for GaussianBlockLaplace), and a path holds only the latest. To keep more, pass a function.

Returns draws, ndraws draws from the fitted approximation as RK packed unconstrained points (coordinates × draws, one column per draw, the order of coordinate_names(rk.model.layout)), their coordinates, and diagnostics: the ELBO trace, up to a constant (elbo, per iteration; elbo_windows, the plain mean of each window, which a single draw can dominate; and elbo_windows_trimmed, the 10% trimmed mean of each window, which the stopping rule reads), clipped_steps (how many global steps had a coordinate's gradient limited to 10 √w times its running rms, with w the batch's largest unit weight, N / B for uniform sampling, so that one extreme draw does not stop that coordinate's optimization), sd_bound (factor, nothing when off, and per global coordinates and bound, Inf where it has none, at_bound, the globals whose marginal sd in the last iterate is at it, and stopgap = true), converged (the optimizer completed its stopping and polishing rules, not a certificate of posterior accuracy), finished (converged, max_iterations reached, or polishing completed after the settling cap; false after stop_after), iterations, stages (the iterations spent exploring, settling and polishing, and settled: whether settling ended on its test rather than at settle_windows), stationarity (whether enabled, thresholds, number of checks, the exploration check at its step change with the drift gate's drift reading, the most recent current check, and settled; the exploration report can fail when settling follows; checks report worst Rhat, minimum ESS and each block's sample count and update clock). Under the ELBO-only rule, converged can still accompany settled=false. The variational parameters q, the packed positions of the global coordinates (globals), seconds of optimization in this call, threads (the tasks this call used), target (below), the units' sampling probabilities, work, visits and draw counts (sampling), and unit_gradient_calls (2 attempts per visit of a unit, 2d per visit of a dense unit of d coordinates under unit_curvature = :orthogonal, plus one auxiliary mean-point gradient attempt for a unit with coupling). An unusable auxiliary point uses a zero baseline and still counts as an attempt. Diagnostics also hold the prepared model and the run's optimizer state (brm_svi_optimizer_checkpoint copies it). The draws come from a copy of the optimizer's random stream: they do not advance rng, and a continued run is unaffected by them. Learned centering can recover population spread lost by the plain factorization; neither the factor family nor optimizer completion guarantees accurate means or calibrated intervals. Compare important population uncertainty with a feasible full-MCMC or exact reference.

The prepared model keeps its minibatch target and worker samplers for its next fit or continuation in this process, so passing diagnostics.model (or the BRMNLMEModel you prepared) prepares neither again. An RKBRMI keeps the model a call prepared from it, the last one: a later call on the same backend with the same ad_backend, shared_point, groupings and unit_partition takes that model and its target, and other options prepare another model, which the backend then keeps instead. A copy or a serialized backend keeps none. A BRMI is lowered to a new RKBRMI, and so prepared, on every call. diagnostics.target reports what this call did: reused (it took the model's target), workers_built and the seconds of that phase. A connected model's target is reused only for the same global_coordinates, separator policy, budgets and cell_units, since those decide its units, and any model's only for the same field_states. The model holds one target, the size of its partition samplers and work arrays, for as long as the model lives; a copy or a serialized model holds none. A call that throws while optimizing does not put its target back, and concurrent calls on one model each use their own. Not with laplace=GaussianBlockLaplace(), which prepares its target on every call.

source
julia
brm_svi_fit([save,] previous, x_new; kwargs...)

Continue on a disjoint new observation window. previous is an SVI result or a data-only BRMSVIState. To continue an interrupted optimization of the same model and data instead, use brm_svi_resume; save, stop_after and checkpoint_every interrupt this window's fit as they do brm_svi_fit's. x_new is the same model on the new window: a BRMI is lowered with the state's frozen preprocessing; an RKBRMI or prepared BRMNLMEModel must already have that preprocessing. A previous fit also accepts raw new data, rebinding its model declaration. A state resumed in another process takes builder(new_data) instead.

The target is q_previous(globals, units) * p(new_data | globals, units). Both the optimizer start and the prior use the previous factors. The history is carried through a Gaussian family, never re-evaluated. This sequential approximation can depend on window order and is not a cumulative-data refit. Under linear coupling (the default) a carried unit's prior is its factor conditional on the globals it was coupled to, so the global/unit dependence it learned is carried; between-unit dependence is dropped, and an uncoupled checkpoint carries independent unit factors. Do not supply overlapping windows: their likelihood would be counted again.

Units are matched by label and semantic coordinate identity. New labels get their authored unit priors under the carried global factor; absent labels retain their factors in the checkpoint and recover them on return. An existing unit's latent coordinate set must stay fixed (persistent statics, not growing time-state blocks). Global coordinates and preprocessing must stay fixed. For nested units, pass the new window's nested_groups map. Only new-window units are minibatched; diagnostics count their gradient calls. Checkpoint size grows with distinct units, not the number of observations.

source
BayesianRegressionModels.brm_svi_optimizer_checkpoint Function
julia
brm_svi_optimizer_checkpoint(fit) -> BRMSVIOptimizerState

A copy, sharing nothing with fit, of the optimizer state of a brm_svi_fit or brm_svi_resume result (or of a BRMSVIOptimizerState), for continuing it with brm_svi_resume.

source
BayesianRegressionModels.brm_svi_resume Function
julia
brm_svi_resume([save,] x, checkpoint; stop_after=nothing,
    checkpoint_every=nothing, ndraws=1000, progress=nothing,
    snapshot=nothing, snapshot_every=nothing, snapshot_draws=0,
    threads=nothing, ad_backend=nothing, shared_point=nothing,
    subject_group=nothing, nested_groups=NamedTuple(), shared_groups=())
    -> (; draws, coordinates, diagnostics)

Continue a brm_svi_fit run on the same target from checkpoint, a BRMSVIOptimizerState or a fit/resume result, exactly as the run would have continued without stopping: the same iterates, random stream, stopping decision and draws, in the same Julia and package versions, at any threads (the fit's option; a run may continue at another). The run keeps its optimizer controls, its max_iterations horizon and step-size schedule; stop_after bounds only this call. A finished checkpoint does no iterations and returns draws of its result. A laplace=GaussianBlockLaplace() run continues its fixed update budget with the same method, and its carry and diagnostics (call counts, numerical records) equal the uninterrupted run's.

x is the model the checkpoint was fitted on, rebuilt with the same data: the @brm model (BRMI), its RKBRMI or a prepared BRMNLMEModel, with the same preparation options as the fit (ad_backend may differ). For a checkpoint of a window fit, brm_svi_fit(previous, x_new), pass x_new; the checkpoint carries previous. The emitted program and callables, the bound data and frozen preprocessing, the packed coordinates, the groupings, the subjects and their coordinates, and the fixed shared values must equal the checkpoint's; a difference is refused before any optimization step, and one in the program, callables, data or coordinates already after lowering, before the model is prepared. The refusal names the differing part, down to the callable's binding and the data column. A @brm model is lowered with the checkpoint's parametrization of its mi(...) completions (which ones the fit lowered non-centered), so that comparison reads no grouping option: a different model is refused by name even when a grouping option is also wrong, and preparation then checks the groupings. An older checkpoint that records no parametrization lowers its @brm model from the grouping options, which are then read (and an invalid one refused) before the comparison when the model has a centred completion. An anonymous function or closure compares by its lowered code and captured values, so the same source continues in another driver, at another line or after other definitions; a named function compares by its module and name. In the same process, pass fit.diagnostics.model (or the BRMNLMEModel the fit was given): it prepares neither the model nor its target and worker samplers again (diagnostics.target.reused, brm_svi_fit). So does an RKBRMI an earlier call prepared a model from with the same ad_backend, shared_point and groupings, since it keeps that model; a BRMI prepares both on every call. The program compares without the file and line of its macro calls (an emitted @kernel definition), so the same model also continues from another checkout, depot, host or BRM version. A checkpoint from an earlier version digested those places, and only the installation that wrote it resumes a program that has one.

save, stop_after, checkpoint_every, ndraws, progress, snapshot, snapshot_every and snapshot_draws work as in brm_svi_fit; save again receives copies of the state. The result has the fit's shape: its diagnostics cover the whole run (elbo, iterations, unit_gradient_calls), except seconds, which counts this call. A cooperative interrupt (Treebars) passes the state of the last completed window to save before it propagates; resume from the last checkpoint save committed.

julia
model = builder(data)
fit = brm_svi_fit(model; rng=Xoshiro(1), stop_after=5_000, ndraws=0) do state
    save_checkpoint("svi.jls", state)
end
# later, possibly in a new process:
state = deserialize("svi.jls")
fit = brm_svi_resume(builder(data), state; stop_after=5_000) do state
    save_checkpoint("svi.jls", state)
end
fit.diagnostics.finished
source
BayesianRegressionModels.rk_logdensity_problem Function
julia
rk_logdensity_problem(backend::RKBRMI; ad_backend, u0) -> problem

A LogDensityProblems-compatible density over the backend's packed unconstrained coordinates (order 1: value + gradient). ad_backend is a DifferentiationInterface AD type (e.g. reverse-mode AutoEnzyme).

u0 is the packed point at which the gradient is prepared. Preparation runs the model once there, so it must be a point where the model evaluates; the returned density does not depend on it. The default is the prior medians, brm_start(backend, (;); base = :prior_median), except that a coordinate whose prior has no finite median keeps the zero point's value instead of being refused: the zero point, the earlier default, is not a point of every model (an ODE unstable at unit rates). Implemented only by the BayesianRegressionModelsReactiveKernelsExt package extension.

source
BayesianRegressionModels.s2z_effect_blocks Function

Return the S2Z blocks selected during model construction.

source
BayesianRegressionModels.select_ranef_centeredness Function
julia
select_ranef_centeredness(unit_effects, log_scales;
                          candidates=0:0.1:1,
                          underflow_log=log(floatmin(Float64)))

Apply the scalar offline partial-centering criterion to ordinary random-effect coordinates. Rows are pilot draws; columns are one scalar (term, group) cell. unit_effects holds noncentered standardized effects and log_scales the matching log standard deviations. The criterion and stable shifted-exponent evaluation are identical to select_hsgp_centeredness; only the coordinate interpretation differs. The result is a fixed-partial specification for a fresh fit and does not adapt during warmup.

source
BayesianRegressionModels.select_s2z_centeredness Function
julia
select_s2z_centeredness(model, draws, unc_names;
    criterion=:position, gradients=nothing, grid=0:0.1:1)

Select one centering per S2Z cell from a saved pilot. With s2z_coordinates=:groups the cells are groups (any compiled centeredness); with contrast coordinates they are the free Helmert contrasts of an endpoint model (s2z_rho=0 or 1). draws and optional gradients are draws × coordinates in the COMPILED model frame; no density or gradient calls are made. Each cell tau_k^c * w has location zero: :position minimizes log SD minus mean log Jacobian, :gradient minimizes the position-gradient correlation and needs matching exact gradients.

The returned centeredness vector is ordered by block, coefficient and then group or contrast. Pass it to adaptive_centering_problem(model, problem, backend; centeredness), with nonlinear_adapt=false for a fixed post-hoc refit. For group coordinates, reshape(centeredness, J, K) is also a valid s2z_rho for a recompiled fixed model. When the model also has total-coefficient blocks, their cells come first: vcat(select_total_centeredness(...).centeredness, s2z.centeredness).

select_s2z_rho instead gives Sean's Fisher-rule weights for the linear interpolation of contrast coordinates.

source
BayesianRegressionModels.select_s2z_rho Function
julia
select_s2z_rho(s2z_model, pilot_model, draws, names; obs_prec, group,
               predictor=nothing, aggregate=:median)

Select per-cell S2Z centering weights from a saved pilot fit. draws/names are the pilot's posterior draws in the COMPILED (unconstrained) frame with one column per name; obs_prec is the draws-by-observations expected observation precision matrix (obs_prec[d, n], caller-computed from the pilot draws, e.g. 1 ./ sigma[d, n].^2 for Gaussian location). No density or gradient calls are made.

For each draw and coefficient, group information matrices are rebuilt from obs_prec and the S2Z block's retained design, per-draw group scales come from the pilot's <binding>_log_scale / <binding>_tau coordinates, and raw reliabilities come from _s2z_fisher_raw. Cells aggregate across draws (aggregate, :median or :mean) and rescale ONCE at the aggregated scale — never median-of-rescaled-rho, which mixes the chart nonlinearity with per-draw scale variation and is fragile under approximate pilots.

The pilot must cover the same grouping with identical levels and row order (checked against the pilot's preprocessing record, loudly refused otherwise). Returns (; rho, raw, sd, carriers, n_draws, group, columns): rho feeds SBBRMI(...; s2z_rho=rho) directly.

source
BayesianRegressionModels.select_total_centeredness Function
julia
select_total_centeredness(model, draws, unc_names;
    criterion=:position, gradients=nothing, grid=0:0.1:1)

Select each total coefficient's centering independently from a saved pilot, in the mean-located frame adaptive_centering_problem samples (each total centred on its column's least-squares fit on the column's group-level design, the mean of the column's totals for a plain block), every other total kept at c = 1. draws and optional gradients are draws × coordinates in the COMPILED model frame. :position minimizes log SD minus mean log Jacobian; :gradient minimizes position-gradient correlation and requires matching exact gradients. No new density/gradient calls are made. The returned centeredness vector can be passed to adaptive_centering_problem; losses preserves every grid score. Only sampled blocks have cells: a block whose totals are emitted in generated quantities has no sampler coordinate to center, and a model whose every block is generated is an error.

source
BayesianRegressionModels.total_effect_blocks Function

Return the exact total-coefficient blocks selected during model construction.

source

Additional exports in this task group:

OriginNames
BayesianRegressionModelsLowRankGlobal, MeanFieldGlobal, RKDesignBinder, brm_filter_resume, brm_nlme_conditional_problem, brm_nlme_joint_map, brm_smc_resume, brm_smc_runs

BRMNLMEModel ​

Prepared population model returned by brm_nlme_model. It retains the RK backend, unit partition and conditional likelihood workspaces used by NLME and variational fitting.

brm_laplace_problem ​

Construct the marginal population target described by BRMLaplaceProblem. The type's docstring lists the constructor keywords and approximation contract.

brm_svi_checkpoint ​

Extract the data-only streaming state described by BRMSVIState. It carries a fitted approximation into a new window. Use brm_svi_optimizer_checkpoint to resume interrupted optimization on the same model and data.

brm_stan_to_rk ​

Apply the reverse coordinate permutation in brm_rk_to_stan's shared contract. Transports with simplex or centered blocks need the point-specific operation below.

brm_stan_point_to_rk ​

Transform a Stan unconstrained point into RK coordinates, including the transport's nonlinear blocks. Its contract is documented with the inverse, brm_rk_point_to_stan.

Draws and summaries ​

Read fitted coordinates, predict responses and summarize conditional quantities. See Warfarin PK/PD.

BayesianRegressionModels.BRMPowerscaleSensitivity Type
julia
BRMPowerscaleSensitivity

Alias for PowerScaling.PowerscaleSensitivity, returned by brm_powerscale_sensitivity. The result contains variables, prior, likelihood, diagnosis, the four pareto_k values, and component-wise reliable flags. Check reliability before interpreting the sensitivities.

source
BayesianRegressionModels.brm_conditional_draws Function
julia
brm_conditional_draws(d::BRMDescriptor, unc_draws::AbstractMatrix, grid;
                      problem=nothing, target=:mean, logical=:auto,
                      response=:auto, scale=:response, seed=1,
                      focal=nothing) -> NamedTuple

Evaluate fitted posterior draws on a prediction grid — the engine behind bambi-style conditional predictions. grid is a NamedTuple of equal-length vectors as built by brm_prediction_grid. unc_draws holds unconstrained posterior draws as rows, in the fitted model's unconstrained order.

The model is reprocessed onto the grid with frozen training constants (brm_execute(d, :reprocess, grid)), so zscale/factor/spline/GP and other Julia-side transforms rebuild exactly as out-of-sample prediction requires, and unseen fitted levels fail loudly there — never silently.

  • target=:mean (default) returns the posterior of the response mean: exact transformed-parameter evaluation on the reprocessed problem, so no RNG and no seed enters. response selects the outcome (:auto takes the sole scalar outcome); scale=:response maps the evaluated linear predictor(s) through the outcome family's mean map (:link returns the raw linear predictor instead — the public predictor value the likelihood sees (for an LHS-linked declaration such as log(mu) that is already response-mapped; exactly what brm_output_draws with role=:linear_predictor yields on fitted draws). logical selects which linear predictor :link returns (:auto takes the outcome's mean predictor, or the sole linear predictor); under scale=:response it must be :auto or one of the outcome's mean predictors. A mean fed by no linear predictor (data/parameter/constant-only arguments) records logical=nothing.

  • target=:predictive returns posterior-predictive draws via the existing brm_predictive_draws machinery on the reprocessed descriptor; seed seeds the first draw exactly as there, and response selects the predictive output.

problem optionally supplies the reprocessed problem (as returned in a previous result) to skip re-instantiation; it must be the problem for THIS grid — a shape mismatch fails inside Stan, never silently. focal is recorded verbatim as plot metadata (a Symbol or collection); it changes nothing about the evaluation.

Returns (; grid, draws, target, logical, response, scale, focal, descriptor, problem) with draws a draws × grid-elements matrix (logical is nothing under target=:predictive and for response means no linear predictor feeds, which have no linear predictor). Response means are outcome-anchored (see the module header): unmapped families, link-transformed observation LHSs, and entangled mean arguments fail closed naming the :link / :predictive alternative.

source
BayesianRegressionModels.brm_conditional_tree Function
julia
brm_conditional_tree(descriptor, unconstrained_draws, grid; kwargs...)
brm_conditional_tree(result::NamedTuple)

Label brm_conditional_draws on :draw × :grid, retaining its result metadata and replacing only result.draws with a TreeData over the same matrix. Grid coordinates are records of the actual grid values (focal columns when specified). Per-chain inputs add :chain. Requires using TreeArrays.

source
BayesianRegressionModels.brm_contrast_draws Function
julia
brm_contrast_draws(cond; by, pairs=:all, how=:diff) -> NamedTuple

Compare conditional draws across the levels of one grid column — the draws half of bambi's comparisons. cond is a brm_conditional_draws result (or any NamedTuple with grid and draws); by names the contrast column (required, like bambi's contrast).

Every level must own the same number of grid rows with identical values in every other column — the factorial shape brm_prediction_grid builds. Anything else (unequal blocks, misaligned rows, fewer than two levels) fails closed rather than subtracting misaligned cells.

pairs selects level pairs (A, B): :all (every unordered pair), :reference (each level against the first), :sequential (each level against its predecessor), or an explicit collection of pairs/tuples. how is :diff (A - B) or :ratio (A / B).

Returns (; draws, labels, pairs, by, how, subgrid, n_sub, target, logical, scale) with draws a draws × (pairs × n_sub) matrix in pairs-major order, labels "A vs B" strings, and subgrid the shared within-pair grid (the first level's block rows). target/logical/ scale are carried from cond when present, nothing otherwise.

source
BayesianRegressionModels.brm_laplace_draws Function
julia
brm_laplace_draws(p::BRMLaplaceProblem, P::AbstractMatrix;
    rng=Random.default_rng(), conditional=0) -> (; draws, diagnostics)

Complete draws from population draws P (p.names rows × draws, e.g. a sampler's posterior_position). At each population draw every unit's random effects are drawn from its Laplace approximation, the Gaussian at its conditional mode with covariance (−H_i)⁻¹, or, with conditional = K > 0, from its exact conditional posterior by importance resampling: K proposals per unit from that Gaussian, weighted by the model's conditional density, one resampled. All units' k-th proposals are scored by one model evaluation.

  • draws — the model's packed unconstrained coordinates (rows, the order of rk_restore_draws) × draws; its population rows are P. Pass it to rk_restore_draws and the other readers of a full RK fit.

  • diagnostics — newton_steps, the Newton steps each draw's mode search took from the prior's mode; with conditional > 0 also importance_ess, units × draws, each unit's effective number of proposals ((Σw)²/Σw², at most K). A small value marks a unit whose conditional posterior is far from Gaussian, where more proposals are needed.

source
BayesianRegressionModels.brm_nlme_draws Function
julia
brm_nlme_draws(m::BRMNLMEModel, θ, σ, ω, unit_draws) -> Matrix{Float64}

Full RK packed unconstrained draws, one column per draw (m.view.coordinates × draws, rows in the order of coordinate_names(rk.model.layout), as rk_restore_draws and rk_draw_values take them), at fixed population values: θ, σ, and Ω's covariance coordinates from NLMEEstimation's ω, with unit i's coordinates taken from unit_draws[i] (the unit's dimension × draws, in its BRMNLMEUnitProblem coordinates). Every unit gives the same number of draws. This is the result shape BRM's approximate-inference methods share, so their output reaches the usual readers and replay paths. Implemented by the NLMEEstimation extension.

source
BayesianRegressionModels.brm_output_draws Function
julia
brm_output_draws(descriptor, constrained_draws, constrained_names;
                 logical, role=nothing)

Extract a model's logical output as a draws × output-elements matrix. Input rows are draws, not the coordinates × draws orientation returned by WarmupHMC. Obtain constrained_names and values with matching transformed-parameter / generated-quantity settings. Resolution uses brm_output_coordinates, so this works for named predictors, parameters, and predictive outputs without parsing emitted names. It does not simulate or transform the supplied values.

role selects one of a target's several carriers. A MixtureModel response y's per-row component-membership probabilities are brm_output_draws(d, draws, names; logical=:y, role=:membership): logical is the response, not the emitted name y_membership.

source
BayesianRegressionModels.brm_output_tree Function
julia
brm_output_tree(descriptor, constrained_draws, constrained_names; logical, role=nothing)

Label a logical output without copying its draws. Requires using TreeArrays. Rows are draws; a vector of per-chain matrices adds an outer :chain axis. logical may also be a discovered BRMOutput, for example a coefficient carrier from brm_outputs. Coefficients use their descriptor labels; observation outputs use their element positions. Scalar outputs have only the :draw axis. Labels follow the supplied constrained-name order for these single-axis outputs.

Random-effect carriers use the fitted :level labels and (predictor, coefficient) addresses on :margin. Standardized draws and effects have :draw × :level × :margin (omit :margin for a one-margin block), scales have :margin, and Cholesky factors have :margin × :margin2. Stratified scales and factors also carry :stratum. These carriers use fitted coordinate order, independently of the supplied name order, with views into the input.

Per-row block contributions use :observation. Model-scope assignments also inherit :observation through elementary pointwise arithmetic and functions of row outputs and scalars, including chains of assignments. Vector length alone does not establish row alignment.

Ragged predictions use flat :observation positions 1:N, where N is the total number of elements. Their aggregate log likelihood uses 1:G on its own :observation axis, one contribution per group, not per element. The output's segments retains the inclusive group ends of the predictive element axis; it does not partition the aggregate likelihood's G columns.

The returned backing aliases the input: treat both as read-only. Unknown output-axis semantics are reported by name, never replaced by guessed labels.

source
BayesianRegressionModels.brm_powerscale_inputs Function
julia
brm_powerscale_inputs(sb::SBBRMI, constrained_draws, constrained_names)

Assemble the (draws, log_prior, log_lik) triple brm_powerscale_sensitivity needs from a fitted SBBRMI. Returns (; log_prior, log_lik, variables, descriptor) where log_prior / log_lik are per-draw joint densities, variables the default sensitivity selection (every parameter column — twins and __ diagnostics excluded), and descriptor the brm_descriptor(sb) the assembly ran through.

constrained_draws is draws × coordinates with constrained_names from the SAME transformed-parameter / generated-quantity settings, and the fit MUST have saved generated quantities (the pointwise log-likelihood twins live there). Models outside the covered surface in src/powerscale.jl (random effects, GPs, smooths, R2D2, non-Normal/non-Exponential priors, …) error by name — a silently incomplete joint prior would be a wrong sensitivity, so there is no partial credit. Pair with the refit comparison from brm-use for those models.

source
BayesianRegressionModels.brm_powerscale_sensitivity Function
julia
brm_powerscale_sensitivity(draws, log_prior, log_lik, names;
    variables=nothing, lower_alpha=0.99, upper_alpha=1.01,
    threshold=0.05, reff=1.0)

Prior/likelihood power-scaling sensitivity over fitted posterior draws, computed by PowerScaling.powerscale_sensitivity using PSIS.jl. draws is draws × coordinates, names contains its column names, and log_prior / log_lik contain one joint log-density per draw. variables selects columns by name (default: all). Use brm_powerscale_inputs to assemble these inputs from an SBBRMI fit with saved generated quantities.

The returned BRMPowerscaleSensitivity reports CJS-distance gradients and diagnoses prior sensitivity or potential prior-data conflict at threshold. reff is the relative efficiency of the inverse importance ratios (1 assumes independent draws). Check the result's reliable flags and pareto_k values before interpreting it; these diagnostics do not establish MCMC convergence.

The summary scales exactly the joint densities supplied. Hierarchical models may need densities restricted to selected prior levels; model-specific density assembly remains the caller's responsibility.

source
BayesianRegressionModels.brm_prediction_grid Function
julia
brm_prediction_grid(d::BRMDescriptor; focal, n=25, fixed=(;)) -> NamedTuple

Build the evaluation grid conditional predictions are computed on: the focal predictor(s) varied, every other model column held at one typical value. This is the data half of bambi's conditional argument; pair it with brm_conditional_draws, which reprocesses the fitted model onto the grid and evaluates it there.

  • focal — a Symbol, a vector of Symbols, a dict, or a vector of pairs. Plain symbols take default values: n points spanning the observed range for continuous predictors, the fitted levels for integer/Bool/categorical ones. A name => values pair (or dict entry) uses explicit values (a scalar or vector); a dict is read in sorted key order, a vector of pairs in the order given. Several focals expand to the full factorial, first focal fastest.

  • n — default grid length for continuous focals (n >= 2).

  • fixed= — name => value overrides for non-focal columns (a typical is otherwise the mean for continuous columns, the most frequent training value — first-seen wins ties — for everything else).

Response columns are filled with their first non-missing training value. That fill is never evaluated: means and predictive draws condition on fitted parameter draws, not on it. It only has to satisfy the Stan data constraints, which a genuinely observed value does by construction. An mi() column is left out of the grid: conditional draws refuse mi models.

The returned NamedTuple of equal-length vectors feeds brm_execute(d, :reprocess, grid) directly. Responses cannot be focal; unseen categorical levels, unknown columns, and missing fills fail closed. Integer focals take integer values (auto grids round to the fitted integer set); joint and ragged responses have no v1 grid.

source
BayesianRegressionModels.brm_predictive_draws Function
julia
brm_predictive_draws(descriptor, unconstrained_draws; problem, seed)

Run the descriptor's native predictive operation once per posterior draw and return one draws × response-elements matrix per logical response. Input rows are draws. This simulates new response values conditional on fitted parameter draws; it does not fit a model. seed is passed to the first draw, with successive integer seeds for subsequent draws. Multiple responses share each execution.

On a prior program (the response column omitted, zero sampler dimensions) each draw is a row of a zero-column matrix: brm_predictive_draws(d, zeros(n, 0); problem, seed) returns n prior-predictive draws of every omitted response.

source
BayesianRegressionModels.brm_predictive_tree Function
julia
brm_predictive_tree(descriptor, unconstrained_draws; problem, seed)
brm_predictive_tree(descriptor, predicted::NamedTuple)

A TreeArrays record of posterior-predictive responses, with a leading :draw axis and descriptor-owned response coordinates. The second form labels the arrays already returned by brm_predictive_draws, without copying or drawing again. Per-chain matrix input retains chains separately. Requires TreeArrays. Ragged responses use flat :observation positions 1:N; group boundaries remain available as segments on the descriptor's predictive output.

source
BayesianRegressionModels.brm_ranef_draws Function
julia
brm_ranef_draws(d::BRMDescriptor, draws, constrained_names;
                id=nothing, group=nothing) -> Vector{NamedTuple}

Every random-effect block's between-group standard deviations, correlation matrix and per-level effects, per posterior draw — lme4's VarCorr plus ranef, for each draw.

draws is draws × constrained coordinates in constrained_names order, as BridgeStan's param_constrain returns them with include_tp=true. Add include_gq=true for an exact total-coefficient block (its deviations are recovered in generated quantities) and for a block no observed likelihood reaches (an omitted response, a prior program, a cv_groups or resample_groups re-draw). The draws must be constrained from the compiled model's own unconstrained frame. adaptive_warmup_mcmc returns adaptively centred draws already in that frame. Centred and non-centred emissions are read the same way.

id = :p selects the shared (… | p | g) block; group = :g selects every block of grouping factor g (a multi-membership block matches any of its member columns). With neither, every block is returned. A selection that matches nothing is an error.

Each block is one named tuple:

  • binding, family, group, id — the emitted block, its grouping factor and its |ID| (or nothing).

  • by, stratum — a stratified gr(g, by=b) block's stratifying column and the label of the stratum this entry reports, nothing for any other block.

  • margins — the ordered (predictor, coefficient) addresses of its terms: ranefcoefnames order for an |ID| block, the design columns of a plain one.

  • levels — the group labels, in the order of the effects' level axis.

  • link, inverse_link — per margin, the margin predictor's LHS link pair, the same pair brm_ranef_sd_coordinates returns.

  • sd — draws × margins: each margin's between-group standard deviation tau, on its predictor's linear-predictor (link) scale. A Student-t block reports its scale tau; a known margin (sd(...) = value) its value.

  • cor — draws × margins × margins: the correlation matrix L L', the identity for a one-margin block.

  • effects — draws × levels × margins: what each level adds to each margin's linear predictor, on the link scale. This is the emitted effect matrix: diag(tau) L z under the default emission, the sampled effects under centered_groups, the level's mixing weight included for Student-t, and Stan's recovered deviation total − A β of an exact total-coefficient block. A subject's own coefficient on the natural scale is inverse_link(population + effect), with the population value from brm_population_effect_coordinates.

  • level_cor — draws × levels × levels: the correlation of the block's levels, L L' of the factor its gr(g; cor=Omega) names (the sampled Omega, or a known correlation supplied as data), for a level-correlated block; nothing for every other block. Each margin's effects then have correlation level_cor across levels.

An exact total-coefficient block reports one entry per absorbed column, each with one margin, as the conventional (… || g) emission reports one block per independent margin. So does a sum-to-zero block (s2z_groups, family :brm_s2z): each column's sd is the block's scale tau, its effects are the recovered per-level effects r + μ (generated quantities, so pass include_gq=true draws), and its id is the one-margin |ID| bucket the block claimed, so id = :p selects it under the same address as without s2z_groups.

A stratified gr(g, by=b) block has one tau and L per stratum (per level of b), and every group belongs to one stratum. It reports one entry per stratum, in the order of the stratum labels: that stratum's sd and cor, and the levels and effects of its groups, in block order. group = :g selects every stratum.

julia
sm = stan_instantiate(sb).model
names = BridgeStan.param_names(sm; include_tp=true, include_gq=true)
draws = reduce(vcat, permutedims(BridgeStan.param_constrain(sm, x;
    include_tp=true, include_gq=true, rng)) for x in unconstrained_draws)
p = only(brm_ranef_draws(brm_descriptor(sb), draws, names; id=:p))
p.margins                     # [(predictor=:mu, coefficient=:Intercept), …]
median(p.sd; dims=1)          # between-subject SDs
median(p.cor[:, 1, 2])        # intercept-slope correlation
p.effects[:, :, 1]            # draws × subjects: intercept deviations
source
BayesianRegressionModels.brm_ranef_tree Function
julia
brm_ranef_tree(descriptor, constrained_draws, constrained_names; id=nothing, group=nothing)
brm_ranef_tree(entries::AbstractVector{<:NamedTuple})

Random-effect draws as a TreeArrays tree of block records. Each record has sd, cor, effects, and, for level-correlated blocks, level_cor. The axes are :draw, :margin and :level; correlation matrices distinguish their second coordinate with :margin2 / :level2. Margin coordinates are (predictor, coefficient) records, and levels are the fitted group labels. An outer :block axis identifies each binding and stratum. Per-chain input adds :chain. Requires using TreeArrays.

Stored effects and scales alias constrained draws. Derived correlations and scales are computed once by the same extraction as brm_ranef_draws; adding labels does not copy them. Treat the returned backing as read-only. The second form labels existing brm_ranef_draws entries without recomputing.

source
BayesianRegressionModels.brm_slope_draws Function
julia
brm_slope_draws(d::BRMDescriptor, unc_draws::AbstractMatrix, grid;
                wrt, eps=1e-4, logical=:auto, scale=:response,
                focal=nothing) -> NamedTuple

Finite-difference slopes of the conditional response mean with respect to grid column wrt — the draws half of bambi's slopes. Evaluates brm_conditional_draws with target=:mean at grid perturbed to wrt ± eps/2 (central differences) and returns the divided difference, a draws × grid-elements matrix.

Slopes are mean-only by construction: finite differences of posterior-predictive RNG draws are RNG noise, not slopes, so there is no target keyword. eps (default 1e-4, bambi's default) must be finite and positive; wrt must be a real-valued non-Bool column, and the perturbed values must round-trip through its element type exactly (integer columns need an integer-compatible eps, e.g. an even integer).

Returns (; grid, draws, wrt, eps, target=:mean, logical, response, scale, focal). logical/response/scale pass through to the underlying mean evaluation; focal is recorded verbatim as plot metadata.

source
BayesianRegressionModels.brm_summarize_draws Function
julia
brm_summarize_draws(draws::AbstractMatrix; probs=[0.95], how=:hdi)
    -> Vector{NamedTuple}

Reduce a draws × elements matrix (as returned by brm_conditional_draws, brm_contrast_draws, or brm_slope_draws) to one summary row per element: (; element, mean, sd, q50, lower_1, upper_1, …) with one lower_k/upper_k pair per entry of probs (nonempty, strictly between zero and one, outermost first).

how=:hdi (default, bambi's default) reports shortest-posterior-mass intervals; how=:eti reports equal-tailed quantiles. At least two draws and finite values are required — a single draw has no interval and a non-finite value has no summary.

source
BayesianRegressionModels.linear_predictor_args Function

All :linear_predictor args from an outcome (>1 means distributional).

source
BayesianRegressionModels.linear_predictor_op Function
julia
linear_predictor_op(brmi::BRMI, name::Symbol) -> Union{ExprColumn,Nothing}
linear_predictor_op(brmi::BRMI, entry) -> Union{ExprColumn,Nothing}

The ~ ExprColumn that defines <name> ~ <rhs>, or nothing if name isn't a ~-bound entry in brmi.operations. An entry of linear_predictors(brmi) reads as its name.

source
BayesianRegressionModels.linear_predictors Function
julia
linear_predictors(brmi::BRMI) -> Vector{NamedTuple}

One entry per ~ op whose LHS is NOT a data column – the intermediate linear-predictor binds (loc ~ 1 + a, log(err) ~ 1 + b, ...). Each entry is (; name::Symbol, link_lhs_fn::Function) where name is the underlying parameter name (e.g. :err for log(err) ~ ...) and link_lhs_fn is the link applied to the LHS (e.g. log; identity when bare).

Declared parameters (sigma ~ Exponential(1)) and kernel(...) bindings are entries too. Pass an entry as it is to popcoefnames, predictors, grouping_factors, dependencies or linear_predictor_op: each reads it as its name, so Dict(lp.name => popcoefnames(brmi, lp) for lp in linear_predictors(brmi)) needs no filtering (popcoefnames answers nothing for an entry that is not a population formula).

source
BayesianRegressionModels.modeled_covariates Function
julia
modeled_covariates(model)

Ordered modeled continuous declarations used by later model operations. Each record exposes logical members, family, supported, rows, per-member missing counts, dependencies, resampled and value_role. Select a scalar member with reprocess(...; resample_covariates=[:x]); selecting a joint member redraws its whole ordered block. This inventory never requires generated Stan names.

source
BayesianRegressionModels.parameter_draws Function
julia
parameter_draws(d::BRMDescriptor, draws, unc_names;
                parameter::Symbol, to::Real) -> Matrix{Float64}

Set ONE declared parameter to the constrained value to in fitted UNCONSTRAINED draws: a copy of draws whose coordinates for that parameter hold the unconstrained image of to, so a subsequent brm_execute(d, :predict; draws = …) or BridgeStan param_constrain(...; include_tp = true) regenerates every output with the parameter fixed at to and every other coordinate held at its fitted value.

This is the parameter counterpart of term_draws, which removes a formula term. For placebo_mag ~ Normal(0, 1) entering loc = … + placebo_mag * unit_placebo, to = 0.0 removes that contribution.

  • d, draws, unc_names — as for term_draws.

  • parameter — the declared name (:placebo_mag), resolved through brm_output; never an emitted Stan name.

  • to — the finite constrained value. A real container (vector, matrix) has every element set to to.

The unconstrained image follows the declaration's own Stan transform: log(to - lower) for a lower bound, log(upper - to) for an upper bound, logit((to - lower) / (upper - lower)) for both, and (to - offset) / multiplier for an affine declaration; an unbounded parameter takes to itself. A to on or beyond a bound is refused (its unconstrained image is infinite). So is anything that is not a sampled, real-valued, top-level declared parameter: a population coefficient, random effect, linear predictor, plate-local value, transformed or generated quantity, a natively constrained type (simplex, correlation, Cholesky factor), and a bound that is not one number fixed by the data (one that reads another parameter, or differs per coordinate; a literal, scalar data and arithmetic over them, fmax/fmin with a structural bound included, are fixed).

Returns a fresh draws × length(unc_names) matrix; draws is left untouched.

julia
no_placebo = parameter_draws(d, draws, unc; parameter = :placebo_mag, to = 0.0)
pinned_sd  = parameter_draws(d, draws, unc; parameter = :sigma, to = 0.5)
source
BayesianRegressionModels.population_draws Function
julia
population_draws(model, draws, unc_names; groups, rng=Random.default_rng()) -> Matrix{Float64}

Population-level ("no random effects") draws: a copy of draws with every random-effect coordinate of the named grouping factors set to zero, so the model evaluates at those factors' population mean.

  • model — the SBBRMI / GenerativePlan the draws were fitted under.

  • draws — draws × coordinates, in unc_names order (an unconstrained posterior draw matrix).

  • unc_names — that model's param_unc_names.

  • groups — a grouping-factor symbol or a collection of them. A factor naming no emitted block is an error.

Every other coordinate — population coefficients, residual scales, and the random effects' own L / tau hyperparameters — is left untouched: only the per-group effect coordinates are zeroed.

Why zeroing is the population mean under both emissions

BRM's default emission is non-centered: the sampled coordinate is z ~ std_normal() and the effect is b = diag_pre_multiply(tau, L) * z. Zero z is therefore exactly b = 0, the population mean. Under the opt-in centered emission (SBBRMI(...; centered_groups = [...])) the same coordinates hold the effects themselves — unconstrained, so the unconstrained value IS the effect — and 0 is their prior mean. Either way the model's per-row contribution of that factor reads exactly zero (ranef_blocks).

A brms-style (… |ID| g) bucket is shared across sub-formulas and is zeroed as one block: selecting its grouping factor zeroes that factor's effects in every sub-formula that shares the bucket, which is what "population-level for g" means.

A grouped HSGP, hsgp(x...; by = g), is selected by its by= column: its standardized basis weights are zeroed, so the term is exactly zero on every row, and so are a hyper-predictor's per-level effects (log(sd(hsgp(x))) ~ 1 + (1 | g)), which puts every level at the population amplitude or length scale. ranef_blocks does not list these coordinates (they are not ranef_* submodels); a factor whose only effects they are is accepted.

For exact total-coefficient blocks, each posterior draw instead recovers one population coefficient vector conditionally and replaces the selected group totals with its implied population means. rng controls this recovery. The input and returned draws are both in the compiled model frame.

Blocks emitted in generated quantities

A selected block whose effect carrier the traced program emits in GENERATED QUANTITIES (RanefBlock.generated, or a total-coefficient block whose totals are generated — for example, no observed likelihood reaches it) has no coordinate in draws, so there is nothing to zero: it is skipped, exactly as transport_draws skips it. Its effects stay what the program makes them: Stan draws them when generated quantities are evaluated. Every quantity that does not read such a block is at the population mean of the selected factors; a quantity that does read one keeps that block's generated between-group variation.

A selected grouping factor whose every block is generated has no coordinate to zero at all, and is an error rather than a silent no-op.

population_model is the exact Stan-side alternative for those quantities: a program in which every block of the selected factors, sampled or generated, contributes exactly zero, evaluated on the fitted draws unchanged.

Example

julia
unc  = BridgeStan.param_unc_names(stan_model)
pop  = population_draws(sb, draws, unc; groups = :subject)
source
BayesianRegressionModels.population_model Function
julia
population_model(sb::SBBRMI; groups) -> SBBRMI

The population program of sb: the same model, in which every random-effect block of the grouping factors groups (a symbol or a collection of them) contributes exactly zero.

Every coordinate stays where the fitted program put it, so the population program has the fitted program's param_unc_names and the fitted draws evaluate on it unchanged. Its generated quantities — predictive draws, unobserved and held-out responses, prior-program outputs — are the population-level predictions of the selected factors:

julia
pop = population_model(sb; groups = :subject)
model = stan_instantiate(pop).model                  # BridgeStan model
BridgeStan.param_unc_names(model) == unc             # the fitted coordinates
BridgeStan.param_constrain(model, draw; include_tp = true, include_gq = true,
                           rng = BridgeStan.StanRNG(model, seed))

brm_descriptor(pop) mounts it like any other model, so brm_execute(d, :predict; draws, seed) reads the same draws.

Grouped HSGPs

A grouped HSGP, hsgp(x...; by = g), is selected by its by= column, though ranef_blocks does not list it: its levels × basis weights read 0.0 * their standardized draws, so the term is zero on every row, and a hyper-predictor's per-level effects (log(sd(hsgp(x))) ~ 1 + (1 | g)) read zero too, so every level sits at the population amplitude or length scale. This agrees with population_draws, which zeroes the same coordinates.

Exact total-coefficient blocks

A selected factor may carry exact total-coefficient blocks (total_effect_blocks, requested with total_groups, e.g. :auto for an independent Gaussian block). Each such predictor reads its block's population mean Z * (A * beta) instead of the group totals — with group-level predictors in the block (TotalEffectBlock.group_columns), each group's own mean Z * (A * (W[g,:] .* beta)) — where beta is the population coefficient the program recovers conditionally in generated quantities (TotalEffectBlock.population): one exact draw per evaluation, so the location agrees in law with population_draws(...; rng). The totals, scales and deviations still report the fitted values.

That location is a generated quantity, so no likelihood can read it: a population program with a selected total block holds out every observed response (recorded in its held_out). Each response's likelihood leaves the model block, while its predictive draw and pointwise log-likelihood stay in generated quantities at the population location; the coordinates are still the fitted program's. Its descriptor offers :predict and :pointwise_loglik, not :fit.

Compared with population_draws

population_draws zeroes the selected factors' coordinates in a draw matrix. On a block the fitted program samples, the two agree: each family returns an effect linear in its standardized draws (or, centered, the effect itself), so zero draws and a zero return are the same evaluation; an exact total block's location has the same law under both. They differ on a block the program draws in GENERATED QUANTITIES (an unobserved or held-out response's block, or every block of a prior program). That block has no coordinate for population_draws to zero, so its quantities keep their re-drawn between-group variation; here they read the population mean too. A factor whose every block is generated, which population_draws refuses, is supported.

What it reports

ranef_blocks(pop) reports each selected block with its fitted family, coordinates and placement and population = true; transport_draws and reprocess carry the population program like any other. Its Stan source differs from the fitted program's (0.0 * … on the selected effects, the population mean on selected totals), so its descriptor id does too.

Refused

  • A selected factor with a sum-to-zero block (s2z_groups).

  • A factor that names no random-effect block and no grouped HSGP.

source
BayesianRegressionModels.predictors Function
julia
predictors(brmi::BRMI, lhs::Symbol) -> Union{NamedTuple,Nothing}
predictors(brmi::BRMI, entry) -> Union{NamedTuple,Nothing}

For a linear-predictor LHS (or an entry of linear_predictors(brmi), read as its name), classify the RHS into:

  • intercept::Bool

  • continuous::Vector{Symbol} – bare predictors over Real data columns.

  • categorical::Vector{Symbol} – bare predictors over Integer data columns.

  • re_terms::Vector{(; group, inner)} – random-effects blocks, with inner recursively the same shape so callers can reach RE-internal predictors. A typed mm(...) term additionally carries groups, the tuple of all membership columns, while group remains its first column for compatibility with scalar-axis consumers.

Works for both bare-LHS LPs (loc ~ 1 + a) and link-transformed-LHS LPs (log(err) ~ 1 + b); the link is captured separately via linear_predictors. nothing only when the RHS is malformed.

source
BayesianRegressionModels.prune_responses Function
julia
prune_responses(brmi::BRMI; keep = <the data-bound responses>, marginalize = false) -> BRMI

The model brmi restricted to the responses keep: their observation statements, every statement and term their likelihoods depend on, and the prior statements addressing what remains, with the model values those read (a name = constant(...) prior centre, a scale parameter). Everything else — the other responses, the predictors, parameters and random-effect margins only they read — is not in the returned model at all, so its emitted programs, brm_descriptor and brm_description show only the kept model. Without pruning, omitting a response's column keeps its parts out of the sampler but re-draws them in generated quantities.

keep is a response name or a collection of them: the formula name or the data column of an observation, or, for one observed inside a @plate for / kernel(...) cell, the cell's formal. It defaults to the responses whose columns are bound in the data; name the responses for a prior program, which binds none. It acts on the formula, so every backend (SBBRMI, RKBRMI, …) builds the pruned model.

A cell that observes kept and pruned responses stays without the pruned observations and the cell statements only they reached; the inputs and model values only those statements read leave with them, and with them the predictors, parameters and margins nothing kept reads. A statement stays when the cell's value, a kept observation, or a cell value that no statement reads (an output the cell reports) reaches it; a reported output computed from what only the pruned observations reach goes with them. As at formula level, a kept statement that reads a pruned response's value keeps that response's observation.

A shared |ID| block that keeps a of its K margins keeps their scale priors. Its correlation prior is, by default, the formula's own at width a: LKJCholesky(a, eta) with the authored (or default, 1) eta, the model one would write without the pruned responses. marginalize = true instead keeps the exact marginal prior of the full block, LKJCholesky(a, eta + (K - a)/2) — the law the omitted-response program samples.

Refused: a name that is not a response; a joint R2D2 budget that would lose terms; a stratified or multi-membership shared block that loses margins.

julia
pk_tumor = prune_responses(builder(data); keep = (:pk_y, :tumor_y))
sb = SBBRMI(pk_tumor)
source
BayesianRegressionModels.recover_population_draws Function
julia
recover_population_draws(model, draws, unc_names; rng=Random.default_rng())

Draw the original population coefficients conditional on each saved total- coefficient draw. Returns one record per predictor with population, totals, and deviations arrays. This exact recovery adds conditional randomness; totals are unchanged. Input draws must be in the compiled model's coordinate frame.

A block whose totals are emitted in generated quantities (no observed likelihood reaches it, for example an omitted response) has no saved total to condition on, so it has no record here. Stan draws its totals, population coefficients and deviations together when generated quantities are evaluated. A model whose every block is generated is an error.

source
BayesianRegressionModels.recover_s2z_draws Function
julia
recover_s2z_draws(model, draws, unc_names; rng=Random.default_rng())

Draw the omitted block means conditional on each saved S2Z draw and recover the original population coefficients (beta = theta - B*m) and group effects (b = r + m). Returns one record per predictor with population, means, deviations and effects arrays. Input draws must be in the compiled model's coordinate frame.

source
BayesianRegressionModels.rk_draw_tree Function
julia
rk_draw_tree(rk::RKBRMI, U, names)
rk_draw_tree(values::NamedTuple)

The named values returned by rk_draw_values as a TreeArrays record of per-name :draw trees. Like rk_draw_values, columns of U are draws. Scalar values are stored directly; vector-valued draws stay separate, with their actual element indices, rather than being stacked. A @plate output has :cell below :draw, then :element for a vector cell or :row × :column for a matrix cell. A vector of per-chain matrices adds :chain. Requires using TreeArrays. The second form labels an existing rk_draw_values result without querying the model again or copying its values. It sees only shapes, so a nested value, a plate output's cells included, raises an error there.

source
BayesianRegressionModels.rk_draw_values Function
julia
rk_draw_values(rk::RKBRMI, U, names) -> NamedTuple

The graph values names of rk (formula values, = assignments, @plate cell outputs) at each draw, the columns of U in rk's unconstrained coordinates: one vector of per-draw values per name, from one prepared value kernel.

A draw's value of a @plate output has one entry per cell in the cell's own shape, as the model reads it: after out[i] = v, value[i] is cell i's number, vector or matrix. reduce(vcat, value) concatenates vector cells.

source
BayesianRegressionModels.rk_restore_draws Function
julia
rk_restore_draws(backend::RKBRMI, U::AbstractMatrix) -> NamedTuple

Restore named constrained parameters from an unconstrained draws matrix U (dimension rows × draws columns, e.g. sampler output): coefficient predictors map to (size × draws) matrices, sampled parameters to length-draws vectors. Implemented only by the BayesianRegressionModelsReactiveKernelsExt package extension.

source
BayesianRegressionModels.term_draws Function
julia
term_draws(d::BRMDescriptor, draws, unc_names;
           predictor::Symbol, term::Symbol, to::Symbol = :zero) -> Matrix{Float64}

Ablate ONE named linear-predictor term in fitted UNCONSTRAINED draws: a copy of draws with that term's coefficient coordinates set to zero, so a subsequent brm_execute(d, :predict; draws = …) regenerates every descriptor output with the term's contribution removed and all other structure — every other term, every other coefficient, the residual scales, a GP term's own length-scale and marginal sd — held at its fitted value.

This is the structural counterpart to population_draws: that zeroes a grouping factor's random effects (a level intervention); this zeroes one formula term. Both are draw-matrix operations on the unconstrained parameter vector, resolved BY NAME, and neither reaches into the constrained space or the compiler-owned coordinate order.

  • d — the BRMDescriptor the draws were fitted under (the same object passed to brm_execute(d, :predict; …)).

  • draws — draws × coordinates, in unc_names order: the unconstrained posterior draw matrix :predict consumes.

  • unc_names — that model's param_unc_names (BridgeStan), in its order. The carrier is looked up by Stan name, so nothing here depends on that order.

  • predictor — the linear-predictor name (:log_F).

  • term — a public formula label of that predictor: an ungrouped-hsgp term label (:hsgp_op_log_dose, the labels brm_term_coordinates uses), or a population coefficient label (:Intercept, a column such as :age, a wrapped term's design key, an interaction column) or categorical predictor (:site in 1 + site or factor(site; cmc=false)) — the addresses brm_population_effect_coordinates resolves.

  • to — the target value for the term's carrier. Only :zero is supported.

Returns a fresh draws × length(unc_names) matrix; draws is left untouched.

Why zeroing removes exactly the term

Each admitted term contributes a summand that is LINEAR in a carrier whose unconstrained coordinate IS its value, so setting those coordinates to zero removes exactly that summand:

  • An ungrouped hsgp(x; …) emits beta_raw ~ std_normal() and contributes PHI * (sqrt_spd .* beta_raw) (_sb_hsgp / _sb_hsgp_aniso, sbimpl.jl), whatever the fitted length-scale (rho) and marginal sd (sigma).

  • A population coefficient is one column of beta_pop in X * beta_pop (popefs); zeroing it removes that column's X[:, k] * beta_pop[k]. A wrapped term such as mo(x) owns one such column under its term label, so term = :mo_x removes the whole monotonic summand (its simplex is kept).

  • A categorical predictor contributes append_row(0., beta)[x] (treatment coding) or beta[x] (cell means) (_sb_cat / _sb_cat_cells); zeroing its whole block makes the term contribute zero on every row, so under treatment coding every level takes the reference level's value.

Everything else fails closed rather than zeroing a coordinate whose removal would mean something else:

  • a grouped hsgp(…; by = …) (a correlated random-effect block — zero its levels with population_draws), and other terms whose contribution is not one coefficient column (dar/rw/cdar processes, car areal fields, s(...) splines);

  • a population carrier whose declaration spells a bound, offset or multiplier (for example effect(mu, :) ~ Exponential(1) declares every coefficient with lower=0: its unconstrained 0 is the constrained 1, and the term's removal sits on the boundary). A single support-limited margin such as effect(mu, x) ~ Exponential(1) leaves the vector declared unbounded (its density enforces the support), so that coefficient zeroes exactly;

  • a coefficient absorbed by an exact total-coefficient block (the (1 | g) intercept under total_groups=:auto), which is integrated out of the sampled model and has no unconstrained coordinate;

  • a carrier absent from the unconstrained draws — re-drawn in generated quantities (an unconditioned program), or assembled from raw draws as a transformed vector (a horseshoe population prior). An R2D2 population prior samples beta_pop itself, so its coefficients ablate like any other;

  • a label naming both an hsgp term and a population coefficient.

to = :zero is the only value with an established meaning; any other target errors. To set a declared parameter to a value, use parameter_draws.

Example

julia
unc     = BridgeStan.param_unc_names(stan_model)          # unconstrained names
full    = brm_execute(d, :predict; problem, draws, seed)  # every term present
linear  = term_draws(d, draws, unc;
                     predictor = :log_F, term = :hsgp_op_log_dose)
no_hsgp = brm_execute(d, :predict; problem, draws = linear, seed)  # term removed
no_site = term_draws(d, draws, unc; predictor = :mu, term = :site)
source
BayesianRegressionModels.transport_draws Function
julia
transport_draws(rk::RKBRMI, replay::RKBRMI, draws::AbstractMatrix;
                resample_covariates, rng=Random.default_rng()) -> Matrix

Map posterior draws of the RK fit rk (one draw per row, the fit's unconstrained coordinates in layout order) onto a forecast replay = reprocess(rk, design; resample_covariates, keep_observed=true). Every coordinate the two share is copied by name. The missing entries of each covariate in resample_covariates are the design's, so they are drawn fresh for each draw: standard normal draws of their non-centered Normal / LogNormal law, which given that draw's parameters is exactly the law of the design's missing values. Pass the same resample_covariates as to reprocess: a missing-entry coordinate of the replay never inherits the fit's draw of the same name, which belongs to a training row.

The result evaluates natively (prepare_query(replay.model, rk_bound_plan(replay), (:mu,))) and through jax_source(replay.model, rk_bound_plan(replay)). Different rng streams give different missing values and the same values at observed rows.

source
julia
transport_draws(from, to, draws, unc_from, unc_to;
                resample = (), rng = Random.default_rng()) -> Matrix{Float64}

Transport fitted draws from model from onto model to — the same @brm declaration re-instantiated at new covariates and/or new group levels — so the fit can be evaluated on new data without refitting.

  • from / to — SBBRMI / GenerativePlan values. to is typically generative_plan(plan, new_df) (the builder form, which rebuilds the same declarations for genuinely new groups), reprocess(sb, new_df) when the groups are unchanged, or reprocess(sb, new_df; resample_groups = [g]) — see the resample-target paragraph below.

  • draws — draws × coordinates in unc_from order; unc_from / unc_to are the two models' param_unc_names.

  • resample — grouping factors whose EXISTING levels should also be re-drawn rather than reused (leave-all-out / out-of-sample semantics). For conventional plain and |ID| blocks this is REFUSED — re-draw Stan-side via reprocess(...; resample_groups=...) instead (rule 2). It is honoured for total-coefficient blocks (conditional recovery, the sanctioned totals route) and for the block kinds with no GQ emission.

  • rng — the source for the surviving Julia-side draws: total-coefficient recovery and the rule-2 exception kinds.

Returns a draws × length(unc_to) matrix aligned to to.

The alignment contract

Every coordinate of to is accounted for exactly once, by NAME:

  1. A random-effect coordinate whose group LEVEL also exists in from (and whose factor is not in resample) is copied from that level's coordinate — by level label, so a reordering, an insertion, or a dropped level cannot misalign it.

  2. A random-effect coordinate for a level from does not have, or for a factor in resample, is drawn fresh — subject to the emission. Under a CENTERED emission (centered_groups) the coordinate holds the effect itself, so the fresh draw is b = C * z with z ~ N(0, 1) and C rebuilt per draw from that draw's fitted tau / L — a draw from the fitted covariance through the model's own transformation (a bare N(0, 1) would be the wrong scale). No StanBlocks generated-quantities re-draw exists for centered blocks, so this Julia-side draw is the route. Under the NON-CENTERED emission, plain (… | g) and shared (… |ID| g) blocks REFUSE fresh draws: population prediction for the Sb backend goes through the StanBlocks model (reprocess(fit, new_df; resample_groups=[g]), whose block is generated=true and skipped here), never through Julia-side randomness. Julia-side N(0, 1) survives only for block kinds with no GQ re-draw: stratified gr(g, by=b) blocks, typed mm(...) blocks, plain (non-bucket) R2D2 blocks, and zerocorr || synthetic margins — exactly a draw from the fitted covariance, because the L / tau hyperparameters are copied per draw by rule 3. A grouped HSGP, hsgp(x...; by = g), follows rules 1 and 2 for its standardized basis weights and a hyper-predictor's per-level effects, which ranef_blocks does not list: a level of g the source has is copied from that level, and a new level (or every level, for g in resample) is refused with the resample_groups route, whose target draws them in generated quantities and is skipped here. Weights on a cor = multigroup((x, y), …) inducing grid are shared by every level and copy row for row.

  3. Every other coordinate must exist in from under the same name and is copied.

Anything that does not fit those three rules raises. In particular a coordinate of to that is absent from from and is not a random effect, a random-effect block to has and from does not, and a block whose term count changed, are all errors — those are the cases where a positional splice would have produced plausible, wrong numbers.

Coordinates that exist in from but not in to (a dropped group level) are simply not carried over.

Resample targets (reprocess(sb, new_df; resample_groups = [g]))

resample_groups moves factor g's standardised draws to the target's GENERATED QUANTITIES, so they are re-drawn Stan-side per draw and are NOT in to's param_unc_names. ranef_blocks(to) reports such a block with generated = true; transport_draws SKIPS it — there is no coordinate to transport. What IS transported is everything that remains a parameter: the population coefficients and, critically, the resampled factor's own L / tau covariance hyperparameters, all copied by NAME (rule 3). The net effect is exact out-of-sample semantics — the target re-draws g's per-level effects from the FITTED covariance, because that covariance is transported. from's per-level draws for g are dropped (they are from-only coordinates), which is correct: the new levels are not the fitted ones. This is the intended consumption path for a resample target; a positional splice of the fitted levels' draws would be the exact wrong answer.

The same rule applies to blocks emitted in generated quantities because no observed likelihood reaches them. A prior program may still have nonzero dimension, for example from observed covariate likelihoods and fitted missing covariates. Transport retains those sampled coordinates by name and leaves generated effects and any generated covariance inputs to Stan. Activity comes from the traced carrier's descriptor kind, not from missing caller-supplied coordinate names: an incomplete sampled block still raises.

Exact total-coefficient blocks follow the same rule. A target block whose totals are generated (its scales are generated with them) is skipped: the target re-draws it Stan-side. A block the target samples but the source generates is refused, because the fitted draws carry nothing to transport onto it.

Example

julia
same_plan = generative_plan(plan, same_df)        # same subjects, new schedule
moved     = transport_draws(sb, same_plan, draws,
                            unc_old, unc_same)    # levels copied by label
pop       = reprocess(sb, new_df;                 # NEW subjects: Stan-side
                      resample_groups=[:subject])
moved_pop = transport_draws(sb, pop, draws, unc_old, unc_pop)  # GQ re-draw
source

Additional exports in this task group:

OriginNames
BayesianRegressionModelsbrm_centerednessplot, brm_centering_lossplot, brm_comparisonsplot, brm_gradientplot, brm_pairplot, brm_posteriorplot, brm_ppcplot, brm_predictionsplot, brm_slopesplot

Descriptions and export ​

Inspect declared structure and emit model descriptions or backend programs. See Backends.

BayesianRegressionModels.BRMDescription Type
julia
BRMDescription

Deterministic description of an existing prepared model. complete is true only when every inventoried semantic component is covered. It certifies inventory coverage, not the independent scientific correctness of handwritten hooks. model_id is the unchanged inference identity; labels, prose and texts do not alter it. texts holds the language the description was written in; a description constructed without it is English.

prose and equations hold every sentence and every equation in inventory order. sections holds the same sentences and equations per described component, (; id, prose, equations) in that order, so a reader sees each part's equations right after its sentences; the Markdown is written from them. A description constructed without sections has one section holding all of prose, then all of equations. documentation retains authored declaration Markdown and provenance; it does not change scientific coverage or numerical identity.

source
BayesianRegressionModels.BRMDescriptionComponent Type
julia
BRMDescriptionComponent

One semantic node. Its stable logical tuple id identifies this use of the actual callable. arguments and keywords contain literals, references and recursive component nodes. children is the inventory a custom hook must inspect before claiming coverage. Axes, named outputs, effective priors and fitted constants come from the selected descriptor. provenance ties the node to the authored declaration and executable model identity. Inputs are read-only.

source
BayesianRegressionModels.BRMDescriptionContext Type

The read-only semantic component supplied to a description hook.

source
BayesianRegressionModels.BRMDescriptionFragment Type
julia
BRMDescriptionFragment(; prose=(), equations=(), covers=(), notation=())

A hook's scientific explanation. Equations are LaTeX without display delimiters. covers lists exact component IDs; covering a parent never covers its children. notation contains records with name, meaning, and optional symbol, axis, unit. Hooks are responsible for the accuracy of their scientific math.

source
BayesianRegressionModels.BRMDescriptionReference Type

A named value and its declared indexing axis, never guessed from its name.

source
BayesianRegressionModels.BRMDescriptionTexts Type
julia
BRMDescriptionTexts

Every text a model description writes itself: its prose sentences, the meanings of the notation it introduces, the words inside its LaTeX, its coverage-gap messages and the Markdown scaffold of brm_description_markdown. Build one with description_texts and pass it as texts= to brm_description; the description keeps it and its Markdown follows it. Labels, units, symbols and hook prose are supplied by the caller and are never translated.

A word in braces is a placeholder the description fills in, such as {owner} or {n_groups}. Braces directly after a letter, \, _ or ^ are LaTeX, not placeholders, so \textit{x} and a_{k} stay literal. The texts named math_* are LaTeX inserted into an equation.

source
BayesianRegressionModels.BRMDescriptor Type
julia
BRMDescriptor

The one authoritative, executable, reflectable value for a @brm declaration. Construct with brm_descriptor.

fieldwhat it is
idstable content identity — StanBlocks' descriptor id, the hash of the generated Stan source, which is also the key instantiate caches the compiled artifact under. Stable across processes; independent of name
nameinformational label (name= at construction, else the plan's own)
formulathe canonical rendering of the parsed declaration (show of the BRMI). Not the literal characters you typed — it is derived from the declaration, so unlike a hand-kept formula_src string it cannot drift from the model that runs
planthe GenerativePlan — every emitted ~ site, in order
stanStanBlocks' ModelDescriptor for the same model, if you need the Stan-level view verbatim
highlightsordered caller-selected BRMHighlights, resolved by stable name against stan.definitions; the full included-definition inventory remains on stan. An optional entry (brm_highlight) the program does not define is absent here
inputsTuple of BRMInput — the data block plus its dataframe provenance
outputsTuple of BRMOutput — everything the model produces, with BRM roles
operationsTuple of BRMOperation — derived, not listed
columnsthe dataframe columns the declaration reads. This is the schema a form should collect for a replay
unpredictableobservation targets whose predictive draw the emitted Stan program does not produce. Empty in the ordinary case; see below
submodelsTuple of BRMSubmodel — the consumer @slic submodels the emitted model inlines, in emission order, with their call site, own declarations and outputs, and derived source
highlight_specsTuple of BRMHighlightSpec — every requested highlight in order, resolved ones with their signature filled in; replay operations re-resolve these

brm_columns(d), brm_operation(d, name), brm_execute(d, name; …) are the accessors.

source
BayesianRegressionModels.BRMDocumentation Type
julia
BRMDocumentation

An authored Markdown docstring attached to a logical declaration. path names the declaration, with enclosing plate/component names before it; owner is its top-level operation. statement is the authored syntax, and file/line record Julia's source location when supplied. Documentation is not executable model code. Access records through brm_documentation, which returns copies so changing an expression cannot mutate a model's metadata.

source
BayesianRegressionModels.BRMHighlight Type
julia
BRMHighlight

One caller-selected Stan definition to feature when presenting a BRMDescriptor.

  • name is the stable definition name resolved by StanBlocks.

  • caption is optional presentation text supplied by the caller.

  • definition is StanBlocks' authoritative definition descriptor, including its emitted source and direct dependency links.

  • closure is that definition plus its exact transitive included dependencies in StanBlocks' authoritative emission order.

BRM never copies or parses the generated Stan source to construct either.

Pass symbols, name => caption pairs and/or brm_highlight specs through the ordered highlights= keyword of brm_descriptor. The full executable definition inventory remains available on d.stan.definitions; d.highlights is only the selected, ordered presentation layer.

source
BayesianRegressionModels.BRMHighlightSpec Type
julia
BRMHighlightSpec

One requested highlight, before it is resolved against a model's Stan definitions. Build one with brm_highlight; brm_descriptor normalizes every highlights= entry to this form.

  • name / caption — as for BRMHighlight.

  • signature — the exact emitted Stan signature to select among overloads, or nothing for a name that must resolve uniquely.

  • optional — when true, a program that defines no Stan function of this name skips the entry instead of raising.

d.highlight_specs keeps the descriptor's requests in order, with each resolved entry's signature filled in. :replay and :reprocess re-resolve them against the new program, so an optional entry absent from one fit is highlighted again on a replay that defines it.

source
BayesianRegressionModels.BRMInput Type
julia
BRMInput

One entry of the emitted Stan data block, with its BRM provenance attached.

The first eight fields mirror StanBlocks' ModelInput (stanblocks-use §30) — name, type (the Stan center type), size (the declared size expressions, not values), constraints, and the four flags:

  • observed — the model conditions on this input (it is the LHS of a ~).

  • held_out — this input is cv-marked, so its likelihood contribution is dropped and it re-draws in generated quantities.

  • derived — this input is another input's declared size (y_n for vector[y_n] y). Re-binding y re-derives it; never ask a user for it.

  • inlined — folded into the generated source, never reaches the data JSON.

The last two are BRM's addition — the schema link back to the dataframe:

  • column — the dataframe column this Stan input was built from, or nothing when it has no single raw column (a design matrix, a level count, a size).

  • transform — the BRM preprocessing kind applied on the way (:zscale, :center, :standardize, :factor, :mo, :spline, :gp, :hsgp, :static, :group_index, :ranef_factor_dummy, :multi_membership, :kernel_subject_count, :kernel_ragged, :axis_extent, :protect, :constant), or nothing when the column is passed through untransformed. A name = constant(expr) input has transform = :constant and no column: replay keeps its fitted value, so a column only expr reads is not part of the replay schema brm_columns.

column/transform are read from the plan's preproc record and the BRMI's own data columns — they are never inferred from the input's name. The fitted constants of a center/zscale/standardize input are brm_transform_constants's, which also covers mi(...) inputs whose transformed value is computed inside the model.

source
BayesianRegressionModels.BRMOperation Type
julia
BRMOperation

One executable operation the declaration supports. Operations are derived, never listed: each appears exactly when the model actually supports it, so a consumer can render one button per operation without maintaining its own list and without rendering a button that will fail.

  • name / title — the identifier and a human label.

  • inputs — the names this operation needs. Read origin to know which namespace they live in: :stan operations take Stan data keys (the neither-derived-nor-inlined subset), :brm operations take dataframe columns.

  • outputs — the descriptor output names it produces (empty when it produces a new descriptor or the Stan source rather than draws).

  • origin — :stan (delegated to StanBlocks' stan_execute), :brm (BRM-level: replay the declaration on new data), or :override (supplied by the consumer through brm_descriptor(...; operations=…)).

  • run — the callable brm_execute invokes, (descriptor; kwargs...) -> result.

See brm_descriptor for the derivation table and the extension points.

source
BayesianRegressionModels.BRMOutput Type
julia
BRMOutput

One thing the compiled model produces, with its BRM meaning attached.

Fields name … source mirror StanBlocks' ModelOutput (stanblocks-use §30): kind is :parameter / :transformed_parameter / :generated_quantity, and generative is :posterior / :draw / :pointwise_loglik / :derived with source naming the observation a :draw or :pointwise_loglik belongs to.

BRM adds:

  • role — what this output means in the formula:

    rolewhat it is
    :population_effecta popefs block — the population-level design and its coefficients
    :random_effecta ranef_* block and its internals
    :group_blocka kernel(...) / plate result and everything declared per cell
    :parameteran ordinary declared prior (sigma ~ Exponential(1))
    :linear_predictora formula linear predictor (mu ~ 1 + x + (1|g)) — an assignment, so no ~ declaration binds it. A linked declaration f(x) ~ … (log(CL) ~ …, logit(p) ~ …) gives the bare x on the response scale, x = inverse(f)(η), not the link-scale η: apply the link to its draws (log.(CL)) for η
    :posterior_predictivea predictive draw of an observation
    :covariate_drawthe selected modeled covariate value consumed by later operations
    :pointwise_loglikan observation's per-element log-likelihood
    :membershipa MixtureModel response's n x K matrix of per-row component-membership probabilities (<response>_membership); source and logical name the response, labels the components, so it is addressed as logical=<response>, role=:membership
    :stan_deriveda Stan-level output no BRM declaration owns
  • declaration — the GenerativeDeclaration this output came from, or nothing for :linear_predictor / :stan_derived. Its twelve fields (family, dimension, constraints, the verbatim expression, …) are documented on GenerativeDeclaration; reach for them instead of re-parsing. An output whose name differs from declaration.target is one of that block's internals (pop_mu_beta_pop under pop_mu).

  • logical — the BRM-level quantity whose value this emitted Stan output physically carries, or nothing for an internal. It is narrower than declaration: pop_mu_beta_pop belongs to the pop_mu declaration but is one of its internals, so it carries no logical target. For a kernel(...) cell value, logical == :qt_loc accompanies an emitted name such as :pk_loc_qt_loc; consumers keep the logical identity while addressing BridgeStan through the emitted name. Every named value a kernel(...) cell assigns carries one too — no annotation. The author bound the name and the value is in every posterior draw, so it is addressable by that name:

    julia
    pk_loc ~ kernel(t, dv, qt_y, log_CL, qt_base) do ts, yy, qy, lCL, qbase
        conc   = exp(-exp(lCL) .* ts)
        qt_loc = qbase .+ slope .* conc     # a cell value, not an observation
        qy ~ normal(qt_loc, qt_sigma)
        conc                                 # the RETURN
    end
    
    brm_output(d, :qt_loc)     # BRMOutput(name = :pk_loc_qt_loc,
                               #           logical = :qt_loc, role = :group_block, …)
    brm_output(d, :conc)       # the same cell's other named value
    brm_output(d, :pk_loc)     # the collected return

    Cell values are ordinary :group_block outputs of the plate declaration and compose with brm_outputs / brm_output_coordinates / segments like any other; their emitted name stays compiler-owned and unparsed. Only a top-level name = ... counts: a slice parameter is an argument (address the positional it came from), and an in-cell ~ is an observation (addressable through its own column's twins, below). Two consequences are deliberate. Scratch is addressable too — CL = exp(lCL) gives logical == :CL — so brm_outputs(d) is wider than the set of quantities an author would call primary. And two cells may name a value the same thing; both are claimed, brm_output(d, :mu) then refuses and names the candidates with their owners, and brm_outputs(d; logical=:mu) returns both for selection on declaration.target. That is the same one-logical-many-carriers contract an observation's two twins already use; the model still builds and unambiguous names still resolve directly. A formula-authored top-level = assignment is claimed the same unconditional way, under its own name: qt_scale = sqrt((1 - r2_qt) * V) gives logical == :qt_scale (role stays :stan_derived) whenever the assignment survives to a posterior-draw carrier. Data-folded assignments never reach the outputs so they stay unclaimed, and an emitted name an earlier claim already owns keeps its existing logical. ⚠ A predictive twin is not a substitute for the location it was drawn from. In the model above qt_y_gen is normal_..._rng(qt_loc, qt_sigma) — noise ADDED — so it answers a different question than qt_loc does. For a predictive or pointwise-loglik twin it is StanBlocks' source — the OBSERVED QUANTITY — which is not always a declaration target. A top-level y ~ Normal(mu, sigma) gives y_gen logical == :y, where :y is also the declaration; a plate-nested yy ~ normal(...) over column dv gives dv_gen logical == :dv, where the declaration is the cell-local yy and :dv is a data column. Both twins of one observation share it, so brm_output needs role= to pick between them.

  • labels — per-element labels when BRM can name them (population coefficients, via popcoefnames), otherwise nothing. A UI that would otherwise print beta_pop.1, beta_pop.2 can print x, g.

  • segments — group boundaries for a RAGGED quantity, carried through from StanBlocks' ModelOutput.segments, otherwise nothing. Group g occupies segments[g-1]+1 : segments[g] (with segments[0] ≡ 0) within this output's element order. Predictive outputs have one value per element; an aggregate :pointwise_loglik instead has one value per group, while its segments still describes the response's element grouping. The ends do not partition that aggregate likelihood's columns. For predictive draws, brm_output_tree keeps element positions aligned with values even when the supplied constrained names are permuted.

  • component — which part of a random-effect block, or of a population, categorical or structured-term block (second table), this output is, or nothing for an output that belongs to no such block. Every :random_effect output of a StanBlocks (SBBRMI) descriptor has one, and so does a block's scale when it is its own statement (a known-value block's sampled scales, an exact total block's scale). A sum-to-zero block (s2z_groups, role :s2z_effect) carries nothing:

    componentwhat it is
    :scalethe per-margin between-group SDs tau (per stratum for a stratified gr(g, by=b) block), sampled or derived (R2D2)
    :log_scalethe sampled log SD of a scalar (1 | g) block, whose SD is exp(log_scale)
    :correlation_choleskythe Cholesky factor L of the correlation matrix (L L'), per stratum for a stratified block
    :standardizedthe standard-normal draw the effects are scaled from (effects = diag(tau) L z), in any of its shapes
    :effectsthe per-level effects on the link scale — under centered_groups the sampled coordinate itself
    :contributionthe per-row values the block adds to its linear predictor
    :mixing_weighta Student-t block's per-level mixing weight
    :level_scale, :level_correlation_choleskya stratified block's stratum tau and L, gathered per level
    :auxiliaryan intermediate of the block's construction that is none of the above: a value StanBlocks hoists out of the block's plate (a centred block's covariance factor diag(tau) L), the permuted factor and onion draws of an omitted response's completion

    The block is the output's declaration.target — the binding that brm_ranef_draws and ranef_blocks report — and its margins are brm_ranef_draws' margins, so posterior coordinates group and label by block and component without reading an emitted name:

    julia
    for o in brm_outputs(d; role=:random_effect, component=:scale)
        o.declaration.target, brm_output_coordinates(o, constrained_names)
    end

    The parts of a population, categorical or structured-term block. A term part's name is the parameter= brm_term_coordinates takes for it:

    componentwhat it is
    :coefficientsthe population coefficient vector (labels names its elements)
    :contrasts / :cell_meansa categorical predictor's K-1 treatment contrasts, or the cell means of an intercept-free predictor's first factor
    :contributionthe per-row value a population or categorical block adds to its linear predictor
    :length_scale, :sd, :basis_weights, :simplex, :ar, :innovations, :mixing, :structured, :unstructured, :effects, the hyper-predictor rolesthe term parameter of that name (hsgp; mo/mo1; dar/rw/cdar; car). A grouped hsgp(...; by=g)'s per-group weights are :basis_weights too, though brm_term_coordinates does not address them
    :valuethe term's own per-row value (hsgp, mo1, dar, rw, cdar, car)
    :auxiliaryany other internal of these blocks: an mo design column, a horseshoe's scales, an hsgp spectral density

    s, t2, gp, me, ar and interval_censored terms have no public parameter roles, and neither do an R2D2 prior's R² and simplex: their outputs carry predictors (and term) but no component.

  • dims — the shape of the output's value (() for a scalar): StanBlocks' ModelOutput.dims, its declared size evaluated against the bound data, composite sizes and transformed-data values included. prod(dims) is the number of names BridgeStan lists for the output, and a one-size square matrix has both axes (cholesky_factor_corr[K] reports (K, K)), so dims and size need not have the same length. A categorical predictor's contrast or cell-mean width from its frozen level set cross-checks it. It is nothing for a hand-assembled output and under a StanBlocks that publishes no dims; BRM needs StanBlocks f175dd6 or later, where dims is the value shape. A 0 marks a carrier with no elements — a one-level treatment factor's contrasts, a one-level ordinal outcome's thresholds — which BridgeStan lists under no name, so brm_output_coordinates returns Int[] for it.

  • predictors — the formula linear predictors whose terms own this output, by their public names (:Vc for log(Vc) ~ …), in formula order, or () for an output no formula term owns (an ordinary prior such as sigma, an observation's twins, a plate cell's values, a :stan_derived intermediate). It covers the population block and its prior (R2D2, horseshoe), every categorical and structured term, every random-effect block, exact-total and S2Z blocks, and the predictor's own value. A block that terms of several predictors own lists every one of them: a shared (… | p | g) block and a joint sd(:, p) ~ r2d2(...) budget, split per margin through brm_ranef_draws' margins. A reference_scale= the author declared stays the author's.

  • term — the formula term this output belongs to, in the address the per-term queries take, or nothing. A categorical block's is its column as written (:g for factor(g; ref=3), the coefficient= of brm_population_effect_coordinates); a structured term's is its term label (:hsgp_t, :mo_dose, :rw_mu_t, Symbol("s(x)"), the term= of brm_term_coordinates). The population coefficient vector and random-effect blocks carry nothing: their elements are addressed by labels, and by block and component. So every posterior coordinate groups by predictor and labels by term and part without reading an emitted name, and the address resolves back to the output:

    julia
    for o in brm_outputs(d; predictor=:mu, kind=:parameter)
        if o.component in (:contrasts, :cell_means)
            brm_population_effect_coordinates(d, :mu, constrained_names;
                                              coefficient=o.term)  # .output === o
        elseif !isnothing(o.term) && o.component !== :auxiliary
            brm_term_coordinates(d, :mu, constrained_names;
                                 term=o.term, parameter=o.component)
        end
    end

role is derived from the declaration, never from the output's name — a user variable may legitimately be called beta_pop or end in _gen.

source
BayesianRegressionModels.BRMPriorDescription Type
julia
BRMPriorDescription

An effective prior, addressed by a logical tuple id. distribution preserves the actual callable and arguments; support includes declared constraints. source records the winning selector or the producer default. anchor is an optional report-supplied URL. Numeric constants are snapshots of the selected prepared model; symbolic hyperparameters remain named references.

source
BayesianRegressionModels.BRMRKDescriptor Type
julia
BRMRKDescriptor

The content identity and input inventory of the program an RKBRMI runs. Construct with brm_descriptor(rk::RKBRMI; name).

fieldwhat it is
id"rk:<sha256>": the hash of the backend's emitted RK program, its definitions, main statements and binding names (without macro-call places or documentation) and its callables (a generated function enters by what it computes). Independent of name and of the data's values: the same program and callables give the same id. It changes with the formula, held_out, completions, car_units or a callable, and when a BRM release emits the model differently
nameinformational label: name= at construction, else :model
formulathe canonical rendering of the declaration (show of brm_source(rk)), as on a BRMDescriptor
inputsTuple of BRMInput, one per input the RK graph binds (rk_bound_data), in that order
columnsthe dataframe columns the declaration reads (brm_columns)
held_outthe responses whose likelihoods the backend withholds. The program does not read them, so they are not among inputs
program(; defs, main, bindings): a copy of the emitted program id hashes

The fields of each input mean what they mean on a Stan descriptor, read for an RK program:

  • type: the element type of the bound value (:Float64, :Int64, …), or the type of a scalar.

  • size: the bound value's size, () for a scalar. An RK program takes its sizes from its inputs' values; an extent computed from the data is an input of its own, with derived = true.

  • constraints is (;) and inlined is false.

  • observed: the program conditions on the input. held_out is false.

  • column: the dataframe column the input is or copies, or nothing for a value BRM generates or the program computes.

  • transform: nothing for a dataframe column: the RK graph does the preprocessing (zscale, group indices, …) itself, so the program reads the raw column. A plate cell's port of a response's nested values (<cell>_input_y) is that response's column too. A fit-role input (<column>_fit) is :fit: a copy of column that the program fits its preprocessing from (a grouping's levels, a center/zscale mean and SD), so a replay keeps the fit's preprocessing. It holds the column's own values on a first build and the training column on a frozen reprocess replay. An input BRM generates names what it holds: :levels (the level table of a factor or mo() term, fitted when BRM plans the model), :level_count, :prior_constant or :known_correlation. A value the program computes from its data (a design matrix, a grouping's level table <g>_fit_levels, each row's level <g>_level), which RK preparation evaluates once and binds in place of its definition, is :computed; on a frozen replay that is the fit's value.

No Stan program is built, so the Stan-only readers (brm_output, brm_operation, the coordinate resolvers) have no method for it. The RK parameters are the backend's (rk_restore_draws).

source
BayesianRegressionModels.BRMSubmodel Type
julia
BRMSubmodel

One consumer-authored StanBlocks @slic submodel that the emitted model inlines, such as the value a _sb_submodel_rhs! hook emits for log_F ~ bioav_emax(op_log_dose). d.submodels lists them in emission order, including submodels called from inside another submodel or a plate cell. BRM's own building blocks (population effects, random effects, HSGP terms, configured prior templates) are not consumer submodels and are not listed.

  • name — the Julia binding the submodel value is defined under (:_sb_bioav_emax), or nothing when the value has no module binding (an unnamed Base.merge configuration).

  • model — the submodel value from the plan's retained snapshot: a StanBlocks.SlicModel, or a StanBlocks.SubmodelFn for a named @slic f(args...) = body submodel function.

  • target — the left-hand side the submodel is called for (:log_F).

  • path — the enclosing plate results and submodel targets, outermost first. (path..., target) is the call's address for submodel=.

  • parent — the index in d.submodels of the enclosing submodel, or nothing when the model body calls it.

  • trigger — the formula statement that produced the call, rendered from the parsed declaration ("log_F ~ bioav_emax(op_log_dose)"), or nothing for a call that no top-level formula statement names (one inside a plate cell or another submodel).

  • declaration — the call site, target ~ <submodel>(...), as a GenerativeDeclaration.

  • inputs — the call site's keyword bindings, declaration.keywords. A named submodel function takes its inputs positionally, in declaration.arguments.

  • declarations — the submodel's own ~ statements, with targets and contexts relative to the submodel body.

  • outputs — the BRMOutputs the call owns: its parameters and its deterministic internals. Outputs of a nested submodel belong to that submodel's own entry. The call's returned value (target itself) is not included. Their emitted names are compiler-owned; resolve one value the body binds with brm_output(d, name; submodel=target) (or brm_output_coordinates with the same keyword), never by building a name.

  • source — the submodel body as Julia prints the value BRM lowers, one statement per line. It is derived from the model that runs, so it cannot drift from it; author comments and alignment are not kept. nothing for a named submodel function, whose body is selected by dispatch at trace time (its declarations are then empty too).

source is a display listing of one submodel. It is not a re-evaluable export of the emitted model.

source
BayesianRegressionModels.GenerativeDeclaration Type
julia
GenerativeDeclaration

One emitted sampling declaration in a GenerativePlan.

  • role is :prior or :observation. A :prior includes structured latent submodels such as popefs, ranef_correlated, and plate, not only scalar distribution calls.

  • target and family are the emitted SLIC binding and RHS head.

  • data_source is the original data key for an observation (including a plate-local alias such as kernel_y => dv), otherwise nothing.

  • draw is the canonical binding a generative executor should use for an observation, otherwise nothing. For top-level observations this matches StanBlocks' current posterior-predictive *_gen name. Nested plate observations are inventoried too, but consumers must discover their actual executable twins through stan_descriptor: the emitted names are based on data_source, not this plate-local target. A ragged base has a flat draw and a group-aggregate likelihood, both carrying the observed group boundaries.

  • context names enclosing plate results, outermost first.

  • expression is an exact snapshot of the emitted ~ expression.

The remaining fields decompose that RHS call so an executor never has to parse the snapshot itself:

  • arguments are the RHS call's positional arguments, in order (the rate of exponential(1), the eta of lkj_corr_cholesky(1.)).

  • keywords is a NamedTuple of every RHS keyword argument, verbatim.

  • annotation is the LHS type annotation (:(vector[3]) for kernel_z::vector[3] ~ ...), or nothing for a bare LHS.

  • dimension normalises the two ways a declaration can spell its size into one tuple: the m/n/o (or size) keyword that StanBlocks' autotype reads, and the LHS ::T[s...] annotation, which wins when both are present. () means the declaration spells no size of its own — it is a scalar, or its extent comes from the data or from a submodel's internals (popefs, ranef_correlated) rather than from this declaration.

  • constraints is the subset of keywords StanBlocks folds into the declared type: lower, upper, offset, multiplier. This is the field that makes a half-normal visible: std_normal(; n=3, lower=0.) and std_normal(; n=3) differ only here.

Entries of arguments, dimension, and constraints are the emitted expressions, not evaluated values: an entry may be a literal, or a Symbol that is a key of the plan's data, or a larger Expr. Resolve symbolic sizes against plan.data.

constraints reports only the constraints spelled on this declaration. Families carry their own implied support (exponential is positive, beta lives on [0, 1]) — that is a property of family, held in StanBlocks' autokwargs table or a ValueFamily's intrinsic support, and BRM deliberately does not duplicate it here.

The declaration is intentionally backend-level: it describes what BRM really emitted after formula terms introduced their latent blocks, rather than a second model-specific interpretation of the @brm source.

source
BayesianRegressionModels.GenerativePlan Type
julia
GenerativePlan

An introspectable, replayable snapshot of an SBBRMI's actual emitted declarations. model, data, and preproc are copied together at plan construction, while declarations inventories every emitted sampling site, including priors introduced inside kernel(...) plates and every observation in a multi-output model.

Construct with generative_plan. stan_code, stan_data, stan_model and stan_instantiate accept a plan and read its model, and reprocess preserves the existing SBBRMI replay contract (including its correct-or-loud unsupported cases). Plans constructed from a reusable @brm builder also retain that builder so generative_plan(plan, new_df) can rebuild the same declarations for genuinely new groups.

This is a declaration plan, not an RNG executor: it does not claim that a component-wise consumer draw is prior-predictive. Its purpose is to expose the one authoritative program and provenance an executor must consume.

source
BayesianRegressionModels.RanefBlock Type
julia
RanefBlock

One random-effect block BRM emitted, described well enough that a consumer can address its draws without reading the generated Stan.

  • binding — the emitted submodel binding (:b_p_subject for a (… |p| g) bucket, :r_<lhs>_<g> for a plain (… | g) term).

  • family — the emitting ranef_* submodel (:ranef_correlated_draws, …).

  • group — the grouping-factor dataframe column, or the tuple of membership columns for a typed mm(...) block. Selecting any member names that shared block.

  • id — the brms-style |ID| bucket symbol, or nothing for a plain ranef. A bucket is shared across sub-formulas, so it is addressed as ONE block.

  • by — the gr(g, by=b) stratifying column, or nothing.

  • levels — the level labels the block's group index was coded through, in index order: the training labels fitted by the emitter (sort(unique(raw)), or levels() for a CategoricalVector). A frozen reprocess target keeps the fitted labels even when its rows carry only some of them; a resample_groups factor has the labels of its new rows. levels[g] is the label of column g of the block.

  • n_terms / n_groups — the block's shape.

  • z — the emitted Stan parameter carrying the block's effect coordinates: the STANDARDISED draw under the default emission, the effects themselves under a centered one.

  • noncentered — see population_draws. Not always true, and not a formality: centered_groups = [:g] emits the *_centered families with noncentered = false. Both emissions are fully supported: population_draws zeroes either (a centered coordinate IS the effect, so 0 is its mean), and transport_draws copies retained levels by label under either while drawing fresh centered levels through the fitted covariance (b = C * z per draw) rather than bare N(0, 1).

  • generated — true iff the traced model emits this block's effect carrier in GENERATED QUANTITIES. This includes resample_groups re-draw targets and blocks with no downstream observed likelihood, even when other parts of the model remain sampled. Such a block is re-drawn Stan-side per draw, so it has NO coordinate in param_unc_names: it is DESCRIBED (shape, levels, group count read from group data and fitted preprocessing) but ranef_coordinates refuses it, while transport_draws and population_draws skip it — its L / tau hyperparameters are the transportable state, and they are copied by name when they remain sampled. The flag comes from the emitted carrier's descriptor kind, independently of the supplied coordinate names.

  • population — true iff the program evaluates this block at its population mean: a population_model artifact, whose block keeps the fitted family, coordinates and placement but whose every consumer reads zero effects.

Obtain with ranef_blocks; resolve to unconstrained coordinates with ranef_coordinates.

source
BayesianRegressionModels.TotalEffectBlock Type

Fitted design, prior and coordinate identities for one exact total-coefficient block.

Group g's total of random column c has mean sum_p A[c,p] * W[g,p] * beta[p] over the absorbed population coefficients beta (population_columns). W is 1 for a coefficient whose column matches a random column; a group-level predictor (group_columns: a column constant within each group, or a random slope column times a per-group value) carries its per-group value.

source
BayesianRegressionModels.brm_columns Function
julia
brm_columns(builder::BRMBuilder) -> Tuple{Vararg{Symbol}}

The data columns a model reads, sorted, without any data: predictors, grouping factors, @plate cell reads and the columns they capture, the columns a groups(...) binding reads, bound and weight columns, imputed covariates, the inputs of name = constant(expr) that are not Julia values in the builder's scope, and observed responses. A ~ statement whose name no other statement reads is an observed response; one that another statement reads is a parameter or predictor. So for a model that declares every parameter it reads (sigma ~ …), the result equals brm_columns(brm_descriptor(builder, df)), except that a column only a constant(...) reads is listed here but not in the descriptor's replay schema, because replay keeps the fitted constant. A name read but declared nowhere is listed as a column. A @plate cell's own names, its = locals and the latents it declares with ~ on a bare name (z ~ Normal(m[i], s), T::shares(total[i]) ~ …), are never columns.

source
julia
brm_columns(d::BRMDescriptor) -> Tuple{Vararg{Symbol}}

The dataframe columns this declaration reads — the schema a form should collect for a :replay / :reprocess. Equivalent to d.columns.

source
BayesianRegressionModels.brm_describe_component Function
julia
brm_describe_component(callable, context::BRMDescriptionContext)

Extend by dispatch on the actual callable or its type. Return a BRMDescriptionFragment, or nothing when no scientific description is known. Ordinary calls nested in assignments and kernel cells use this same hook. Per-request hooks=(callable => context -> fragment, ...) override dispatch. No model fitting, sampling or callable execution occurs during description.

source
BayesianRegressionModels.brm_description Function
julia
brm_description(d::BRMDescriptor; hooks=(), labels=Dict(), prior_anchors=Dict(), texts=description_texts())
brm_description(prepared::Union{SBBRMI,GenerativePlan}; ...)

Describe the selected prepared model without fitting or sampling. Per-call hooks are actual-callable => context -> fragment pairs. labels binds logical symbols and supplied meanings/units. prior_anchors maps logical prior tuple IDs to report links. texts selects the language BRM writes in, e.g. description_texts(:de); the description keeps it for its Markdown and hooks read it with brm_description_texts(context). Unsupported semantic nodes remain explicit coverage gaps; an incomplete result is never labeled a complete model description.

source
BayesianRegressionModels.brm_description_binding Function
julia
brm_description_binding(context, name::Symbol)

Resolve an authored component-local name without parsing generated carriers. Returns (name, role, value, prior_ids); aliases point at public arguments, parameters link to exact logical prior IDs. Missing/ambiguous names fail loudly.

source
BayesianRegressionModels.brm_description_components Function

Return the complete, ordered recursive semantic inventory.

source
BayesianRegressionModels.brm_description_markdown Function
julia
brm_description_markdown(description)

Render deterministic Markdown with display LaTeX, an effective prior table, notation entries and explicit coverage diagnostics. Each described part's sentences are followed by its own equations (description.sections). An incomplete description opens by naming how many parts have no description and their callables. Every prior row owns a model-scoped anchor; component references link to these targets by default. prior_anchors remain additional outbound links. Use prefix for repeated model instances. The page is written in the description's language (texts= of brm_description).

source
BayesianRegressionModels.brm_description_math Function
julia
brm_description_math(context, argument)

Render any public argument/reference/component as escaped LaTeX using the context's notation. Rendering an unknown call does not establish coverage.

source
BayesianRegressionModels.brm_description_prior Function

Resolve the exact logical prior ID returned by a component binding.

source
BayesianRegressionModels.brm_description_prior_references Function
julia
brm_description_prior_references(context)

Ordered logical prior IDs bound to this component, its quantities and descendants. Resolve them with brm_description_prior; link their default rendered targets with brm_description_prior_anchor. This does not parse generated parameter names.

source
BayesianRegressionModels.brm_description_record Function
julia
brm_description_record(context, argument)

Return the named public fields of a statically declared record argument. References resolve through authoritative local bindings; field values retain their parameter/data references and expression components. No code is executed. An unresolved, cyclic or non-record argument raises an ArgumentError.

source
BayesianRegressionModels.brm_description_symbol Function
julia
brm_description_symbol(context, name::Symbol)

Return the LaTeX notation bound to an actual logical name. Default identifiers are escaped. An explicit notation symbol is trusted caller-supplied LaTeX.

source
BayesianRegressionModels.brm_description_texts Function
julia
brm_description_texts(description_or_context)

The BRMDescriptionTexts a description was written with. A hook reads it from its context to write its own prose in the same language, e.g. by dispatching on brm_description_texts(context).locale.

source
BayesianRegressionModels.brm_descriptor Function
julia
brm_descriptor(sb::SBBRMI; name=nothing, operations=Dict(), titles=Dict(), highlights=())
brm_descriptor(plan::GenerativePlan; …)
brm_descriptor(builder::Function, df; mod=@__MODULE__, cv_groups=Set(), held_out=(), …)

Derive the one authoritative executable semantic descriptor for a @brm declaration. See BRMDescriptor for the fields.

The builder form is the one to prefer — it keeps the @brm builder, so the descriptor can also offer :replay (rebuild the declaration for genuinely new groups):

julia
builder = @brm begin
    sigma ~ Exponential(1)
    mu ~ 1 + x + (1 | subject)
    y ~ Normal(mu, sigma)
end
d = brm_descriptor(builder, df; mod=@__MODULE__, name=:my_model)

The derived operations

Each is offered exactly when the declaration supports it. Nothing is listed by hand, so an operation that appears can be executed.

operationoriginoffered when
:transpile:stanalways
:instantiate:stanalways
:fit:stanthe traced model has ≥1 parameter and ≥1 likelihood term
:predict:stanthe Stan program emits ≥1 posterior-predictive draw and ≥1 BRM observation resolves to it
:pointwise_loglik:stanthe Stan program emits ≥1 pointwise log-likelihood
:replay:brmthe descriptor was built from a @brm builder (rebuild on a new dataframe, e.g. new subjects)
:reprocess:brmthe declaration has no random-effect block, or every random-effect block has frozen same-group preprocessing (plain/`

:replay / :reprocess take the new dataframe positionally and return a NEW BRMDescriptor; their inputs are the dataframe columns in d.columns, not Stan data keys. :reprocess forwards both freeze_constants= and the checked new-population resample_groups= CV/GQ re-emission described by reprocess. Both forward held_out=: the default keeps the descriptor's hold-outs, and a value replaces them (held_out=() holds nothing out), as for reprocess and generative_plan.

The builder form's held_out keyword names one response or a collection of responses — a strict subset; holding out every observation is refused. A partial selection removes only those likelihoods; the remaining observations still offer :fit, and the parameters a held-out likelihood reads stay parameters (given a fit). To not condition on a response, omit its column instead. For prior draws there is no separate operation: keep the model identical, omit the response column from the data, and sample the :instantiate problem (fixed_param) — the program lowers to generated quantities automatically.

Extension points

These three keywords let a consumer extend presentation and operations rather than fork the descriptor:

  • operations — a name => … mapping applied AFTER derivation:

    • a callable (d; kwargs...) -> result adds a new operation (or replaces an existing one's run), recorded with origin = :override;

    • a full BRMOperation replaces the entry outright;

    • nothing suppresses a derived operation (hide a button the surface should not show).

  • titles — a name => String mapping relabelling any operation.

  • highlights — an ordered collection of included Stan definition names, name => caption pairs, or brm_highlight specs. Names resolve through StanBlocks' authoritative definition inventory and fail closed when absent, except an entry built with brm_highlight(...; optional=true), which is skipped when the program defines no function of that name. Order and captions are presentation metadata only and do not change d.id or the executable model.

Overriding a name the model does not offer is allowed (that is how you add one); suppressing a name that was never derived is a loud error, because it means the caller is holding a stale operation list — exactly the parallel registry this type exists to remove.

Failing closed

Five cases raise rather than degrade, because each is unrecoverable in a consumer that keys on names:

  1. A declaration target that is also a Stan data input. Every consumer keys on the name (form field, result target, BridgeStan lookup), so this cannot be auto-resolved. Rename the binding.

  2. Two declarations resolving to the same Stan output. Ambiguous provenance; the descriptor refuses to pick one.

  3. brm_operation(d, name) for an operation the model does not offer — errors and names the operations it does offer, so the discovery never moves into the consumer.

  4. Suppressing an operation that was not derived (see above).

  5. Selecting an absent required or a duplicate Stan definition highlight. BRM accepts only names that StanBlocks reports in the executable definition inventory. Only an entry marked optional=true through brm_highlight may be absent; it is then skipped.

One case deliberately does not raise, because it is a legitimate model: an observation whose predictive draw the Stan program does not emit is recorded in d.unpredictable and simply excluded from :predict's outputs. If that leaves no draws at all, :predict is not offered. The consumer never sees a predict button that would fail — which is the point.

source
julia
brm_descriptor(rk::RKBRMI; name=nothing) -> BRMRKDescriptor

The descriptor of the RK program rk runs: its content identity id, its inputs with their dataframe provenance, and the columns and formula of its declaration (see BRMRKDescriptor). It reads the backend's own program, so held_out, completions and car_units are the backend's, and it builds no Stan program: it also describes a model whose law exists only on RK, such as a whole-vector _rk_observation_source! family without an @lpxf twin. Requires the ReactiveKernels extension, as every RKBRMI does.

source
BayesianRegressionModels.brm_distribution_type Function
julia
brm_distribution_type(constructor)

Describe the distribution returned by a callable used in a BRM formula. Distribution types describe themselves. A factory function can extend this trait, for example brm_distribution_type(::typeof(my_prior)) = Normal, so BRM recognizes a sampled declaration and its scalar/vector shape without executing the factory before its sampled arguments exist. The original call, including its keywords, is retained. Return nothing for non-distribution callables. Stan emission additionally requires the factory's Stan translation.

source
BayesianRegressionModels.brm_documentation Function
julia
brm_documentation(model; path=nothing)

Read authored declaration docstrings from a builder, bound model or backend, without preparing a backend or running a scientific helper. Records retain raw Markdown, logical paths and source provenance. A tuple-LHS docstring belongs to each expanded declaration. path selects an exact logical path (a Symbol selects a top-level declaration). Later declarations in merge(::BRMI, ...) replace earlier documentation at the same operation, including an undocumented replacement. Builder merges retain the authored statements and their docs.

source
BayesianRegressionModels.brm_documentation_markdown Function
julia
brm_documentation_markdown(model)

Render authored declaration documentation as Markdown for HTML and PDF pipelines. The same records back source printing and semantic model views; the Markdown remains authored prose, not a claim of generated scientific description coverage.

source
BayesianRegressionModels.brm_highlight Function
julia
brm_highlight(name, caption=nothing; optional=false) -> BRMHighlightSpec

A highlights= entry for brm_descriptor. It mixes freely with bare names and name => caption pairs, which are required entries.

With optional=true the entry is skipped when the fitted program defines no Stan function named name, for example a likelihood helper that only a conditioned response emits. A required entry still raises on an absent name, so a misspelt required name never disappears silently. A name selected twice raises whether or not either entry is optional.

julia
d = brm_descriptor(sb; highlights=(
    :pk_recurrence => "PK recurrence cell",
    brm_highlight(:response_category_lpmfs, "Ordinal response model"; optional=true),
))
source
BayesianRegressionModels.brm_ladder_fit Function
julia
brm_ladder_fit(rk::RKBRMI; ad_backend, upto = 4, integrate = :auto,
    start = nothing, draws = 1000, conditional = 0, rng = Random.default_rng(),
    continue_from = nothing, subject_group = nothing, nested_groups = (;),
    shared_groups = (), saem_options = nothing, sampler = nothing,
    max_cell_width = 128) -> NamedTuple

A staged fit of rk over its sparse embedded Laplace (brm_laplace_problem with integrate, by default brm_laplace_plan's choice). It climbs the rungs up to upto (1 to 6); every rung is a complete result that starts the next:

  1. Effect modes at the population start (start, a vector over the problem's population coordinates; default the prior medians).

  2. The mode of the embedded-Laplace marginal (brm_laplace_mode; needs Optim, which using WarmupHMC loads). With integrate = :auto the plan is measured again at this point, and where a gated term switches the problem is rebuilt and the mode found again from the same point.

  3. SAEM from rung 2's point over the units the call names (subject_group, nested_groups, shared_groups, as for brm_nlme_model), integrating the families of the plan's admitted terms and sampling the rest (NLMEEstimation 0.2.4; Laplace-EM when every family is integrated; saem_options are its SAEMOptions, or a tuple or vector of options for successive phases). Each phase starts at the previous phase's packed point with fresh stochastic averaging. With :auto, its final point re-measures the plan for the next phase or rung. fit.ladder records its gap to rung 2: the difference of the Laplace target's values at the two points (rung 2 is its maximum; SAEM's MAP is taken in NLMEEstimation's covariance coordinates, so the gap holds that change of coordinates as well as the Laplace error) and the largest coordinate gap. Without named units, or without NLMEEstimation loaded, it is skipped and named.

  4. Effects given the point: draws Laplace draws through the factor (brm_laplace_draws, conditional proposals per draw for importance resampling).

  5. (5a) The population's curvature at the point, from central differences of the Laplace gradient: a dense matrix over the population coordinates only, labelled a diagnostic. Its standard errors are never the delivered posterior. Above 128 population coordinates this dense diagnostic is skipped with a reason. (5b) Sampling the Laplace marginal: sampler(problem, init, rng) draws the population coordinates from the sparse problem started at the point, and each draw's integrated effects are drawn through the factor. Its check's comparison reports the sampled mean and standard deviation, the mean shift in curvature standard errors, and the ratio of standard deviations, in problem.population order.

  6. Exact: sampler on the full model (rk_logdensity_problem), started from the last draw of the highest rung below.

sampler = (problem, init, rng) -> draws (dimension × draws) runs rungs 5b and 6, for example (p, init, rng) -> Matrix(adaptive_warmup_mcmc(rng, p; init).posterior_position) with WarmupHMC; without it they are skipped and named. At rung 5b the callback may instead return a completed brm_smc_fit(problem; rng, ...). Its weighted outer cloud is resampled to equally weighted columns before conditional completion; conditional applies here as at rung 4. The rung is named :population_sampling, with method=:smc or :callback. Use upto=5 for a Laplace-only callback: rung 6 still needs a sampler for the full-model target.

max_cell_width bounds local integrated footprints before derivative preparation, as in brm_laplace_plan. Automatic replanning preserves that bound; an explicit plan keeps its own. If no terms are admitted, the workflow uses the full sampled model's value and gradient.

solver and matrixfree select the conditional algebra as in brm_laplace_problem. Omitted values use an explicit plan's policy or the automatic defaults. Replanning and continuation retain that policy; continuation uses the existing target and does not change numerical options.

Returns (; draws, point, problem, plan, rungs, ladder):

  • draws: the packed draws of the highest sampling or point rung climbed (coordinates × draws); the curvature diagnostic keeps rung 4's draws;

  • point: the population point (rung 3's, else rung 2's);

  • problem, plan: the sparse problem and its plan;

  • rungs: each rung's result;

  • ladder: one check per rung, a rung skipped with its reason.

continue_from = fit continues an earlier fit of the same RK backend, preserving its automatic or explicit integration choice. A previously skipped rung runs when its units or sampler are supplied. Running SAEM on continuation rebuilds the later rungs from its new point.

source
BayesianRegressionModels.brm_length_scale_floor Function
julia
brm_length_scale_floor(d::BRMDescriptor, logical::Symbol; term::Symbol)

The fitted length-scale validity floor of one hsgp term: the value length_scale_floor stands for in that term's length_scale(...) prior and the lower bound of its default declaration. logical and term address the term exactly as in brm_term_coordinates (term=:hsgp_t for hsgp(t)), but no posterior draws are needed: the floor is fitted data.

Returns a Float64 for an isotropic term (the strictest axis's floor, which its one length scale is bounded by) and a Vector{Float64} with one floor per axis for iso=false. A k = 1 basis has no usable floor and returns 0.0. Grouped (by=), periodic, model-derived-axis and hyper-predicted terms are covered. A descriptor of reprocess(...; freeze_constants=false) returns the re-derived floor. The value is the same whether or not the term's prior names length_scale_floor:

julia
d = brm_descriptor(builder, df; mod=@__MODULE__)
floor = brm_length_scale_floor(d, :mu; term=:hsgp_t)
"allowed length-scale interval [$(round(floor; sigdigits=3)), 24.0]"

A term that is not an hsgp term, or an address that names no unique term, errors with the available labels.

source
BayesianRegressionModels.brm_model_view Function
julia
brm_model_view(model; title="Model", id=nothing)

An inspectable model declaration, with data/parameter roles and value ranks. Load HTMXObjects to enable this view. It returns an HTMXObjects semantic tree, usable as a route result or inside another page, with HTML, Markdown and plain-text projections. Authored declaration docstrings and their source provenance come from brm_documentation.

id names this view's elements: its tab set takes id and the Source tab's nested definition tabs take <id>-source, so ARIA references and #id links reach exactly this view. Pass a distinct id to each view when one page shows several. Without it, each tab set takes HTMXObjects' default id, which is derived from what its tabs show and, from HTMXObjects 0.1.118, from its tab bar's name, which carries title. Two views of one model under one title then share their ids; with an older HTMXObjects, views under different titles do too. An id must be a non-empty string without whitespace.

Pass a BRMI, a data-free BRMBuilder or BRMComponent, a prepared RKBRMI, or an existing BRMDescriptor. Reachable component source comes from brm_components, retaining separate call paths and shared definitions. Each component call's own declarations are listed with their roles under the exact call path (left › b); declarations of a call inside a plate cell are marked as made once per iteration. The view does not bind data, prepare, fit or evaluate a model. Unknown dimensions stay explicit. A builder lists potential data inputs; bind it first to distinguish observed data from latent declarations. A descriptor adds its exact carrier dimensions and roles. Value rank (number of axes) is never inferred from the number of free coordinates. Component input tables distinguish required inputs and optional defaults, shown without evaluation. Joint observations label each authored response column as response data.

RK inspection requires ReactiveKernelsPPL 0.1.93 or later. A replay that shares an earlier build leaves current parameter dimensions unresolved: that build's layout still describes its original binding. The data table for an RKBRMI describes its retained source declaration, which a replay can also share.

source
BayesianRegressionModels.brm_operation Function
julia
brm_operation(d::BRMDescriptor, name::Symbol) -> BRMOperation

The named operation. Fails closed: an operation this model does not offer errors and names the ones it does, so the discovery never moves into the consumer.

source
BayesianRegressionModels.brm_output Function
julia
brm_output(d::BRMDescriptor, logical::Symbol; role=nothing, submodel=nothing)
    -> BRMOutput

Return the unique emitted output that physically carries the BRM quantity logical. This resolves BRM meaning to Stan representation without parsing an emitter-owned name. For example, the cell value qt_loc under pk_loc ~ kernel(...) resolves to an output named pk_loc_qt_loc while retaining logical == :qt_loc.

logical is normally a declaration target. It is also the name of any value a kernel(...) cell assigns — see the logical field on BRMOutput — which is how to address a fitted noise-free in-cell location, with no annotation on the term.

One logical target legitimately has several carriers, and role is how you pick one. An observation pk_conc ~ Normal(loc, sigma) emits a posterior-predictive twin and a pointwise-log-likelihood twin, both carrying logical === :pk_conc. Ask for the one you mean:

julia
brm_output(d, :pk_conc; role=:posterior_predictive)   # the *_gen carrier
brm_output(d, :pk_conc; role=:pointwise_loglik)       # the per-element loglik

The emitted names (pk_conc_gen, …) are StanBlocks' to choose and are NOT part of this contract; that is the whole point of asking by role. A mixture response's membership matrix is addressed the same way, brm_output(d, :y; role=:membership), although it is emitted as y_membership. Passing an emitted name as logical is an error that names the logical=/role= address of that carrier.

A consumer @slic submodel's own values are addressed through submodel=. A submodel called by effect ~ saturating(dose) whose body declares slope ~ normal(…) owns that parameter, but the same name may be declared by another submodel or by the model itself, so it carries no model-wide logical. Name the call instead — its target, its (path..., target) tuple, or an entry of d.submodels — and logical is then a name the submodel body binds (a ~ declaration or an = assignment):

julia
brm_output(d, :slope; submodel=:effect)
brm_output(d, :loc; submodel=(:effect, :inner))     # a call inside another submodel

An address matching no call or several calls, and a name the body does not bind, are errors that list what is available. A bare brm_output(d, :slope) that misses says which submodel= to pass.

Fails loudly when the target has no emitted carrier or still maps to several; the caller must never guess from descriptor order in either case. The several-carriers message lists each candidate WITH its role, so the fix is the role= to add rather than a name to hardcode.

source
BayesianRegressionModels.brm_output_coordinates Function
julia
brm_output_coordinates(d::BRMDescriptor, logical::Symbol, constrained_names;
                       role=nothing, submodel=nothing) -> Vector{Int}

Resolve a logical BRM output to its columns in BridgeStan's constrained param_names (or an equivalent posterior name vector). Resolution first uses brm_output to obtain the descriptor's emitted name, then matches only that exact name or its documented container coordinates (name.1, name.1.1, …). It never parses a compiler-owned plate suffix.

role disambiguates a target with several carriers, exactly as on brm_output — a posterior-predictive slice of an observation is

julia
brm_output_coordinates(d, :pk_conc, param_names; role=:posterior_predictive)

submodel= addresses a consumer @slic submodel's own value, exactly as on brm_output:

julia
brm_output_coordinates(d, :slope, param_names; submodel=:effect)

The returned integers index constrained_names in their existing order. For a ragged predictive carrier in element order, group g is coordinates[segments[g-1]+1 : segments[g]]. Under a name permutation, use brm_output_tree's observation coordinates to identify those element positions. An aggregate ragged likelihood has one coordinate per group; its segments describes the response elements, not likelihood columns. This axis-order preservation is deliberate, and is the one ordering contract that differs from the label-indexed resolvers (brm_population_effect_coordinates, brm_term_coordinates, brm_ranef_sd_coordinates), which return carrier element order under any axis permutation.

A missing carrier is an error, which catches descriptor/artifact drift instead of returning an empty posterior slice. The one exception is a carrier with no elements (a 0 in its BRMOutput dims, such as a one-level treatment factor's contrast vector): BridgeStan lists it under no name, so its coordinates are Int[].

source
julia
brm_output_coordinates(output::BRMOutput, constrained_names) -> Vector{Int}

Resolve an already-discovered emitted carrier to its columns in BridgeStan's constrained param_names (or an equivalent posterior name vector). Matching is exactly the logical resolver's: only output.name and its documented container coordinates (name.1, name.1.1, …) match; compiler-owned plate suffixes are never parsed.

This overload is for internal carriers that have no public logical target, such as the Cholesky factor inside a correlated random-effect block. A missing carrier remains an error rather than an empty posterior slice, except a carrier with no elements (a 0 in output.dims): a one-level treatment factor's contrast vector or a one-level ordinal outcome's thresholds resolve to Int[], so mapping every sampled output of a descriptor needs no special case.

source
BayesianRegressionModels.brm_outputs Function
julia
brm_outputs(d::BRMDescriptor; logical=nothing, role=nothing, kind=nothing,
            component=nothing, predictor=nothing, term=nothing,
            submodel=nothing) -> Vector{BRMOutput}

Every emitted output matching the given semantic filters, in descriptor order. Each filter accepts a Symbol or any collection of them, and an omitted filter does not constrain. This is the discovery query — it can legitimately return zero, one, or many; use brm_output when exactly one is required.

julia
brm_outputs(d; role=:posterior_predictive)          # every predictive carrier
brm_outputs(d; logical=:pk_conc)                    # every carrier of one target
brm_outputs(d; role=(:parameter, :random_effect))   # either role
brm_outputs(d; component=:correlation_cholesky)     # every random-effect block's `L`
brm_outputs(d; predictor=:mu)                       # everything that feeds `mu`
brm_outputs(d; predictor=:mu, term=:treatment)      # one categorical block of `mu`
brm_outputs(d; submodel=:effect)                    # every output one submodel call owns

component= selects parts of random-effect blocks — scales, correlation factors, standardized draws, effects — and of population, categorical and structured-term blocks — coefficients, contrasts, length scales, simplexes — by the component field of BRMOutput, which lists them.

predictor= selects the outputs whose predictors include it, so a block shared by several predictors is returned for each of them; term= selects by the term field (a categorical column or a term label).

submodel= scopes the query to one consumer @slic submodel call (see BRMSubmodel): the outputs that call owns, its outputs field. It takes the call's target, its (path..., target) tuple, or an entry of d.submodels, and an address that matches no call or several calls is an error. Within that scope logical names values the submodel body binds — its own ~ declarations and = assignments (logical=:slope for slope ~ normal(…) in the body called for effect).

Filtering here is on BRM meaning (logical / role / component / predictor / term / submodel) or Stan representation (kind) — never on the emitted NAME, which the compiler owns.

source
BayesianRegressionModels.brm_population_effect_coordinates Function
julia
brm_population_effect_coordinates(d::BRMDescriptor, logical::Symbol,
                                  constrained_names;
                                  coefficient=:Intercept)

Resolve one formula-level population coefficient or categorical contrast block to its exact constrained posterior coordinates without constructing or parsing an emitted pop_* / cat_* name. Returns a named tuple with:

  • logical / coefficient — the public formula address;

  • output — the owning coefficient or contrast BRMOutput;

  • coordinates — the matching indices in constrained_names;

  • link — the function applied on the formula LHS (identity, log, …);

  • inverse_link — the transform from the fitted linear-predictor scale back to the declared quantity (identity, exp, …);

  • recovered — true when the coefficient was absorbed by an exact total-coefficient or a sum-to-zero block and the coordinates address its recovered generated carrier rather than a sampled parameter (false otherwise; categorical contrast blocks are never absorbed, so the categorical result omits it).

A categorical predictor is addressed by the formula column, just like its effect(logical, column) prior. Its result additionally contains predictor, coding, the frozen reference_level and ordered nonreference_levels, plus contrasts, which pairs every non-reference level with its reference level and exact constrained coordinate. A cell-mean coded block (coding === :cellmeans, the first categorical term of a predictor without an intercept) has no reference: reference_level === nothing, nonreference_levels lists every level, contrasts is empty and cells pairs each level with its coordinate. For example, coefficient=:indication resolves the K-1 block in log(Vc) ~ 1 + indication; the block's emitted spelling stays private. A factor(g; ref=3) term remains addressable as coefficient=:g and reports the fitted reference and contrast order after recoding. A plain Vector{String} column has no contrast block of its own: its level columns sit in the predictor's population coefficient vector, so output is that carrier, but the result has the same shape and its levels are the column's strings.

For log(Vc) ~ 1 + weight, ask for logical=:Vc. The returned intercept is on the log scale, link === log, and inverse_link === exp; the emitted pop_log_Vc_beta_pop spelling remains private.

Resolution is fail-closed. Missing or duplicate logical predictors, missing or duplicate population carriers, unavailable/duplicate coefficient labels, and descriptor/artifact coordinate drift all error rather than selecting by descriptor order.

Axis-order free: constrained_names may list the carrier's elements in any order — each labelled element resolves by its emitted .i suffix, so a reversed or permuted axis returns the same elements a native-ordered axis does (a single-element carrier is trivially order-free). brm_output_coordinates is the deliberate exception: a whole-carrier slice preserves axis order.

Generated-aware: for an unconditioned program (the same model with the response column omitted from the data), the numeric coefficient and categorical contrast carriers move from parameters into generated quantities under the same constrained names, so pass constrained_names built with include_gq=true (BridgeStan.param_names(prob.model; include_tp=true, include_gq=true)) and this resolves the GQ carrier exactly as it resolves the sampled :parameter in an ordinary fit — including the coefficient labels, so an unconditioned descriptor keeps its addressable population coordinates. A sampled carrier is preferred when both exist.

Exact-total aware: when an exact total-coefficient block absorbed the requested coefficient, the conventional population carrier cannot address it — the coefficient was integrated out of the sampled model, not merely moved. The compiled model still exposes the recovered coefficient in generated quantities (TotalEffectBlock.population, indexed like population_columns), and this query resolves it there: the returned output is the recovered carrier, the coordinates index it, and recovered is true (a sampled conventional resolution carries recovered=false). The link pair is the predictor's either way. A recovered draw is one exact conditional sample per posterior draw, so it carries conditional RNG noise a sampled parameter does not; consumers that need sampled-frame quantities must refuse recovered=true loudly rather than mix the two frames silently.

Sum-to-zero aware: a sum-to-zero block (s2z_groups) integrates its block means μ into the population coefficients it matches, so the sampled theta = β + B μ is not the conventional coefficient β. Such a coefficient resolves to the recovered conventional coefficients theta - B μ in generated quantities, with recovered=true. It pairs with the recovered effects r + μ that brm_ranef_draws reports for the block: both use the same μ draw, so a row's X β + Z b equals the sampled X theta + Z r exactly, with no recovery noise, and inverse_link(population + effect) is a level's own value. Names without generated quantities are refused with the remedy (include_gq=true).

source
BayesianRegressionModels.brm_ranef_sd_coordinates Function
julia
brm_ranef_sd_coordinates(d::BRMDescriptor, logical::Symbol, constrained_names;
                         id::Symbol, coefficient=:Intercept)

Resolve one margin's FITTED between-group standard deviation (tau) in a shared correlated random-effect block to its exact constrained posterior coordinate, without constructing or parsing an emitter-owned <binding>_tau name. This is the random-effect-scale sibling of brm_population_effect_coordinates: that resolver gives the population LOCATION of a margin, this one gives its group SCALE, so a consumer can form a population-predictive quantity such as inverse_link(intercept_draw + sd_draw * z) with no name interpretation.

logical is the margin's PUBLIC linear-predictor name — the bare inner name for an LHS-link LP (:Vc for log(Vc) ~ …); id is the brms-style |ID| bucket symbol (:p for (1 | p | subject)); and coefficient is the margin's coefficient label (:Intercept for an intercept-only block, a slope column for a correlated slope). These are exactly the ordered addresses ranefcoefnames(brmi, id) reports, in the same order the emitted tau vector uses.

The returned named tuple carries logical, id, coefficient, the owning BRMOutput, coordinates (the one matching index into constrained_names), and the margin predictor's LHS link / inverse_link — the SAME link the population-effect resolver returns for that predictor, so the intercept and the scale live on one scale and compose directly:

julia
d  = brm_descriptor(builder, df; mod=@__MODULE__)
mu  = brm_population_effect_coordinates(d, :Vc, constrained_names;
                                        coefficient=:Intercept)
tau = brm_ranef_sd_coordinates(d, :Vc, constrained_names;
                               id=:p, coefficient=:Intercept)
loc   = constrained_draws[:, only(mu.coordinates)]
scale = constrained_draws[:, only(tau.coordinates)]
Vc_upper = tau.inverse_link.(loc .+ scale .* quantile(Normal(), 0.975))

Both the sampled-scale families (sd(:, id) ~ Exponential(...) and the default half-normal) and the derived-scale R2D2 families (sd(:, id) ~ r2d2(...), whose tau is a transformed parameter — so pass constrained_names / constrained_draws that INCLUDE transformed parameters) are covered; the resolver follows the block's emitted scale carrier either way, and centering does not change the carrier.

It fails closed — never selecting by descriptor order or parsing a compiler-owned name — when the |ID| bucket, margin, or scale carrier is absent, ambiguous, or has drifted from the supplied constrained names. A block whose scale is not a per-margin tau vector — a scalar (1 | g) intercept (scale exp(log_scale)) or a stratified gr(g, by=b) block (one tau per stratum) — is refused with a message naming the family, rather than returning a coordinate of a different quantity.

Axis-order free: constrained_names may list the tau elements in any order — the margin resolves by its emitted .i suffix, so a reversed or permuted axis returns the same coordinate a native-ordered axis does.

Generated-aware: for an unconditioned program (the same model with the response column omitted from the data) StanBlocks re-draws the shared-|ID| scale from brm_ranef_sd_rng into generated quantities under the same <binding>_tau name (the resolver already follows that name + :random_effect role, so no kind branch is needed). Pass constrained_names with include_gq=true (and, as for the R2D2 derived-scale family, include_tp=true) and it resolves the GQ tau carrier exactly as it resolves the sampled one in a fit.

Exact totals: an |ID| that an exact total-coefficient block absorbed (see total_effect_blocks; total_groups=:auto does this for independent margins) keeps this address. Its margin's SD is that block's total scale, the SD of each group's total around the population value A β, and the returned coordinate is that scale's element. A block emitted in generated quantities needs constrained_names that include them.

source
BayesianRegressionModels.brm_source Function
julia
brm_source(backend::Union{SBBRMI,RKBRMI}) -> BRMI

Return the BRMI backend was built from, exactly as passed to SBBRMI(brmi; ...), RKBRMI(brmi) or RKBRMI(brmi, plan, built): brm_source(SBBRMI(brmi)) === brmi for every model.

parent(backend) is the model the backend lowered: the source after BRM resolved its relative prior addresses (optional(...) priors and grouping-column sd/cor/ranef addresses). It is === to the source only when the model has none, so establish that a backend came from a given BRMI with brm_source, not parent. Two backends built from one BRMI have === parents.

A backend BRM derives from another keeps that backend's source whenever it keeps its parent (hold-out marks, population models, reprocess replays that reuse the fitted model). A replay BRM rebuilds from the model rebound to new data reports that rebound model, as its parent does.

source
BayesianRegressionModels.brm_term_coordinates Function
julia
brm_term_coordinates(d::BRMDescriptor, logical::Symbol, constrained_names;
                     term::Symbol, parameter::Symbol)

Resolve one formula term's internal sampled parameter to its exact constrained posterior coordinates. logical names the linear predictor and term is the public term label BRM derives from the formula term alone (for example :mo_op_diet or :hsgp_op_log_dose; hsgp(x, y) is :hsgp_x_y). A term repeated in several predictors — one mo(c) column, or hsgp(...) over the same axes — keeps that one label in each, and logical selects whose carriers resolve. The predictor-scoped logical names a repeat's outputs carry in brm_outputs(d) (:hsgp_alpha_i_x_y) depend on declaration order and are not term labels. Supported parameter roles are:

termparameter
mo(...):simplex
mo1(...):simplex, :value
ungrouped hsgp(...):length_scale, :sd, :basis_weights, :value
grouped hsgp(...; by=...):length_scale, :sd, :value
hsgp(...) with hyper-predictor(s):length_scale_intercept, :length_scale_ranef_sd, :length_scale_ranef_z, :sd_intercept, :sd_ranef_sd, :sd_ranef_z — only the planned pieces — and :value
dar(...):ar, :sd, :innovations, :value
rw(...):sd, :innovations, :value
cdar(...):ar, :sd, :innovations, :value
car(...; type=:bym2):sd, :mixing, :structured, :unstructured, :effects, :value
car(...; type=:icar):sd, :structured, :effects, :value

A car term's label is :car_<logical>_<area>. :effects is its per-area field (one coordinate per area of the fitted graph, in sorted label order, islands included) and, like :value, a transformed parameter; :structured is the standardized ICAR field over the areas with neighbours, grouped by connected component.

:value is the term's own collected contribution: the per-row vector this predictor's occurrence of the term adds to the linear predictor. It is a transformed parameter, so build constrained_names with include_tp=true. For a term repeated in several predictors it is the one selector that reaches each predictor's own value. mo(...) has no :value: its output is a design column that the magnitude coefficient in beta_pop scales, so its contribution combines brm_population_effect_coordinates(...; coefficient=:mo_<c>) with the :simplex role.

The returned named tuple contains logical, term, parameter, the owning BRMOutput, coordinates, and the formula LHS link / inverse_link. For example:

julia
brm_term_coordinates(d, :log_F, constrained_names;
                     term=:mo_op_diet, parameter=:simplex)
brm_term_coordinates(d, :log_F, constrained_names;
                     term=:hsgp_op_log_dose, parameter=:basis_weights)
brm_term_coordinates(d, :log_F, constrained_names;
                     term=:hsgp_op_log_dose, parameter=:value)

Resolution follows the formula term to its logical term output, then selects a parameter owned by that declaration. Consumers never construct or parse the compiler-owned carrier name. Missing or duplicate predictors/terms/owners, unsupported parameter roles, and descriptor/artifact coordinate drift all error rather than selecting by descriptor order.

coordinates are in carrier element order regardless of the order of constrained_names: each element resolves by its emitted .i suffix, so a reversed or permuted axis returns the same elements a native-ordered axis does.

On a term whose hyper is predicted (log(length_scale(...)) ~ ...), the :length_scale / :sd role itself names no sampled carrier and errors, redirecting to the hyper roles above; the per-group hyper values (rho_vec/sigma_vec) are deterministic transforms with no role.

Generated-aware: for an unconditioned program (the same model with the response column omitted from the data) StanBlocks re-draws every term carrier from its prior into generated quantities under the same constrained name, so pass constrained_names built with include_gq=true (BridgeStan.param_names(prob.model; include_tp=true, include_gq=true)) and this resolves the GQ carrier exactly as it resolves the sampled :parameter in an ordinary fit; a sampled carrier is preferred when both exist.

source
BayesianRegressionModels.brm_transform_constants Function
julia
brm_transform_constants(x) -> Tuple
brm_transform_constants(x, name::Symbol) -> NamedTuple

The fitted constants of every center, zscale and standardize term of a fitted model, or of the one named name. x is an SBBRMI, its GenerativePlan, a BRMDescriptor of either, or an RKBRMI.

Each record is

(; name, kind, column, source, center, scale, observed_only)
  • name — the transformed value's name, which is also its population coefficient label (:standardize_age_yr for standardize(age_yr)). An expression inner has a hashed name (:zscale_expr_301a4a5c for zscale(log(w))); list the records to find it by source. A per-group field read at row positions, standardize(age_yr)[subject], is :standardize_age_yr_subject; its constants are fitted over age_yr and each row's value is (age_yr[subject] - center) / scale.

  • kind — :center, :zscale or :standardize.

  • column — the single name the transform reads (:age_yr), or nothing for an expression inner.

  • source — the inner as written: a Symbol (:age_yr) or an Expr (:(log(w))).

  • center, scale — the fitted constants: the transformed value is (x .- center) ./ scale, exactly as the model applies it. center has scale == 1.0; zscale/standardize use the sample SD (n - 1).

  • observed_only — true when the inner reads an mi(...) covariate: the constants are fitted on its observed entries only and the transform is applied inside the model. The record keeps the coefficient's name either way.

The constants are the ones the backend applies, so they follow replay: reprocess(sb, new_df) (frozen, the default) reports the training constants, and reprocess(sb, new_df; freeze_constants=false) the refitted ones. They are never recomputed here. Numerically, zscale/standardize use a streaming mean and scaled sums of squares, so a hand mean/std agrees only to floating-point roundoff. The SB center mean is sum(x) / length(x), the RK graph's the streaming mean, so the two backends' center agree to roundoff.

A name that is not a fitted center/zscale/standardize term errors, listing the fitted names. On an RKBRMI, a transform used only as an & interaction operand is staged under an internal name and is not listed.

source
BayesianRegressionModels.brm_two_stage_fit Function
julia
brm_two_stage_fit(sampler, x; minibatch_size=nothing, options=nothing,
    threads=Threads.nthreads(), stage1=nothing, kwargs...) -> NamedTuple

A two-stage approximate posterior for a model with conditionally independent units (the subjects of brm_nlme_view):

  1. Population: SAEM (brm_nlme_fit with NLMEEstimation.saem) estimates θ, σ and Ω. With minibatch_size = b, each iteration's E-step samples a random batch of b units (NLMEEstimation.SAEMOptions(minibatch_size=b)); options passes a whole SAEMOptions instead. Other keywords go to brm_nlme_fit (start, inits, progress, rng, …); pass rng for a reproducible stage 1, since SAEM otherwise draws from the global RNG. stage1 reuses an earlier brm_nlme_fit(x, saem; …) result of the same x instead (its model is the one sampled), for example to resample the units with another sampler.

  2. Units: every unit's conditional posterior at those estimates, brm_nlme_unit_problem, is sampled by sampler(problem). It returns a dimension × draws matrix in the problem's coordinates (WarmupHMC's posterior_position orientation), and every unit returns the same number of draws. Units are sampled on threads tasks. Each model call takes its own prepared evaluator of the model's cells (see brm_nlme_model, "Calls from several tasks"), so sampler must be safe to call concurrently (an independent RNG per unit, as below). A nested model without subject cells samples on one thread: its units evaluate through the whole-model sampler.

Each unit's posterior is exact given the population estimates; the population uncertainty is not propagated (empirical Bayes). That is negligible with many units and is not negligible with few.

Returns (; draws, coordinates, units, unit_draws, stage1): RK packed draws as brm_nlme_draws assembles them, their coordinate names, the unit problems, each unit's draws, and the stage-1 brm_nlme_fit result. Implemented by the NLMEEstimation extension.

julia
using NLMEEstimation, WarmupHMC, Random
fit = brm_two_stage_fit(RKBRMI(model); minibatch_size=64) do unit
    run = adaptive_warmup_mcmc(Xoshiro(unit.subject), unit)
    Matrix(run.posterior_position)
end
source
BayesianRegressionModels.column_data Function
julia
column_data(brmi::BRMI, name::Symbol)

Underlying data vector for a NamedColumn-over-DataColumn entry, or the value of a data-only assignment (kreis_b = kreis[gem_b], evaluated as the backends evaluate it). nothing if name is neither.

source
BayesianRegressionModels.compiles Function
julia
compiles(sb::SBBRMI; re=true) -> Bool

Return true if sb successfully transpiles and compiles via BridgeStan (i.e. stan_instantiate succeeds), false otherwise. Strictly stronger than transpiles: a model that transpiles can still fail to compile if stanc rejects the generated Stan or the C++ build fails. Call-site independent for the same lowering-time registration reason as transpiles above. Set re=false to swallow the error and just return false; the default re=true rethrows.

source
BayesianRegressionModels.data_args Function

All :data args from an outcome (e.g. Binomial trials column).

source
BayesianRegressionModels.data_columns Function
julia
data_columns(brmi::BRMI) -> Vector{Symbol}

Every name in brmi.operations that is a NamedColumn over a DataColumn (i.e. every actual data column referenced by the formula).

source
BayesianRegressionModels.dependencies Function
julia
dependencies(brmi::BRMI, name::Symbol) -> NamedTuple
dependencies(brmi::BRMI, entry) -> NamedTuple

Recursively walk the ~ body of name, collecting every data column

  • intermediate LP it transitively references: (; data::Vector{Symbol}, intermediates::Vector{Symbol})

For y1 ~ Normal(loc, err) with loc ~ 1 + a + (1|g1) and log(err) ~ 1 + b, dependencies(brmi, :y1) returns (; data=[:a, :g1, :b], intermediates=[:loc, :err]). RE grouping factors count as data deps. An entry of linear_predictors(brmi) reads as its name.

source
BayesianRegressionModels.description_texts Function
julia
description_texts(locale::Symbol=:en; texts...) -> BRMDescriptionTexts

The BRMDescriptionTexts for locale (:en or :de), with any of its texts replaced by keyword:

julia
const DE = description_texts(:de; effective_priors="A-priori-Verteilungen:")
description = brm_description(d; labels, texts=DE)
brm_description_markdown(description)   # German throughout

An unknown locale or text name throws an ArgumentError, and so does a text that drops a placeholder the English text has or adds one it lacks.

source
BayesianRegressionModels.effect_priors Function
julia
effect_priors(brmi::BRMI) -> Vector{NamedTuple}

Return the population-coefficient prior statements captured by @brm, in formula order. Each entry has

julia
(; predictor, coefficient, family, arguments, keywords, expression, elementwise)

Both slots are always present: predictor and coefficient are each either a Symbol or Symbol(":"), the wildcard meaning every value of this slot. coefficient uses the same labels as popcoefnames, including :Intercept — or a whole-interaction a&b key for an effect(lp, a & b) statement, which the backends fan out over every column the term emits. expression is the exact parsed RHS ExprColumn; family, arguments, and keywords are its decomposed, directly inspectable parts. elementwise is true for effect(lp, block) .~ Family.(args...), which gives each coefficient of the block Family(args...) with its array-valued arguments read at the coefficient's position; family, arguments, and keywords then decompose that element law.

A Symbol(":") slot is the default layer: the SBBRMI backend applies such a statement to every parameter it reaches, and lets a more specific statement — one with fewer wildcard slots — override it. Two statements of equal specificity reaching one parameter have no winner and error, as do addresses matching no parameter at all.

source
BayesianRegressionModels.generative_plan Function
julia
generative_plan(sb::SBBRMI) -> GenerativePlan
generative_plan(builder::Function, df; mod=@__MODULE__, cv_groups=Set(), centered_groups=Set(), held_out=()) -> GenerativePlan
generative_plan(plan::GenerativePlan, new_df; cv_groups=plan.cv_groups, centered_groups=nothing, held_out=<plan's hold-outs>) -> GenerativePlan

Snapshot the declarations BRM actually emitted. The inventory is derived from sb.model.model, so auto-introduced population coefficients, random-effect blocks, named linear predictors consumed by kernel(...), observation families, and multiple outputs cannot drift from the fitted model.

Use the reusable-builder form when future schedules may contain new groups:

julia
builder = @brm begin
    sigma ~ Exponential(1)
    mu ~ 1 + x + (1 | subject)
    y ~ Normal(mu, sigma)
end
plan = generative_plan(builder, schedule; mod=@__MODULE__)
new_population_plan = generative_plan(plan, new_schedule)

The SBBRMI form has no reusable formula builder to apply to genuinely new groups; use reprocess on that plan for the existing frozen-constant replay semantics instead.

centered_groups selects the centered parameterization per grouping factor, exactly as in SBBRMI. The builder form defaults to empty; the plan form defaults to nothing, which infers the source plan's own centered groups — read off its emitted declarations, so a centered fit rebuilds centered unless explicitly overridden. A group named in both cv_groups and centered_groups is refused by the SBBRMI constructor, as at fit time.

held_out takes the SBBRMI form. The plan form defaults to the source plan's hold-outs; a value replaces them, and held_out=() holds nothing out.

source
BayesianRegressionModels.grouping_factors Function
julia
grouping_factors(brmi::BRMI, lhs::Symbol) -> Vector{Symbol}
grouping_factors(brmi::BRMI, entry) -> Vector{Symbol}

The grouping-factor symbols in <lhs> ~ ...: the last arg of every (... | g) term plus the by= group of every hsgp(x, by=g) term. Empty if no grouping term or the LP isn't introspectable. An entry of linear_predictors(brmi) reads as its name.

source
BayesianRegressionModels.hierarchical_outcomes Function
julia
hierarchical_outcomes(brmi::BRMI)

outcomes(brmi) filtered to those whose linear predictor has any RE term.

source
BayesianRegressionModels.outcomes Function
julia
outcomes(brmi::BRMI) -> Vector{NamedTuple}

Return one entry per <response> ~ Family(args...) likelihood (i.e. every ~ op whose LHS is a NamedColumn over a DataColumn):

(; response::Symbol, family, args::Vector{NamedTuple})

args is the family-arg list, classified per arg into one of:

  • (; role=:data, name) – e.g. Binomial's trials column.

  • (; role=:linear_predictor, link_fn, link_lp) – a latent LP referenced bare (link_fn=identity) or via a unary wrap like exp(eta) / logistic(odds). Distributional models with multiple LPs (e.g. Normal(loc, err) where both loc ~ ... and log(err) ~ ...) produce one entry per LP.

  • (; role=:joint_means, names) – the ordered row-aligned predictors of an MvNormalCholesky joint response.

  • (; role=:covariance_factor, name) – that joint response's declared LKJCovarianceFactor.

  • (; role=:constant, value) – numeric literal.

  • (; role=:expression, expr) – catch-all opaque ExprColumn.

source
BayesianRegressionModels.popcoefnames Function
julia
popcoefnames(brmi::BRMI, lhs::Symbol) -> Union{Vector{Symbol}, Nothing}
popcoefnames(brmi::BRMI, entry) -> Union{Vector{Symbol}, Nothing}

Ordered labels of the population-level beta_pop coefficient columns for linear predictor lhs, as emitted by the sbimpl backend (SBBRMI). The k-th returned symbol labels the parameter column pop_<lhs>_beta_pop.k 1:1, so a consumer can turn raw pop_<lhs>_beta_pop.N posterior columns into human-readable names without re-parsing the formula.

Only terms that sbimpl folds into the popefs design matrix appear, in formula (left-to-right) order:

  • the intercept 1 is INCLUDED (labelled :Intercept), at its formula position — conventionally first, 1 + …; there is NO separate pop_<lhs>_Intercept parameter;

  • plain continuous (Real, non-integer) predictors — one column each, labelled by the column name;

  • single-beta wrapped terms (mo, me, protect, log(x), x^2, …) — one column each, labelled by the emitted design key;

  • an interaction a & b — one label per expanded treatment-contrast column: int_a_x_b for continuous × continuous; int_c_x_g_lvl_k for continuous c × categorical g (levels 2..K — the continuous operand first, whatever the surface order); int_g_lvl_j_x_h_lvl_k for categorical × categorical.

EXCLUDED — emitted as their OWN parameters, NOT beta_pop, so they never appear in pop_<lhs>_beta_pop:

  • integer- or CategoricalVector-typed bare predictors → cat_<lhs>_<name> (K−1 treatment contrasts; K cell means for the first categorical term of a predictor without an intercept);

  • offset(x) → x itself, with fixed coefficient one;

  • mo1(c) → mo1_<c>; s(x) and t2(x,z) → their own fixed/range coefficients and smoothing scales;

  • explicit-coefficient coef * a (own scalar);

  • random-effects blocks (… | g) → per-group ranef parameters.

Needs a data-bound BRMI (any fitted model has one): the population-vs- categorical split reads each predictor's element type. Returns Symbol[] when lhs has no population columns (e.g. loc ~ (1 | g)), and nothing when lhs names no population formula of brmi: an unknown name, or a binding sbimpl emits as its own declaration rather than a beta_pop design — a declared parameter (lhs ~ Normal(0, 1)), an assignment (lhs = …), an observation, or a kernel(...) submodel binding. linear_predictors lists declared parameters and kernel(...) bindings too, and an entry of it reads as its name, so a scan passes each entry as it comes and needs no filtering: Dict(lp.name => popcoefnames(brmi, lp) for lp in linear_predictors(brmi)).

These are the labels the effect(lhs, label) ~ Normal(...) prior address resolves against — with ONE addition that is deliberately not listed here, because it is not a beta_pop column: a categorical / integer-coded predictor (bare, or wrapped in factor(...)) is addressable by its COLUMN name, which sets one shared Normal prior over its K-1 treatment contrasts (cat_<lhs>_<c>_beta). A predictor without an intercept codes its first categorical term by K cell means instead; the column name then covers all K, and each is also addressable on its own as <c>_lvl_<k> (k = the level's position in the fitted level order). Everything else in the EXCLUDED list above still owns parameters no effect(...) address reaches.

An interaction term is also addressable WHOLE, the way the formula spells it: effect(lhs, a & b) sets one shared Normal prior over every beta_pop column the term emits, in either operand order; a direct int_… label address refines it on that column alone.

source
BayesianRegressionModels.primary_lp Function

The first :linear_predictor arg from an outcome, or nothing.

source
BayesianRegressionModels.priors_of Function
julia
priors_of(brmi::BRMI) -> BRMI

Return the PRIOR fragment of a parsed model: a BRMI holding only its prior-address statements — the effect(...) / sd(...) / cor(...) / simplex(...) / latent(...) / length_scale(...) / r2d2(...) block — in formula order. This is the "set the priors to the only thing" view: printing the result shows just the prior specification, which is often longer than the structural model and distracting inside the full listing.

It is the inverse partition to structure_of; together they split a BRMI so that Base.merge(structure_of(brmi), priors_of(brmi)) recomposes an equivalent model. Scalar parameter declarations such as sigma ~ Exponential(1) are NOT priors here — they declare a parameter and stay in structure_of (brms prints them with the model too).

A BRMI prints as its source statements, so string(structure_of(brmi)) and string(priors_of(brmi)) are the model's structure and prior cards.

julia
julia> using BayesianRegressionModels

julia> brmi = @brm (; x=[1.0, 2.0], y=[0.1, 0.2]) begin
           mu ~ 1 + x
           y ~ Normal(mu, 0.5)
           effect(mu, Intercept) ~ Normal(0, 1)
       end;

julia> priors_of(brmi)
effect(mu, Intercept) ~ Normal(0, 1)
source
julia
priors_of(builder::BRMBuilder) -> BRMBuilder
structure_of(builder::BRMBuilder) -> BRMBuilder

The same split for a model that has no data yet: the builder of the source's prior-address statements, and the builder of the rest, each in formula order. A builder prints as its source, so string(structure_of(builder)) and string(priors_of(builder)) are the structure and prior cards of builder(df), without building it. An optional(...) prior stays in priors_of as written, since only data decide whether its address exists.

Each part is a builder exactly as if its statements were written as their own @brm block, so merge(structure_of(builder), priors_of(builder)) builds an equivalent model. As for merge of builders, each part is brm(source; mod) of its statements: names resolve in the builder's module.

julia
julia> using BayesianRegressionModels

julia> builder = @brm begin
           mu ~ 1 + x
           effect(mu, Intercept) ~ Normal(0, 1)
           y ~ Normal(mu, 0.5)
       end;

julia> structure_of(builder)
mu ~ 1 + x
y ~ Normal(mu, 0.5)

julia> priors_of(builder)
effect(mu, Intercept) ~ Normal(0, 1)
source
BayesianRegressionModels.r2d2_priors Function
julia
r2d2_priors(brmi::BRMI) -> Vector{NamedTuple}

Return the whole-predictor variance-decomposition statements captured by @brm — the effect(lp, :) ~ r2d2(...) / effect(:, :) ~ r2d2(...) family — in formula order. Each entry has

julia
(; predictor, family, arguments, keywords, expression)

predictor is a Symbol for the explicit effect(lp, :) form and nothing for the wildcard effect(:, :) form, which the SBBRMI backend resolves only when the model has exactly one population predictor — a decomposition is per-predictor, so there is nothing to share. family is the marker function (r2d2); keywords carries the decomposition's R2 / tau_bsv / alpha settings.

These statements are deliberately separate from effect_priors: a Colon address configures a joint prior over every population column of its predictor plus that predictor's random-effect margins, rather than overriding one labelled coefficient.

source
BayesianRegressionModels.ranef_blocks Function
julia
ranef_blocks(model) -> Vector{RanefBlock}

Every random-effect block model emitted, in declaration order. model is an SBBRMI, a GenerativePlan or a BRMDescriptor.

Each block's carrier placement (generated) is read from the traced program. A descriptor already holds that trace, so ranef_blocks(d) is a lookup; an SBBRMI or GenerativePlan traces its program again on every call. Use the descriptor when resolving blocks repeatedly.

This is the authoritative answer to "which parameters carry grouping factor g's effects, and is the emission non-centered?" — read off the emitted declarations, not off the @brm source and not off the generated Stan text.

Coverage and the loud edges

Recognised families are the ranef_* submodels in sbimpl.jl. A declaration whose family name begins with ranef_ but is absent from the emission table raises: that is a new parameterization no consumer of this API can be assumed to handle, and the whole point of routing through here is that such a change cannot pass silently.

Structured-latent blocks whose prior is :iid_normal or an element-wise non-normal (_sb_emit_block_draw!) emit an ordinary std_normal / dist declaration rather than a ranef_* submodel, and are deliberately NOT reported — there is nothing in the emission that distinguishes them from any other vector prior. hsgp(x, by=g) and any other structured field whose prior is :correlated_normal goes through ranef_correlated_draws and IS reported, with id === nothing.

Example

julia
sb = SBBRMI(builder(df); mod=@__MODULE__)
for b in ranef_blocks(sb)
    println(b.group, " → ", b.z, "  ", b.n_terms, "×", b.n_groups)
end
source
BayesianRegressionModels.ranef_coordinates Function
julia
ranef_coordinates(block::RanefBlock, unc_names) -> Matrix{Int}

Resolve block to positions in the unconstrained parameter vector, returned as an n_terms × n_groups matrix of 1-based indices into unc_names.

unc_names is the compiled model's unconstrained parameter names — BridgeStan's param_unc_names(model), in its order. Each coordinate is located by its Stan NAME. Any coordinate the block expects and unc_names does not carry is an error listing the missing names, because that is exactly the shape a silent misalignment takes (a template that dropped a covariate level, or a model rebuilt with a different parameterization).

One carrier breaks pure name lookup: for an array[n_groups] vector[n_terms] Stan parameter (:group_term), Stan's unconstrained_param_names lists names array-index-fastest (.1.1, .2.1, …) while the unconstrained vector itself reads array-element-major ([s][t] at (s-1)*n_terms + t) — a stanc3 asymmetry, measured against param_constrain, not against the name list. There the names locate only the block's contiguous SEGMENT (its start is their minimum resolved position, and a non-contiguous name set is a loud error); position (t, g) within it is start + (g-1)*n_terms + (t-1). This holds under either name order, so a Stan that one day lists these names in layout order needs no change here.

ranef_coordinates(blocks, unc_names) -> Vector{Matrix{Int}}

maps over several blocks.

source
BayesianRegressionModels.ranef_effect_priors Function
julia
ranef_effect_priors(brmi::BRMI) -> Vector{NamedTuple}

Return random-effect covariance-prior statements captured by @brm, in formula order. Each entry has

julia
(; class, id, predictor, coefficient, family, arguments, keywords, expression)

class is :sd, :cor, or :ranef (the block's standardized law, such as ranef(:, ID) ~ TDist(nu)). id is the address target: an |ID|, or the grouping column of random-effect blocks written without one (see @brm). predictor === nothing means the statement is not predictor-specific — sd(:, ID), and cor(:, ID), since a shared |ID| covariance block spans every predictor that slices it; cor(lp, g) names the correlated block of one predictor grouped by an ID-less column g. coefficient === nothing means the whole block rather than one margin. sd(lp, ID, coef) carries both symbols. Use ranefcoefnames for the authoritative ordered margin addresses of a shared |ID| block.

source
BayesianRegressionModels.ranefcoefnames Function
julia
ranefcoefnames(brmi::BRMI, id::Symbol) -> Union{Vector{NamedTuple},Nothing}

Ordered (predictor, coefficient) addresses of the marginal SDs in the shared random-effect block selected by public |ID| symbol id. The k-th entry labels the k-th tau element emitted by the SBBRMI backend. Categorical random slopes use the exact dummy-column symbols emitted into the random-effect design matrix: <c>_dummy_2 … <c>_dummy_K under a random intercept, and <c>_dummy_1 … <c>_dummy_K for the first categorical term of an intercept-free block such as (0 + c | ID | g) (every level owns a group-level effect; opt out with factor(c; cmc=false)). Interaction slopes (a & b) use the exact emitted int_… design-column symbols shared with the population path: int_a_x_b for continuous × continuous, int_c_x_g_lvl_k for continuous × categorical, int_g_lvl_j_x_h_lvl_k for categorical × categorical.

Returns nothing when id is absent. Reusing one ID with multiple grouping factors is ambiguous on the public ID-only surface and raises.

source
BayesianRegressionModels.reprocess Function
julia
reprocess(rk::RKBRMI, new_data; freeze_constants=true, resample_groups=(),
          held_out=<the fit's hold-outs>) -> RKBRMI

Bind new_data to the fitted RK model rk with the TRAINING fit's preprocessing, reusing its executable graph (rk.model; no rebuild) and its translated program: a replay only binds its own data. The returned backend evaluates the same draws on the new rows: densities through rk_logdensity_problem, authored values through ReactiveKernels.prepare(rk2.model.spec; have, want, bound=rk_bound_data(rk2)), and RKPPL's queries over a binding, posterior-predictive draws included, through rk_bound_plan.

  • freeze_constants=true (default; prediction and replay): center / zscale / standardize anchors, completed-covariate anchors, factor, mo and group level sets, spline fits, HSGP intervals and length-scale floors, R2D2 variances and name = constant(expr) values are the training fit's. A one-row design is fine. An unseen factor, mo or group level is an error.

  • freeze_constants=false: fresh-fit semantics, equivalent to rebuilding on new_data (RKBRMI of the rebound model); its coordinates need not match rk's.

  • resample_groups=[:g]: group g takes its levels from new_data (new subjects); everything else stays frozen. The replay is a model of its own rows: its coordinates hold the new levels' standardized draws in place of the fit's, so a draw of the fit does not apply to its density or queries. To evaluate a draw of the fit with the new levels' effects in have (have=(:unconstrained, :b_p_g, ports...)), bind the design with rk_design_binder(rk; resample_groups), whose inputs keep the fit's level set.

  • held_out: the response hold-outs of the replay, as in RKBRMI.

  • resample_covariates=[:x], keep_observed=true: forecast new rows of a fit with an mi(x) covariate. The design's observed x values are used as given; its missing entries are coordinates of the replay, in place of the fit's training gaps, and every other coordinate is the fit's. transport_draws(rk, replay, draws; resample_covariates=[:x]) maps the fit's posterior draws onto the replay, drawing the design's missing entries from their law. It needs a non-centered Normal or LogNormal completion without group totals (RKBRMI(model; completions=[:x])), whose missing entries are standard normal draws of that law. Its coordinates are its own, so the replay builds its own kernel (one compilation) rather than sharing rk.model. keep_observed=false (drawing every row of x) is SBBRMI's population prediction and is refused here.

new_data supplies every data column the model reads. With freeze_constants=true it may omit numeric scalar inputs (their fitted values are kept) and responses: responses are bound without values, so authored values (want=(:mu,), @plate cell outputs) evaluate on the new rows, while the density and other queries that read an omitted response are refused, naming it. Bounded likelihoods (censored, truncated, interval_censored) plan without their response; their bound columns stay required. A model whose planning reads the response values (for example an mi(y) response, or an Ordinal, CategoricalLogit or Categorical response, whose levels the graph codes) needs them.

A supplied numeric scalar a prior reads must equal the fitted value, or the replay is refused: a design cannot change a fitted prior. That covers every sampled parameter's law, a @plate cell latent's included, and a scalar it reads through an assignment. A scalar only a @plate cell's values or observations read (a dose, a known observation scale) is a design input, and takes the design's value.

source
julia
reprocess(sb::SBBRMI, new_df; freeze_constants=true,
          resample_groups=(), resample_covariates=(),
          held_out=<the fit's hold-outs>) -> SBBRMI

Re-materialise the SBBRMI's Stan data dict against new_df, re-running the Julia-side preprocessing (decision nr3v8n A) — so the silent-stale-constant bug of a naive per-column sb.model(; col=…) rebind is avoided. Returns a NEW SBBRMI that REUSES the already-transpiled Stan model (byte-identical stan_code when shapes are stable) with the new data dict.

  • freeze_constants=true (default — prediction / replay): apply the training constant to new_df (z-score with training mean/sd, map factor codes via the training level set, rebuild the spline/HSGP basis on the training eigenbasis/(mean, L)). This is the operation the downstream PKPD app hand-rolls outside BRM.

  • freeze_constants=false (fresh-fit semantics): re-derive each constant from new_df, then apply.

  • resample_groups=() (default): retain the fitted random-effect coordinates. Naming one or more ordinary grouping factors (for example [:subject]) re-emits the model with cv-contagious sizing for them (the fitted model; with freeze_constants=false, the formula rebuilt on new_df), derives those groups' levels from new_df, and marks their indices so their standardized effects are re-drawn in generated quantities from the fitted covariance. Predictor constants remain frozen unless freeze_constants=false is also requested. This changes Stan source by construction; it is the new-population/CV twin of the default same-group replay. Naming the by column of a cdar(step; by=g, cor=C) term redraws every level of g that new_df names, a level the fit did not see included: its whole path over the step grid (and any appended forecast steps) is drawn in generated quantities from the fitted sigma, rho, given the fitted levels new_df does not name, which keep their fitted paths (with C = I the levels are independent). The fitted coordinates stay the fit's. A level the fit did not see needs C over the sorted union of the fitted and new_df's levels in new_df (its fitted block equal to the fit's); this needs the default freeze_constants=true.

  • resample_covariates=() (default): retain fitted covariate completions. Select logical modeled continuous members to redraw all their rows inside the emitted program, conditional on retained posterior hyperparameters. Selecting a joint member selects its whole block. Dependent modeled declarations must be selected together. This opt-in path requires frozen training anchors and a conventional non-centered total_groups=() fit; it composes with resample_groups and removes selected missing-cell coordinates. Discover members and consumed output roles with modeled_covariates, then use transport_draws with the actual compiled coordinate names.

  • held_out (default: what sb holds out): the response hold-outs of the replay, in the SBBRMI held_out form. A value replaces sb's hold-outs, and held_out=() holds nothing out. Every parameter keeps its role and coordinates, so the fit's draws replay as before. It composes with resample_groups and resample_covariates.

  • A response the fit observed but new_df lacks is predicted given the fit (a forecast): it is held out without values (StanBlocks' maybecv(:y)), so every parameter stays a parameter, its draw y_gen keeps the fit program's name and is shaped by the other arguments (segments for a ragged response), and the program has no y input and no y_likelihood. Its descriptor offers :predict, and :fit only while another response stays bound. This covers top-level, plate-cell and grouped (y[rows[i]]) responses, also together with resample_groups (rows of groups the fit never saw; frozen preprocessing). A joint (MvNormalCholesky) response, and a forecast together with resample_covariates or with resample_groups under freeze_constants=false (both rebuild the program from the formula), are not supported and error.

Covered: the Julia-side transforms (zscale/standardize/center/factor/ mo/s/t2/gp/hsgp), interval-censored predictor splits, protect/implicit-fn columns (re-materialised on new_df), typed mm(...) and ordinary plain/|ID| random-effect group indices, sum-to-zero (s2z_groups) blocks (rows re-coded through the fitted levels, any subset of them; the fitted centering weights kept; frozen only), kernel(...) subject counts and ragged(x, group) columns, continuous × continuous interaction columns, typed observation weights, categorical outcomes, pass-through raw columns (plain data, me obs values, ar time), and data-only model-scope assignments (evaluated again on new_df; a constant one reads keeps its fitted value unless freeze_constants=false). A consumer _sb_submodel_rhs! term is called again on new_df, and every data key it writes comes from that call (its scalar keyword columns follow freeze_constants); the call must emit the fitted statements. A derived non-vector key with no preprocessing record is carried through when the replay DataFrame supplies its raw column; StanBlocks then retraces the derived carrier (for example a vector-of-vectors column becomes the ragged mem/ends data). Frozen replay errors loudly on an unseen fitted level. A stratified gr(g, by=b) block replays its rows into the fitted levels, each level in its fitted stratum (a row placing a level in another stratum is refused); drawing new levels of one (resample_groups) is not supported.

source
BayesianRegressionModels.required_brm_inputs Function
julia
required_brm_inputs(d::BRMDescriptor) -> Vector{Symbol}

The Stan data keys a consumer must actually supply — the neither-derived-nor-inlined subset of d.inputs. The BRM analogue of StanBlocks' required_inputs; for the dataframe schema use brm_columns.

source
julia
required_brm_inputs(d::BRMRKDescriptor) -> Vector{Symbol}

The inputs of the RK program that are not extents the data compute: the neither-derived-nor-inlined subset of d.inputs, as for a BRMDescriptor.

source
BayesianRegressionModels.restan_data Function
julia
restan_data(sb::SBBRMI, new_df; freeze_constants=true,
            resample_groups=(), resample_covariates=(),
            held_out=<the fit's hold-outs>) -> Dict

Thin convenience over reprocess: the prepared Stan data dict for new_df, ready for a param_constrain! replay. Equivalent to stan_data(reprocess(sb, new_df; freeze_constants, resample_groups, held_out)). Same freeze_constants semantics (default true = training constants applied to new data), and accepts the same resample_groups and held_out keywords. A non-empty resample_groups also changes the Stan program; call reprocess when you need the corresponding SBBRMI/source as well as this data-only convenience result. See reprocess for the covered-terms list and error cases.

source
BayesianRegressionModels.rk_artifact_inputs Function
julia
rk_artifact_inputs(artifact) -> Dict

The input columns of a complete emitted RK artifact. Fitted geometry may retain cached preparation columns in artifact.plan.columns; an emitted assignment owns that value, so its name is excluded from the inputs. Use this dictionary with public lower_rkppl and bind_data when replaying printed source directly. rk_translate_artifact selects the same inputs automatically.

source
BayesianRegressionModels.rk_bound_data Function
julia
rk_bound_data(rk::RKBRMI) -> NamedTuple

The bound inputs of rk's executable graph for its own data: pass them as bound= to ReactiveKernels.prepare(rk.model.spec; have=(:unconstrained, keys(bound)...), want, bound). For reprocess'd backends these are the new data's inputs with the training preprocessing frozen. They are the columns of rk_bound_plan(rk). On a resample_groups replay they bind the design's levels of the resampled groupings, so they pack the replay's own coordinates, not the fit's; the inputs of a cut at a draw of the fit come from rk_design_binder. Implemented by the ReactiveKernels package extension.

rk_bound_data(rk::RKBRMI, source::ReactiveKernels.JAXSource) -> NamedTuple

The inputs of the Python/JAX module emitted by jax_source(rk.model, rk_bound_plan(rk)), under exactly the names its prepare_data takes. Pass the returned fields to prepare_data by name. This includes scalar data and constants under their authored names, even when the native graph binds them under internal names, and the values of data-only definitions the module cannot translate. Values come from the current binding, so a frozen replay keeps its fitted preprocessing and a fresh replay refits it. Inputs and returned values must be treated as read-only.

The one-argument method returns the native graph's inputs; use this two-argument method to collect inputs for the emitted module.

source
BayesianRegressionModels.rk_bound_plan Function
julia
rk_bound_plan(rk::RKBRMI) -> ReactiveKernelsPPL.StructuralPlan

The RKPPL binding of rk's program to its own data: the bound plan every query of rk evaluates on rk.model. For a reprocess'd backend it binds the new data, with the training preprocessing frozen and the responses the data omit left absent. (rk.model, rk_bound_plan(rk)) is the (built, plan) pair RKPPL's queries take (rkppl-use §14), so each of them applies to rk as documented there. Posterior-predictive draws on a new design, for example:

julia
replay = reprocess(rk, design; resample_groups=[:subject])
targets = predictive_targets(replay.model, rk_bound_plan(replay))
# WANT predictive_node(replay.model) in a cut over replay.model.spec, then
draws = predictive_draws(value, targets, rng)

Without resample_groups, prepare_predictive(replay.model, rk_bound_plan(replay)) draws the whole model at a draw u of the fit. Every query of rk reads this one plan: read it, never mutate it. Implemented by the ReactiveKernels package extension.

source
BayesianRegressionModels.rk_design_binder Function
julia
rk_design_binder(rk::RKBRMI; resample_groups=(), held_out=<the fit's>) -> RKDesignBinder

The graph inputs of new designs (prediction scenarios) for the fitted model rk, built once, at a draw of the fit. binder(design) returns the inputs rk_bound_data(reprocess(rk, design; resample_groups, held_out)) holds, as a NamedTuple, without planning, emitting or lowering the program again: the first design of each kind (the same columns, column types, empty columns and missing values) is replayed in full, and every later one is checked and bound into that replay's lowered program.

  • resample_groups=[:g] (new levels of g): the inputs keep the fit's level set of g (g_fit_levels), which sizes g's standardized draws as in the fit, while the rows read the design's own levels by position (g_level). So u is a draw of the fit for any number of new levels, and the new levels' effects come in HAVE (have=(:unconstrained, :b_g, ...), one row per new level in level order). This is where binder(design) differs from rk_bound_data(reprocess(...)): that replay is a model of its own rows, whose new levels' standardized draws are its own coordinates. A block whose draws the design's own columns size (gr(g, by = s), or a multi-membership block of a data-free fit) is refused on a design that gives it other levels than the fit's.

  • binder.fitted holds the inputs no design changes (the training columns behind fitted anchors, a car(...) term's fitted graph, constant(...) values, a resampled grouping's fitted level set). Bind them once with ReactiveKernels.prepare(spec; have, want, bound=binder.fitted) and pass the rest per design; values that read only them are then computed once.

  • A numeric scalar a design omits (a prior argument the fitted state carries) takes the fit's value, as on reprocess, and stays on the cached path. It is among binder(design)'s inputs, not binder.fitted: a design of another kind may hold it.

  • What the program fits from those inputs alone and binding evaluates (spline and HSGP fits, fitted means and SDs, level sets) is taken from the first design of each kind and bound frozen into every later one (RKPPL's bind_data(…; frozen)): a later design computes only what its own columns determine, such as a basis at its rows.

  • A design is refused exactly where reprocess refuses its values: unseen factor, mo or group levels, HSGP axis values past the fitted basis interval or fixed domain, non-finite HSGP axis values, a rows= column that is not 0/1 or not as long as the axis, a missing axis value in a row the mask carries, a car area outside the fitted graph, ragged labels that name no cell, and per-cell inputs whose cell counts disagree, and a numeric scalar a prior reads or the program holds as a literal, at another value.

  • Checks of data-only model assignments read their values from the bound program, so derived axes, grouping keys and masks use the same cached path.

  • A model whose inputs include a value BRM derives from the design in Julia replays every design in full; show(binder) names those inputs.

source
BayesianRegressionModels.rk_model Function
julia
rk_model(name::Symbol)

Return a BRM-owned native statistical KernelSpec after loading ReactiveKernels and ReactiveKernelsPPL. Available models: :gp_exp_quad_cov, :gp_periodic_cov and :dual_hsgp. Covariance graphs compose into authored RK/RKPPL models; StatisticalPreparation provides the matching covariance call wrappers. The dual HSGP preserves its 44 packed coordinates, live partial centeredness, LogNormal(0,4) hyperpriors, standard-normal weights and normalized likelihood.

source
BayesianRegressionModels.rkppl_model Function
julia
rkppl_model(name::Symbol)
rkppl_model(rk::RKBRMI) -> ReactiveKernelsPPL.RKPPLModel

Return a BRM-owned statistical submodel by name, or the captured RKPPL source of an existing RK backend. Load ReactiveKernels and ReactiveKernelsPPL first.

Available names: :varying_coefs, :varying_coefs_correlated, :varying_coefs_centered, :varying_coefs_centered_correlated, :varying_stratified, :varying_stratified_correlated, :horseshoe_coefs, :r2d2_coefs, :penalized_smooth, :t2_smooth, :hsgp_effect, :hsgp_periodic_effect, :hsgp_grouped_effect, :car_icar, :car_bym2, :monotonic, :differenced_ar1 and :ordered_logistic. Their data come from StatisticalPreparation (tps_basis, cr_basis, t2_basis, hsgp_basis, hsgp_periodic_basis).

r ~ rkppl_model(:car_icar)(area, from, to) and :car_bym2 are the areal field of BRM's car(area; edges=(from, to), type=:icar | :bym2) term over raw labels: each row's area in area, one neighbour pair per entry of from and to. They prepare the graph in the model with StatisticalPreparation.car_graph and return each row's effect: sigma * phi[area] (ICAR), or sigma * (sqrt(rho / s_c) * phi + sqrt(1 - rho) * theta)[area] (BYM2, with s_c the area's component scaling factor and theta standard-normal area noise). phi ~ ICAR(node1, node2) covers the areas with neighbours, with one soft sum-to-zero sum(phi_c) ~ Normal(0, 0.001 * n_c) per connected component; an island reads 0 under ICAR and sigma * theta under BYM2. Priors: sigma ~ HalfNormal(1), rho ~ Beta(0.5, 0.5). The graph's areas are the labels of area, from and to. Lowering them needs ReactiveKernelsPPL 0.1.145. jax_source does not translate a model that calls them yet (their field sizes are read from the graph the model prepares); the same statements over car_graph's fields bound as data give the same densities and translate, and they also take car_graph's nodes.

The backend overload captures its retained emitted declarations in the same module as their submodels, callable bindings and kernel definitions. It is cached once per emitted program and shared by replays that share that program. Treat the returned model and its source as read-only.

This is unbound source, not the backend's executable kernel or fitted binding. Use rk_bound_plan for observation roles, bound data and frozen preprocessing. Capturing the source neither binds data nor changes the fit.

source
BayesianRegressionModels.stan_data Function
julia
stan_data(sb::SBBRMI) -> Dict

Return the prepared Stan data generated from sb.model. Forwards to StanBlocks.stan_data in the current world, preserving visibility of consumer-defined hooks as in stan_code. Prefer this over StanBlocks.stan_data(sb.model) when the data may be materialized inside the same function that built sb.

source
julia
stan_data(model::StanBlocks.SlicModel) -> Dict

Return the prepared Stan data for a SLIC model, using the same world-age-safe boundary as stan_data(::SBBRMI). This is the supported data entry for a model rebuilt from an emitted SBBRMI after construction — for example a cv_groups model whose group index was marked with StanBlocks.stan.maybecv just before tracing. This boundary also preserves visibility of consumer-defined family hooks in an older compiled caller.

source
julia
stan_data(model::StanBlocks.StanModel) -> Dict

Return the prepared Stan data of a traced model, such as the result of stan_model, at the same world-age-safe boundary.

source
StanBlocks.stan_instantiate Function
julia
stan_instantiate(sb::SBBRMI; kwargs...) -> StanProblem

Compile sb.model via BridgeStan. Forwards to StanBlocks.stan_instantiate in the current world, for the same lowering-time registration reason as stan_code above. Prefer this over StanBlocks.stan_instantiate(sb.model) when the build may run inside a function that also built sb.

source
StanBlocks.stan_model Function
julia
stan_model(sb::SBBRMI; kwargs...) -> StanModel

Trace sb.model end to end. Forwards to StanBlocks.stan_model in the current world, preserving visibility of consumer-defined hooks as in stan_code above. Prefer this over StanBlocks.stan_model(sb.model) when the trace may run inside a function that also built sb.

source
BayesianRegressionModels.structure_of Function
julia
structure_of(brmi::BRMI) -> BRMI

Return the STRUCTURAL fragment of a parsed model: a BRMI holding everything that is NOT a prior-address statement — linear predictors, likelihoods, and scalar parameter declarations (sigma ~ Exponential(1)) — in formula order. This is the "suppress the priors when printing" view: printing the result shows the model without the prior block that swamps it.

Inverse partition to priors_of: Base.merge(structure_of(brmi), priors_of(brmi)) recomposes an equivalent model.

source
BayesianRegressionModels.term_priors Function
julia
term_priors(brmi::BRMI) -> Vector{NamedTuple}

Return the prior statements captured by @brm that address a term's own parameters — the sd, ar, simplex, latent, length_scale and mixing heads applied to a term rather than to a coefficient or a grouping factor — in formula order. Each entry has

julia
(; class, term, predictor, component, family, arguments, keywords, expression,
   qualifiers)

class is :term_sd, :term_ar, :term_simplex, :term_latent, :term_length_scale or :term_mixing. term is the canonicalised term key: the term as the formula spells it, minus numeric and keyword arguments, so me(x, 0.5) and me(x) both key as Symbol("me(x)"), interval_censored(x; upper=lloq) keys as Symbol("interval_censored(x)"), and hsgp(x; k=20) keys as Symbol("hsgp(x)"). predictor === nothing means the statement is the default layer for every linear predictor carrying that term; a Symbol restricts it to one. component is nothing except for sd(lp, t2(x, z), rr), where it names one of the tensor smooth's three penalty blocks. qualifiers holds the address's literal keyword values (hsgp(x; cov=:periodic) gives (; cov=:periodic)): the address reaches only terms whose keywords agree, which picks one of several same-axes terms on a predictor.

Which parameter each class reaches:

spellingparameter
sd(lp, s(x))the smoothing SD sds
sd(lp, t2(x, z), rr|rn|nr)one of the three tensor smoothing SDs
simplex(lp, mo1(c))the monotonic-increment Dirichlet concentration
latent(lp, me(x))the latent true covariate x_true
latent(lp, interval_censored(x))the covariate values on BLOQ rows
sd(lp, gp(x)) / sd(lp, hsgp(x))the GP marginal amplitude sigma
length_scale(lp, gp(x)) / length_scale(lp, hsgp(x))the GP length scale rho
ar(lp, dar(time))the differenced-AR persistence coefficient beta
sd(lp, rw(time))the random walk's innovation scale sigma
sd(lp, cdar(step)) / ar(lp, cdar(step))the grouped stationary AR(1) walk's marginal SD sigma (its innovation SD is sigma * sqrt(1 - rho^2)) / persistence rho
sd(lp, car(area)) / mixing(lp, car(area))the areal effect's scale sigma / BYM2 spatial share rho

Standardized raw innovations (b_pen_raw, z, beta_raw, epsilon, and car's phi / theta) are deliberately NOT addressable: they carry no independent scale, and giving them a prior would duplicate or confound the model-scale parameter above (decision 145tp0o).

source
BayesianRegressionModels.transpiles Function
julia
transpiles(sb::SBBRMI; re=true) -> Bool

Return true if sb successfully transpiles to Stan source, false otherwise. Forwards through stan_code, so — like the rest of the BRM trace surface — it re-enters the compiler in the current world and is call-site independent: build + predicate inside one function works on a freshly built model, while direct StanBlocks.transpiles(sb.model) from the same frame dies with ‘brmvectorprior∗‘ismissing‘lpxfexpr‘ (snag two-sbbrmi-fits-f2beca06). Set re=false to swallow the error and just return false; the default re=true rethrows.

source

Additional exports in this task group:

OriginNames
BayesianRegressionModelsBRMDescriptionCoverage, brm_description_prior_anchor, rk_translate_artifact

stan_code ​

Re-exported from StanBlocks. stan_code(sb::SBBRMI) returns the emitted Stan program for the bound model; stan_data returns its corresponding data.

Response families ​

Construct response distributions and prior families. See Response families.

BayesianRegressionModels.AR1Normal Function
julia
@plate for p in groups(g; order = t)
    y[p] ~ AR1Normal(mu[p], sigma, phi; time = t[p])
end

Gaussian observations whose residuals follow an AR(1) process along each group's series, in the order of the integer time column t: y[s] - mu[s] = phi^k * (y[s-k] - mu[s-k]) + e[s], where k is the number of time steps since the previous entry. The plate is the grouping: groups(g; order = t) gives one cell per group, with its rows in t order.

  • sigma is the innovation SD. The first entry comes from the stationary law Normal(mu, sigma / sqrt(1 - phi^2)), so |phi| < 1 is required. This is the exact AR(1) likelihood (brms' ar(cov = TRUE)).

  • A gap of k steps uses phi^k and innovation variance sigma^2 (1 - phi^(2k)) / (1 - phi^2): the exact density of the process observed only on the recorded steps. Each series' times must be whole numbers, each at most once; the model refuses others when it is built, naming the group and value.

  • Without time, consecutive rows are one step apart: the plain recursion.

  • An argument that reads the group's rows (mu[p], sigma[p], or a cell local computed from one) varies along the series; any other argument is shared. log(sigma) ~ 1 + (1 | g) read as sigma[p], or atanh(phi) ~ 1 + (1 | g) read as phi[p], lets the scale or the persistence vary by group.

@brm keeps the statement as written, and each backend calls a BRM-owned submodel holding the recurrence (an @slic submodel on SBBRMI, an @rkppl one on RKBRMI), the cell's series passed as its arguments:

julia
@scan begin
    y[1] ~ Normal(mu[1], sigma[1] / sqrt(1 - phi[1] ^ 2))
    for s in 2:length(time)
        k = time[s] - time[s - 1]
        y[s] ~ Normal(mu[s] + phi[s] ^ k * (y[s - 1] - mu[s - 1]),
                      sigma[s] * sqrt((1 - phi[s] ^ (2 * k)) / (1 - phi[s] ^ 2)))
    end
end

SBBRMI's submodel reads a shared argument as its one value, and RKBRMI's receives it filled to the series' length. show and the descriptor print the statement; the generative plan declares an AR1Normal observation of y. Each entry's pointwise log likelihood is its conditional density given the series' earlier entries, and with y omitted the cell draws whole trajectories.

Order 1 only. For another innovation family, a higher order or a different start or gap rule, write the @scan yourself (see kernel).

source
BayesianRegressionModels.BetaBinomial2 Type
julia
BetaBinomial2(trials, mean, precision)

Beta-binomial distribution parameterised by success probability mean and positive concentration precision.

source
BayesianRegressionModels.BinomialLogit Type
julia
BinomialLogit(n, logitp)

Binomial distribution parameterised on the logit scale. Both BRM backends use a logit-native log-pmf and avoid an inverse-logit round trip for density evaluation.

source
BayesianRegressionModels.CategoricalLogit Type
julia
CategoricalLogit(eta2, eta3, ...)
CategoricalLogit(@brm(formula))

Reference-class categorical distribution. Class 1 has logit zero and each argument is the logit for one subsequent class. The support is 1:(length(params(d)) + 1).

Inside an outer @brm model, the concise nested-@brm form is normalised to one ordinary scalar linear predictor per non-reference outcome class. Those predictors share formula structure while fitting distinct coefficients.

source
BayesianRegressionModels.CircularVonMises Type
julia
CircularVonMises(mu, kappa; interval=(-pi, pi))

Von-Mises distribution represented on one fixed half-open principal interval. interval must be a finite pair (lo, hi) with hi - lo == 2pi. The density is exactly Distributions.jl's VonMises(mu, kappa) after mapping both the mean and observation to equivalent angles, while rand maps native von-Mises draws back into [lo, hi).

This surface is deliberately distinct from Distributions' VonMises, whose support moves with mu. In an @brm formula the StanBlocks backend uses the same fixed-interval contract and lowers density and RNG evaluation to Stan's native von_mises_lpdf and von_mises_rng.

source
BayesianRegressionModels.CloglogLink Type

Complementary-log-log inverse link for Ordinal.

source
BayesianRegressionModels.Cumulative Type

Cumulative-link ordinal probabilities, P(Y <= k) = F(d * (cut[k] - eta)).

source
BayesianRegressionModels.DoubleIntervalCensored Type
julia
DoubleIntervalCensored(pc, lower, upper, interval)

A PrimaryCensored delay truncated to [lower, upper] and observed through a secondary window of width interval starting at the observed value. Construct it with double_interval_censored.

source
BayesianRegressionModels.Flat Type

An improper uniform prior on the real line. Prior-only simulation is undefined.

source
BayesianRegressionModels.HiddenMarkov Type
julia
HiddenMarkov(initial, transition, emissions; log_weights = false)

The law of a sequence y[1], …, y[T] observed through a hidden state z[1], …, z[T] in 1:K that moves as a Markov chain:

  • initial[k] is the probability that z[1] = k;

  • transition[i, j] is the probability of a move from state i to state j (each row sums to one, as in Stan, StanBlocks, ReactiveKernels and HiddenMarkovModels.jl). A K × K × (T - 1) array gives the move into step t at slice t - 1; singleton axes broadcast;

  • emissions holds one distribution per state: y[t] | z[t] = k follows emissions[k]. A K × T matrix of distributions gives the law of every state at every step.

logpdf(d, y) sums the density over every state path with the forward algorithm, in log space. With log_weights = true, initial and transition hold the logarithms of those weights (a log-softmax, say); no probability is formed, and -Inf is a structural zero.

Inside a @brm @plate cell, y[s] ~ HiddenMarkov(init, Gamma, Categorical.(eachrow(Phi))) observes cell s's sequence y[s]. The emission argument is a broadcast of a Distributions family over per-state arguments (Normal.(mu, sigma), Categorical.(eachrow(Phi)), Poisson.(lambda)), a vector of laws with one per state ([Normal(m, s), Poisson(l)], families may differ), or a comprehension [Normal(mu[k], s) for k in 1:K]; a broadcast argument with a second, step axis gives laws that change with the step. A column-stochastic matrix Θ (Θ[j, i] the move from i to j) is passed as permutedims(Θ), or declared with simplex columns, eachcol(Θ[1:K, 1:K]) .~ Dirichlet(K, 1), and passed transposed.

source
BayesianRegressionModels.Horseshoe Type
julia
Horseshoe

Carvalho-Polson-Scott horseshoe shrinkage prior marker. Use as a prior on a coefficient:

julia
coef ~ Horseshoe()
coef ~ Horseshoe(local_scale=0.5, global_scale=0.1)

local_scale and global_scale are positive finite formula constants and default to one. sbimpl emits the standard reparameterised hierarchy beta = raw * lambda * tau. Each scalar call owns its own tau; "global" means global only within that call, not shared across several coefficients. Marker struct only — the @brm parser never constructs an instance.

source
BayesianRegressionModels.LKJCovarianceFactor Function
julia
LKJCovarianceFactor(K; scale_prior=Exponential(1), shape=1)

Formula-only composite prior for the Cholesky factor of a K-dimensional covariance matrix. The StanBlocks backend samples positive marginal scales and an LKJ correlation Cholesky factor, then binds diag_pre_multiply(scales, L_corr) to the declaration's left-hand side.

Use the result with MvNormalCholesky. This is a formula marker rather than a Distributions.jl constructor.

source
BayesianRegressionModels.LogitLink Type

Logistic inverse link for Ordinal.

source
BayesianRegressionModels.MvNormalCholesky Function
julia
MvNormalCholesky(mean, factor)

Formula-only multivariate Normal family whose second argument is already the lower Cholesky factor of the covariance. A vector response such as [y1, y2] ~ MvNormalCholesky([mu1, mu2], L_res) is one row-wise joint likelihood, not two conditionally independent scalar likelihoods. Wrap the vector LHS in mi(...) for explicit joint missing-value completion.

source
BayesianRegressionModels.NegativeBinomial2 Type
julia
NegativeBinomial2(mu, phi)

Negative-binomial distribution parameterised by positive mean mu and positive shape/precision phi, matching Stan's neg_binomial_2(mu, phi).

source
BayesianRegressionModels.OrderedLogistic Type
julia
OrderedLogistic(eta, cutpoints)

Ordered-logistic distribution with location eta and strictly increasing cutpoints. The support is 1:(length(cutpoints) + 1).

Inside @brm, y ~ OrderedLogistic(eta) remains the cumulative-link formula shorthand: BRM prepares and estimates the cutpoints. A standalone numeric distribution must supply them explicitly.

source
BayesianRegressionModels.Ordinal Type
julia
Ordinal(structure, link, eta, thresholds; discrimination=1)

Executable ordinal distribution with independently typed probability structure and inverse link. structure is Cumulative or StoppingRatio; link is LogitLink, ProbitLink, or CloglogLink. discrimination is finite and strictly positive.

For a cumulative model, thresholds must be strictly increasing and eta must be scalar. For a stopping-ratio model the thresholds are stage-specific intercepts and need not be ordered; eta may be either one shared scalar or a vector with one value per non-terminal stage. The support is 1:(length(thresholds) + 1).

Inside @brm, omit thresholds to have BRM allocate them, for example y ~ Ordinal(Cumulative(), ProbitLink(), eta): BRM prepares the fitted outcome levels and threshold parameters, and the formula-only keywords discrimination= and per_threshold= are documented in the likelihood guide. Or give the thresholds yourself, at model scope or in a @plate cell, as this four- or five-argument call: y[rows[e]] ~ Ordinal(Cumulative(), ProbitLink(), eta[rows[e]], cuts) with cuts one examiner's own vector. The response then holds the category codes 1:(length(thresholds) + 1), and a cumulative vector that is not strictly increasing gives the point log density -Inf.

source
BayesianRegressionModels.OrdinalLink Type

Supertype for typed ordinal inverse-link choices used by Ordinal.

source
BayesianRegressionModels.OrdinalStructure Type

Supertype for the ordinal probability construction used by Ordinal.

source
BayesianRegressionModels.PrimaryCensored Type
julia
PrimaryCensored(dist, primary_event)

The law of U + X: a delay X ~ dist that starts at a primary event U ~ primary_event known only to lie in a window. Construct it with primary_censored.

source
BayesianRegressionModels.ProbitLink Type

Standard-normal inverse link for Ordinal.

source
BayesianRegressionModels.SkewDoubleExponential Type
julia
SkewDoubleExponential(mu, sigma, tau)

Asymmetric double-exponential distribution with the exact parameterization of Stan's native skew_double_exponential(mu, sigma, tau). sigma is the native Stan scale and tau is the probability mass at or below mu, so cdf(d, mu) == tau. At tau == 0.5, this is exactly Laplace(mu, sigma).

Distributions.jl represents the same family as SkewedExponentialPower(mu, sigma_sepd, 1, tau), with sigma == 4sigma_sepd*tau*(1-tau). BRM uses that identity as the executable Julia receipt while lowering this type directly to Stan's native family.

source
BayesianRegressionModels.StoppingRatio Type

Stopping-ratio ordinal probabilities, P(Y = k | Y >= k) = F(d * (cut[k] - eta[k])).

source
BayesianRegressionModels.TruncatedNormal Function
julia
TruncatedNormal(mu, sigma, lloq, uloq)

Historical BRM spelling for the censored normal observation model. Numeric arguments construct Distributions.jl's exact Censored(Normal(mu, sigma), lloq, uloq) distribution, including its boundary atoms. The name is retained for formula compatibility.

source
BayesianRegressionModels.ZeroInflatedPoisson Type
julia
ZeroInflatedPoisson(lambda, zi)

Mixture of a point mass at zero (probability zi) and Poisson(lambda).

source
BayesianRegressionModels.coarsened Function
julia
coarsened(Ordinal(structure, link, eta; ...); upper)

Formula marker for coarsened ordinal evidence: a record that says only that the category lies in an inclusive range of the response's ordered levels. The observed response column holds the lowest category the record allows, and upper names a column holding the highest:

julia
y_min ~ coarsened(Ordinal(Cumulative(), ProbitLink(), eta); upper=y_max)

Each row contributes log P(y_min ≤ Y ≤ y_max), the summed probability of its categories; equal labels are an exact category. Both columns hold labels of one ordered level set, which the response column defines as for Ordinal: a CategoricalVector keeps its declared levels, so levels = 0:4 keeps an unobserved 4, and a plain vector uses sort(unique(y_min)). Every upper label must be one of those levels and must not precede its row's lower label. Thresholds, discrimination= and per_threshold= are the base Ordinal's. Predictions draw single categories from the uncoarsened Ordinal law.

Unlike interval_censored, whose response column is an open lower endpoint (y, upper], both endpoints here are inclusive category labels. SBBRMI and RKBRMI (native density, gradients and jax_source) implement it.

source
BayesianRegressionModels.double_interval_censored Function
julia
double_interval_censored(dist; primary_event = Uniform(0, 1), lower = nothing,
                         upper = nothing, interval = nothing)

A delay with a censored primary event, truncation and a censored secondary event: X ~ dist starts at an unknown time U ~ primary_event, only delays U + X in [lower, upper] are observed (right truncation by the observation time is upper), and each observation y is the start of its secondary-event window [y, y + interval]. Its log density at y is

log(F_pc(y + interval) - F_pc(y)) - log(F_pc(upper) - F_pc(lower))

with F_pc the CDF of primary_censored(dist, primary_event). This is epidist's marginal delay model. The keywords follow CensoredDistributions.jl's double_interval_censored (primary censoring, then truncation, then the secondary window), except that y is the window's start as recorded rather than rounded down onto a grid of width interval; for data on that grid the two coincide. Without interval the observation is an exact secondary-event time and contributes the truncated density.

In a @brm model:

julia
delay ~ double_interval_censored(LogNormal(mu, sigma);
    primary_event = Uniform(0, pwindow), upper = obs_time, interval = swindow)

where delay is the start of the secondary window measured from the start of the primary window, and pwindow, obs_time and swindow are numbers or data columns. Wrap it in weighted(..., fweights(n)) for aggregated rows.

source
BayesianRegressionModels.interval_censored Function
julia
interval_censored(base; upper)
interval_censored(x; upper, lower=0)

Formula marker for genuine interval evidence. On a response RHS, the observed response column supplies each interval's lower endpoint and upper supplies its upper endpoint:

julia
y_lower ~ interval_censored(Normal(mu, sigma); upper=y_upper)

Each row contributes the base family's probability over (y_lower, y_upper], exactly CDF(y_upper) - CDF(y_lower). The lower endpoint is open for discrete families too; unlike inclusive truncation it receives no predecessor shift. Posterior prediction remains on the uncoarsened base-response scale. This is separate from Distributions.jl's censored, which is the distribution of clamp(X, lower, upper) and therefore has atoms at its thresholds.

Inside a linear predictor, x is the observed covariate and upper is its row-specific quantification limit:

julia
mu ~ 1 + interval_censored(concentration; upper=lloq)

By convention, concentration == lloq marks a BLOQ row; values above lloq are exact. BLOQ rows allocate latent predictor values between lower (zero by default) and lloq with a truncated Normal prior; configure that prior with latent(<lp|:>, interval_censored(concentration)) ~ Normal(...). This predictor form is implemented by SBBRMI.

The marker is intentionally formula-local: unlike truncated and censored, there is no existing Distributions.jl value with these per-row evidence semantics for BRM to construct outside @brm. It lives in the backend-neutral formula layer so weak-dependency backends can inspect it without loading StanBlocks.

source
BayesianRegressionModels.primary_censored Function
julia
primary_censored(dist, primary_event)

The distribution of a delay X ~ dist measured from the start of the time axis when its primary event happened at an unknown time U ~ primary_event: the law of U + X. dist is a LogNormal, Gamma or Weibull; primary_event is a Uniform(a, b) window. Same signature and meaning as CensoredDistributions.jl's primary_censored with its analytical solutions.

In a @brm model, delay ~ primary_censored(LogNormal(mu, sigma), Uniform(0, w)) observes exact secondary-event times (measured from each primary window's start) with a primary-event window of width w, a number or a data column. For secondary events known only to a window, and for truncation by the observation time, use double_interval_censored.

source

Additional exports in this task group:

OriginNames
DistributionsArcsine, Bernoulli, BernoulliLogit, Beta, BetaBinomial, Binomial, Categorical, Cauchy, Chisq, Dirichlet, DirichletMultinomial, Erlang, Exponential, Frechet, Gamma, Gumbel, InverseGamma, InverseGaussian, LKJCholesky, Laplace, LocationScale, LogNormal, Logistic, MixtureModel, Multinomial, MvNormal, NegativeBinomial, Normal, NormalCanon, Pareto, Poisson, Rayleigh, SkewNormal, SkewedExponentialPower, TDist, Uniform, VonMises, Weibull, censored, logpdf, product_distribution
BayesianRegressionModelsHurdlePoisson
LogExpFunctionslog1mexp, log1pexp, logexpm1, logistic, logit, logsumexp

truncated ​

Re-exported from Distributions. truncated(distribution; lower, upper) normalizes the density over the retained interval. See bounds and vectors for the difference from restricted. | StatsFuns | normcdf, norminvcdf |

Terms and priors ​

Declare structured effects, preprocessing and formula priors. See the term catalogue.

BayesianRegressionModels.assign Function

Marker function for literal-binding (lhs = rhs) operations in a @brm block. Dispatch tag only — never called.

source
BayesianRegressionModels.center Function

Marker for center(x) — mean-centre x. Dispatch tag only.

source
BayesianRegressionModels.constant Function
julia
name = constant(expr)

A scalar or array computed from the data when the model is built, such as a prior hyperparameter calibrated on the observations, a grid a plate cell reads or a known correlation matrix:

julia
@brm begin
    ec50_loc = constant(mean(log.(conc)))
    log_ec50 ~ Normal(ec50_loc, 1)
    ...
end

expr is ordinary Julia, evaluated once on whole columns of the data. A bare name in it that is not a field of the data resolves in the builder's scope. The result must be one finite real number or an array of them (a vector, a matrix, …); an array's shape is fixed by that evaluation. The constant is Stan data on SBBRMI and a bound value on RKBRMI, usable wherever a data field of the same value is.

Replay keeps the fitted value, like standardize's mean and SD: reprocess, reprocess(...; resample_groups) and generative_plan(plan, new_df) reuse it without the new data supplying it, and reprocess(...; freeze_constants=false) evaluates expr again on the new data. Dispatch tag — see _brm_resolve_constants.

source
BayesianRegressionModels.doublepipe Function

Marker function for the brms || zero-correlation random-effects operator. Dispatch tag only — never called.

source
BayesianRegressionModels.effect Function
julia
effect(linear_predictor, coefficient)
sd(linear_predictor, id[, coefficient])
cor(:, id)
cor(linear_predictor, group)

Address a prior BRM owns, by naming the parameter as the head and the target in the slots. Every slot is one name or :, and : means the default — the base layer that a more specific statement overrides:

julia
@brm begin
    log_ka ~ 1 + weight + (1 | pk | subject)
    effect(log_ka, Intercept) ~ Normal(log(1 / 8), 0.8)
    effect(log_ka, weight)    ~ Normal(0, 0.1)
    sd(:, pk)                 ~ Exponential(2 / 3)
    cor(:, pk)                ~ LKJCholesky(2, 2)
end

The grammar is <quantity>(<linear predictor | :>, <target…>). effect addresses a population coefficient, a categorical column's K-1 treatment contrasts, or — for the first categorical term of a predictor without an intercept — its K cell means, each also addressable as <column>_lvl_<k>; sd and cor address a shared |ID| random-effect covariance block. sd's trailing coefficient slot may be omitted and means :, so sd(:, pk) is the block-wide scale and sd(log_ka, pk, weight) is one margin, while sd(log_ka, pk) sets every margin log_ka contributes. Because : is positional rather than a trailing omission, sd(:, pk, weight) addresses the weight margin across every predictor slicing the block. Correlation priors on a shared |ID| are block-wide by construction — one covariance spans every predictor that slices it — so cor(:, ID) takes : in the predictor slot.

A random-effect block written without an ID — plain (… | g) or uncorrelated (… || g) — is addressed by its grouping column, as brms' group = is:

julia
@brm begin
    mu ~ 1 + c1 + (1 + c1 || probe)
    log(sigma) ~ 1 + (1 | probe)
    sd(:, probe)     ~ Exponential(50)   # every margin grouped by `probe`
    sd(sigma, probe) ~ Exponential(1)    # more specific: `sigma`'s block
    sd(mu, probe, c1) = 0.5              # a known value
end

One column can group several independent blocks — each predictor's block and one block per || term — and an sd statement sets every margin of them it matches, most specific first. cor(:, g) sets the correlation of the one correlated block grouped by g; with one per predictor, write cor(<linear_predictor>, g). ranef(<linear_predictor|:>, g) ~ TDist(nu) sets the law of the matching blocks. An addressed block lowers as a one-predictor |ID| block under a generated ID (|lp__g|, the k-th || term |lp__g__nocor__k|); a block no statement reaches is left as written. An |ID| block keeps its ID address only, and a name that is both an |ID| and the grouping column of a block without one is refused as ambiguous.

An interaction term is addressed the way the formula spells it: effect(mu, gen & mathz) sets one shared Normal prior over every beta_pop column the gen & mathz term emits — one column for a continuous × continuous interaction, K-1 for a continuous × categorical one. Operand order does not matter (a & b and b & a are the same address). Each emitted column keeps its own int_… label (see popcoefnames), and addressing one of those labels directly refines the whole-term address on that column alone.

There is deliberately no concise, predictor-inferring form: name the linear predictor or write :. Two statements reaching the same parameter resolve most-specific-wins — fewer : slots wins — and an exact tie is an error.

The whole-predictor Colon address is also how the joint variance-decomposition family r2d2 attaches: effect(lp, :) ~ r2d2(...) decomposes every population coefficient of lp at once, while effect(lp, :) ~ Normal(...) is simply the default layer for those columns.

effect is an address marker, not a callable function; sd and cor are rewritten onto it by the macro and are not exported. Use effect_priors, ranef_effect_priors, r2d2_priors, and ranefcoefnames to inspect the captured statements and margin labels.

source
BayesianRegressionModels.factor Function
julia
factor(x; ref=k, cmc=true)

Treat x as a categorical predictor with optional reference level ref. Dispatch tag — backend buckets it into the categorical-predictor path in introspection.jl and _sb_cat (sbimpl).

Under an intercept the term is K−1 treatment contrasts against ref. As the first categorical term of a predictor WITHOUT an intercept it is cell-mean coded (K coefficients, no reference) — brms / R model.matrix semantics. cmc=false (brms' name, "cell-mean coding") switches that off and keeps the treatment contrasts, e.g. to pin one group of an intercept-free predictor at zero.

source
BayesianRegressionModels.gr Function
julia
gr(group; by=strata)

brms-style stratified grouping marker. (1 | gr(subj, by=diagnosis)) gives each level of by its own random-effect covariance structure. Dispatch tag only — backend interpretation lives in the shared preparation layer, the sbimpl ranef walker and the RK emitter.

source
BayesianRegressionModels.groups Function
julia
groups(g; order = nothing)
groups(g => labels; order = nothing)

The indices of each group of the vector g.

groups(g) has one group per distinct value of g, in sorted order of the values. groups(g => labels) has one group per entry of labels, in that order: the indices of g that hold that label (none, if no entry of g does). An entry of g whose label is not listed is in no group. Within a group the indices are in ascending order (a vector indexed like g) when it is given, ties in index order, and in index order otherwise.

julia
julia> groups(["b", "a", "b", "a"]; order = [4, 9, 1, 2])
2-element Vector{Vector{Int64}}:
 [4, 2]
 [3, 1]

julia> groups(["b", "a", "b", "a"] => ["b", "c", "a"])
3-element Vector{Vector{Int64}}:
 [1, 3]
 []
 [2, 4]

julia> groups(["b", "a", "d", "a"] => ["a", "b"])
2-element Vector{Vector{Int64}}:
 [2, 4]
 [1]

In a @brm model, @plate for p in groups(probe; order = day) has one cell per group of the data vector probe, and p is that group's indices: a read x[p] of a value indexed like probe is x at those indices in that order. A plate over subjects reads another vector's entries per subject through a model-scope binding, events = groups(event_subject => subject), as x[events[i]]; an entry whose label names no cell is read by no cell. A response observed through a binding, y[events[i]] ~ …, must have every entry in a cell. Either way the cell means what the same loop computes in Julia. See kernel.

source
BayesianRegressionModels.kernel Function
julia
@plate for i in eachindex(per_subject_axis)
    pred[i] = cell(data[i], per_subject_lp[i])
end

General group-local submodel surface: broadcast an inline cell over the groups of the linear predictors it reads.

The per-subject LP formulas own the population effects, covariates, links and random-effect buckets — they are ordinary @brm formulas declared in the same block. @plate for derives ONE shared grouping from those LPs and evaluates the body once per group. An indexed read is that group's slice; an indexed LHS is a model-scope output, while a bare LHS is local to the cell:

julia
log_CL ~ 1 + weight + (1 | p | subject)
log_Vc ~ 1 + (1 | p | subject)

@plate for i in eachindex(log_CL)
    CL = exp(log_CL[i])
    Vc = exp(log_Vc[i])
    conc[i] = pk_cell(t_obs[i], dose[i], CL, Vc)
end

When the cell's last statement is its final indexed assignment, as conc[i] = ... is here, that right-hand side is the cell's return value and the plate stores it once. An indexed output that later cell statements read is bound as a cell value first and then returned.

A cell needs no indexed output. When its only indexed statements are observations (dv[i] ~ Normal(cp, sigma) after a bare cp = ...), it has no collected result: cp stays a cell local and nothing is stored at model scope. Both backends build such a cell.

A plate over long-format rows iterates groups, an ordinary function: in @plate for p in groups(g; order = t), p is one group's indices (one cell per distinct label of the data vector g, in sorted order, its indices in ascending t), so a read x[p] is x at those indices (a response, a data vector, or a predictor indexed like g), as the same Julia loop reads it. Values shared by every row are read bare. Such a cell observes, and collects no result (loc[p] = …): nothing outside it could tell which group a collected value belongs to.

A cell may hold a @scan begin … end recurrence, one per cell: seeds by literal index, then one for loop of steps reading earlier entries at a fixed lag. A carried array the scan writes (h[t] ~ Normal(phi * h[t - 1], s)) is a latent state per cell; observing the cell's own response entry by entry (y[i][1] ~ …, y[i][t] ~ Normal(… y[i][t - 1] …)) gives each entry's conditional density, and with y omitted the block draws whole trajectories. AR1Normal observes a group's series under one such recurrence.

Indexed inputs split by kind. A data vector with one entry per cell is read x[i], and a vector of per-cell vectors gives cell i its own vector. A vector or linear predictor indexed like another grouping vector — dose events, say — is read at the cell's indices through a model-scope binding:

julia
log_F  ~ 1 + vessel + mo(diet) + hsgp(log_dose)     # one value per dose event
log_CL ~ 1 + weight + (1 | p | subject)             # one value per subject
doses = groups(dose_subject => subject)             # each subject's dose indices
obs = groups(obs_subject => subject)

@plate for i in eachindex(log_CL)
    effective_dose = dose_amount[doses[i]] .* exp.(log_F[doses[i]])
    pred[i] = pk_cell(t_obs[obs[i]], effective_dose, log_CL[i])
    dv[obs[i]] ~ normal(pred[i], sigma)
end

groups(dose_subject => subject) is, for each entry of subject, the indices of dose_subject that hold it, so x[doses[i]] is x at subject i's doses, as the same Julia loop reads it. Entries join their cell by label, never by position. Every binding one plate reads names the same label vector, and under a random-effect predictor that is the predictor's grouping vector. When no predictor carries a random effect, the label vector lists the cells: a district total observes the summed rate of its facilities,

julia
log_lambda ~ 1 + (1 | fac | facility)                # one value per facility
facilities = groups(fac_district => district)       # each district's facilities

@plate for d in eachindex(Y)                        # Y: one total per district
    Y[d] ~ Poisson(sum(exp.(log_lambda[facilities[d]])))
end

and the plate has one cell per entry of district, in that order. A facility whose district district does not list is read by no cell, so the cells may observe only some districts' totals; a response observed through a binding (y[obs[i]] ~ …) must have every entry in a cell. An index vector into another grouping's entries — an event schedule's global read number per observation — is read as positions among the cell's indices of that grouping, indexin(obs_read[obs[i]], reads[i]) with reads = groups(read_subject => subject); an index that belongs to another subject is refused, and something.(indexin(…), 0) keeps 0 as "no index". A binding no cell reads is refused.

A per-subject linear predictor is passed as that group's scalar value. One with random effects over several groupings — Kreise nested in Länder, (1 | land | land) + (1 | kreis | kreis) — is read on the grouping whose column lists one unique label per entry; the others are ordinary terms of its value. One without a random effect defines no grouping of its own: it is read per subject as a random-effect predictor defines the subjects — or, in a panel with no random effects, as the pre-grouped vectors do — so its data vectors must have one entry per subject.

@brm lowers this annotated-loop surface to the shared kernel IR, so SBBRMI and RKBRMI use the same grouping, ragged, observation, and omitted-outcome paths. kernel(...) do is deprecated and emits a deprecation warning when a model is constructed. It remains a temporary source-compatibility spelling while known consumers migrate; new code should use @plate for. The much older model= / obs= spelling and its anonymous n_eta block remain removed. A name such as eta_CL is merely a user-chosen ordinary linear-predictor name—there is no kernel-owned eta vector or positional eta-index contract in the current API.

source
BayesianRegressionModels.me Function
julia
me(x_obs, sd_x)

brms-style measurement-error predictor marker. me(x_obs, sd_x) declares that the observed x_obs has Gaussian measurement error with SD sd_x; the backend allocates a latent x_true and emits the observation likelihood x_obs ~ Normal(x_true, sd_x). Dispatch tag — see _sb_me.

source
BayesianRegressionModels.mi Function
julia
mi(y)

Missing-data marker. Wrap a response LHS (mi(y) ~ Normal(...)) to opt into the brms-style observed/imputed split: observed rows feed the likelihood, missing rows become parameters drawn from the same family. For a correlated continuous block, use mi([x, z]) ~ MvNormalCholesky([x_loc, z_loc], L) with an earlier L ~ LKJCovarianceFactor(2; ...) declaration. Rows may have different missing patterns; later formulas read completed x and z columns. See _sb_emit_mi! (sbimpl) for backend dispatch.

source
BayesianRegressionModels.mm Function
julia
mm(group1, group2, ...; weights=nothing, normalize=true)

Multi-membership grouping marker for random effects. Each observation belongs to two or more grouping levels and receives the weighted sum of their shared random-effect coefficients. weights is either omitted (equal 1/M weights) or a tuple of one data column per group. Supplied weights must be finite, nonnegative, and have a positive row total; by default each row is normalized to sum to one. Set normalize=false to preserve valid supplied magnitudes.

@brm lowers this surface immediately to a typed MultiMembershipTerm; the Stan backend validates and materializes it, including when data are replayed through reprocess.

source
BayesianRegressionModels.mo Function

Monotonic effect with a free coefficient (brms-style mo); scales the simplex-based mo1 contrast.

source
BayesianRegressionModels.mo1 Function

Monotonic effect with coefficient fixed to 1; uses a simplex over successive ordered levels.

source
BayesianRegressionModels.offset Function
julia
offset(x)

Fixed-slope (no beta) contribution to a linear predictor. brms-style offset(...) — adds x directly to the predictor without allocating any parameters. Dispatch tag only.

source
BayesianRegressionModels.protect Function
julia
protect(x)

brms I(...) analogue: literal-escape wrapper around an expression so the formula parser doesn't try to re-interpret it. In formula-eval contexts it's a no-op on Real — generic broadcast/materialise paths handle protect(expr) without a dedicated dispatch.

source
BayesianRegressionModels.r2d2 Function
julia
r2d2(; R2=Beta(1, 1), tau_bsv=nothing, alpha=1)

R²-induced Dirichlet Decomposition prior for a whole linear predictor, applied through a effect Colon address:

julia
@brm begin
    log_CL ~ 1 + weight + age + (1 | p | subject)
    effect(log_CL, :) ~ r2d2(R2 = Beta(1, 1), tau_bsv = 0.5)
end

One total between-subject scale tau_bsv is split by R2 into an explained and a residual part. The explained part is allocated across the predictor's population columns by a Dirichlet simplex phi ~ Dirichlet(alpha), giving column k the derived prior scale

beta_scale[k] = sqrt(phi[k] * R2 * tau_bsv^2 / Var(x_k))

while the predictor's random-effect margins take the residual scale sqrt((1 - R2) * tau_bsv^2) — for a latent per-subject parameter the random effect is the residual, which is the motivating PK reading (decision kx8wkd).

Keywords:

  • R2 — a Beta prior on the explained fraction. Defaults to Beta(1, 1).

  • tau_bsv — the total scale. A positive number fixes it; omitted, it becomes a sampled half-standard-normal parameter, which is the only option for a latent predictor with no observed response to anchor it.

  • alpha — the symmetric Dirichlet concentration over population columns.

Within a shared brms-style |ID| bucket the decomposition is all-or-nothing: if any linear predictor slicing the bucket is r2d2-scoped, all of them must be, so the bucket's tau is one wholly derived vector rather than a part-sampled hybrid (decision 1db6zkr). The correlation factor L stays free and shared — r2d2 constrains marginal variances and says nothing about cross-predictor correlation.

r2d2 is a formula marker, not a callable function; the SBBRMI backend lowers it. Inspect captured statements with r2d2_priors.

The same marker on a random-effect SD address is the partial-R2D2M2 form:

julia
@brm begin
    sigma_pk ~ Exponential(1)
    sigma_qt ~ Exponential(1)
    log_CL   ~ 1 + (1 | p | subject)
    qt_base  ~ 1 + (1 | p | subject)

    sd(:, p) ~ r2d2(mean_R2=0.5, prec_R2=2,
                    concentration=1, reference_scale=sigma_pk)
    sd(qt_base, p) ~ r2d2(reference_scale=sigma_qt)
    cor(:, p) ~ LKJCholesky(2, 2)
end

This spelling samples one block-wide R2, allocates its odds R2 / (1 - R2) across the addressed marginal variances with a Dirichlet simplex, and derives margin j as tau[j] = reference_scale[j] * sqrt(phi[j] * R2 / (1 - R2)). R2=Beta(a,b) and the equivalent mean/precision spelling are both accepted; alpha= and concentration= are aliases. A more-specific sd(lp, id[, coefficient]) statement under a block-wide decomposition may override only reference_scale, which is how one correlated block can span observation channels with different residual units. cor(:, id) remains an independent LKJ prior and the non-centred draw geometry is unchanged.

Without a block-wide sd(:, id) statement, every R2D2 SD address owns its own R2 and simplex. A one-margin address has a deterministic simplex[1] and is therefore the per-margin ICC construction. Unaddressed margins retain their ordinary half-standard-Normal scale prior. Random-effect R2D2 is SBBRMI-only; centered and stratified buckets remain unsupported, while non-centred resample_groups replay redraws only the standardised group coordinates and transports the fitted R2, simplex, reference scales, and correlation factor.

Adding include= to the block-wide statement makes it the JOINT R2D2M2 budget: the block's one R2 and one Dirichlet simplex also allocate population components of every linear predictor slicing the block —

julia
@brm begin
    sigma_pk ~ Exponential(1)
    sigma_qt ~ Exponential(1)
    log_CL  ~ 1 + wt + indication + (1 | p | subject)
    qt_base ~ 1 + wt + indication + (1 | p | subject)

    sd(:, p) ~ r2d2(mean_R2=0.5, prec_R2=2, concentration=1,
                    reference_scale=sigma_pk,
                    include=(:population, :contrasts))
    sd(qt_base, p) ~ r2d2(reference_scale=sigma_qt)
    cor(:, p) ~ LKJCholesky(2, 2)
end

:population adds each predictor's non-intercept beta_pop columns, :contrasts its categorical treatment-contrast coefficients; :ranef names the margins, which are always allocated. A component of predictor m is scaled by m's own margin reference: a margin keeps tau[j] = reference_scale[m] * sqrt(phi[j] * R2 / (1 - R2)) and a coefficient or contrast takes reference_scale[m] * sqrt(phi[k] * R2 / ((1 - R2) * Var(x_k))), the design-column variance adjustment of the whole-predictor form (a contrast's dummy variance is its level frequency's p * (1 - p)). Intercepts stay outside. With include=, reference_scale= is optional: an omitted margin reference is a sampled half-standard-normal, so the statement then allocates LATENT between-group variation rather than an observed-outcome R². Per-column effect(lp, coef) ~ Normal(...) and effect(lp, categorical) ~ Normal(...) statements inside the scope are refused, as is a scoped predictor that also carries effect(lp, :) ~ r2d2(...); include= belongs on the block-wide statement only. The emitted carriers (pop_<lp>_beta_pop, cat_<lp>_<col>_beta, the block's derived tau) and every descriptor reader are unchanged.

source
BayesianRegressionModels.ragged Function
julia
kernel(ragged(x, group), ...) do ...

The kernel input that groups a vector by a grouping vector naming the subject of each entry. A @plate for cell does not write it: it reads x[rows[i]] through a model-scope rows = groups(group => labels) binding (see kernel and groups), which lowers to ragged(x, group, labels). The model-scope ragged(x, group) statement and the in-cell ragged(x, group)[i] read are retired and refused with the binding that replaces them (todo 1nfukuv): they changed what x[i] means in a cell without saying so there.

The formula-level observation ragged(y, group) ~ Family(pred, ...) is retired the same way: observe the response in the cell that computes its prediction, y[rows[i]] ~ Family(pred[i], ...). ragged remains only as a positional of the deprecated kernel(...) do spelling: ragged(x, group), ragged(x, group, labels) or ragged(idx, group; into = target).

ONE VALUE PER ENTRY OF x — no expansion happens anywhere. If an event schedule stores a compact schedule (one entry per dose OP, carrying an interval and a count) then x has one value per OP. Grouping requires one group key per entry of x and joins those keys to the kernel's subject labels. That is local validation of the grouping operation, not an inner-shape contract between cell arguments.

Dispatch tag only — kernel-argument lowering lives in _sb_kernel_doblock! (sbimpl) and the RK kernel preparation.

source
BayesianRegressionModels.restricted Function
julia
restricted(D, lower, upper)
restricted(D; lower, upper)

A prior law: the distribution D's density on [lower, upper], not renormalized. It is Stan's law for a bounded declaration, real<lower=lo, upper=hi> x; x ~ D;. Either keyword may be omitted for a one-sided bound. Write it in a prior position, x ~ restricted(Normal(0, 1), a, b).

When the bounds and D's arguments are constants, restricted and truncated give the same posterior. They differ when the mass of D inside the bounds moves with sampled parameters:

  • restricted restricts the joint prior to the bounds, so learned arguments feel how much mass lies inside, as in hand-written Stan;

  • truncated is the normalized law: draw the arguments, then draw from D truncated to the bounds.

D(args...; lower, upper) keywords on a prior meant restricted. They are deprecated in its favour (decision 0q18o98).

source
BayesianRegressionModels.s Function
julia
s(x)

Add a penalized one-dimensional thin-plate regression spline to an SBBRMI linear predictor. The fixed rank-10 basis contains the unpenalized null space {1, x} and eight penalty-whitened range columns whose shared smoothing standard deviation has a standard half-normal prior.

The public syntax is exactly one finite numeric predictor, s(x). At least ten unique training values are required; keyword arguments such as k= and knots= are not supported. The term owns its complete smooth contribution and does not receive an additional population coefficient.

Prediction and replay through reprocess or restan_data use the frozen training basis by default. This marker is implemented only by the StanBlocks backend; it is not a deterministic B-spline expansion.

See Formula terms for an example and a comparison with bs(...) formulas. Dispatch tag — see _sb_s.

source
BayesianRegressionModels.standardize Function

Marker for standardize(x) — alias-style mean/SD standardisation. Dispatch tag only.

source
BayesianRegressionModels.t2 Function
julia
t2(x, z; k=(5, 5), basis=(:cr, :cr), full=false)

Tensor-product smooth marker. The StanBlocks backend builds cubic-regression- spline margins, separates their null and penalized spaces, and gives the RR, RN, and NR tensor blocks independent smoothing scales. The current surface is two-dimensional, supports only basis=(:cr, :cr), and requires full=false. Prediction/replay freezes the training knots and penalty decomposition by default. See Formula terms for the full contract. Dispatch tag — see _sb_t2.

source
BayesianRegressionModels.weighted Function
julia
weighted(distribution, weights)

Formula marker for a typed observation weight. The second argument is a StatsBase weight constructor over a dataframe column, for example aweights(replicate_k), fweights(repeats), or weights(power).

The weight type is semantic. Analytic weights modify a supported observation distribution's precision (currently Normal); frequency and generic weights scale model and pointwise log-likelihood contributions while preserving the base distribution's predictive RNG. Lowering is implemented by the StanBlocks backend; this marker is never called directly.

source
BayesianRegressionModels.zscale Function

Marker for zscale(x) — z-standardise x (subtract mean, divide by SD). Dispatch tag only.

source

Additional exports in this task group:

OriginNames
StatsBaseAbstractWeights, AnalyticWeights, FrequencyWeights, ProbabilityWeights, UnitWeights, Weights, aweights, fweights, pweights, uweights
StatsAPIweights

Fields ​

Declare spatial and temporal fields, then recover or predict their values. See Space-time fields.

BayesianRegressionModels.ar Function
julia
ar(time; p=1)

Autoregressive-noise predictor marker. Adds an AR(p) noise process ordered by time. Only p=1 is supported in the current sbimpl emitter. Dispatch tag — see _sb_ar1.

source
BayesianRegressionModels.brm_gmrf_predict Function
julia
brm_gmrf_predict(rk::RKBRMI, draws, field; east, north, time, channel=nothing,
    neighbors=nothing, rng=nothing) -> Matrix

The read-pair field field (field ~ 0 + gmrf(...; neighbors=m), named by its predictor) at points the fit need not have read, one row per point and one column per column of draws, on the scale the model reads it: the term's SD times the standardized field. draws are rk's packed coordinates, as brm_svi_fit and the samplers return them.

A point follows the term's covariance given its neighbors nearest read positions at the read times around it (default: the term's own count). With rng each entry is drawn from that conditional; without it, each is the conditional mean at that draw. A point on a read state returns that state.

Marginals are the law's, but the points are conditionally independent of each other given the states, so a joint quantity over several new points, such as an areal total, is not. The mesh form predicts through reprocess and has no such restriction.

source
BayesianRegressionModels.brm_multigroup_coherence Function
julia
brm_multigroup_coherence(d::BRMDescriptor, draws, constrained_names;
                         predictor=nothing, distances=Float64[]) -> NamedTuple

The multigroup coherence over known coordinates of a grouped HSGP, hsgp(t; by = g, cor = multigroup((x, y), lambda; k)), per posterior draw. draws is draws × constrained coordinates in constrained_names order, as BridgeStan's param_constrain returns them. predictor selects the term's linear predictor when the model has more than one such term.

  • term, predictor, group, coordinates — the term's label, linear predictor, grouping factor and coordinate fields.

  • frequency, period — per basis function, the angular frequency ω = √(Σ_a ω_a²) of the temporal basis and its period 2π / ω, in the time axis' unit.

  • range — draws × basis functions: each frequency's spatial range λ / (ρ ω).

  • resolution, resolved — the finest range the approximation resolves and, per draw and frequency, whether the range is at least that. While λ ≥ 2√(ln 100) · resolution, every unresolved frequency has less than 1/100 of the zero-frequency spectral amplitude.

  • distances, coherence — draws × basis functions × distances: the correlation exp(-d² / (2 r²)) of two levels at each distance d.

source
BayesianRegressionModels.brm_multigroup_field Function
julia
brm_multigroup_field(d::BRMDescriptor, draws, constrained_names;
                     times, coordinates, predictor=nothing) -> Array

The fitted multigroup term f(t, s) of a grouped HSGP with known level coordinates at every pair of times (a vector on the term's time axis) and locations: an array of draws × times × locations. coordinates gives the locations as the term takes its own, one vector per coordinate axis ((xs, ys) for multigroup((x, y))), or as a matrix with one row per location and one column per axis. At a fitted level's own coordinates this is that level's fitted series; at any other location it is the term's prediction there from the same draws (a neighbour prediction for a held-out level). draws and constrained_names are as for brm_multigroup_coherence.

source
BayesianRegressionModels.car Function
julia
car(area; edges=(from, to), type=:icar | :bym2)

Areal spatial effect over an adjacency graph. area is the grouping column of the rows; edges names two equal-length data vectors whose k-th entries are the labels (values of area) of two neighbouring areas. Each undirected pair is listed once; self-loops, repeated pairs and missing labels are refused. The graph's nodes are every label in edges and in area, so an area without rows keeps its place in the graph, and an area without neighbours is an island.

type=:icar emits sigma * phi[area], where phi carries the intrinsic CAR prior -1/2 * sum((phi[i] - phi[j])^2) over the edges plus a soft sum-to-zero per connected component of at least two areas; islands get no spatial effect. type=:bym2 emits the Riebler et al. (2016) convolution sigma * (sqrt(rho / s) * phi + sqrt(1 - rho) * theta)[area] with independent standard-normal theta, the mixing share rho in [0, 1], and s the scaling factor of each component (the geometric mean of the diagonal of the generalized inverse of its ICAR precision), computed from the graph at preparation; an island's effect is sigma * theta (Freni-Sterrantino et al. 2018).

It is a direct predictor summand: the formula intercept carries the level and no population coefficient multiplies it. sd(lp, car(area)) addresses sigma (default half-Normal(0, 1)), mixing(lp, car(area)) the BYM2 rho (default Beta(0.5, 0.5)). On replay the graph is frozen from the fit and every row must name a fitted area. Dispatch tag — see _sb_car_icar / _sb_car_bym2.

source
BayesianRegressionModels.cdar Function
julia
cdar(step; by=group, cor=C)
cdar(step; by=group)

Grouped, correlated, stationary AR(1) deviation marker. For every level g of the by group column and every distinct value w of the step column (sorted, shared by every level), the StanBlocks backend emits

delta[:, 1] = sigma * L * eta[:, 1], delta[:, w] = rho * delta[:, w-1] + sigma * sqrt(1 - rho^2) * L * eta[:, w],

with L L' = C the Cholesky factor of the group correlation (or covariance) matrix C — a P × P matrix given as a data field or a literal, P the number of group levels — 0 <= rho <= 1, sigma > 0, and standardized innovations eta. Every level starts at its stationary law, so sigma * sqrt(C[g, g]) is the marginal SD of each deviation and sigma * sqrt(1 - rho^2) scales the innovations. Without cor (or with cor = I, a data field holding LinearAlgebra.I) the levels are independent, the C = I walk with no P × P matrix (_sb_cdar_iid), so its data and its cost are linear in the number of levels. Each row contributes delta[group(row), step(row)] directly, with no additional population coefficient, and a level-step without rows is a latent state on the grid. sd(lp, cdar(step)) addresses sigma and ar(lp, cdar(step)) addresses rho. On replay the group levels and C are frozen from the fit, and steps after the last fitted one are appended (a forecast): their innovations are drawn in generated quantities, so each level continues from its fitted state. A replay with resample_groups=[:<by column>] redraws the levels its rows name, also levels the fit did not see, given the fitted levels it does not name (C over the union of levels comes from the replay data; independent levels read none); see reprocess. Dispatch tag — see _sb_cdar and _sb_cdar_iid.

source
BayesianRegressionModels.dar Function
julia
dar(time; p=1)

Differenced-autoregressive trajectory marker. The StanBlocks backend emits the weekly path

x[1] = 0, d[t] = beta * d[t-1] + sigma * z[t], x[t+1] = x[t] + d[t],

with 0 <= beta <= 1, sigma > 0, and standardized innovations z. It is a direct predictor summand, so a formula intercept supplies the initial level and no additional population coefficient multiplies the path. The time values must be finite and strictly increasing. Only p=1 is supported. Dispatch tag — see _sb_dar1.

source
BayesianRegressionModels.gmrf Function
julia
gmrf((east, north), time[, channel]; mesh=(vertices=xy, cells=triangles),
     spatial=:matern, temporal=:ou, cor=Omega)

A space-time Gaussian Markov field on a supplied triangular mesh. xy has two columns in projected physical coordinates; each row of triangles has three vertex indices. An observation reads the piecewise-linear interpolation of three vertices at its time and channel. All distinct observation times form the state grid. Elapsed times retain their physical units, including gaps.

The spatial law is the mass-lumped finite-element Matérn with smoothness ν=1 and κ=√2/ℓ_space, with natural Neumann boundaries. Its amplitude is the continuum marginal SD; finite-mesh variances, especially near boundaries, need not equal that amplitude. Time has stationary OU correlation exp(-abs(t-s)/ℓ_time). The optionalchannelcolumn usescor, a known correlation matrix or a declaredLKJCholeskyfactor in fitted channel order. Omittingcoruses independent channels. Use@plate for independent fields.

sd(lp, gmrf((east, north), time)) addresses the amplitude; length_scale(lp, gmrf((east, north), time), space) and the corresponding time component address the two lengths. Each defaults to LogNormal(0, 1) in the coordinates' units. Include the channel argument in an address when present. The term adds its field directly, without a population coefficient. Frozen replay retains the mesh, times and channels, and can evaluate new spatial locations inside that mesh. New state times or channels require a conditional prediction law and are refused by frozen replay.

gmrf((east, north), time[, channel]; neighbors=m, cor=Omega)

The same covariance without a mesh: a nearest-neighbour (Vecchia) sparse precision whose state is one coordinate per channel at each distinct (east, north, time) the rows read, so its size follows the data rather than vertices × times. A state conditions on its m nearest lower-order positions read at its own time, the previous read of its own position and of each of those, and, when its own position was not read at the previous read time, its m nearest among the latest earlier reads, reaching back until they hold at least m. The spatial correlation is the continuum M₁(κ r) = κ r K₁(κ r), so there is no mesh boundary or resolution effect; the approximation is the conditioning set, which leaves the time factor exact on positions read at the same times. On irregular read support, the joint temporal covariance is approximate too. Frozen replay reads only fitted (position, time) pairs.

gmrf((east, north), time[, channel]; multiresolution=m, cor=Omega)

A sparse spatial basis of shared stationary OU paths. The spatial basis uses Matérn-1 nearest-neighbour conditionals in a deterministic maximin order and retains at most 1 + m * (1 + floor(log2(P))) inverse-factor entries per position. The same normalized coefficients read every time, so temporal covariance is exactly exp(-abs(t-t′)/ℓ_t) on irregular support, marginal SD is exactly σ, and channel covariance is Ω. Spatial covariance remains an approximation; measure its error on the read support. Larger m does not guarantee monotonically smaller pointwise error.

Each innovation keeps only the union of its readers' times, without completing the position × time grid. Frozen replay retains these innovation identities and accepts fitted (position, time, channel) reads only. Both read-support forms are model-scope fields, support RKBRMI and SBBRMI, and accept integer m from 1 through 100, written as a literal or held by a scalar data field or name = constant(expr) (neighbors = nb): the count sizes the fitted support only, so models that differ in it build one Stan program and emit one RK program, and a frozen replay refuses data holding another count. Select exactly one of mesh=, neighbors=, and multiresolution=. Hyperparameter addresses and priors are the same for all three forms.

source
BayesianRegressionModels.gp Function
julia
gp(x...; cov=:exp_quad, iso=true, jitter=1e-9)
gp(x; cov=:periodic, period, jitter=1e-9)

Exact latent Gaussian-process predictor for the StanBlocks backend. Accepts one-or-more real-valued axes, with an isotropic squared-exponential kernel by default; set iso=false for one length scale per axis. cov=:periodic selects Stan's periodic kernel sigma^2 exp(-2 sin^2(pi |x - x'| / period) / rho^2) over exactly one axis and requires the numeric formula constant period. jitter stabilizes the covariance Cholesky factor. Dispatch tag — lowering lives in _sb_gp / _sb_gp_aniso / _sb_gp_periodic (sbimpl).

source
BayesianRegressionModels.hsgp Function
julia
hsgp(x...; k=20, c=1.5, cov=:exp_quad, iso=true, by=nothing,
     domain=nothing, orthogonal_to=nothing)
hsgp(x; k=20, cov=:periodic, period)

Hilbert-space approximate Gaussian-process predictor. The StanBlocks backend supports variadic axes, per-axis k/c tuples, isotropic or anisotropic length scales, and optional group-specific basis weights via by=. For raw data axes, domain=(lower, upper) fixes the approximation interval instead of deriving it through c. A one-dimensional model-derived axis, such as the sampled x from log(x) ~ ..., requires that explicit domain and evaluates its basis inside Stan. orthogonal_to=:linear removes the intercept and current linear-x directions from a one-dimensional basis, so x + hsgp(x; ...) separates the linear slope from residual nonlinear shape. orthogonal_to=:intercept removes only the intercept direction, from a basis over any number of axes: every basis column is centered over the term's rows, so the term sums to zero over them and a level elsewhere in the model is not shared with the field. With by=g both projections are fitted per level: each group's basis is centered (and, for :linear, de-trended) over that group's own rows, so every group's field sums to zero over its rows. Both projections are fitted on the training rows and frozen on replay; neither combines with anchor=.

k, c, domain, period and anchor are numbers the model reads: a literal, or a data field holding the scalar or per-axis value (or name = constant(expr)), as hsgp(t; k = kk, c = cc) with kk and cc in the data. Models that differ only in them build one Stan program and emit one RK program (RKBRMI reads them as inputs); the basis has prod(k) functions. ReactiveKernelsPPL lowers that program once across them too, and across a moved fitted length-scale floor (ReactiveKernels snag rkppl-sized-vect-69604d32, from ReactiveKernelsPPL 0.1.108, which BRM's floor exceeds). A frozen replay keeps the fitted values and refuses data that holds others.

cov=:periodic selects the periodic-kernel approximation of Riutort-Mayol et al. (2023) over exactly one raw-data axis: k harmonics of 2pi / period give 2k cosine/sine basis functions whose spectral weights come from the kernel's modified-Bessel expansion. It needs no boundary factor, so c, domain, by, orthogonal_to, and iso=false are refused, and the numeric formula constant period is required. In formulas this method is used only as a dispatch tag.

source
BayesianRegressionModels.hsgp_boundary_check Function
julia
hsgp_boundary_check(d::BRMDescriptor, draws::AbstractMatrix, names;
                    predictor::Symbol, term::Symbol)

Post-fit verdict on whether a fitted hsgp term's length scale lives where the Hilbert-space approximation still represents the kernel. An HSGP over a domain of half-width L fitted on data extending to extent keeps a margin L - extent past the data; once posterior rho approaches that margin the prior covariance silently distorts (boundary eats edge-point variance), while the model still transpiles, samples, and returns finite draws. This check reports the distortion ratio per group and flags at 1.0 — it reports, never fails: a flagged term fitted fine, it just may not be the GP you asked for.

Returns (; predictor, term, n_groups, margin, floor, mean_rho, ratios, flagged, floor_binding):

  • margin — the fitted past-data margin (c-1)/c * L, from the frozen basis fit (for an auto-fitted domain L = c * extent, so this is exact);

  • mean_rho / ratios — per-group posterior-mean rho and mean_rho / margin (n_groups == 1 for a bare term, even a grouped one, whose hyper value is scalar-shared; one entry per group for a hyper-driven term, with rho reconstructed as exp(eta) from the hyper-LP coefficients, never sliced from a transformed parameter);

  • flagged — whether any ratio reaches 1.0;

  • floor_binding — per-group posterior probability the hyper value sits below the approximation-validity floor (mean(rho < floor)): structural 0.0 for a default-floor bare term, measured otherwise. In particular a hyper-driven term's sub-floor mass is likelihood-flat prior reported as posterior — this number says how much.

draws is draws × coordinates with names its constrained axis (the same orientation every resolver here takes); carriers resolve through brm_term_coordinates, so an unconditioned program (response column omitted) works with include_gq=true names exactly as a fit does.

v1 covers one-dimensional auto-fitted exp_quad terms, grouped or not, bare or hyper-driven. Periodic, multi-axis, anisotropic, model-derived-axis, and explicit-domain= terms refuse loudly: their boundary geometry needs its own margin rule, and a wrong margin here would be worse than none.

source
BayesianRegressionModels.hsgp_coordinate_draws Function
julia
hsgp_coordinate_draws(descriptor, constrained_draws, constrained_names;
                      predictor, term, centeredness=nothing,
                      basis_gradients=nothing)

Read one ungrouped squared-exponential HSGP from its descriptor, returning draws × basis matrices coordinates, sampled_coordinates, unit_weights, physical_weights, and log_scales, plus physical length_scales (draws × axes, or one column for an isotropic term, whose length scale every axis reads), marginal_sd, and sampled/display centeredness vectors. Input rows are draws. centeredness=nothing preserves the fitted coordinates; a scalar or per-basis vector transforms the SAME draws to u = s^c z. No new fit is run.

When provided, basis_gradients must be draws × basis gradients of the log density with respect to the sampled basis coordinates, at these same draws. The returned gradients are with respect to the displayed coordinates, holding hyperparameters fixed. This is not a transport of hyperparameter gradients or a warmup loss history. finite records representable displayed position/gradient pairs; non-finite values are never silently discarded.

WarmupHMC's finalized online draws are already in the original model frame: constrain those draws normally, and pass the learned centeredness only as the display transformation. Do not apply a second sampler back-transform.

source
BayesianRegressionModels.hsgp_population_curve Function
julia
hsgp_population_curve(d::BRMDescriptor, draws, constrained_names, grid;
                      predictor::Symbol, coefficient::Symbol,
                      term::Symbol)

Evaluate the population exposure contribution of one model-derived, one-dimensional hsgp(...; orthogonal_to=:linear) term on a fixed grid. The returned named tuple contains grid and three draws × grid matrices:

  • linear — the population coefficient contribution beta * grid;

  • hsgp — the residual nonlinear HSGP contribution;

  • total — linear + hsgp, the quantity consumers normally want.

draws must contain CONSTRAINED posterior draws as rows, in constrained_names order. The names must include transformed parameters: the sampled model-derived axis is required to reconstruct the fitted projection for each draw. With BridgeStan, obtain both with include_tp=true, include_gq=false.

The public addresses come from the formula. For mu ~ ... + x + hsgp(x; orthogonal_to=:linear, ...), use predictor=:mu, coefficient=:x, and term=:hsgp_x. Compiler-owned carrier names are resolved through the descriptor and never form part of this API.

The curve is population-only: it includes no intercept, other covariates, or group-specific random slopes. The grid must lie inside the fixed domain fitted by the model. Raw-data, grouped, multidimensional, non-orthogonal, and non-HSGP terms fail closed rather than returning a quantity with different semantics.

source
BayesianRegressionModels.hsgp_transform_draws Function
julia
hsgp_transform_draws(coordinates, log_scales; from=0.0, to, gradients=nothing)

Transform saved HSGP basis coordinates between centering frames without a model handle. Both matrices have draws × basis shape. from and to are scalar or per-basis centeredness values. Optional gradients are with respect to the input basis coordinates at fixed hyperparameters; returned gradients are with respect to the output coordinates. Returns coordinates, gradients, and a finite mask. This is a post-fit change of coordinates, not new sampling or loss fitting.

source
BayesianRegressionModels.multigroup Function
julia
multigroup(Omega, tau)

The frequency-dependent level correlation of a grouped HSGP, hsgp(x...; by = g, cor = multigroup(Omega, tau)). Each basis frequency ω correlates the levels of g by exp(-(ρ ω)² / 2 · D2) with the Gram distance D2 = 2 tau (1 - Omega): levels share their slow components more than their fast ones, and the lag-0 correlation of two levels is (1 + D2)^(-1/2) (one axis). Omega is an LKJCholesky declaration or a known correlation matrix, as for cor = Omega; tau is a declared positive scalar parameter or a positive constant. Formula-only: it is read by @brm and never called.

multigroup((x, y), lambda; k = 20, method = :hsgp, c = 1.5)
multigroup((x, y); k = 20, method = :hsgp, c = 1.5)

The same coherence over known level coordinates: D2 = |s_i - s_j|² / lambda², so frequency ω correlates two levels at distance d by exp(-d² / (2 r²)) with spatial range r = lambda / (ρ ω). One coordinate field per axis (one to three axes), each holding one value per level of g in the grouping's level order, as a known cor = C has one row per level. lambda is a declared positive scalar parameter or a positive constant, in the coordinates' unit; left out, the term declares its own (see below). Each frequency's correlation is approximated with k functions per axis, rescaled to a unit diagonal, so the cost grows linearly in the number of levels: method = :hsgp (the default) uses a sine basis over a box of half-width √(L₀² + (3.2 r)²) with L₀ = c · half-extent (c = 1.5 by default); method = :inducing, meant for approximate-inference loops, places inducing points on a grid of spacing √(h₀² + (r / 1.5)²) with h₀ = extent / (k - 1) per axis.

The approximation resolves ranges down to r₀: the HSGP length-scale floor of the box L₀, or 1.25 base spacings h₀. A frequency whose range is below r₀ has ρ ω > lambda / r₀, so its spectral amplitude stays below 1/100 of the zero-frequency amplitude (the HSGP truncation tolerance) whenever lambda ≥ 2√(ln 100) r₀ ≈ 4.3 r₀; a larger k lowers r₀. With lambda left out, the term's own spatial scale has the prior LogNormal(log(E), 1), E the coordinates' largest extent, bounded below at 2√(ln 100) r₀. A declared lambda's prior is its author's: give it lower = ... at that bound, or raise k. brm_multigroup_coherence reports r₀ and which frequencies are resolved.

source
BayesianRegressionModels.rw Function
julia
rw(time)

Random-walk trajectory marker. The StanBlocks backend emits the path

x[1] = 0, x[t+1] = x[t] + sigma * z[t],

over the sorted distinct values of time — i.e. dar(time) with the differences' persistence fixed at zero — with sigma > 0 and standardized innovations z; each row reads the point of its own time value, so rows may share a time (several groups per day get one shared walk). It is a direct predictor summand: a formula intercept supplies the initial level and no additional population coefficient multiplies the path. sd(lp, rw(time)) addresses sigma; the term has no persistence, so ar(lp, rw(time)) is refused. On replay, times after the last fitted one are appended (a forecast): their innovations are drawn in generated quantities, so the walk continues from its fitted end. Dispatch tag — see _sb_rw1.

source
BayesianRegressionModels.select_hsgp_centeredness Function
julia
select_hsgp_centeredness(unit_weights, log_scales;
                         candidates=0:0.1:1,
                         underflow_log=log(floatmin(Float64)))

Choose one fixed partial-centering exponent per HSGP basis weight from a pilot fit. Rows are pilot draws and columns are basis frequencies. unit_weights contains the noncentered standard-normal coordinates and log_scales contains the corresponding log spectral standard deviations.

For candidate c, the loss is

log(std(unit_weights .* exp.(c .* log_scales))) - mean(c .* log_scales)

evaluated with a per-column exponent shift. A candidate is inadmissible when its centered coordinate scale would fall below underflow_log; importantly, the c=0 endpoint is evaluated without multiplying by log_scales, so it remains valid even when a physical high-frequency scale is -Inf.

The result is a named tuple with centeredness, the candidate losses, an admissible mask, and the normalized candidates. This is an offline pilot-then-refit rule. It does not update geometry during warmup.

source

Exported for backends (not a user API) ​

These names are exported so the StanBlocks and ReactiveKernels backends can reach them; they will be un-exported in a separate source change.

BayesianRegressionModels._brm Method
julia
_brm(formula::Union{Expr,AbstractString}; df=nothing) -> Expr

The macro-free entry point behind @brm. Parses a formula block and returns either a function definition (df=nothing, default) or a let-wrapped BRMI construction (df supplied): code that the macro compiles where it is written. To build a model from a runtime Expr without evaluating code, use brm.

source
BayesianRegressionModels._rk_callable_source! Method
julia
_rk_callable_source!(definitions, bindings, entry, f)

Source provider for an exact ordinary callable identity used by an emitted expression, including calls nested inside an anonymous kernel. Return nothing to keep the existing callable binding. To claim it, append an ordinary Julia function entry(...) ... end or an explicit ReactiveKernels.@kernel entry(...) = begin ... end compatible with the emitted call's inputs, optionally append helper definitions and separately named leaf bindings, and return a non-nothing value. The emitted entry replaces the original binding; existing call sites retain their arguments. Graph definitions may expose named plate/scan recipes; ordinary Julia functions do not make their internal loops visible to RK. Domain source may choose a new scientifically equivalent API rather than retain a historical argument count. Provider graph definitions precede their emitted reader/cell graphs; place helper graph definitions before entries that compose them.

entry is the callable's own name (nameof), made fresh with trailing underscores only where the emitted program already reads that name or the name has another fixed meaning in RK source: an export of Core, Base, Distributions or LogExpFunctions, RKPPL's built-in vocabulary, or an import of the emission module. Closures, anonymous functions and callable objects receive the generic brm_value_function.

The provider receives no values, lowered plan or derivative. It supplies its own native mathematics, evaluated in the build's own module with only the names _rk_observation_source! lists; bind any other function it calls as a separately named leaf. An entry cannot also be bound, and rebinding the original callable as its own leaf is refused. Providers sharing a helper may each append it: an equal definition (source locations aside) under one name is emitted once, at its first position, while different definitions under one name are refused. Extend with import BayesianRegressionModels: _rk_callable_source!.

source
BayesianRegressionModels._rk_submodel_rhs! Method
julia
_rk_submodel_rhs!(definitions, statements, data, bindings, target, f, rhs)

Native source extension for target ~ f(...) deterministic or statistical submodel bindings. Return non-nothing to claim the binding, or nothing to retain ordinary population-formula preparation. The caller owns all four mutable collections. rhs retains the original positional and keyword column references; parameter-dependent values must remain named source references.

Append ordinary @rkppl submodel definitions and/or ordinary Julia function definitions, then ordinary main statements producing target. A submodel is an assignment definition, written bare (name(args...) = begin ... end) or with its macro (ReactiveKernelsPPL.@rkppl name(args...) = begin ... end); both spellings emit the bare assignment, which evaluation applies @rkppl to. Explicit ReactiveKernels.@kernel graph definitions keep their macro. data holds preparation-only inputs, and bindings holds exact callable identities. All declarations, priors and observations must be visible in this source; the extension never receives a lowered PPL plan or derivative. An emitted entry owns its callable name: bind its existing leaf functions under separate names, or bind an existing entry without defining it again. The source is evaluated in the build's own module with only the names _rk_observation_source! lists, so a function any of it calls is bound the same way; an @rkppl body and main statements also read RKPPL's vocabulary by name. Defining and binding the same name is rejected before any definitions are evaluated. Hook calls sharing a helper may each append it: an equal definition (source locations aside) under one name is emitted once, while different definitions under one name are rejected. Extend this method with import BayesianRegressionModels: _rk_submodel_rhs!. Model-specific downstream mathematics stays in the downstream extension.

source
BayesianRegressionModels._sb_submodel_rhs! Method
julia
_sb_submodel_rhs!(stmts, data, target, f, rhs)

sbimpl extension hook. Override (e.g. in a downstream -ext.jl) to route target ~ f(...) where f is a known SLIC submodel family (a dose-response or time-course submodel, …) straight to target ~ <slic>(; kwargs), bypassing the population-linear-predictor wrap (which would otherwise multiply the submodel output by a fresh β).

Return anything non-nothing to claim the binding; return nothing to fall through to the default linear-predictor path. The default method (this one) returns nothing.

Use import BayesianRegressionModels: _sb_submodel_rhs! (not using) when adding methods from a downstream module so the binding is extended rather than shadowed.

Data keys and grouping columns. A hook may store and read data under any column's own name, including a column the same model uses as a ranef grouping factor (the g in (… | g), (… | ID | g), or gr(g, by=…)), in any formula order. BRM itself reads a grouping column only through the dense integer index it derives (g_idx, level count n_g; g__by__b_* for gr(g, by=b)), and drops the raw g from the Stan data only when no emitted statement reads it (_sb_settle_group_columns!). A statement that reads g while data[g] holds string labels is refused at build: store an integer coding under g, or read g_idx. The derived index names belong to BRM: if one already holds a different value when BRM writes it, the build is refused (_sb_set_group_index_datum!).

Replay. reprocess calls the hook again on the replay DataFrame and takes every data key it writes from that call, so a key the hook derives from the term's columns (a schedule, an index, a count) is re-derived for the new rows. Its vector columns come from the new DataFrame; a scalar keyword column keeps the fitted value unless freeze_constants=false. A value the hook computes from the data itself is re-computed, so a calibration that must keep its fitted value is a name = constant(expr) passed to the term as a keyword. On the replay the hook must emit the statements it emitted for the fit.

source
BayesianRegressionModels.brm_hsgp_multigroup_inducing_weights Method
julia
brm_hsgp_multigroup_inducing_weights(z, omega2, rho, coordinates, positions, lambda)

The coordinate coherence of multigroup((x, y), lambda; method = :inducing, inducing = (ux, uy)): the predictive process of free inducing positions (points × axes). Per frequency b, with range r_b = lambda / sqrt(sum_a rho_a^2 omega2[b, a]), level i's weight is a_i' z[:, b] / |a_i|, a_i = L \ k(s_i), with L the Cholesky factor of the positions' kernel (jitter 1e-8) and k(s_i) the kernel between the level and the positions, so the levels' correlation has a unit diagonal. z is points × frequencies standard normals. Each frequency costs a Cholesky factor of the points and levels × points² for the solves. StanBlocks' twin is the @stanonly deffun of the same name in src/sbimpl.jl; keep both in lockstep.

source
BayesianRegressionModels.brm_multigroup_coordinate_grid Function
julia
brm_multigroup_coordinate_grid(coordinates, k, method, c=1.5) -> (center, scale, r_min)

The data-derived geometry of multigroup(coordinates, lambda; k, method, c): per axis the midpoint of the coordinates and the approximation's base scale, and the resolution r_min every frequency's spatial range enters with: the range is √(r² + r_min²) for the exact kernel's range r. Hilbert space (method = 2, the formula default): the base box half-width c · extent / 2 and the HSGP length-scale floor of that box. Inducing points (method = 1): the base spacing extent / (k - 1) and 1.25 times the largest of them.

source
BayesianRegressionModels.brm_multigroup_inducing_resolution Method
julia
brm_multigroup_inducing_resolution(coordinates, n_points) -> r_min

The finest spatial range n_points free inducing positions are taken to resolve: that of a grid of as many points over the levels' extent, 1.25 spacings extent / (n_points^(1/D) - 1) of the longest axis.

source
BayesianRegressionModels.parse! Method
julia
parse!(x; info) -> Expr

Walk a formula expression once, classifying every bare Symbol into info.alllocals (as :nonlocal for data columns, :local for literal bindings, :maybelocal for response-side names that may or may not be observed). Returns the rewritten expression with ~/= statements lowered into @n/@x calls. Used internally by _brm.

source

The following internal definitions are linked from the exported docstrings.

BayesianRegressionModels._adaptive_cdar_centering_blocks Function
julia
_adaptive_cdar_centering_blocks(model, unc_names)

Resolve the compiled coordinates and frozen walk geometry for every cdar(step; by=group, cor=C) term in an SBBRMI or GenerativePlan.

This is the backend-internal companion to adaptive_centering_blocks, following the same descriptor-to-declaration route as _adaptive_hsgp_centering_blocks. Each of the P * W innovations is one scalar cell with zero location and its marginal prior spread sigma * sqrt(C[p, p] * (1 - rho^(2w)) / (1 - rho^2)); c=0 is the emitted eta frame. The marginal SD may be <lower=a> or <lower=a, upper=b> and the persistence any declared interval inside [0, 1] (an explicit Uniform(a, b) prior narrows either); the cells read both through Stan's own transform. The metadata is intentionally fail-closed: a persistence interval leaving [0, 1], a scale without a finite lower bound, a missing or misshapen frozen factor, and declaration/artifact coordinate drift all raise before a reparametrizer is built. A walk emitted in generated quantities (no observed likelihood reaches it) has no sampler coordinate and is skipped.

source
BayesianRegressionModels._adaptive_hsgp_centering_blocks Function
julia
_adaptive_hsgp_centering_blocks(model, unc_names)

Resolve the compiled coordinates and fixed spectral geometry for every ungrouped and grouped squared-exponential HSGP and every ungrouped periodic HSGP in an SBBRMI or GenerativePlan. A grouped term contributes one block per group level; all of them share the term's spectral scales, so each level's basis weights adapt as independent scalar cells around the same per-basis frame. A periodic term contributes one block whose harmonics carry the cosine/sine spectrum; its cells join the same HSGP pair order as squared-exponential cells. A grouped term whose levels are correlated (cor=) or scaled per level (a hyper-predictor) is resolved by _adaptive_hsgp_level_centering_blocks instead.

This is the backend-internal companion to adaptive_centering_blocks. It follows BRM's formula-term descriptor to declaration-owned parameter roles, then reads the declaration's compiler-owned spectral data binding (omega2 for squared-exponential terms, harmonics for periodic ones). It never parses generated Stan or assumes a global parameter order. A multi-axis squared-exponential term carries one length scale per axis (iso=false) or its single isotropic length scale, which every axis's frequencies read, as in the compiled spectrum. Length scales and marginal SDs may be <lower=a> or <lower=a, upper=b> (an explicit Uniform(a, b) prior); the cells read them through Stan's own transform. The metadata is intentionally fail-closed: unknown covariances, grouped periodic terms, a scale without a finite lower bound or with an offset/multiplier, and declaration/artifact coordinate drift raise before a reparametrizer is built. A term emitted in generated quantities (no observed likelihood reaches it) has no sampler coordinate and is skipped, like a generated random-effect block.

source
BayesianRegressionModels._adaptive_hsgp_level_centering_blocks Function
julia
_adaptive_hsgp_level_centering_blocks(model, unc_names)

Resolve every grouped squared-exponential HSGP whose levels are correlated (cor = Omega or a known correlation matrix) or scaled per level (a hyper-predictor on its sd or length_scale) in an SBBRMI or GenerativePlan: one _HSGPLevelAdaptiveCenteringBlock per term, read from the descriptor's term roles, the emitter's weight-block plan and the term declaration's compiler data (omega2, rho_lower, L_level), never from a parsed name. The companion of _adaptive_hsgp_centering_blocks, which resolves every other HSGP; together they cover each term exactly once. A term emitted in generated quantities is skipped, and a multigroup coherence, a non-zero compiled centeredness and declaration drift raise.

source
BayesianRegressionModels._s2z_fisher_raw Function
julia
_s2z_fisher_raw(infos, sd) -> Matrix

Per-(group, coefficient) RAW reliability in [0, 1] from one draw's expected observation information: the whitened projected posterior-vs-prior fraction clamp(1 - restricted[k,k] / (1 - 1/J)) BEFORE the interpolation-weight rescale. infos[j] is group j's M x M expected-information matrix and sd the M prior scales of that draw.

The offline selector aggregates THIS quantity per cell across draws (median or mean) and rescales once at the aggregated scale via _s2z_rescale_rho. brms instead rescales each draw at its own scale and then takes the median, which mixes the nonlinearity of the rescale with the draw-to-draw variation of the scale.

source
BayesianRegressionModels._s2z_rescale_rho Function
julia
_s2z_rescale_rho(raw, sd) -> Real

brms interpolation-weight chart: raw / (raw + (1 - raw) * sd). Applied once to aggregated raw reliability at the posterior-median scale, not per draw.

source