PPL API
Exported interfaces are grouped by kind. The entries below come from the revision used to build this site.
Types
ReactiveKernelsPPL.ArrayParameter Type
ArrayParameter(name, family, args, dims, support_override, label)One declared array-valued parameter: a plain value the model reads by name (z, z[g], z[1], B * w, L[2, 1]), never a hidden coefficient block. Two kinds of family:
An elementwise family (any
SAMPLED_ARITYkey): the surfacez[1:K] .~ Normal.(mu, s)— independent draws per element, with Distributions.jlNormal.(…)broadcast semantics.argsuse positional keys(arg1, …); each is a Real literal, a Symbol (a scalar parameter/assignment name, an array parameter, a data column, a derived column, or a vector-valued assignment — read per element), a literal vector (Expr(:vect, …), per element), or a value expression (per element).support_overridefollowsSampledParameter(HalfNormal.(s)is:normal+:positive).:lkj_cholesky—L ~ LKJCholesky(K, eta): the lower-triangular Cholesky factor of a K×K correlation matrix (Distributions.jlLKJCholesky(K, eta)density,uplo = 'L').args = (arg1 = eta,), a finite positive literal;dimsis[K, K].A multivariate slice family
<stem>_<slices>(mv_slices.jl):eachrow(B[a, b]) .~ D(_rows),eachcol(B[a, b]) .~ D(_cols) orb[ax] ~ D(_vector) — every slice of the array one draw of the multivariateD. Stems:mvnormal_cholesky(args = (arg1 = mean, arg2 = factor)),mvnormal((arg1 = mean, arg2 = covariance)),dirichlet((arg1 = concentration,), rows/cols only) andordered_normal((arg1 = m, arg2 = s, arg3 = K)forOrdered(Normal(m, s), K), rows/cols only). A vector argument is a shared value or a per-slice:(eachrow(M))/:(eachcol(M))expression; matrices and scalars are shared. Multivariate normal slices are centered (the entries are the coordinates); simplex and ordered slices constrain along each slice.
A phi ~ Dirichlet(alpha) simplex is not an array parameter: it stays a VectorParameter, which definitions already read as a model-level value (phi[1], cumsum(phi), a gather cum[c]).
dims holds one entry per array axis, each either a literal Int (from 1:K) or the surface sizing expression, resolved against bound data: :(levels(g)) (the sorted distinct values of grouping column g; reading z[g] then looks each observation's value up on that axis), :(length(levels(g)) - k) (from 1:length(levels(g)) - k: a positional axis of that many elements, k a literal ≥ 0, bare length(levels(g)) for 0), :(axes(M, d)) or :(size(M, d)) (axis d of a bound matrix or a design matrix M). Arrays have one or two axes.
ReactiveKernelsPPL.AssignmentSpec Type
AssignmentSpec(name, expr)One scalar temporary (slice 1): expr may reference scalar names and whole-column reductions only. Row-varying (elementwise) assignments fail closed emitter-side with "precompute the column". A bare Symbol aliases another scalar name; a bare Real is a folded literal.
ReactiveKernelsPPL.CellBatch Type
A callback-scoped packed point; construct with with_cell_batch.
ReactiveKernelsPPL.CellFactorQuery Type
Scalar outer or summand query; construct with prepare_cell_factor_query.
ReactiveKernelsPPL.CellQuery Type
CellQueryThe log density of one cell of the plates that observe the selected observations: for an @plate for i in … loop, the densities its iteration i observes; for an elementwise observation (y .~ …), the density of entry i. Construct with prepare_cell_query and call q(u, i). The call paths carry the Base.invokelatest barrier, as SamplerQuery's do. Not thread-safe: prepare one per thread.
ReactiveKernelsPPL.CellSampler Type
CellSamplerA CellQuery with its prepare_ad gradient over the packed unconstrained vector. Construct with prepare_cell_sampler; use cell_value_and_gradient!. Not thread-safe: prepare one per thread.
ReactiveKernelsPPL.ColumnRef Type
Reference to a raw data column: a key into StructuralPlan.columns.
ReactiveKernelsPPL.CompactCellAD Type
CompactCellADA prepared ReactiveKernels derivative operator over one cell's log density, active over selected packed coordinates: the boundary of prepare_compact_cell_sampler. Construct one with prepare_compact_cell_ad. The ReactiveKernels derivative calls accept it in place of the prepared operator, with base, active, indices, cell (as cell_value_and_gradient! takes them) in place of the operator's point: ad_gradient_and_hvp(q, tangents, base, active, indices, cell), ad_gradient_hvp_and_third(q, tangents, base, active, indices, cell) and the other verbs QueryAD takes. Directions, gradients and results are over the selection, in indices order. base and indices are read only. Each call carries the Base.invokelatest barrier. Not thread-safe (one per caller).
ReactiveKernelsPPL.CompactCellSampler Type
CompactCellSamplerA prepared cell gradient over selected packed coordinates. The packed base point is read-only, and the derivative is returned only in the order of indices. The sampler keeps the current selection as a map over every packed coordinate, rewritten when a call selects different positions. Prepare one sampler per concurrent caller.
ReactiveKernelsPPL.ContractValidationError Type
ContractValidationError <: ExceptionThrown by validate_plan when a structural plan violates the slice-1 input contract. Loud, never silent: every message names the offending node label for BRM-side attribution.
ReactiveKernelsPPL.DensityFactor Type
An authored atomic density event, identified by kind, site and one-based entry.
sourceReactiveKernelsPPL.DensityFactors Type
A binding-scoped catalogue of authored prior and coordinate-Jacobian factors.
sourceReactiveKernelsPPL.DesignBlock Type
DesignBlock(kind, column, addressee, width, labels, levels, elements)One term's design contribution. labels are coefficient labels in column order (:Intercept for intercepts, the column name for continuous and monotonic terms, col_level over mapped levels for factors, empty for offsets and beta-free summands). levels is meaningful for factors only (the map's evaluated values). column is the data column except for spline/hsgp summands (the basis id), monotonic blocks (the increments key naming the contrast recipe), and matrix blocks (the matrix name). elements is meaningful for matrix blocks only (the matrix columns in order, nothing at intercept positions — per-element prior addresses and intercept flags for consumers that fan out). axis is meaningful for factors only: the data-only graph expression of the map's labels (_axis_labels_expr), which the contrast reads instead of a literal.
ReactiveKernelsPPL.DesignMatrix Type
DesignMatrix(name, columns, label)One user-bound design matrix (X = hcat(ones(length(x1)), x1, x2)): columns in hcat order, nothing marking intercept-ones positions. Data/derived columns only (length-n by bind/construction); latent, scan, parameter, and nested-matrix names are rejected — the SB me mirror stays affine and nested hcat stays a follow-up. The generator emits each matrix once (X = Float64.(hcat(...))); MatrixTerms reference it by name and splice X * view(coef, ...) matvecs. Width is static (length(columns)); the surface sizes coefficient vectors from it.
A matrix no matrix term and no GLM response reads is a VALUE matrix (the program reads X as a matrix: var.(eachcol(X)), X * v over an array): bind_data builds it from its data columns and binds it under its name, so every reader sees a bound data matrix (_value_design_matrix_names).
ReactiveKernelsPPL.DesignShape Type
Full design shape of one predictor: ordered blocks + total width.
sourceReactiveKernelsPPL.DiscreteLatentQuery Type
DiscreteLatentQueryA prepared query of the posteriors of a program's summed-out discrete latents (prepare_discrete_latents). q(u) returns them at the parameters u; discrete_latent_draws draws the latents. Not thread-safe: prepare one per thread.
ReactiveKernelsPPL.FactorSelection Type
A set of authored atomic events from one density catalogue.
sourceReactiveKernelsPPL.FrozenValues Type
FrozenValues(values::NamedTuple, inputs::NamedTuple)Data-only definitions frozen by value: what frozen_values reads from a binding and bind_data's frozen keyword binds in place of evaluating them. values holds each definition's value. inputs describes each data input those definitions read, as (type, size): the type the program declares for it (Vector{Float64}, Float64, …) and its size, never its values. A binding that leaves such an input out binds it absent with that type and size, so the program is the one a binding with the input generates.
ReactiveKernelsPPL.JoinedWindows Type
JoinedWindowsWindows of one recurrence joined through their boundary state, from prepare_joined_windows. Evaluate with joined_value_and_gradient! or call it on a joined point; its coordinates are joined_coordinates. Not thread-safe: prepare one per thread, as for SamplerQuery.
ReactiveKernelsPPL.JoinedWindowsProblem Type
JoinedWindowsProblemJoinedWindows as a log density over its joined coordinates. With LogDensityProblems loaded it implements dimension, capabilities (first order), logdensity and logdensity_and_gradient. Not thread-safe. Like SamplerQuery, it answers -Inf (gradient NaN) where a numerical method cannot evaluate the model (ReactiveKernels.NumericalFailure).
ReactiveKernelsPPL.LayoutEntry Type
One packed slice: a coefficient block, a scalar latent, a scan vector latent, a per-cell latent block, a leveled vector latent (cutpoints, thresholds, simplex), a joint-outcomes LKJ Cholesky factor, or an elementwise array parameter (:array, column-major over dims). lo is the constrained lower bound of an :interval/:floored transform (:interval also sets hi; an :upper transform sets hi only; NaN otherwise). A real bound is stored as Float64, or in the number type of the sampled values it was resolved from (an AD dual while differentiating constrain). An elementwise array's bound may instead be an array of its declared shape, one bound per element (elementwise). dims is the axes of a declared array, including an LKJ factor (empty for legacy scalar/block entries).
ReactiveKernelsPPL.LayoutTable Type
Packed unconstrained layout: ordered entries + total dimension.
sourceReactiveKernelsPPL.LevelMap Type
LevelMap(predictor, column, values, source, subset)Ordered level values sizing one full-rank factor term: values is the coefficient position↔level mapping (binder-evaluated from the grouping column, [] pre-bind). source is the levels function (:levels only). subset selects from DataAPI.levels(column): : (full cover), a literal UnitRange{Int}, a literal Vector{Int} of positions, or (lo, :end). Keyed by (predictor, column) — one map per factor term.
ReactiveKernelsPPL.LikelihoodFamily Type
Slice-1 likelihood families (D3 narrow slice), plus the leveled slice-2 families (categorical / ordinal / multinomial): reference-coded multi-logit categorical, cumulative-logit ordinal with ordered cutpoints, general typed ordinal (2 structures × 3 links), shared-simplex multinomial over a count matrix, plain categorical over simplex probabilities, the joint correlated-outcomes family (per-row MvNormal over a Cholesky factor), and the finite-mixture family (per-row log-sum-exp over K same-family univariate components, SB MixtureModel mirror).
ReactiveKernelsPPL.LikelihoodSpec Type
LikelihoodSpec(family, link, response, predictor, scale, weights, evidence, label[, trials[, range]])One independent response. scale is the response's auxiliary — Gaussian sigma, NB2 dispersion phi, Gamma shape alpha, hurdle p_zero, InverseGaussian shape lambda, BetaBinomial2 precision phi, VonMises concentration kappa, NB1 success probability p, LogNormal scale sigma, Weibull shape k — either scalar (parameter, assignment, folded literal, or a raw per-observation data column) or a ScalePredictorRef. The latter includes LogNormal sigma and Weibull k. Probability auxiliaries (hurdle p_zero and NB1 p) take values in [0, 1]; other scale/shape auxiliaries take positive values. The link need not guarantee support: the density checks the evaluated value. (One slot covers every admitted family; a two-auxiliary family such as Beta needs a new field — noted, not built.) nu is the StudentT degrees of freedom, nothing otherwise: a sampled parameter/assignment name, a bound data name, a finite-positive literal, or a ScalePredictorRef (predictor-fed per-observation nu — the scale-slot mechanism, with its own _ppl_sc_<label>_nu node so scale and nu predictors coexist). zi is the ZIP/ZIB zero-inflation probability and accepts the same value forms. Fixed nu data must be finite positive reals; fixed zi data must be finite reals in [0, 1]. A value is fixed when it reads no sampled name, as a column, a computed argument or a definition, and binding checks the rows the response observes. Model-valued inputs use the lazy density guard. weights is a frequency/power-objective column (D1); analytic/precision weights fail closed emitter-side. trials is the Binomial/BetaBinomial2 trial count (Int column or Int literal), nothing otherwise. range carries a literal y[1:N] range, or the indexed response expression for eachindex, axes and : selections, including positive literal trailing indices. nothing means the whole column. Literal one-dimensional ranges retain their full-cover check; indexed expressions select the stated response cells. An explicit indexed observation loop also selects its row operands before evaluating the retained cell; a top-level slice uses ordinary broadcasting.
Leveled families (categorical / ordinal / multinomial) use the trailing fields, built with keywords (n_levels=, thresholds=, extra_predictors=, count_columns=, ordinal_structure=, discrimination=, threshold_columns=); every other family leaves them at their defaults:
n_levels: category count K (nothing= infer at bind: from the response column for OrderedLogistic/Ordinal/Categorical, structurally — 1 + predictor count — for CategoricalLogit, structurally — column count — for Multinomial). A CategoricalLogit overlogit_sliceskeepsnothing: its K is the slice length + 1 at run time.thresholds: shared ordered/vector parameter (VectorParameter), shared data vector, orThresholdRowsfor vectors broadcast per observation for OrderedLogistic/Ordinal;nothingotherwise.extra_predictors: CategoricalLogit non-reference predictors afterpredictor(class order 2..K is[predictor; extra_predictors...], K−1 total); empty otherwise.logit_slices::rowsor:colsfor a CategoricalLogit response over the slices of one logit matrix (y .~ CategoricalLogit.(eachrow(E))oreachcol(E)),nothingotherwise.predictorthen names the matrix valueE, which the response reads whole (the GLM-object precedent): noPredictorSpec, noextra_predictors, and non_levels. Each slice holds observationi's K−1 non-reference logits, with class 1 the zero reference, so K is the slice length + 1 at run time.count_columns: Multinomial count columns afterresponse(category order 1..K is[response; count_columns...]); empty otherwise.ordinal_structure::cumulative/:stoppingfor OrdinalFam,nothingotherwise.discrimination: OrdinalFam positive latent scale (nothing= 1.0),nothingotherwise: a positive Real literal, a finite-positive data column, a legacy predictor name, or aScalePredictorRefwhose link belongs to this discrimination use. Modeled values have finite-positive support checked by a lazy likelihood guard.threshold_columns: OrdinalFam per-threshold design columns (StoppingRatio only), empty otherwise.threshold_coefs: the (K−1)×p threshold-coefficient matrix packed as a:vector_normalVectorParameter(required exactly whenthreshold_columnsis non-empty),nothingotherwise. Stage-major: stage j occupies entries(j−1)*p+1 .. j*p.threshold_effects: an ordinary N×(K−1) matrix value for stopping-ratio responses, subtracted fromthresholds[j] - eta[i]before discrimination. It replaces, and cannot accompany, the legacy threshold design fields.
Multinomial/Categorical responses name their shared-simplex VectorParameter in predictor (no linear predictor — the scan-state precedent). A Gaussian-identity response may likewise name a PlateParameter in predictor: a latent-mean observation (x_obs ~ Normal(x_true, sd) with scalar constant sd — the SB me mirror).
Joint correlated-outcomes responses (MvNormalCholeskyFam, SB [y1..yK] ~ MvNormalCholesky([mu1..muK], L)) use the trailing joint fields, built with keywords (extra_responses=, factor_scales=, factor_corr=); every other family leaves them at their defaults:
extra_responses: joint outcome columns afterresponse(outcome order 1..K is[response; extra_responses...], K ≥ 1); empty otherwise. Each outcome's mean is an identity-link linear predictor:predictorfor outcome 1,extra_predictors(reused from the CategoricalLogit shape) for outcomes 2..K.factor_scales: the joint factor's positive scale vector (VectorParameter, K scales),nothingotherwise.factor_corr: the joint factor's LKJ Cholesky factor (VectorParameter, K×K),nothingotherwise.
Joint widths are structural (K = 1 + length(extra_responses)): no n_levels, no bind-time size inference — the factor parameters carry concrete sizes validated against K.
GLM-object responses (NormalIDGLMFam, BernoulliLogitGLMFam, PoissonLogGLMFam) name their design matrix in predictor (no linear predictor — the object owns eta, the Multinomial/Categorical scan-state precedent): an intercept-free DesignMatrix, or any matrix value (bound data, a definition) the object reads whole. They carry the split coefficients in the trailing glm_alpha/glm_beta fields, built with keywords; every other family leaves them at their defaults:
glm_alpha: the scalar intercept — a value's name or a number (the generator prepends the ones column andalpha; a literal zero prepends nothing) —nothingotherwise.glm_beta: the coefficient vector's name (one element per matrix column),nothingotherwise. A declared array or any other value carries its own prior; otherwise the plan's population priors address each design-matrix column by the response label (_glm_coefficient_block).
Finite-mixture responses (MixtureFam, SB y ~ MixtureModel(comps, w) mirror) carry K same-family univariate components in the trailing mixture fields, built with keywords; every other family leaves them at their defaults:
mixture_family: the shared component family (v1: Gaussian/identity, Bernoulli-logit, Poisson-log, Binomial-logit, NB2-log, Gamma-log, Beta-logit),nothingotherwise.mixture_locs: per-component location uses, length K (K ≥ 1): each a predictor name (link-space, inverted per the component link), a sampled scalar parameter name, or a numeric literal (both constrained-scale, no inversion). Empty otherwise.mixture_scales: per-component scale uses, length K: each the component'sscale-slot use (nothing, parameter/assignment name, literal, per-observation column, orScalePredictorRef) — required exactly when the component family takes a scale auxiliary. Empty otherwise.mixture_weights: the length-K mixing weights: a literalVector{Float64}(finite, nonnegative, sums to 1), a shared bound numeric vector, a:simplex_dirichletVectorParametername, or aMixtureComplementWeightspair (K == 2), orMixtureWeightRowsnaming an ordinary value with one probability vector per observation;nothingotherwise.mixture_trials: one trial-count column or literal per Binomial component when their arguments differ. Empty whentrialssupplies the shared argument.mixture_components: lowered constructor graphs for heterogeneous full-real components. Each carries its own argument list; the legacy family/location/ scale slots remain empty on this route.
predictor is an anchor only (first location predictor, else first scale predictor, else the weights simplex name, else the first location/scale parameter name, else the response name); scale is nothing. Mixture widths are structural (the number of component graphs or location slots): no n_levels, no bind-time size inference. Binomial components may have distinct trial counts. Case-A mi() missingness (SB parity, log density only) names its observed-row index column in the trailing mi_jobs field, built with keywords (mi_jobs=); every other response leaves it at nothing:
mi_jobs: theJobscolumn (sorted-ascending uniqueIntrow indices, a nonempty selection on the response's full observation axis). The response, every Multinomial count column and every joint outcome cross PACKED (aligned withJobs); they ride the managed-columns exemption. Vector predictors and trials gather by full-rowJobs; shared probabilities and covariance factors stay whole. GLM objects select full design rows before constructing eta. Only observed rows contribute, with no missing response latent (SB keepsy_misin generated quantities here). Scalar observation families compose with weights, evidence, ranges and trials. A range filters Jobs on the full axis and the same packed outcome positions; Case-B downstream merged-response uses fail closed emitter-side.
VonMises responses (VonMisesFam, SB brm_von_mises mirror) carry the principal-interval endpoints in the trailing interval field, built with keywords (interval=); every other family leaves it at nothing:
interval:nothingfor exactVonMises(moving inclusive support[mu - pi, mu + pi]), or the(lo, hi)literal pair forCircularVonMises(fixed half-open support[lo, hi), finite withlo < hiand width exactly2pi— the BRM_brm_circular_intervalrule). The generator wraps mu into[lo, hi)per cell and guardsyto the support, exactly the SB branch structure.
ReactiveKernelsPPL.LogDensity Type
LogDensity(f, args...)Convenience sampling RHS whose density is f(value, args...). Observed use requires no geometry or random generator. Parameter use also needs a sampling_geometry method, as for any other external RHS. When f names a module-visible function-shaped KernelSpec (including an extracted object endpoint), lowering emits its direct call, so the numerical graph composes inside the density's observation plate. Ordinary Julia callables retain the numerical callback path.
ReactiveKernelsPPL.MixtureComplementWeights Type
MixtureComplementWeights(param, param_first)2-component mixture weights from one :unit-support sampled parameter ([s, 1-s] when param_first, [1-s, s] otherwise): the collapsed Beta-weight shape. The complement sums to 1 by construction, so no simplex validation applies; the generator threads the constrained scalar and logs each arm directly.
ReactiveKernelsPPL.ParamName Type
Reference to a sampled parameter or scalar assignment by name.
sourceReactiveKernelsPPL.ParameterGeometry Type
ParameterGeometry(shape, unconstrained; support, constrain, unconstrain,
logjac, coordinate_names=nothing)Caller-owned parameter geometry. shape is the constrained shape (empty for a scalar); unconstrained is the packed dimension, independently of that shape. They may contain data-only Julia expressions, evaluated when binding data, never by evaluating sampled values. support describes the support; the density and inverse must enforce it. Endpoints are ordinary pure Julia callables: constrain(u, shape, args...), unconstrain(value, shape, args...) and logjac(u, shape, args...). The first returns the constrained value, the second a packed vector, and the third the log absolute Jacobian. Host and kernel execution call these same endpoints. coordinate_names, when supplied, has one Symbol per packed coordinate. Draw generation is outside this contract.
Endpoints may also be function-shaped @kernel graphs. The descriptor prepares their host callables once; generated transforms compose the graph when every argument is explicitly supplied (including keywords). Thus supported row operations retain their locality and actual coordinate dependencies. Calls with omitted defaults or splatted arguments retain the prepared numerical path, as do ordinary Julia callbacks. A local transform does not factorize its density.
ReactiveKernelsPPL.PartitionSampler Type
PartitionSamplerA PartitionQuery with its prepare_ad gradient: compact, over each partition's footprint (the packed coordinates it reads), or dense over the whole packed vector. Construct with prepare_partition_sampler; use partition_value_and_gradient!, partition_batch_value_and_gradient! and partition_footprint. Not thread-safe: prepare one per thread.
ReactiveKernelsPPL.PlateParameter Type
PlateParameter(name, family, args, support_override, range, label)One per-cell latent parameter VECTOR (@plate sampling statement, e.g. theta ~ Normal(mu, tau)): size independent draws from family, one per plate cell, packed as one contiguous block. family/args/support_override follow SampledParameter exactly (POSITIONAL (arg1, …) keys, Distributions.jl semantics). Arguments may be shared scalars or per-cell data/derived columns. range is the plate's index set: the Symbol of the column v of an eachindex(v) / axes(v, 1) plate (one cell per entry of bound or defined v), a literal UnitRange{Int} defining its own cells (the 1:N case), or nothing (the consuming response establishes the axis in hand-built plans). A real-support prior (normal/cauchy/half-versions) lays out identity (an unconstrained block); positive/unit support constrains per element.
ReactiveKernelsPPL.PlateParameter Method
Provenance/range default to the consuming response's axis under the name.
sourceReactiveKernelsPPL.PopulationPrior Type
PopulationPrior(predictor, addressee, location, scale)
PopulationPrior(predictor, addressee, family, location, scale[, nu])Per-addressee population prior addressed by (predictor, column|:Intercept). family is one of POPULATION_FAMILIES (:flat contributes 0.0 — StanBlocks flat-token parity — and ignores location/scale/nu); nu is the StudentT degrees of freedom (NaN otherwise, always a literal). A factor source column address applies one shared prior across its full-rank level block (one coefficient per mapped level); a matrix broadcast applies one shared family with per-element locations/scales. location/scale are literals or sampled-hyperparameter names (the centered-hierarchical shape: validation pins a scalar sampled parameter or scalar assignment for a location, a positive-support sampled parameter for a scale). The 4-arg form is Normal. The emitter fills Normal(0,1) defaults so coverage is complete by construction — except factor coefficients, whose broadcast prior also sizes the block and is therefore required, never defaulted.
ReactiveKernelsPPL.PredictiveLaws Type
PredictiveLawsThe laws of one response's entries, shaped like the response (predictive_laws). Indexing builds that entry's Distributions.jl law from the arguments the graph computed; nothing is stored per entry.
ReactiveKernelsPPL.PredictiveQuery Type
PredictiveQueryA prepared posterior-predictive query (prepare_predictive). Call it as q(u, rng) for one draw of every observation at the parameters u, or use predictive_draws! and predictive_laws. Not thread-safe: prepare one per thread.
ReactiveKernelsPPL.PredictorSpec Type
One named linear predictor: additive terms over raw columns.
sourceReactiveKernelsPPL.QueryAD Type
QueryADA prepared ReactiveKernels derivative operator over one query of a built program, plus the program's LayoutTable. Construct one with prepare_query_ad. The ReactiveKernels derivative calls accept it in place of the prepared operator, with the unconstrained vector as the one argument: ad_gradient(q, u), ad_value_and_gradient!(q, g, u), ad_pullback(q, seed, u), ad_pushforward(q, tangents, u), ad_hvp(q, tangents, u), ad_gradient_and_hvp(q, tangents, u), ad_third(q, tangents, u), ad_gradient_hvp_and_third(q, tangents, u) and their other value/in-place forms. Each call carries the Base.invokelatest barrier the query's build-time code needs, so they are safe from compiled callers. Not thread-safe (one per caller).
ReactiveKernelsPPL.RKPPLBoundModel Type
Inputs bound to a captured program, awaiting explicit observations. Use binding | (; y) or condition(binding; y) to lower and bind it. With nothing left to observe, the binding is the plan bind_data(binding) lowers it to: build_kernel, kernel_expr, assign_layout, the prepare_* queries and model_view(built; bound) accept it in place of that plan.
ReactiveKernelsPPL.RKPPLDocumentation Type
RKPPLDocumentationAn authored Markdown docstring, separate from a model's numerical program. path is a tuple of literal author names (never private lowering identifiers). owner is :declaration, :instance, or :definition. definition names the reusable definition that supplied the text, or is nothing for caller text; origin is its path within that definition. file and line retain the Julia source location when available (nothing, 0 otherwise).
Definition records have an empty path on a captured submodel and the use-site path on a lowered plan. An instance can carry both its own use-site docstring and its reusable definition's docstring. Markdown is retained without parsing, interpolation, or rendering.
sourceReactiveKernelsPPL.RKPPLModel Type
RKPPLModelA captured @rkppl block. model(; x, g) binds inputs and pins any named declaration. Observe values explicitly: model(; x, g) | (; y), or condition(model(; x, g); y), returns a bound StructuralPlan. fixed stores merge pins, rewrites stores scoped statement replacements, conditioned stores explicit observations, marginalized the latent recurrences integrated out by marginalize, marginal_values the filter values each marginalize call names (predictive, filtered) and chains those markov_chains lowers in their states for WarmupHMC's Markov chains. Operations return new models.
ReactiveKernelsPPL.RKPPLModelView Type
RKPPLModelViewSeparate views of one built @rkppl program, returned by model_view:
inputs/outputs: the kernel's HAVE inputs and WANT outputs;coordinates: the packed sampler coordinates,coordinate_names(layout);code: the planned ReactiveKernels expression,code_expr(spec);graph: the structural graph,kernel_graph(spec); its text display lists values and recipes with plate and scan bodies nested, and its HTML display is the interactive DAG;source: the generated pre-build kernel definitionkernel_expr(bound, layout), ornothingwhen no bound program was given;prepared: the exact expression of a supplied prepared query, ornothing.
Code expressions are printed without display rewrites. Only line-number nodes are removed from a copy for presentation.
show renders the views as labeled sections in plain text or HTML.
ReactiveKernelsPPL.RKPPLSubmodel Type
RKPPLSubmodel(name, argnames, body, mod)A captured reusable submodel definition (@rkppl sm(a, b) = begin … end), mirroring StanBlocks @slic f(args…)=body. argnames are the positional inputs bound by name at the use site; body is the block AST — density / deterministic = statements followed by a trailing RETURN expression; mod is the defining module (for symbol resolution). A trailing return x and a bare trailing x are equivalent spellings. The RETURN selects the submodel kind: a bare trailing Symbol that is the LHS of an internal slot .~ family.(...) response is a RESPONSE POINTER, not a value — it maps to the data column at an observation-stream use site (y ~ sm(...)), so a stream body carries no trailing binding; any other return is a latent VALUE bound to a non-data LHS (latent = <return>). Invoked as latent ~ sm(a, b) and expanded inline by lower_rkppl (see _expand_submodels): the submodel owns a lexical namespace under the LHS and its mathematics is spliced into the parent plan, so a submodel lowers like a hand-inlined model — transparent and reusable, never an opaque node.
A body holds any statement a top-level program can: ~ / .~ / = statements, indexed and sized priors (c[levels(g)] .~ Normal.(0, s), b[axes(X, 2)] .~ …), @plate and @scan blocks, and calls to other submodels. Scope access is static:
every name the body binds — a
~/.~/=left-hand side (the base name of an indexed one), a@plateresult, cell or loop variable, a@scancarried state, step local or loop variable, ado-block argument — receives a private identifier; its author path is retained separately.z.breads localbof callz. Index expressions keep their shape;each argument is replaced by the call's argument expression; a body may observe (
~/.~) an argument bound to a data column, and binding an argument name any other way fails;function names, keyword names and every name the body does not bind are left as written (a free name refers to the calling program);
a nested call expands after the enclosing body is substituted, so paths compose (
z ~ outer(…)→w ~ inner(…)→bgivesz.w.b); it resolves in the module that defined the enclosing submodel. Recursion fails.
Bare z denotes the actual return value, including in Julia function arguments. z.b is local-first: when b is absent from the scope it reads getproperty(z, :b) on that return value. Explicit getproperty(z, :b) always reads the return value. Ordinary caller assignments cannot write locals; explicit merge operations replace their declarations. Locals never create unqualified caller bindings. a.b_c, a_b.c, and caller a_b_c coexist. A per-cell call (col[i] ~ sm(…) inside @plate for i …) admits scalar ~ / = statements over bare names; col[i].b reads local b at cell i, and col.b is the array of those locals. Loop variables remain scoped to their loop and cannot be read outside it.
constrain and restore_draws return nested NamedTuples of sampled locals (nt.z.b, nt.z.w.b); coordinate_names uses dotted author paths. These draw containers omit deterministic locals, observed slots and return values. unconstrain accepts the same nested containers. Rebuild prepared layouts and draw mappings when migrating from flattened submodel names.
A fused stream def (design + coefficients inside, Stan bernoulli_logit_glm-style) keeps the response shell but NOT the predictor name: its affine local belongs to the data LHS's scope (y.mu), and an inline compound location synthesizes (y_eta) — both move the lowered predictor. Ordinary parameter names follow their declarations; legacy construct-owned coefficient blocks follow the predictor. To factor design + coefficients into a def WITHOUT moving names, return the affine from a latent def and bind it at a named use site (mu ~ affine_def(X, b), then y .~ family.(...mu...)): the use-site LHS names the predictor, and the plan is identical to the hand-written decomposed program.
ReactiveKernelsPPL.ResponseEvidence Type
ResponseEvidence(kind, lower, upper)Censoring/truncation evidence wrapper on an admitted family (D3 response evidence). Bounds are real literals or names of data, sampled values and ordinary definitions (scalar or per observation). For :interval_censored the response itself is the lower endpoint, so lower must be nothing and upper is required. The interval is open below: the cell is log(CDF(upper) - CDF(response)) for (response, upper]. :censored is the clamp law (Y = clamp(X)): rows at a bound take the CDF mass (yv ≤ lower / yv ≥ upper), never the density.
ReactiveKernelsPPL.SMCCarriedReference Type
SMCCarriedReferenceData-only Gaussian summary of a posterior in a fixed unconstrained coordinate frame. Construct with carry_smc. The owned reference, frame and calibration_id contain no old observations, prepared queries or trajectories. Treat them as read-only. The frame includes the caller's model/preprocessing identity and the packed layout; the calibration ID identifies this summary. For full-frame targets, fit_diagnostics is nothing for externally supplied or fixed-basis summaries; basis=:fit carries the bounded WarmupHMC fitting diagnostics as owned data. Selective carries also report joint recompression.
ReactiveKernelsPPL.SMCDegeneracyError Type
SMCDegeneracyError <: ExceptionAll particle positions are exactly equal in a positive-dimensional SMC cloud. state is the preserved input state (not a copy; treat it as read-only), including its unchanged continuation RNG and normalizer. phase is :input, :stage or :rejuvenation. diagnostics is the rejected stage summary, or nothing when the input itself was collapsed. A rejected stage is not appended to state.history.
This detects full spatial collapse, not partial degeneracy or inadequate mixing. Constant density ratios, a constant coordinate, a single initial ancestor and zero movement alone do not trigger it. Zero-dimensional targets are exempt. Use independently prepared tuning with rejuvenate_smc to attempt recovery; a failure must not be treated as a completed posterior.
For a parameter-learning filter, phase can also be :filter_step or :rollover. The latter reports nonpositive/nonfinite Gaussian marginal scales, including partial coordinate degeneracy. The failed observation is not consumed. diagnostics holds the attempted filter stage, or rollover scale/coordinate details. Use tune_filter_smc(error.state; rng, init, ...) to independently prepare recovery at the current window, then rejuvenate_smc and retry the failed observation. Input and recovery failure semantics are the same.
ReactiveKernelsPPL.SMCNonfiniteError Type
SMCNonfiniteError <: ExceptionAn invalid SMC endpoint or bridge evaluation. position is a copied, exact unconstrained proposal; value is the evaluated log density or log-density ratio, and gradient is a copied gradient when one was evaluated (otherwise nothing). quantity is :density, :gradient or :logratio; endpoint is :source, :target or :bridge. temperature is the bridge temperature at evaluation, before advancement for weight/ratio checks.
NaN and +Inf densities and nonfinite gradients at finite densities fail fast. The existing -Inf outside-support convention is preserved. Initial clouds are evaluated by their first smc_step, not by initialize_smc.
Error display is bounded, including display with a backtrace: inspect the fields for the full numerical diagnostic, and catch_backtrace() for the caller stack. Mutation failures cross the worker-task boundary as this same exception, without a nested task trace. The input cloud and RNG are preserved.
ReactiveKernelsPPL.SMCOptions Type
SMCOptions(; ess_fraction=0.8, stepsize=0.25, metric=nothing,
moves=2, max_tree_depth=6, max_stages=1000,
min_increment=1e-12, history_limit=128, tuning=nothing,
nthreads=Threads.nthreads(), cloud_kernels=0)Adaptive bridge and fixed NUTS configuration. metric is a vector of positive diagonal scales, or WarmupHMC's plain scale_data record for a correlated bounded-reflection scale; nothing means ones. These are not precisions. With the default cloud_kernels=0 the metric, step size and tree depth stay fixed during mutation, with no adaptation using the particles being moved. tuning=tune_smc(...) instead selects a fixed kernel from an independent, precomputed, bridge-specific pilot schedule. Scheduled kernel settings override stepsize, metric, moves and max_tree_depth for production mutation. Each stage resamples, then takes moves invariant NUTS transitions.
cloud_kernels=J (J >= 1) instead fits each stage's kernels to the stage target's weighted cloud before moving it: a diagonal Gaussian mixture with at most J components (count chosen by BIC, each component holding at least ten effective particles) gives every component its own diagonal scales, and its step size is tuned on discarded trial transitions towards a mean NUTS acceptance statistic of 0.8, starting from stepsize (or the scheduled kernel's). Each move selects a component from the mixture responsibilities at the particle's position and accepts the NUTS proposal with probability min(1, r_j(x')/r_j(x)), so every move leaves the stage target invariant given the fit; J=1 is one cloud-fitted diagonal metric. Particles in different modes, such as relabelled mixture components, then move with scales fitted near them rather than those of one pilot chain. The stage history's kernel records the fit, step sizes, tuning_evaluations (included in evaluations) and selection_rejections. Work is linear in particles, dimensions and components. Like the ESS temperature rule, this adapts to the cloud, so the evidence estimate is consistent but not exactly unbiased. ess_fraction selects the next temperature by bisection on the weight ESS, before resampling. A bridge that cannot progress by min_increment, or needs more than max_stages, throws without advancing its input state. nthreads bounds the number of concurrent particle-mutation workers and independent adaptive grid pilots (default Threads.nthreads()); each owns its sampler and AD scratch. Weighting, resampling and child-seed draws retain their serial order. Particle counts need not divide the worker count. A fixed seed and worker count reproduce the cloud and diagnostics; nthreads=1 preserves the serial random stream. Use an AD backend supporting concurrent evaluation (for Enzyme, the dogfood concurrent-GC repair is required until released). Only the last history_limit stage summaries are retained.
ReactiveKernelsPPL.SMCReference Type
SMCReference(location, scale)A normalized Gaussian distribution in the model's unconstrained coordinates. This is an importance reference, not a draw from the model prior. The bridge scores its actual normalized density and the full model posterior (including dependent priors and the Jacobian). scale is a vector of diagonal scales or WarmupHMC's plain scale_data record (load the SMC dependencies first). The latter represents a correlated, bounded-reflection Gaussian without a dense covariance. Fields location and scale own validated copies; treat them as read-only. smc_reference returns another owned copy. A public two-dimensional example is scale=(; diagonal=[sqrt(2.0),sqrt(0.02)], indices=[[1,2]], reflections=[[cos(pi/8),sin(pi/8)]]), with covariance [1.01 0.99; 0.99 1.01]. See WarmupHMC's scale_from_data/scale_data contract for the operator representation. All sampling, scoring and mutation use the rebuilt data operator, including its floating-point representation.
Selective carries also produce (kind=:diagonal_lowrank, diagonal=D, vectors=Q, values=v), representing covariance Diagonal(sqrt.(D)) * (I + Q * Diagonal(v) * Q') * Diagonal(sqrt.(D)). Here D is positive, Q has orthonormal columns and v > -1 elementwise. This compact covariance is accepted as an importance reference, including for prepared-density targets; it is not a WarmupHMC mutation metric. Its storage is linear in dimension at fixed rank, with no dense covariance.
ReactiveKernelsPPL.SMCTuningPartial Type
SMCTuningPartialAn interrupted adaptive tune_smc call, not a production tuning schedule. progress is the last observational boundary record; checkpoint owns the outer tuning continuation and WarmupHMC's active checkpoint payload, including its RNG and retained draws. Treat both fields as read-only. Resume with tune_smc(target; resume=partial, original_keywords...), or serialize this record for a fresh process. With checkpoint_dir, resume=true reads the directory's latest checkpoint instead. See tune_smc for identity checks, configuration, disk retention and cooperative stop boundaries.
ReactiveKernelsPPL.SMCTuningSchedule Type
SMCTuningScheduleData-only result of tune_smc. temperatures and kernels describe a finite, precomputed schedule. Each kernel records stepsize, metric (scales), moves and max_tree_depth. Production selects the nearest temperature knot (ties select the higher knot), using only its temperature and this configuration. source and target bind the schedule to the exact bridge; reference is the normalized initial reference, or nothing for a posterior update. pilot records the copied initial/final RNG, initial position and bounded pilot work.
Arrays in this record must remain read-only. Initialization, updates and resume copy and validate the schedule. Checkpoints include it; resuming never reruns pilot adaptation. A schedule is not a stationary posterior sample.
sourceReactiveKernelsPPL.SampledParameter Type
SampledParameter(name, family, args, support_override, label)One scalar latent with positional (arg1, arg2, …) arguments in Distributions constructor order (Exponential uses scale). Arguments may read data, sampled parameters or ordinary definitions. Explicit support follows SupportOverride; truncation normalizes and restriction preserves the density.
ReactiveKernelsPPL.SamplerQuery Type
SamplerQueryReusable sampler-space density + gradient over a built program: the prepared :posterior value kernel plus its prepare_ad gradient preparation. Construct with prepare_sampler; not thread-safe (one per caller). The call paths below carry a Base.invokelatest barrier.
The barrier copies nothing: a gradient call allocates only what the prepared gradient itself allocates, and a value call adds one boxed Float64.
With LogDensityProblems loaded, a query is a first-order LogDensityProblems target over all layout.total packed coordinates, for WarmupHMC, Pathfinder or an optimizer: it implements dimension, capabilities (LogDensityOrder{1}), logdensity (q(u)) and logdensity_and_gradient, which returns a fresh gradient vector on every call. Give each concurrent chain its own query; a deepcopy is an independent query.
A point where a numerical method cannot evaluate the model, such as an ODE its solver cannot integrate there (ReactiveKernels.NumericalFailure, for example ReactiveKernels.ODESolveFailure), is outside the target's support: the value is -Inf and the gradient is filled with NaN, as Stan rejects a proposal whose ODE solve fails. Every other exception propagates. The query evaluates the next point as usual afterwards.
ReactiveKernelsPPL.ScalePredictorRef Type
ScalePredictorRef(predictor, link)A per-observation auxiliary use, including scale, shape, probability, Student degrees of freedom and zero inflation. predictor names the PredictorSpec, whose emitted value is unchanged. link belongs to this use: identity reads the value directly; log, logit, probit and cloglog apply exp, logistic, normcdf and cexpexp, respectively. Several positions may share the same predictor under different links. The generator binds each transformed vector once and threads it through the likelihood plate. A value outside the distribution parameter's support contributes -Inf through a lazy density branch.
ReactiveKernelsPPL.ScanSetup Type
ScanSetup(target, index, kind, family, args, expr[, support])One literal-index seed fill of a @scan carried array target, mirroring ScanStep:
kind === :sample—target[index] ~ Dist(args…): a sampled seed.familyis an internal family symbol (see the surface's_PARAM_FAMILIES),argsthe positional distribution-argument expressions andsupportitsSupportOverride(restricted,truncatedand half priors, as for a scalar parameter);exprisnothing.kind === :assign—target[index] = expr: a deterministic seed (a literal, or an expression over scalar parameters, definitions and earlier seeds).family/args/supportarenothing.
ReactiveKernelsPPL.ScanSpec Type
ScanSpec(states, loopvar, lo, hi, setup, step, maxlag, label)One sequential recurrence (@scan begin <setup>; for loopvar in lo:hi … end end): the carried arrays states (in first-seed order; one or more — a tuple carry), the loop variable and range lo:hi (hi a literal Int or a data length Symbol), the ordered setup seed fills (every carried array seeded at 1:lo-1), the ordered recurrence steps, and the maximum backward lag read. Each carried array is a plan-level latent the recurrence produces (the value visible after the block); the per-step locals and loopvar are scoped to the recurrence and never enter the plan name table.
ReactiveKernelsPPL.ScanStep Type
ScanStep(kind, target, indexed, family, args, expr[, support])One @scan recurrence-body statement.
kind === :sample— a~statement: a carried array at the loop index (indexed = true,targetone of the scan'sstates, centered form) or a fresh per-step local innovation (indexed = false, non-centered form).family/args/supportdescribe the distribution, as for aScanSetup;exprisnothing.kind === :assign— a=statement: a carried array's deterministic write (indexed = true) or a per-step deterministic local (indexed = false).expris the RHS AST;family/args/supportarenothing.
Statements run in order, as in a Julia loop body: a step reads a carried array's backward lags a[t - k], its current value a[t] once an earlier step wrote it, and locals defined by earlier steps.
ReactiveKernelsPPL.SliceProblem Type
SliceProblemOne slice of a SliceSampler as a log density over its compact coordinates, with the binding's other coordinates held at a base point it owns. With LogDensityProblems loaded it implements dimension, capabilities (first order), logdensity and logdensity_and_gradient. Not thread-safe. Like SamplerQuery, it answers -Inf (gradient NaN) where a numerical method cannot evaluate the model (ReactiveKernels.NumericalFailure).
ReactiveKernelsPPL.SliceSampler Type
SliceSamplerSlices of one bound model, from prepare_slices. Evaluate one with slice_value_and_gradient!; its coordinates are slice_coordinates and its labels slice_labels. A label set's coordinates and prior terms are worked out on its first use and kept. Not thread-safe: prepare one per thread, as for PartitionSampler.
ReactiveKernelsPPL.StructuralPlan Type
StructuralPlan(responses, predictors, population_priors, parameters,
assignments, derived, columns, n_obs)Complete emitter→thin-layer input. columns maps RAW-column names to plain vectors (derived columns are never bound — they compute in-graph from derived); parameters, assignments, derived, each plate_parameters latent, each vector_parameters latent, and each scans state share one name table (duplicates rejected). N≥1 independent responses; shared predictor Symbols allowed. levelmaps sizes every factor term (binder-evaluated values); plate_parameters carries per-cell latents, vector_parameters leveled-response latents (cutpoints/thresholds/simplexes), scans sequential-recurrence latents, and matrices user-bound design matrices referenced by MatrixTerms (empty for a plain population-GLM plan). array_parameters are the declared array-valued parameters (ArrayParameter) the model reads by name. submodel_scopes records lexical author paths separately from the private identifiers used by the mathematical plan. cell_broadcasts maps each response observed by a dotted @plate cell (y[i] .~ D.(…)) to the names that cell reads per index; when the bound response holds one array per index, each cell broadcasts over its own entries. named_values keeps each authored alias the lowering absorbed addressable by its name: name => node binds name to the graph value node. factors are distribution densities on deterministic definitions; they add no coordinate or transform and contribute to prior, or to likelihood when explicitly conditioned. A SampledParameter factor is a scalar density (d ~ Normal(m, s)); an ArrayParameter factor is the density of a vector definition, elementwise (d .~ Normal.(m, s), a built-in scalar family with no dims) or joint (d ~ MvNormal(m, S), the <stem>_vector slice family). cell_priors names scalar sums of conditional draw densities computed by retained cell scans; their coordinates and transforms belong to ordinary array parameters. frozen holds the data-only definitions a binding takes by value (FrozenValues, bind_data(…; frozen)); it is empty otherwise. cell_latents maps the packed array parameter of each dotted @plate cell latent (v[i] .~ D.(…) over arrays) to its authored name and the data-only definition holding each index's dimensions; draws show it as one array per index under that name. cell_geometries maps the packed array parameter of each undotted @plate cell latent with a caller-owned joint geometry (c[i] ~ F(…)) to its CellGeometry; draws show it as one constrained value per index under the authored name.
ReactiveKernelsPPL.SubmodelScope Type
A lexical submodel call: its authored path, return-value binding, and local bindings. Identifiers are private plan names; path and local keys are author names. A per-cell call owns arrays of its scalar local values.
ReactiveKernelsPPL.SurfaceLoweringError Type
SurfaceLoweringError <: ExceptionThrown by lower_rkppl and the @rkppl macro forms when a model block is not slice-1 lowerable. Every message names the offending statement and the fix; IR-level defects behind a well-formed surface are lowering bugs and surface as ContractValidationError from the trailing validate_structure call instead.
ReactiveKernelsPPL.TermKind Type
Slice-1 predictor term kinds (core set; stretch adds variants later). LatentTerm carries a per-cell latent parameter vector (a PlateParameter) as a linear-predictor value (lp = theta or an unscaled summand, identity design) — the random-effects / per-observation-latent location. ScanSummandTerm splices a sequential-recurrence state into the predictor scaled by a sampled scalar coefficient (u .* beta, SB's ar latent path with its free popefs beta), or unscaled when its coef is nothing (mu = a .+ x).
ReactiveKernelsPPL.TermSpec Type
TermSpec(kind, columns, options, addressee, label)One additive predictor term: structure only, never materialized designs (D5a). addressee is the prior address (source column or :Intercept), never a per-level label. An optimized ordinary parameter read carries parameter (its declaration name) and sign in options; its declaration owns the prior and coordinates. Factor sizing lives in the plan's LevelMaps (full-rank over exactly the mapped levels; no contrasts, no reference dropping — that machinery was BRM-specific and is gone). A ContinuousTerm may name a per-cell latent (PlateParameter) instead of a data column: the latent vector enters the design with a free coefficient (the SB me mirror).
ReactiveKernelsPPL.VectorAssignmentSpec Type
VectorAssignmentSpec(name, expr)One in-graph derived column (contract v3): expr is elementwise over bound raw columns (dotted arithmetic/comparisons/math, ifelse, bare-column reductions as scalar subterms) plus scalar parameter/assignment references. Length is n_obs by construction (every admitted form preserves length); the generator emits the computation into the kernel body and bound= partial evaluation folds data-only derivations exactly once (the StanBlocks transformed-data analog). A bare-Symbol expr aliases another column (raw or derived). Factors take raw grouping columns only (levels need pre-evaluation knowledge); continuous/offset terms and reduction arguments admit derived names.
ReactiveKernelsPPL.VectorAssignmentSpec Method
Provenance defaults to the derived column's own name.
sourceReactiveKernelsPPL.VectorParameter Type
VectorParameter(name, family, args, size[, label])One constrained VECTOR parameter for a leveled response (cutpoints, thresholds, or a shared simplex), packed as one contiguous block:
:ordered_normal— an ordered cutpoint/threshold vector with an elementwiseNormal(arg1, arg2)prior (Stanorderedsemantics: no factorial normalizer) + the ordered-transform Jacobian. The surfacec ~ Ordered(Normal(m, s), n); unlinked (a free-standing ordered value) it carries a literal extent or a data-only expression resolved at bind.:vector_normal— a plain (unconstrained, identity-transform) vector with an elementwiseNormal(arg1, arg2)prior (stopping-ratio stage thresholds). Cauchy, Laplace, Logistic and StudentT have corresponding:ordered_*and:vector_*element-density families.:ordered_flatand:vector_flat(args = (;)) have zero element density: the surfacec ~ Ordered(Flat(), n)andt[1:n] .~ Flat.()thresholds.:simplex_dirichlet— a simplex with aDirichlet(arg1)prior (arg1a literal concentration vector — frozen data, the coefficient-prior precedent) + the stick-breaking Jacobian.:positive_exponential— a positive K-vector with an elementwiseExponential(arg1)prior (the joint factor's scales;arg1a finite positive literal or a scalar parameter/assignment name — sampled scale hyperparameters ride the scalar-prior shape).:cholesky_corr_lkj— a K×K LKJ Cholesky factor with anlkj_corr_cholesky(arg1)prior (arg1the shape hyperparameter, a finite positive literal), packing K(K−1)/2 thetas.
size is the constrained length (K−1 for thresholds, K for a simplex), or a bound name or data-only expression resolved at bind. nothing fills from a linked response or concentration. Element prior arguments may be scalar literals, data or declared values. K=1 is uniform: zero-length threshold vectors carry no statements/prior/Jacobian, a 1-simplex is the constant [1.0], and a 1×1 LKJ factor packs zero thetas (constraining to [1.0] with a 0.0 prior node — Stan's K=1 LKJ). Joint-factor sizes are STRUCTURAL (size = the joint width K, concrete — never nothing).
Functions
ReactiveKernels.jax_source Method
jax_source(built, plan; values = (), doc = nothing, float_type = Float64) -> JAXSourceA Python module for the build_kernel output built, evaluating the program with jax.numpy over the sampler boundary: the packed unconstrained parameters, then the prepared data. Its functions:
prepare_data(data...): the functions' data inputs, computed in host NumPy from the data the model is bound with, by the names the model reads them (sorted, or by name; a name Python reserves, such asclass, only by name, through**data), including the data-only definitionsbind_dataevaluates; frozen definitions are inputs too;log_density(unconstrained, data...): the:samplervalue (prior, likelihood and log Jacobian), the log density a NumPyro or BlackJAX sampler targets as-log_densitypotential;log_prior,log_likelihoodandlog_jacobian: its parts;constrain(unconstrained, data...): adictof every declared parameter's constrained value (an empty parameter has none), plus each value named invalues(a definition such as:mu).
Where a numerical method cannot evaluate the model (a ReactiveKernels.NumericalFailure natively, such as an ODE solve that fails or exceeds its step budget), the density functions answer -inf, as the native sampler targets answer -Inf, also from a plate cell, a scan step or a branch, under jax.jit, jax.grad and jax.vmap; their gradient there is unspecified. constrain raises there. Any other runtime check still raises.
Module constants describe the inputs: DIMENSION (the length of unconstrained), PARAMETERS (each parameter's 0-based start/stop in unconstrained, its transform and dimensions), INPUTS (the parameter names in order), DATA (each prepare_data parameter's dtype and rank) and UNTRANSLATED (each data-only definition prepare_data takes as an input instead of computing it, with the reason; {} when none).
float_type = Float32 emits the module in float32 (ReactiveKernels.jax_source's float_type): unconstrained, the data and every value are float32, and the module does not turn on JAX's 64-bit mode. The default Float64 module is its reference.
The module docstring starts with the generated line naming ReactiveKernelsPPL.jax_source, then Data: (the names prepare_data takes) and Model documentation: (each statement's docstring, by name). doc adds the author's description of the model between the generated line and Data:: a string, or a Julia docstring such as @doc TOY_MODEL (its Markdown text). A docstring written above const TOY_MODEL = @rkppl … belongs to the binding, not to the model value, so the caller passes it.
plan is any binding that generates the same program as built, as for prepare_query; its values only type the inputs. Data arrays keep Julia's dimension order and integer index data stay 1-based. See ReactiveKernels.jax_source for the translation.
ReactiveKernelsPPL.accumulate_cell! Method
accumulate_cell!(batch, operator, direction, weight, active, indices, cell)Accumulate one compact cell's weighted derivative contraction in an active cell_pullback! callback. An outer factor takes sums, active, indices, cell last; a summand takes active, indices, cell, term. There is no base argument: the pass owns its copied packed point. Pass nothing as direction for order zero.
Returns (weighted_contraction, local_derivative). The local derivative follows the ordinary compact operator's shape (including independent sum derivatives for an outer factor), and is reused on the next call. Consume or copy it before reusing the operator. Its packed-coordinate entries are also accumulated into the pass's gradient. Sum entries are returned for the caller's chain rule; sum inputs remain independent, exactly as for factor AD.
ReactiveKernelsPPL.admitted_elementwise Method
Elementwise vocabulary the thin layer can lower in derived columns: (dotted operators, dotted math functions) (ext handshake predicate).
ReactiveKernelsPPL.admitted_families Method
Families the thin layer can lower (ext handshake predicate).
sourceReactiveKernelsPPL.admitted_functions Method
Assignment functions the thin layer can lower (ext handshake predicate): scalar/reduction vocabulary plus vector-returning whole-column functions — the BUILT-IN vocabulary. Beyond it, an = definition may call any function visible in the model's module (functions as values): a data-only call is evaluated once by bind_data, any other runs in the generated kernel.
ReactiveKernelsPPL.admitted_terms Method
Term kinds the thin layer can lower (ext handshake predicate).
sourceReactiveKernelsPPL.assign_layout Method
assign_layout(plan) -> LayoutTableAssign packed coordinates: legacy coefficient blocks in plan.predictors order, then ordinary sampled, plate, vector and array parameters in plan order (pinned, deterministic). Affine readers add no coordinates. Assumes validate_plan passed.
ReactiveKernelsPPL.bind_data Method
bind_data(plan, columns; roles=Dict(), dims=Dict(), conditioned=plan.conditioned,
frozen=plan.frozen) -> StructuralPlancolumns accepts a symbol-keyed AbstractDict or a NamedTuple of data values, as does value-based lower_rkppl. Named tuples use the same binding and validation path as dictionaries; neither container nor its values is mutated. Attach columns to a structure-only plan (or rebind an already-bound one, replacing columns + roles): infer column roles, merge explicit roles over them, and run data validation. Returns a NEW bound plan; the input is untouched. Inference precedence: response > trials > evidence > weight > group > predictor > data; term columns are the only :predictor source, so assignment/extra columns stay :data; :group is an explicit role. The retired dims argument accepts only an empty dictionary; array dimensions and plate ranges come from authored expressions. Data values are numbers or arrays of any shape; observation values follow their authored broadcast axes and structured operations retain their own shape requirements. Data-only module definitions needed by structural consumers are evaluated here, once, and bound under their own names — never supplied by the caller. Whole-value definitions used only by scalar factors or parameter-dependent module calls remain in the graph for RK preparation to freeze, independently of conditioning. A model-level definition may be a number or an array of any shape and carries no n_obs requirement. So does a model-level data input: a column every definition reads only inside an argument of an undotted module call (gx_m = f(gx), or inlined (b .* f(gx))[g]) and no response, predictor or other slot names — it may have any length or shape and never sets n_obs (see _model_level_inputs).
frozen (FrozenValues, as frozen_values reads it from another binding) supplies data-only definitions by value: each takes its frozen value exactly where binding would have evaluated it, whether binding binds it as data or RK preparation folds it (a whole value a parameter-dependent call reads, supplied to preparation as a HAVE value). A data input that only frozen definitions read may be left out: binding binds it absent with the type and size frozen records, so the program is the one a binding with that input generates, and nothing reads it. Supplying a frozen definition as data is refused, as for any definition. A rebinding keeps its plan's frozen values unless frozen replaces them; frozen = nothing evaluates every definition again.
Binding resolves module values and calls in a package-owned latest-world scope, including definitions just evaluated in a builder.
sourceReactiveKernelsPPL.block_name Method
In-graph coefficient-block name for a predictor (mu → mu_coef).
ReactiveKernelsPPL.block_read Method
block_read(offset, width) -> ExprPacked-slice read (view(unconstrained, lo:hi), @ppl vector shape).
ReactiveKernelsPPL.build_kernel Method
build_kernel(plan) -> (; spec, layout, program)Validate, assign layout, emit, and evaluate a self-contained @kernel program for plan. spec is the KernelSpec (callable after prepare with have=(:unconstrained, data…)); layout is its LayoutTable (R10 read API for the sampler side). program is the generated program the graph evaluates: prepare_query accepts any bound plan that generates the same program, with other row counts and data values or an equivalent lowering in another gensym-created isolation module, and refuses one that generates another.
Concurrency: build_kernel is concurrency-safe. Independent plans may be built from concurrent tasks with no caller-side synchronization: a build binds nothing in a shared module and takes no package lock. Construction compiles little per-model code, so concurrent builds largely run in parallel; Julia serializes only the compilation that remains (1.10: all compilation; 1.12 and 1.13: type inference).
The returned spec closes over build-time eval'd code. Construction resolves module bindings in a package-owned latest-world scope, including just-evaluated kernels; subsequent execution uses its own boundary: prepare it and call it through prepare_query / prepare_sampler (which carry the Base.invokelatest world-age barrier) or wrap those calls in Base.invokelatest yourself.
ReactiveKernelsPPL.carry_smc Function
carry_smc(target, reference::SMCReference; calibration_id)
carry_smc(selective_target, reference::SMCReference; calibration_id, maxrank=16)
carry_smc(completed_state; calibration_id, scale=nothing, parameters=nothing,
basis=nothing, max_reflections=16, maxiter=100, progress=nothing)Copy a calibrated Gaussian posterior into the target's coordinate frame for bounded-window updates. The first form accepts an externally calibrated reference. A tuning schedule's reference is a normalized proposal, not a posterior moment estimate. The second form uses the completed cloud's weighted mean and, by default, its marginal standard deviations (population moments, not a dense covariance). Supply a diagonal scale or a portable WarmupHMC scale_data record to preserve learned correlations. Zero or nonfinite marginal scales require an explicit valid scale.
basis=portable_scale instead fits the completed cloud's weighted marginal variances after whitening by that scale, then replaces its diagonal magnitudes while retaining its learned reflection directions. Thus proposal scale inflation does not become posterior variance. This costs O(particles × dimension × bounded reflections), with O(dimension) working storage and no dense covariance. It discards cross-covariances in the supplied basis: exact covariance requires that basis to diagonalize the posterior covariance. Use an independently learned orientation, for example smc_reference(schedule).scale, in the selected frame. basis and explicit scale are mutually exclusive; scale is copied as given.
basis=:fit learns directions from the completed weighted cloud through WarmupHMC's public fit_gaussian_moments, then carries its mean and portable scale. max_reflections, maxiter and progress apply to this fit. Use this route when a supplied pilot basis omits posterior correlations. It fits the selected coordinates when parameters is given, without slicing full-frame geometry. Work is O(d N (1 + k maxiter)), workspace O(d N + d k + N), and retained size O(d (1 + k)); no dense covariance or old cloud is retained. These are posterior summary moments, not production-kernel adaptation. The owned fit_diagnostics contains reflections, iterations, relative_residuals, converged and effective_sample_size. Residual convergence does not certify covariance accuracy; finite reflection/iteration budgets may lose correlations. :fit learns the leading covariance directions in native coordinates, so when coordinates differ greatly in scale its reflections go to the widest ones and correlations among narrow coordinates are discarded.
basis=:correlation instead fits the leading correlation directions: it standardizes the weighted cloud by its marginal standard deviations, finds up to max_reflections directions with the same fitter (maxiter applies), keeps their weighted variance, and lets the remaining directions share the remaining standardized variance equally (probabilistic PCA). At most the distinct-position ESS minus 2 directions are kept; with none, the carry is the diagonal one. The reference scale is the diagonal-plus-low-rank form (kind=:diagonal_lowrank, diagonal, vectors, values), which is invariant to rescaling coordinates. It is what the learning filter's window boundaries use, and it is the calibration to use for parameter learning in a model whose posterior correlates parameters on different scales (hierarchical intercepts and group effects). As an importance reference it is not a mutation metric. Work O(d N k maxiter), retained size O(d (1 + k)); no dense covariance is formed. fit_diagnostics holds directions and effective_sample_size (over distinct positions).
This is an assumed-density approximation to the old posterior. A Gaussian summary is exact only for a Gaussian posterior with matching moments; fitting it from a finite cloud introduces Monte Carlo error too. The cloud itself is not retained. This summary is a prior for subsequent windows, not production kernel adaptation. Mutation tuning still uses independent pilot RNGs/positions.
parameters=(:name, Symbol("nested.name"), ...) selects complete authored static parameter blocks from a completed full-frame fit, excluding historical scan coordinates. The producer packs their unconstrained marginal and carries only their portable native geometry. scale, if supplied, must be in this selected frame; slicing a full correlated scale does not produce its marginal scale. Use smc_parameters to restore the selected constrained tuple. Static transform dependencies must also be selected. Data-only scalar bound expressions are folded once, so old observations are not retained. Custom geometry containing callable objects is not represented by this native projection; use a static-only calibration and an explicit mapping for it. For selective windows (coordinates=:auto), omit parameters: carrying integrates the inactive conditional into the full joint Gaussian. The external-reference form bounds joint rank by maxrank; completed states use max_reflections. Completed selective states return .fit_diagnostics.marginal for the compact fit and .joint for recompression; the external form returns the joint diagnostics directly. Their rank, discarded_rank and relative_loss describe the retained rank and discarded correction's spectral norm in the diagonal-whitened frame, not posterior accuracy.
ReactiveKernelsPPL.cell_pullback! Method
cell_pullback!(visit, gradient, pullback, u)Run visit(pullback) at a copied packed point u, then write the accumulated gradient to gradient. In the callback, call accumulate_cell! for each weighted value, first directional derivative, or second directional derivative. After the callback, one shared-prefix pullback propagates their combined cotangent. Local and direct packed derivatives are included too.
The shared cache refreshes automatically when a coordinate its prefix reads changes. Ordinary compact/factor derivative verbs also accept the active pullback in place of their base argument. They use the copied point without scanning shared coordinates again, and do not add to the accumulated gradient. Raw vector calls check the prefix's coordinates on every call, or every shared coordinate when there is no prefix. Do not change those coordinates through another operator during the callback: that invalidates the pass and throws. A shared coordinate the prefix does not read reaches a cell only through the pass's copied point, so changing it elsewhere leaves the pass valid. A failed callback produces no output; the next call resets all accumulation storage. Calls cannot be nested or run concurrently on the same pullback.
Within visit, call accumulate_cell! with the current pullback, derivative operator, direction, weight, active coordinates, coordinate indices, and cell position.
ReactiveKernelsPPL.cell_reductions Method
Reduction names in the order used by the outer factor's sum vector.
sourceReactiveKernelsPPL.cell_value_and_gradient! Method
cell_value_and_gradient!(s::CellSampler, g, u, i)Cell i's log density and its gradient with respect to the packed unconstrained vector, written into g. Returns (value, gradient).
ReactiveKernelsPPL.cell_value_and_gradient! Method
cell_value_and_gradient!(sampler::CompactCellSampler, gradient, base, active, indices, cell)Return one cell's density and write only the selected-coordinate gradient. base and indices are not mutated. The active values overlay base at the sorted positions in indices. Consecutive calls with equal indices check the selection once.
ReactiveKernelsPPL.coefficient_priors Method
coefficient_priors(shape, priors) -> (locations, scales)Expand per-addressee PopulationPriors to per-coefficient location and scale vectors in design-column order (via coefficient_prior_specs). A factor addressee fans out to its whole contrast block (one shared prior); a matrix block looks up each element addressee in turn (per-column priors).
ReactiveKernelsPPL.constrain Method
constrain(layout, unconstrained) -> NamedTupleHost-side constrain of the packed vector. Parameters keep their author names; submodel locals are nested (nt.z.b, nt.z.w.b). Scalar, vector, and array leaves retain their constrained shapes. Values follow the number type of unconstrained (Float64 for plain reals). Deterministic submodel locals and return values are read in the model rather than included in this draw container. The generator emits the equivalent transforms inside the mathematical graph.
Concurrent calls may share a completed layout when its inputs and bound values remain read-only. Built-in transforms synchronize their lazy endpoint caches; caller-owned geometry and functions evaluated in bounds must themselves allow concurrent calls. Each call constructs its own result containers.
sourceReactiveKernelsPPL.coordinate_identities Method
coordinate_identities(layout) -> Vector{@NamedTuple{path::Tuple{Vararg{Symbol}}, index::Tuple}}One identity per packed coordinate, in packed order, that names what the coordinate means rather than where the binding put it, so the same coordinate of two bindings of one program (a slice and the whole, one window and the next) compares equal:
pathis the authored path, as inparameter_metadata:(:b,), or(:z, :b)inside a submodel.indexhas one entry per packed axis. An axis declaredlevels(g),unique(g)or as a data vector holds that axis's bound label (the level ofg, with the declaration's selection applied). So does the positional twin1:length(levels(g)), whose positions are the levels ofginlevels(g)order, as in BRM's group effects (z[1:length(levels(g)), 1:K], read at each row's level position). Any other axis holds its one-based position, including1:length(levels(g)) - k, which does not say which levels it leaves out. A scalar's index is(). A legacy coefficient holds its design label. The packed axis of a slice transform (a simplex or ordered row or column) is positional; its other axis keeps its labels. Coordinates of a joint cell latent or cell geometry are positional within their array.
So z[levels(station)] .~ Normal.(0, s) packs (path = (:z,), index = ("st-05",)) wherever st-05 falls in that binding's levels(station), while coordinate_names names its position (z.2 in one binding, z.4 in another). Labels are data: comparing identities across bindings assumes the same level values mean the same thing in both.
ReactiveKernelsPPL.coordinate_names Method
coordinate_names(layout) -> Vector{Symbol}Flat per-coordinate author paths, such as b, z.b, and z.w.1. Scoped locals use dotted paths; literal identifier segments that contain punctuation use Julia's var"..." spelling. Length equals layout.total.
ReactiveKernelsPPL.coordinate_read Method
coordinate_read(offset) -> ExprScalar packed-coordinate read (unconstrained[o]).
ReactiveKernelsPPL.density_factors Method
density_factors(built, plan) -> DensityFactorsInventory authored prior and coordinate-Jacobian events of a bound model. Each DensityFactor has kind (:prior or :log_jacobian), authored site, and one-based entry. Elementwise declarations have one event per element (linear, column-major order); a joint law or coupled transform stays atomic. Built-in identity transforms contribute no Jacobian events; a caller's geometry retains its authored Jacobian even when it returns zero. Conditioned declarations are observations and are excluded.
The catalogue belongs to this program and binding. Select events with select_factors, inspect their structural packed-coordinate support with factor_support, and evaluate them with prepare_query or prepare_query_ad. Catalogue and query preparation may inspect the whole model; repeated selected evaluation uses precomputed row plans.
ReactiveKernelsPPL.design_name Method
Design-matrix recipe name for a predictor (mu → _ppl_design_mu).
ReactiveKernelsPPL.design_recipe Method
design_recipe(shape, n_rows; plates) -> Union{Nothing,Expr}_ppl_design_<pred> = Float64.(hcat(<blocks…>)), or nothing for a width-0 (offset-only) predictor or a predictor with no static (data-only) blocks. n_rows is the design row count (obs-level: n_obs; subject-level: n_sub), as a number or as an expression over bound data (_predictor_rows_source). Blocks: intercept → ones(n), continuous → the bare column, factor → full-rank dummies over mapped levels, matrix → one part per element (ones(n) at intercept positions, the bare column otherwise — matrices hold data/derived columns only, so no latent wrap). plates names the per-cell latent vectors (a ContinuousTerm may scale one — the SB me mirror): a latent part wraps as Float64.(col), which materializes the layout's packed-slice view to a dense vector so the hcat stays homogeneous — a mixed Vector/SubArray hcat lowers through a Union-typed path Enzyme cannot differentiate.
ReactiveKernelsPPL.design_shape Method
design_shape(pred, columns; levelmaps, matrices) -> DesignShapeAnalyze one predictor's terms against raw columns. Factor blocks read their levels from levelmaps (keyed by predictor name + column); columns stay the source for continuous/offset terms. Matrix blocks read their columns from matrices (keyed by the term's matrix name).
ReactiveKernelsPPL.discrete_latent_draws Method
discrete_latent_draws(q::DiscreteLatentQuery, u, rng) -> NamedTuple
discrete_latent_draws(value, rng; position = nothing) -> NamedTupleOne exact draw of every summed-out discrete latent from its posterior, keyed like the posteriors: a hidden Markov observation's state path (Vector{Int}, one state per step; draw_hmm_states) and a mixture response's components (Vector{Int}, one per observation, drawn independently). value is the value of discrete_latents_node in any cut; position = k selects draw k of a vectorized cut. Only rng supplies randomness, in key order, so a seeded rng reproduces the draws.
ReactiveKernelsPPL.discrete_latents_node Method
discrete_latents_node(built) -> SymbolThe graph value of built that holds the posteriors of its summed-out discrete latents: the value prepare_discrete_latents evaluates. WANT it in any cut of built.spec beside other values, and vectorize that cut over draws; its leaves are numeric arrays, stacked on a trailing draw axis. Draw the latents of draw k with discrete_latent_draws(value, rng; position = k).
ReactiveKernelsPPL.factor_coordinates Method
factor_coordinates(catalogue, event) -> Vector{Int}
factor_coordinates(selection) -> Vector{Int}Packed coordinates owned by an authored draw or transform, excluding its hyperparameters and other read dependencies. Joint laws and coupled transforms own their whole packed block. A density on a derived expression owns no new coordinates; a flat prior still owns its declared coordinates despite having empty read support. Ownership comes from lowering/layout metadata at catalogue creation, not from factor_support or numerical derivatives.
For a set of fresh coordinates, select an event by these owned coordinates and retain it whole. If only part of an atomic block is fresh, that event cannot be split. Use factor_support separately to determine all inputs it reads.
ReactiveKernelsPPL.factor_support Method
factor_support(selection; u0 = nothing) -> Vector{Int}Sorted structural packed-coordinate support of the selected factors, including hyperparameters and transform dependencies. This is a conservative compiler read footprint: numerical zeros do not remove coordinates. u0 supplies only an exemplar; the support follows the bound indices and both branch arms.
ReactiveKernelsPPL.filter_checkpoint Function
filter_checkpoint(state)
resume_filter(target, checkpoint)Copy a versioned data-only checkpoint: finite carries, fixed parameter ensemble, weights, ancestry, bounded diagnostics and continuation RNG. Rebuild target from the original authored model and fixed data after restart. Resume checks the model/port/configuration signature, Julia/package versions and state shape. No compiled closures or stream observations are serialized. Exact continuation requires identical captured code and versions. Persist only trusted checkpoints with Julia Serialization; atomic file replacement remains the caller's job.
ReactiveKernelsPPL.filter_parameter_names Function
filter_parameter_names(model; observations=(:y,), inputs=(), data=(;))
filter_parameters(model, constrained_values; kwargs...)Identify static declarations outside authored scans, expanding the model's submodels. Names use authored dotted paths. filter_parameters selects and copies only those values from a flat or nested constrained named tuple/dict. Historical latent seeds, innovations and carried paths are excluded. Use it on each calibrated posterior draw before passing an ensemble to the filter; no retained training trajectories are needed. Inputs and already pinned values are not fixed parameters to extract. Requires the filtering extension.
ReactiveKernelsPPL.filter_step Function
filter_step(state, observation::NamedTuple; inputs=(;), condition_state_only=false,
groups=nothing)Advance one authored time slice and return a new conditioned cloud. The predictive_logscore is the log weighted mean of the new observation likelihood over the propagated, pre-assimilation particles; log_normalizer accumulates these scores. Then SequentialMonteCarlo weights/resamples the whole particle, including its independently owned finite carries. Each fixed parameter member retains its own conditional cloud; its mass is updated by its predictive score. carries[i].name[end, group] is a current state value; grouped state names are qualified as Symbol("group_binder.name"). weights combine member mass and equal conditional particle weights after resampling. Each bounded history entry contains the predictive score, the previous parameter-mass-weighted mean conditional ESS, parameter ESS, unique immediate parents and surviving original lineages. These expose state and parameter degeneracy; they do not guarantee Monte Carlo accuracy.
For parameters already calibrated on a training history, warm up the finite states on that history with condition_state_only=true. This conditions each member's latent states while preserving its parameter mass and the accumulated log_normalizer; it avoids counting the training likelihood twice. Cold initialization followed by ordinary steps updates both. Resume from a compatible joint checkpoint needs no warm-up. The warm-up flag is recorded in diagnostics.
Every engine invocation has exactly two iterations; even scalar engine diagnostics have bounded length. State and checkpoint retention is independent of elapsed time at fixed particle count, lag depth, group count and history_limit. Input state and RNG survive any failed step unchanged. All-zero, NaN and positive-infinite likelihood weights fail visibly.
ReactiveKernelsPPL.filter_stream Function
filter_stream(state, records; steps=typemax(Int), stop=state->false)Process records (observation=(; y=...), inputs=(; x=...)). Check stop before requesting each record; it may implement a cooperative interrupt. Return at the last completed observation. No iterator or stream history is retained. Use a stateful iterator when resuming consumption of the same live stream.
ReactiveKernelsPPL.frozen_values Method
frozen_values(bound, names) -> FrozenValuesThe values of the data-only definitions names (a Symbol or a collection of them) in the binding bound, as bind_data's frozen keyword takes them. A definition is data-only when it reads data alone, never a parameter: one binding evaluates (a fitted mean, a level set) or one RK preparation folds (a whole value a parameter-dependent call reads, such as an HSGP interval), which bound.columns does not hold. Each uses the binding's existing result or is evaluated on first demand from bound's data; a definition bound itself froze keeps its frozen value. The result also records the type and size of every data input those definitions read (never its values), so a binding that omits such an input still generates the same program.
Extract the data-only definitions from the fitted binding, then pass the result through bind_data's frozen keyword when binding prediction data.
ReactiveKernelsPPL.initialize_filter Function
initialize_filter(target; rng::Random.Xoshiro, particles=1000,
ensemble=nothing, weights=nothing, history_limit=32)Create an owned cloud before time 1, without advancing the supplied RNG. An optional fixed ensemble is a vector of complete parameter named tuples with the same keys/types as target.parameters. particles is the number of conditional state particles per ensemble member. weights gives the ensemble's initial normalized probability masses (uniform by default). Filtering reweights and resamples this finite approximation; it does not replenish static parameter diversity. Resampling stays within each member's conditional state cloud. Inspect parameter_mass, ESS, and surviving lineages for degeneracy. No implicit prior is sampled or scored.
ReactiveKernelsPPL.initialize_filter_smc Function
initialize_filter_smc(target; rng::Xoshiro, members=64, particles=128,
window_length=32, ess_fraction=0.5,
options=SMCOptions(), history_limit=32,
boundary=nothing, max_reflections=16)Initialize an owned parameter ensemble from its carried Gaussian and a separate conditional particle filter per member. Each new record reweights members by their predictive scores. Replenishment is triggered by the effective sample size over distinct parameter positions: the weights of bitwise-identical members are summed, so resampled copies count once. When it falls below ess_fraction*members, or any member has zero likelihood, resample the current parameter/conditional-filter pairs by their updated weights and move the selected members. Their retained window likelihood estimates and conditional clouds survive selection. Only one fixed-budget replenishment is attempted per step.
Each move proposes a Gaussian random walk whose covariance is 2.38^2/d times the members' weighted covariance before resampling (Roberts, Gelman and Gilks' scaling), fixed for the whole replenishment. That covariance keeps up to max_reflections leading correlation directions of the members, fitted in their marginally standardized frame with WarmupHMC.fit_gaussian_moments, so coordinates on very different scales are treated alike. The retained directions keep their weighted variance, and the remaining directions share the remaining standardized variance equally (probabilistic PCA). At most the distinct-position ESS minus 2 directions are kept. With none, or max_reflections=0, the walk is diagonal with the members' weighted marginal spread. Work and storage are O(members × d × directions), and no d × d matrix is formed. A diagonal walk leaves the narrow parameter combinations that the data pin down, such as a hierarchical intercept plus its group effects, and is rejected there. Its particle-Metropolis acceptance ratio is the window Gaussian prior ratio times the proposed/current window likelihood estimate ratio. Each proposal rebuilds conditional states from the frozen boundary. Rejections retain the previous estimate and conditional cloud. The kernel contributes only moves, the proposals per member. A coordinate whose weighted spread is zero cannot move: a population whose spread has vanished stays collapsed and fails as described below. Its recovery needs the independently tuned kernel of rejuvenate_smc.
After window_length records, replace the parameter posterior by a Gaussian with the members' weighted mean and their weighted covariance, summarized as above (up to max_reflections leading correlation directions). Then independently resample the weighted finite states into a pool of particles states as the next boundary, and draw a new ensemble and independent initial state clouds from these summaries. A diagonal boundary (max_reflections=0) treats the marginal widths of correlated parameters as independent information. Where the data inform only combinations, such as a hierarchical intercept and its group effects, the next window then contracts the population again, and every window compounds it. The calibration you supply is the first window's prior, so carry it with the same correlated summary (carry_smc(fit; parameters, basis=:correlation)); a diagonal calibration over-contracts the first window, and basis=:fit keeps few correlations when parameters differ greatly in scale. This discards parameter–state dependence and Gaussianizes the parameter posterior; it is an explicit assumed-density approximation, not exact full-history SMC². With a finite ensemble, the spread in directions that the data never inform still drifts downward from window to window, because each boundary estimates it again from the members; more members reduce the drift. Nonpositive/nonfinite marginal scales fail with SMCDegeneracyError at rollover; no scale is invented. Full spatial coincidence is checked on input and after the configured mutation pass, so resampling from one parent still gets its chance to move. An error preserves the input state in error.state and the rejected summary in error.diagnostics; no observation or RNG draw is committed on failure. Attempt explicit rejuvenate_smc recovery before retrying that observation. A constant coordinate alone is allowed within a window, until a Gaussian boundary needs its positive marginal scale. Cost and retained state are bounded by members, particles, groups and the chosen window length, not elapsed time.
Use filter_step/filter_stream, filter_checkpoint and resume_filter(target, checkpoint). Records include observations, inputs and optional active groups; missing observations keep the ordinary filter meaning. This learning route consumes new data once. For state-only training warm-up, first use the ordinary filter, then pass its state as boundary. Its weighted finite states are pooled independently of the new parameter draws; its time and group clocks are preserved, but its training scores are not added again. The boundary filter must have the same source/configuration identity. The learning state retains the sampled pool, never that old filter or its history. Caller RNGs, input states and observations remain unchanged on success/failure.
Supported read-only diagnostics on the returned state are positions (unconstrained static coordinates, one member per column), parameter_mass (normalized weights), time, window, window_length, records (the retained window; use length(state.records)), predictive_logscore, log_normalizer and history. Each retained history entry exposes time, window, window_steps, parameter_ess_before, parameter_ess_after, distinct_ess_before, distinct_ess_after, replenished, boundary_reset, boundary_directions, unique_parents, proposals, accepted, distinct_members, moved_members, coordinate_sd, kernel, proposal_scale, proposal_directions, kind, likelihood_evaluations, reference_evaluations and predictive_logscore. kind is :assimilate or :rejuvenate. parameter_ess_* counts members, copies included; distinct_ess_* counts distinct parameter positions and triggers replenishment. proposal_scale is the random walk's per-coordinate standard deviation in an assimilation replenishment (empty otherwise), and proposal_directions the correlation directions it kept. boundary_directions is the number the step's rollover kept (0 without one). reference_evaluations counts NUTS steps on the Gaussian reference, which only :rejuvenate recovery takes. moved_members counts final positions differing from the selected parent (or recovery input); accepted proposals may leave a position unchanged. coordinate_sd is the weighted marginal spread in unconstrained coordinates. History is capped by history_limit; counting replenished there counts only retained steps. For lifetime counts, accumulate the latest entry after each step with history_limit >= 1. Equal weights after resampling do not demonstrate mixing; inspect pre-resampling ESS, ancestry, actual movement and spread too.
ReactiveKernelsPPL.initialize_smc Function
initialize_smc(target; rng, particles=1000,
reference=SMCReference(zeros(d), ones(d)), options=SMCOptions())Draw the initial reference cloud, at temperature zero. Copies rng (an explicit Random.Xoshiro) and never advances the caller's RNG. The returned state owns its particle positions, normalized weights and continuation RNG. Call smc_step for one completed stage, or smc to finish the bridge. With options.tuning, an omitted reference uses the schedule's exact reference; an explicit different reference rejects before drawing any particles.
ReactiveKernelsPPL.isbound Method
Bound plans carry columns or a resolved observation-free execution size. bind_data also binds prior-only programs with no input columns.
ReactiveKernelsPPL.jacobian_term Method
jacobian_term(entry) -> Union{Nothing,Expr,Symbol}This entry's log-Jacobian contribution (nothing for identity). A scalar constrained support splices the bijector's logjac endpoint over the same coordinate the constrain edge reads (shared via structural CSE); a per-cell latent (plate) block sums its companion logjac plate (_plate_logjac_name); a leveled vector entry reads the ordered coordinates or the simplex transform's scalar Jacobian; an LKJ declared LKJ entry reads the retained sum over the partials shared with its transform. Legacy structural-margin LKJ blocks sum their named scalar edges.
ReactiveKernelsPPL.joined_coordinates Method
joined_coordinates(joined) -> Vector{NamedTuple}The joined coordinates in order: per coordinate the window that holds it first, its packed position there, and its coordinate_identities path and index. A joined point and gradient follow this order.
ReactiveKernelsPPL.joined_point Method
joined_point(joined, us) -> Vector{Float64}The joined point of the windows' packed points us: each joined coordinate from the window that holds it first. Fed inputs and later copies of shared coordinates in us are not read.
ReactiveKernelsPPL.joined_problem Method
joined_problem(joined) -> JoinedWindowsProblemThe joined windows as a log density of the joined point, for an optimizer, Pathfinder, a sampler or a variational fit.
sourceReactiveKernelsPPL.joined_value_and_gradient! Method
joined_value_and_gradient!(joined, g, x) -> (value, g)The joined windows' log density at the joined point x and its gradient over joined_coordinates, written into g. A fed input's derivative flows back through the previous window's boundary output.
ReactiveKernelsPPL.kernel_expr Method
kernel_expr(plan, layout; name=:ppl_model) -> ExprThe @kernel definition expression (Expr(:(=), signature, body)). Pure (no eval): the generator tests inspect and evaluate it. plan may also be a binding with nothing left to observe (model(; x)), read as bind_data(binding), exactly as build_kernel reads it.
ReactiveKernelsPPL.lkj_chol_constrain Method
lkj_chol_constrain(u, K) -> MatrixHost-side LKJ Cholesky-factor transform: Stan's partial-correlation C-vine (user direction — follow Stan where possible; the hyperspherical form survives as lkj_chol_constrain_hyperspherical). Packed column-block order for j in 2:K, i in 1:(j-1) (Stan's unconstrained order): z[i,j] = tanh(u), upper factor w[i,j] = z[i,j]*d[i-1,j] and w[j,j] = d[j-1,j], where the running product d[i,j] = d[i-1,j]*√(1-z[i,j]²) starts at d[0,j] = 1, and L = w'. Like Stan's running sum of squares, each column costs one square root per partial. The in-graph twins carry the identical left-associated running product, so host and graph agree bit-for-bit. K=1 constrains [] to [1.0].
ReactiveKernelsPPL.lkj_chol_constrain_hyperspherical Method
lkj_chol_constrain_hyperspherical(u, K) -> MatrixRETAINED alternative to lkj_chol_constrain (the pre-vine thin-layer-owned parameterization): row i >= 2 is a unit vector from i-1 logistic angles theta = pi*sigma(u) packed ROW-major: L[i,j] = cos(theta_j) * prod(sin(theta[1:j-1])), L[i,i] = prod(sin(theta)). Valid density, same constrained space — kept for comparison, not wired into any layout.
ReactiveKernelsPPL.lkj_chol_logjac Method
Log-Jacobian of lkj_chol_constrain: Stan's vine Σ_{i<j}((j-i+1)/2)·log(1-z[i,j]²) with z = tanh(u) (the L→L' Jacobian plus the tanh terms — NOT the manual's corr_matrix formula, which carries the L→LL' step too). FD-verified. The in-graph twin unrolls the identical sum over the shared z temps, so host and graph agree bit-for-bit. K=2: log(1-tanh(u)²).
ReactiveKernelsPPL.lkj_chol_logjac_hyperspherical Method
Log-Jacobian of lkj_chol_constrain_hyperspherical: per-angle (i-j)*log(sin theta) + logistic log(pi) + log(s) + log1p(-s), summed row-major.
ReactiveKernelsPPL.lkj_chol_unconstrain Method
Inverse of lkj_chol_constrain: sequential vine inversion (w = L'; z[1,j] = w[1,j]; z[i,j] = w[i,j]/Π_{ip<i}√(1-z[ip,j]²)), then u = atanh(z). Loud on non-square input, non-positive diagonals, and out-of-(-1,1) partials (not a Cholesky factor).
ReactiveKernelsPPL.lkj_chol_unconstrain_hyperspherical Method
Inverse of lkj_chol_constrain_hyperspherical: hyperspherical inversion per row (theta_j = atan(hypot(row[j+1:i]), row[j])), then u = log(theta) - log(pi - theta).
ReactiveKernelsPPL.lkj_corr_cholesky_logpdf Method
lkj_corr_cholesky_logpdf(L, eta) -> Float64Host-side LKJ Cholesky log-density (Stan lkj_corr_cholesky_lpdf, propto=false): diagonal sum over rows 2..K plus lkj_logconst. Stan's op order is preserved verbatim (per-diagonal (Km1-k-1)*ld + (2*eta-2)*ld; the eta == 1.0 single-term branch) so joint parity against Stan holds to 1ulp. K=1 is exactly 0.0.
ReactiveKernelsPPL.lkj_logconst Method
lkj_logconst(K, eta) -> Float64LKJ normalizing constant: verbatim port of Stan's do_lkj_constant (Lewandowski–Kurowicka–Joe 2009, theorem 5), INCLUDING the eta == 1.0 fast branch — the joint parity case compares against Stan's lkj_corr_cholesky_lpdf with the same branch taken, so the branch dispatch is load-bearing, not cosmetic. K=1 is ±0.0 (== 0.0 either way — the eta==1.0 branch yields -0.0, exactly as Stan does).
ReactiveKernelsPPL.logjac Method
logjac(layout, unconstrained) -> RealHost-side total log-Jacobian, using the same source-coordinate formulas as the in-graph terms (positive: u; unit: -log1pexp(-u) - log1pexp(u)).
ReactiveKernelsPPL.lower_rkppl Method
lower_rkppl(ast, data_names; mod=Main) -> StructuralPlan
lower_rkppl(ast, data; mod=Main) -> StructuralPlanLower a captured @rkppl block AST to a data-free (unbound) plan. data_names (or the keys of data, a dict or NamedTuple of values) declares supplied values. Pass their observation roles separately with conditioned = (:y, :tau). The keyword accepts names or the keys of a NamedTuple/dict. A conditioned sampling declaration contributes likelihood at its constrained value, with no sampled coordinate or transform Jacobian. Unconditioned supplied names must be inputs; remove a sampling declaration with a merge pin to supply it as an input instead. Runs validate_structure before returning. The BRM emitter calls this entry point directly with ASTs.
mod is the module against which latent ~ sm(args...) call heads are resolved to RKPPLSubmodels; a resolving call is expanded inline before partitioning (see _expand_submodels), and a call inside a submodel body resolves against that submodel's defining module.
Functions as values: an = definition may call any function visible in mod (a submodel body: in its own defining module). Call heads outside the built-in value vocabulary resolve to GlobalRefs at lowering, and an undefined one fails here naming it. An undotted call takes and returns whole Julia values; a dotted call f.(...) is elementwise, observation aligned exactly when an argument is; v[c] with an observation index is a gather. A data-only definition calling such a function is evaluated once by bind_data and bound as data; one that a parameter-dependent expression consumes (named or inline) is evaluated once by preparation and never differentiated. Any other call runs in the generated kernel under generic AD (an RK-owned derivative rule, when the callee is one, is used by Enzyme). A parameter-dependent undotted call may read observation columns and return a scalar or an observation-length vector for use as a location or predictor operand. Julia checks its concrete shape when evaluated. A data column read only inside whole-value calls, with no per-observation consumer, is a model-level data input of any length at bind.
Input ownership and concurrency: lower_rkppl is concurrency-safe and takes no lock, so independent lowerings run concurrently. Neither ast nor the submodel bodies reachable through mod is mutated, so one AST may be lowered repeatedly and shared across tasks. Submodel and function resolution only READ mod bindings (isdefined / getfield — no eval, no registration), so definitions in distinct private modules never collide: one fresh Module per lowering, each holding its own @rkppl name(args...) = ... defs, is sufficient for concurrent independent lowerings.
Lowering resolves these bindings in a package-owned latest-world scope, including kernels and imports just created by Core.eval in a builder. No caller-side invokelatest is needed for lowering on Julia 1.12 or later.
Declared coefficients are ordinary named parameters. A scalar b ~ Fam(...) keeps its name, prior and transform when an affine term reads it as b .* x. A sized declaration such as c[levels(g)] or b[axes(X, 2)] remains an array parameter when read as c[g] or X * b. Affine optimization records references to those values and may pack their reads for a matrix multiply. Other predictors, assignments and prior arguments can read the same declaration without changing its coordinates or adding another prior.
Data are values of any shape. Given the values (data), lowering reads each one's shape: a number has no observation axis, so it lowers as a model-level value — exactly as the definition s = 2.0 would read, except that bind_data binds the number and the kernel takes it as a typed scalar argument (y .~ Normal.(mu, s) broadcasts it, as Julia does). Every @rkppl entry point (the model call, @rkppl data, merge pins) lowers with the values. Given names only, binding a number to an ordinary broadcast argument also keeps Julia's scalar broadcasting. A number bound to a response is one observation. A value holding one array per index (t = [[0.1, 0.7], [0.2]]) makes every @plate cell that reads it at the loop index, directly or through values computed from it, one iteration of its Julia loop whatever operators the cell applies (t[i] * a, -t[i]). So does a definition reading only data that a cell reads at the loop index (rows = part(g, cells), then x[rows[i]] * a), when its value holds one array per index: lowering evaluates such a definition to see that. Names alone cannot show this, so such a plan refuses those arrays at binding.
frozen (FrozenValues, from frozen_values) lowers a design that freezes data-only definitions by value: each data input the record describes and data omits (a fit-role copy x_fit of training data) is data of its recorded type and size, so the plan is the one lowering with that input gives. The plan carries frozen, and bind_data binds it by default.
ReactiveKernelsPPL.marginalize Method
marginalize(model, names::Symbol...; predictive = (;), filtered = (;)) -> modelIntegrate the latent @scan arrays names out of model exactly, as a Kalman filter. model is an RKPPLModel or a binding of one (model(; inputs...)); the result composes with | and condition as the model does. The model source keeps the recurrence as written.
A marginalized array x qualifies when
its
@scancarriesxalone, seeded once:x[1] ~ Normal(m0, s0)orx[1] = m0;each step is linear-Gaussian in the previous state: centred,
x[t] ~ Normal(a * x[t - 1] + c, s), or non-centred,e ~ Normal(mu, sigma); x[t] = a * x[t - 1] + c + b * e, wherea,b,c,s,muandsigmamay read parameters, data, definitions, the loop index and earlier step locals but notxor an innovation. Locals that are themselves linear inx[t - 1]and the innovations (w = s * e) may enter the write;one statement reads it, a Normal observation of a whole observed data vector whose location is affine in it and whose scale does not read it:
y .~ Normal.(offset .+ loading .* x, noise). Amissingentry ofyis a step that only predicts: the filter carries the state through it without an update, and the likelihood has no term for it.ymay also be a vector the model defines without readingx, such as measured rows merged in time order with bounded latents of censored ones (data augmentation:gap[1:K] .~ restricted.(Flat.(), 0, Inf),y = vcat(measured, limit .- gap)[order]). The filter then observes each entry at its value, and the scan's length is supplied. Condition the measured rows,| (; measured): their entries' one-step-ahead predictive densities are then the likelihood and:pointwise.measured, and the other entries' are prior factors. Bound as an input instead,measuredis not conditioned, and every entry's density is a prior factor. Rows may instead observe the state at their steps,y .~ Normal.(offset .+ loading .* x[step], noise)withstepbound integer data: a step may have several rows or none. The filter then runs over events (each step, then its rows in order), the scan's length is supplied, and each row's pointwise density is its predictive given the rows before it in that order.
Any other form is refused with a SurfaceLoweringError naming the statement. Each scalar coefficient may vary by step (irregular gaps exp(-gap[t] / range), a reset r = 0 where a new series starts).
A top-level @scan carrying several arrays, or reading one at a lag above 1 (seeded at x[1], …, x[p], its loop from p + 1), has a vector state: name every array it carries, marginalize(model, :level, :slope). Each seed is a Normal draw or a value affine in the seeds above it, and each step writes every array once, affine in the lags a[t - k], the values written above it in the same step and Normal innovations (a local linear trend level[t] ~ Normal(level[t - 1] + slope[t - 1], s), an AR(2) x[t] ~ Normal(a1 * x[t - 1] + a2 * x[t - 2], s)). One statement reads the arrays, y .~ Normal.(offset .+ loading_a .* a .+ …, noise), an observation of bound data without missing entries whose location is affine in them. The filter carries the window a[t - j], j < p, of every array, and the draws return each array under its name. A vector state observed otherwise or in a @plate cell is refused.
A recurrence a submodel holds is named by its author path: marginalize(model, Symbol("z.x")) for the array x of z ~ sm(…) (a nested call: Symbol("z.w.x")). It integrates out as its top-level spelling does, and its draws nest under the call, draws.z.x, as constrain nests sampled locals.
A recurrence in a @plate for g in … cell integrates out one filter per index, when the cell's @scan carries x as above and one statement of the cell observes it, y[g] .~ Normal.(offset .+ loading .* x, noise), with y bound data holding one vector per index. A cell definition or per-index output read only by that observation (loc[g] = level[g] .+ x) is part of it. Each of offset, loading and noise is one value per index (a declared array or data vector read as a[g], a parameter, a cell scalar) or one value per entry of y[g] (data holding one vector per index read as w[g], and broadcasts of these). The draws hold one trajectory per index.
The marginalized program's density is the exact marginal density of the observations given the remaining parameters, so coordinate_names and the layout no longer contain x or its innovations. :pointwise.y holds the one-step-ahead predictive densities (0 at a missing entry), whose sum is the marginal likelihood; for a merged y, :pointwise.measured holds those of the measured entries. Exact draws of x given the parameters come from prepare_marginalized_latents and marginalized_latent_draws.
The filter's values become named values of the program when the call names them. predictive names the one-step-ahead predictive law of each observed entry given the entries before it, any of predictive = (location = :mu, variance = :v, scale = :sd); filtered names the filtered mean and variance of the state given the observations up to each step, filtered = (mean = :m, variance = :v), or per array for a call integrating out several, filtered = (level = (mean = :level_mean,), slope = (variance = :slope_var,)). Each name is an ordinary value: prepare_query(built, plan, (:mu, :sd)) returns it, jax_source(built, plan; values = (:mu, :sd)) emits it in constrain, kernel_expr shows it. A predictive value holds one value per entry of y (at a missing entry, its forecast from the entries before it), one per row for rows observing x[step], and in a @plate cell one vector per index (mu[g]); a filtered value holds one value per step (one vector per index in a cell). Nothing is added when nothing is named, and naming values leaves the density unchanged. A name the model already uses, a name starting with _rkppl, a name given twice, and a call naming values for recurrences that different statements observe are refused: call marginalize once per recurrence, marginalize(marginalize(model, :x; …), :z; …).
Marginalize the model or its binding before observing it: marginalize(model(; inputs...), :x) | (; y). A bound plan (the result of |) is already lowered and is refused.
ReactiveKernelsPPL.marginalized_latent_draws Method
marginalized_latent_draws(q::MarginalizedLatentQuery, u, rng) -> NamedTuple
marginalized_latent_draws(filtered::NamedTuple, rng) -> NamedTupleOne exact draw of every marginalized recurrence given the parameters u, keyed by latent name (Vector{Float64}, one value per entry; for a recurrence per @plate index, one such vector per index), by forward filtering, backward sampling over q(u). Only rng supplies randomness, in key order and then index order, so a seeded rng reproduces the draws. At posterior draws of the parameters, parameters and latents together are exact draws from the joint posterior of the model as written.
ReactiveKernelsPPL.markov_chains Method
markov_chains(model, names::Symbol...) -> modelMark the latent @scan arrays names as Markov chains for WarmupHMC's adaptive centring (WarmupHMC 0.3.1 or later). model is an RKPPLModel or a binding of one; the result composes with |, condition and merge as the model does. adaptive_centering_problem then gives each marked recurrence one WarmupHMC.MarkovChain, whose warm-up chooses per time step how far to centre it: centred where observations pin it, the innovation where they do not.
A marked array x qualifies as for marginalize: its @scan (top level, or a statement of a @plate cell) carries x alone, seeded once (x[1] ~ Normal(m0, s0) or x[1] = m0), and each step is linear-Gaussian in x[t - 1], centred (x[t] ~ Normal(a * x[t - 1] + c, s)) or non-centred (e ~ Normal(0, 1); x[t] = a * x[t - 1] + c + s * e). The coefficients may read parameters, data, definitions and the loop index, but no value a chain or an adaptive cell transforms. Unlike marginalize, any observation may read x.
The program is lowered in the states: a non-centred step becomes its centred law, so the packed coordinates are the states of x (its sampled seed, then each step) instead of its innovations. The density of every other parameter is unchanged. Any other form is refused with a SurfaceLoweringError naming the statement.
A recurrence per @plate index is one chain too, not one per index: its states are every index's, in plate order and in time order within an index. Each index's first state has coefficient 0, so its location is that index's own seed location and the chain restarts there. Warm-up's controls are per state, so no centring makes one index's states depend on another's. Draws are in the model's frame under any controls.
WarmupHMC.reparam_sources(rp) of the problem adaptive_centering_problem returns shows the chains as chains: one (; phi, c) per marked array, sorted by name, each with one entry per state. An index contributes its scan's length with a sampled seed and one fewer with a fixed seed x[1] = m0, which is not a state. Before warm-up every entry is phi = 0, c = 1, the model as written. adaptive_centering_problem throws a ContractValidationError rather than build a chain whose recorded states do not match the packed seed and step blocks of x in number.
ReactiveKernelsPPL.model_view Method
model_view(built; bound = nothing, query = nothing) -> RKPPLModelView
model_view(spec, layout; bound = nothing, query = nothing) -> RKPPLModelViewDisplay an existing build. built is the (; spec, layout) returned by build_kernel, including the built model a BRM RKBRMI backend retains as backend.model. The built program, structural graph and coordinates need nothing else.
Pass bound, the bound StructuralPlan (or the binding) that was built, to add the generated pre-build kernel definition, and query, a kernel returned by prepare_query or a SamplerQuery, to add its prepared program (with its bound data folded in as literals). These values are only read; the model is not bound, built, prepared or evaluated again. The code pane lowers the stored spec to obtain its planned expression.
ReactiveKernelsPPL.offset_name Method
Offset-vector recipe name for a predictor (mu → _ppl_offset_mu).
ReactiveKernelsPPL.offset_recipe Method
offset_recipe(shape; scalars, n_rows, broadcast) -> Union{Nothing,Expr}_ppl_offset_<pred> = col1 .+ col2 .+ … over offset-term columns, or nothing when the predictor has no offset terms. A sum with a scalar assignment from scalars gets n_rows rows (_ppl_rows; a number or an expression over bound data) unless broadcast retains its scalar shape; the sum is then a statement of its own, returned before it in a block, so a cell computes it at its rows (_ppl_rows_at).
ReactiveKernelsPPL.ordered_constrain Method
ordered_constrain(u) -> VectorHost-side ordered transform (Stan ordered): y[1] = u[1], y[i] = y[i-1] + exp(u[i]). The in-graph transform uses the same recurrence. Like every host transform, it follows the input's number type and returns Float64 values for plain reals.
ReactiveKernelsPPL.parameter_metadata Method
parameter_metadata(built) -> Vector{<:NamedTuple}
parameter_metadata(layout::LayoutTable) -> Vector{<:NamedTuple}Inspect the constrained parameters of an existing build_kernel result (including a BRM backend's model) or its layout. Each record contains:
path: a tuple of authoredSymbolname segments. Submodel namespaces remain separate segments; a literal dot in a name remains part of that name.rank,shape: the constrained value's number of dimensions and size tuple. A scalar has rank0and shape().element_shapes:nothingfor ordinary scalar/array parameters; for a container of cell values, a fresh vector of size tuples, including scalar()and empty cells. Its outershapeis(number_of_cells,).ncoordinates: the parameter's packed unconstrained coordinate count. This can differ from its constrained size (e.g. a length-three simplex has two coordinates). Parameters with zero coordinates are retained.
Records follow the depth-first leaf order of constrain's named result. Split coefficient runs are grouped under their exposed predictor name. Only parameters present in the layout are reported, not data, conditioned values or derived quantities.
This reads stored layout dimensions and bound cell-shape tables. It does not bind, build, prepare, fit or evaluate a model, bound expression, data operation, or caller-owned geometry endpoint. Returned containers do not alias the layout.
Dimensions belong to the supplied layout's binding. Reusing a build with new data (for example BRM reprocess) does not update that build's layout. To inspect a different binding, supply its already-created layout. A bound StructuralPlan alone is not accepted: this accessor does not assign a layout or infer current dimensions from a different binding.
ReactiveKernelsPPL.parse_scan_block Method
parse_scan_block(block; label = :scan) -> ScanSpecParse the inner begin … end block of a @scan annotated loop into a ScanSpec. Pure and syntactic — see this file's header for the grammar and boundaries. Every rejection raises SurfaceLoweringError.
ReactiveKernelsPPL.partition_batch_value_and_gradient! Method
partition_batch_value_and_gradient!(s::PartitionSampler, g, u, labels; weights = nothing)The summed log density of the partitions in the collection labels, and its gradient over the whole packed vector, written into g for a compact sampler too. Returns (value, g). u is read only. A label may repeat, which counts its partition again, and an empty collection gives zero. weights, one number per label, multiplies each partition's term, as a minibatch's scale does.
Every label adds to one cotangent of the shared values, and one pullback through them runs at the end, so a batch costs its partitions' footprints plus one pullback. Sweeping the same labels through partition_value_and_gradient! runs that pullback once per label. A batch does not make the shared values local, so it costs at least that one pullback: for most of a model's partitions an ordinary whole-model gradient can be cheaper. A sampler prepared without partitioned or without shared values has no pullback to share, and its batch is the plain sum.
The first call prepares the batch's operators, and native AutoEnzyme reverse is required, as for prepare_cell_accumulator. A unit's own coordinates are at partition_footprint(s, label; shared = false) in g.
ReactiveKernelsPPL.partition_labels Method
partition_labels(q) -> VectorThe distinct keys of the partitioned observations, in first-seen order over the observations named at preparation: every label the query accepts.
sourceReactiveKernelsPPL.partition_value_and_gradient! Method
partition_value_and_gradient!(s::PartitionSampler, g, u, label; shared = true)The partition label's log density and its gradient, written into g: over partition_footprint(s, label), in that order, for a compact sampler (length(g) must be the footprint's length), or over the whole packed vector otherwise. Returns (value, g). u is read only.
With shared = false, return only the derivatives of the coordinates named by partitioned at preparation. A compact destination follows partition_footprint(s, label; shared = false); a dense destination retains the full packed length, with every shared-coordinate entry zero. The value is unchanged. This reuses the shared prefix's value and differentiates only local coordinates, without allocating derivatives for its cached frontier.
ReactiveKernelsPPL.pool_smc Function
pool_smc(clouds::AbstractVector) -> (; log_normalizer, cloud_weights,
effective_clouds, positions, weights)Combine independent SMC clouds of one prepared target into one evidence estimate and one weighted sample. Each cloud is an SMC state or its smc_checkpoint record, in any mix. Each cloud's normalizer estimate Ẑ_c = exp(log_normalizer) is unbiased only up to the adaptive temperature and kernel choices, so averaging Ẑ, not log Ẑ, is the consistent combination:log_normalizeris the log of the clouds' mean Ẑ,cloud_weightsare Ẑ_c / ΣẐ,effective_cloudsis 1/Σcloud_weights², andpositionsholds every cloud's particles side by side, each weighted by its cloud weight times its weight in the cloud (weights sums to one).
When a mode or grouping takes over along the path, a cloud may hold it with a few particles in poor positions that its moves improve only slowly. Until they do, the stages weigh that mode too little, so that cloud's log Ẑ is low; ESS, temperatures and the stage summaries do not show it. Because Ẑ itself is about unbiased, that error is one-sided: clouds that end alike but differ in log Ẑ are not noise around the truth, and the highest clouds dominate the pool. effective_clouds near one says the pool rests on one cloud and the clouds disagree, so more clouds or particles are needed. With probability at least 1 - α, log Z ≥ log_normalizer - log(1/α), to the extent Ẑ is unbiased.
All clouds must share the temperature and the prepared target's model, binding and frame identity; below temperature 1 they must also share the source. The inputs are not mutated.
Clouds run in separate processes pool through their checkpoints: each process saves smc_checkpoint(state) with Julia Serialization, and one process deserializes the records and passes them here. That process needs this package's SMC extension loaded to read them, but no prepared target: pooling reads each record's stored identity, normalizer, particles and weights and evaluates no density, so the records may come from other hosts. A record must pass the checks resume_smc makes without a target (schema, particles, bridge state, a completed stage). Package versions are not compared. Save the checkpoint, not the SMCState: a serialized state carries its target (prepared queries, AD backend, a prepared density's factory and problem), so reading it back needs the model's code and backend loaded and holds only what Serialization can reproduce of them.
ReactiveKernelsPPL.predictive_draws! Method
predictive_draws!(out::NamedTuple, value, targets, rng; position = nothing) -> out
predictive_draws!(out::NamedTuple, q::PredictiveQuery, u, rng) -> outDraw every observation into out (a result of predictive_draws or q(u, rng), or arrays of the same shapes), reusing its storage.
ReactiveKernelsPPL.predictive_draws Method
predictive_draws(value, targets, rng; position = nothing) -> NamedTuple
(q::PredictiveQuery)(u, rng) -> NamedTupleOne posterior-predictive draw of every observation, keyed like :pointwise and shaped like the responses, from the laws predictive_laws gives for value, targets and position. q(u, rng) draws at the parameters u. Entries are drawn in order (column-major, then index by index for a response holding one array per index), so a seeded rng reproduces the draws, and passing a copy of one RNG at every posterior draw reuses one stream.
ReactiveKernelsPPL.predictive_laws Method
predictive_laws(value, targets; position = nothing) -> NamedTuple
predictive_laws(q::PredictiveQuery, u) -> NamedTupleThe law of every observation, keyed like :pointwise: a lazy PredictiveLaws array shaped like each response (a number bound to a response is one observation, as in :pointwise), and a vector of them for a response holding one array per @plate index.
value is the value of predictive_node in any cut, and targets is predictive_targets of the design that cut evaluates. A cut vectorized over draws returns the value stacked on its trailing axis: position = k takes draw k's laws, without copying. q(u)'s laws are predictive_laws(q, u).
ReactiveKernelsPPL.predictive_node Method
predictive_node(built) -> SymbolThe graph value of built (build_kernel's result) that holds every observation's law arguments: the value prepare_predictive evaluates. WANT it in any cut of built.spec, or of a graph composed from it, beside other values and with any HAVE that determines it (random effects, interventions or design data as runtime inputs), and vectorize that cut over draws like any other. Then turn its value into laws or draws with predictive_laws, predictive_draws or predictive_draws!, given predictive_targets.
Use predictive_targets for the binding and retain the node in the prepared cut. After vectorization, the position keyword of predictive_draws selects one draw.
The value holds numbers only (one array per law argument), so a vectorized cut stacks it on its trailing draw axis; its layout is otherwise not part of the interface.
sourceReactiveKernelsPPL.predictive_targets Method
predictive_targets(built, plan) -> NamedTupleThe shape each observation's draws take on the binding plan of the program built was built from, keyed like :pointwise: the bound response's shape, or, for a response plan leaves absent, the shape of the operands it broadcasts with. A response holding one array per @plate index takes each index's shape (from the law values themselves when the response is absent and no data the cell reads per index fix it). Pass it to predictive_laws and predictive_draws with the value of predictive_node on a cut over the same design.
ReactiveKernelsPPL.prepare_cell_accumulator Method
prepare_cell_accumulator(query, backend, u0; order=0, cell0=1, term0=1, sums0=nothing)Prepare additive mixed derivatives from a prefix-cached CompactCellAD or CellFactorAD. order and backend follow RK's prepare_ad_accumulator: 0 accumulates gradients, 1 local-direction HVPs, and 2 third contractions with two local directions. The resulting gradient includes shared coordinates. For an outer factor, the direction also includes its independent sum inputs, as (sum_direction, coordinate_direction). Use the same cached factor owner for all operators participating in a cell_pullback! pass.
ReactiveKernelsPPL.prepare_cell_factor_ad Method
prepare_cell_factor_ad(prepare_operator, f, factor, base0, indices0, backend, exemplars...;
cell0 = 1, term0 = 1)Prepare the outer density (factor = :outer) or one summand (factor = j) with any RK derivative preparation accepted by prepare_compact_cell_ad. The outer uses two active ports (sums, active), so its directions and derivatives are tuples of those vectors. Call RK derivative verbs with base, sums, active, indices, cell last. A summand has only active; call with base, active, indices, cell, term last, where term is a position in reduction_rows(f, j, cell), not a row label. Select the packed coordinates read directly by the outer, or by that summand, respectively. Selections may change between calls as for prepare_compact_cell_ad.
Each prepared operator owns its compact selection map; use one per concurrent caller. base and indices are read only. Empty reductions have no summand calls and contribute a zero sum to the outer. cell0 and term0 select the preparation exemplar; use a nonempty cell for a backend that evaluates its summand exemplar. The outer's exemplar sums are evaluated from base0 once at preparation and always form a vector, including a single reduction.
ReactiveKernelsPPL.prepare_cell_factor_query Method
prepare_cell_factor_query(f::CellFactors, factor) -> CellFactorQueryPrepare a scalar value query for the outer density (factor = :outer) or one summand (factor = j), without AD or a compact coordinate selection. Call the outer as q(u, sums, cell) and a summand as q(u, cell, term). sums follows cell_reductions(f); term is a position in reduction_rows(f, j, cell), not a row label. Empty reductions have no summand calls. With no reductions, pass an empty sum vector to the outer.
An AbstractVector{Float64} packed point is passed through without copying, so a recording vector can observe the reads made by that evaluation. Recording observes only the executed path. For a structural footprint, including both arms of retained branches, prepare fp = ReactiveKernels.partition_footprint_kernel(q.kernel) once and call Base.invokelatest(fp, args...).unconstrained with the same arguments as q. The result is sorted unique packed indices, or :whole; the latter means collect(eachindex(u)). Structural footprints may be conservative, as for prepare_cell_query. The outer footprint treats the supplied sums as independent and therefore contains only its direct packed-coordinate reads. Scalar vector reads such as eta[anchor[cell]] retain row demand through elementwise predictors, including when the same predictor feeds a sum.
Use these footprints to select compact coordinates for prepare_cell_factor_ad. The public kernel property also supports RK's code_expr and partition_locality inspection. Other real-valued packed vectors are converted to Vector{Float64}, as for CellQuery.
Native preparation uses a packed Vector{Float64}, Int positions and a Vector{Float64} of sums, so that a strict cell knows which of its values are numbers. Query calls keep other argument types by preparing and caching a specialization for them, as CellQuery does. Without a shared prefix, direct calls to q.kernel and its full footprint kernel require those exact types.
ReactiveKernelsPPL.prepare_cell_factors Method
prepare_cell_factors(built, plan, observation; on_error = nothing, locality = nothing)Discover sums read by one observation's cell, including sums in earlier plates composed into it. The model may name a sum or write it inline. Factored sums have elementwise operands with data-defined gathered rows; other sums remain in the outer computation. This includes weighted operands sum(exp.(eta[rows[k]]) .* w[rows[k]]) and a cell-local mu = exp.(eta[rows[k]]) used by several sums, such as NegativeBinomial2(sum(mu), phi * sum(mu)^2 / sum(mu .^ 2)). Ordinary array sums such as sum(z[rows[k]] + w[rows[k]]) also expose local summands, including through transparent forwarding helpers. Base array dispatch and the original full-array shape checks must be proved; addition is not treated as a broadcast with singleton expansion. Typed identity assignments between plates do not hide these sums when the input already satisfies the declaration; real conversions remain in the graph. cell_reductions(f) gives the reductions in graph order; reduction_rows(f, j, cell) gives reduction j's row labels in term order. When several operands gather different arrays, labels come from the first gather; each term still reads all operands at its corresponding position.
Use prepare_cell_factor_query for values and packed-coordinate footprints before selecting coordinates for prepare_cell_factor_ad. Both prepare the outer density (:outer) or one summand (reduction index j). With no sums the outer is the ordinary cell. The outer's sum inputs are independent values: their dependence on the packed point is supplied by the summand operators and the chain rule.
A sum whose summands read another sum (a density total over dose .* f.(t), with dose a sum) is no reduction: it stays in the outer factor, which reads the inner sum from its sum vector and computes the total at its own rows.
Pass partitioned = :z, u0 = u (or partitioned = :none when cells own no parameter) to cache shared-only whole-array producers before factoring. Values refresh when the shared coordinates change. Compact factor AD then selects only partitioned coordinates. Mixed shared derivatives use prepare_cell_accumulator and cell_pullback!; operators prepared from this factor family share one prefix cache and pullback pass. Inside the callback, factor derivative verbs accept the active pullback in place of base, reusing its copied point without rescanning shared coordinates.
ReactiveKernelsPPL.prepare_cell_pullback Method
prepare_cell_pullback(owner, backend, u0)Prepare one shared pullback for a CellFactors or CompactCellAD constructed with partitioned. backend is a reverse backend. Use cell_pullback! to accumulate contributions from operators sharing this owner's cache. Storage is linear in the packed point and shared frontier, independent of the number of cells; no cell-by-population Jacobian is formed. One object per concurrent caller, including its owner and associated cell operators.
ReactiveKernelsPPL.prepare_cell_query Method
prepare_cell_query(built, plan, observations; on_error = nothing, locality = nothing,
partitioned = (), u0 = nothing) -> CellQueryPrepare the summed log density of ONE cell of the observations named in observations (a name or a collection of names), evaluated at an unconstrained point u and a position i: q(u, i). Each observation's pointwise values come from a plate (:pointwise's array for that name); cell i is that plate's entry i, so
sum(q(u, i) for i in eachindex(pointwise.y)) == pointwise likelihood of ylocality says what preparation does with a model value the cell reads at its rows but would compute whole (RK plate_cell): :error refuses the query with a ReactiveKernels.PartitionLocalityError naming each such value and its statement, :warn names each once per process, :ignore says nothing; nothing reads the ReactiveKernels preference cell_locality ("warn" unless set). ReactiveKernels.partition_locality(q) lists the executed residual's values.
Optional partitioned identifies parameters that can change between local evaluations, using the names, parameter => level_labels or :none accepted by prepare_partition_sampler. Other coordinates are shared. The query caches their intermediate values across cells and local changes, compares the shared coordinates those values read by value (including in-place edits), and refreshes when one changes. A shared coordinate they do not read needs no refresh. Row-capable calculations remain in the residual. This cell declaration identifies cache dependencies; it adds no per-key separability claim because a cell query has no partition key. A partition query checks separability when the same declaration is supplied.
Native preparation initially uses a packed Vector{Float64} and an Int cell position. Query calls preserve other AbstractVector{Float64} inputs and cache specializations for their argument types, including Cartesian indices. Other element types are converted to Float64. Direct calls to q.kernel require the initial exact types. u0 supplies a valid packed preparation point for the shared prefix; it defaults to zeros. It is copied. Each query owns its cache and is not thread-safe. q.kernel remains the original packed-coordinate kernel for the footprint recipe below; through-prefix dependencies are not lost. For cached evaluation call q(u, i), and use partition_locality(q) to inspect its residual.
For an @plate for i in eachindex(y) loop holding one array per index (y[i] .~ …), entry i is the sum of iteration i's densities. Several observations of one loop share the position: q(u, i) adds their cells.
Only cell i of each plate runs, through the plate's own body (RK plate_cell): an @plate for loop's location plate is composed into it, so the cell's own observations cost what one iteration costs. Values the cell reads whole, such as a predictor vector log_k indexed by log_k[i], are computed whole. Observations without a pointwise plate (a scalar ~ observation, a joint multivariate response) are refused naming the observation. plan must generate the program built was built from, as for prepare_query.
For the packed coordinates a cell reads, use RK's structural footprint API: prepare ReactiveKernels.partition_footprint_kernel(q.kernel) and evaluate it at the packed point and cell position. Its unconstrained field is either a vector of read positions or :whole.
Prepare q and footprint once per selected observation (or observations sharing a cell position), then vary i. This needs no AD preparation, cell key column, or plan per cell. For a single call, ReactiveKernels.partition_footprint(q.kernel, u, i).unconstrained prepares and caches the footprint kernel. Positions are sorted, unique linear indices into u; :whole means the whole packed vector. This is a structural read set, including both arms of a retained lazy branch and reads multiplied by zero, not a numerical nonzero-gradient test. To form a sparse Hessian pattern, union the cliques of the individual cell supports (restricted to the desired coordinates); a clique of their union introduces cross-cell pairs.
The set can be conservative: array captures read inside a retained conditional can contribute their entire packed block, even with locality = :error. That setting checks values requested at rows; it does not guarantee a minimal footprint for every capture. Inspect the supports of the actual model before assuming a fixed per-cell width.
ReactiveKernelsPPL.prepare_cell_sampler Method
prepare_cell_sampler(built, plan, observations, u0; backend, on_error = nothing, locality = nothing) -> CellSamplerprepare_cell_query plus a prepare_ad gradient with active = :unconstrained; the position stays a constant (an Int). u0 is a length-consistent exemplar and backend a DifferentiationInterface backend, as for prepare_sampler. locality is passed to prepare_cell_query.
ReactiveKernelsPPL.prepare_compact_cell_ad Method
prepare_compact_cell_ad(prepare_operator, built, plan, observations, base0, indices0,
backend, exemplars...; on_error = nothing, locality = nothing)
-> CompactCellADPrepare a ReactiveKernels derivative operator over one cell of the observations named in observations, differentiating with respect to the packed coordinates at the sorted, unique positions indices0 over the read-only packed base base0, as prepare_compact_cell_sampler does for the gradient. prepare_operator is the ReactiveKernels preparation to apply (prepare_ad, prepare_ad_pullback, prepare_ad_pushforward, prepare_ad_hvp or prepare_ad_third), and exemplars are its arguments between the backend and the point: the directions for an HVP or a third-order derivative, each of the selection's length.
For a Hessian block, supply one unit direction per selected coordinate to prepare_ad_hvp. For a third-order contraction, supply the requested direction to prepare_ad_third.
With one unit direction per selected coordinate, the HVP columns form the cell's Hessian block over its selection, from one call. The returned vector ∇(vᵀ H v) is the third-order contraction D³ℓ[v, v, ·] over the selection. At evaluation the selection may change, as for the compact sampler: the active vector and the selection keep the exemplar's type and length, and so do the directions. locality is as for prepare_cell_query.
With partitioned = :z (or the partition declaration accepted by cell queries), cache opaque whole-array computations that depend only on the remaining, shared coordinates. The compact selection must then contain only partitioned coordinates: these derivatives condition on the shared point. The cache refreshes when shared coordinates change. For exact mixed shared derivatives, prepare a prepare_cell_accumulator and accumulate a pass with cell_pullback!, which applies the shared prefix's pullback once after collecting all cell contributions. Inside that callback, pass its active CellPullback in place of base to reuse the fixed point without checking all shared coordinates per cell.
ReactiveKernelsPPL.prepare_compact_cell_sampler Method
prepare_compact_cell_sampler(built, plan, observations, base0, indices0; backend, on_error = nothing, locality = nothing)Prepare a cell value and gradient over the sorted, unique packed positions indices0. locality is as for prepare_cell_query. At evaluation, the selected positions may change, provided the active vector and selection retain the exemplar's type and length. The packed base is passed read-only; selected coordinates are supplied separately. This keeps the active AD point and gradient proportional to the selected cell's coordinates rather than the full layout. A packed read selects either an active coordinate or a constant base coordinate. Ordinary native AutoEnzyme(; mode = Enzyme.Reverse) differentiates that read on the Enzyme dogfood line; registered Enzyme (0.13.218 measured) refuses it under static activity (EnzymeRuntimeActivityError), an Enzyme limitation tracked by Enzyme snag static-reverse-s-f9483e9c. The sampler holds one Int32 per packed coordinate, mapping each to its position in the selection.
ReactiveKernelsPPL.prepare_discrete_latents Method
prepare_discrete_latents(built, plan) -> DiscreteLatentQueryPrepare the posteriors of the discrete latents the observations of plan sum out, on the graph built (build_kernel of a binding of the same program). The query returns a NamedTuple keyed by observation name:
for a whole-event hidden Markov observation (
y ~ LogDensity(law, …)with one ofDistributionKernelSources' hidden Markov laws), the law's state posterior:probabilities[t, k], the probability of statekat steptgiven every observation;log_filtered[t, k], its log probability given the firsttsteps; and thelog_transitionweights the law reads;for a plain finite-mixture response (
y .~ MixtureModel(…)),probabilities[i, k], the probability that observationi(in the response's column-major order) came from componentk.
At posterior draws of the parameters these are the latents' conditional posteriors; discrete_latent_draws draws the latents themselves, so parameter and latent draws together are exact draws from the joint posterior.
Call the prepared query at an unconstrained point to obtain the latent probabilities. Pass the query, point, and an explicit random-number generator to discrete_latent_draws for a sampled state path.
A program with no summed-out latent has none to prepare, and one whose latents are not covered (hidden Markov observations in @plate cells or dotted; mixtures with evidence, weights, missing entries, ranges, packed rows or arrays per index) is refused, naming them.
ReactiveKernelsPPL.prepare_filter Function
prepare_filter(model::RKPPLModel; model_id, observations=(:y,), inputs=(),
parameters=(;), data=(;), drifting=(), groups=(;), frozen=FrozenValues())
prepare_filter(model::RKPPLModel, bound::StructuralPlan; kwargs...)Compile finite-lag @scan seeds, transitions and observation laws from the authored model, including expanded submodels and @kernel providers with ordinary finite scan operations. Load Distributions, Random and SequentialMonteCarlo 0.7. WarmupHMC is not needed for filtering. parameters are calibrated, constrained values held fixed for the entire stream. Array declarations of any rank and eachrow/eachcol slice priors select the whole calibrated array; their priors are not evaluated or scored again. data holds fixed model inputs, never an accumulating observation history. frozen substitutes a FrozenValues record directly, without retaining its original training inputs. New observations and covariates arrive as named tuples to filter_step. The bound-plan overload defaults to frozen=bound.frozen, obtains required fixed inputs from that binding, and retains only those read by the projected transition. It excludes observation/input histories and batch horizons. The returned target.data contains those selected fixed values; checkpoint resume compares them independently of model_id. Computed covariates/designs are recomputed from new input ports; only explicitly frozen definitions use their fitted values. Pass an exported FrozenValues record explicitly when the binding has not yet applied it. Unfrozen fixed inputs actually read by the transition remain retained. Scoped data names use the same authored dotted paths as fixed parameters. The scan's upper bound names the batch horizon; filtering extends the same recurrence one time slice at a time. Its seed observations are assimilated too. Models with no carried state use the same path with empty carries. Temporal hcat design columns and their products with fixed coefficient vectors are projected one row at a time, including constant ones/zeros/fill columns whose dimension is length of a stream port.
Source-recorded @traceable helpers can also supply a finite recurrence: a vector output allocated with Vector{T}(undef,length(x)) or similar(x), one for t in eachindex(x) loop, scalar carries initialized before the loop, current-element reads and output writes, and a returned output vector. The compiler derives the carries and transition from that source, preserving its arithmetic and lazy branches. It never executes or unrolls the helper during preparation. This projection currently accepts Float64 temporal inputs and carries; whole-history seeds, arbitrary gathers, nested loops and loop-control transfers (break/continue) are not yet projected. A gather of the projected output must equal the group's current clock. These are compiler limitations, not requirements on ordinary helpers.
For a grouped helper path=helper(x[g],...), declare inputs=(:x,:index,...) for every changing covariate. Each step supplies one current value per group, for example inputs=(;x=[0.2,0.4],index=[1,1]). A broadcast scalar observation law accepts (;y=[0.1,0.3]) or singleton cell vectors. Time covariates and warm-up inputs must be supplied; new observations do not invent them. Fixed vector events retain their axes and authored broadcasts. A direct multivariate law or whole-event LogDensity retains its vector computation, including a helper call, instead of treating event entries as time steps.
drifting names sampled carried states that the author interprets as dynamic parameters. Their authored transitions define the dynamic-parameter model; there is no implicit parameter jitter or reinterpretation of old carries. The ordinary cumulative update_smc remains the static-parameter replay route.
The initial implementation stores scalar Float64 states with literal bounded lags, ordinary scalar definitions, normalized Distributions laws, and one level of fixed-size @plate groups. groups=(;g=1:G) fixes the plate's group axis; filter_step(...;groups=(;g=[2,5])) advances only selected groups, each on its own clock. Models mixing global and grouped recurrences require synchronized slices. All groups share each particle's global parameters. The authored plate domain must match that fixed axis: eachindex/length of a stream port or a fixed bound range is supported; domain mismatches fail. Arbitrary-history scans, growing groups, general whole-trajectory transformations are refused. Omitted observation names or missing entries skip conditioning but advance selected groups; omitted groups do not advance. Missing observed recurrence states are drawn from their authored law. Observation/input arrays retain the original group positions. Other whole-vector calls cannot yet be projected as elementwise work. Opaque scalar user functions must themselves have bounded work/storage per invocation. Kernel-provider scans currently require scalar carry/output, invariant seeds/shared arguments and include_init=false. model_id must change with captured code, frozen preprocessing or semantics; captured functions must remain pure and unchanged. program on the returned target is the actual generated host program, including its random draws.
ReactiveKernelsPPL.prepare_filter_smc Function
prepare_filter_smc(filter_target, calibration::SMCCarriedReference;
parameters=nothing, parameter_id=nothing, backend,
calibration_model_id=filter_target.signature.model_id)Prepare bounded-window parameter learning over an authored finite-state filter. parameters(u) maps an unconstrained position to the complete constrained parameter named tuple expected by filter_target; use the model's existing prepared parameter transformation. parameter_id identifies that pure, unchanging mapping and its frozen preprocessing. It must change when they do. Omit both to use the native mapping from carry_smc(completed; parameters=...). backend prepares ordinary AD of the smooth Gaussian reference only. Load the SMC and filtering dependencies. No derivative of particle resampling is used.
The same SMCCarriedReference can initialize prepare_smc_window and this filter. Its frame.model_id must match calibration_model_id. By default this is the filter's model_id. When a consumer has separately verified that its batch and streaming IDs name compatible source/frozen semantics, it can pass the exact batch ID explicitly. Both identities remain bound into checkpoints; the ordinary filter's identity is unchanged, including for boundary transfer. A completed SMC cloud is supplied through carry_smc (Gaussian moment approximation). The prepared target retains no calibration observations or trajectories.
ReactiveKernelsPPL.prepare_joined_windows Method
prepare_joined_windows(built, plans, u0s; boundary, backend,
locals = (), on_error = nothing) -> JoinedWindowsJoin windows of one recurrence through their boundary state. plans are bindings of the program built was made from, one per window in time order (each window's rows, one build for every window); u0s are exemplar packed points of each. boundary is one pair output => input or a collection of them:
outputnames an authored value of a window, its state at the window's end (h_out = h[T], or a per-index output of a@plateof recurrences);inputnames a declared parameter that the window's recurrence starts from (h_in ~ Normal(0, 2)read by the seedh[1] = h_in), a scalar or an array with an elementwise support.
Entry j of a window's output is the end of the trajectory that starts at entry j of the same window's input, so an array output has the input's length and order. The joined model feeds window k's output entry to the entry of window k + 1's input with the same coordinate_identities (a level label of levels(g), or the position): a fed input entry is no longer a coordinate, and its prior and Jacobian are dropped. An input entry no earlier trajectory reaches (a unit that starts in this window) keeps its coordinate and its prior.
The joined log density is the sum of the windows' log densities with
every fed input entry set to the previous window's output, mapped through its support's unconstraining transform, and its prior and Jacobian terms dropped;
every coordinate that an earlier window holds, by identity, being that window's coordinate, with its prior and Jacobian counted only there (a global such as a step scale, or a unit's static matched by its level label).
Coordinates of a @scan's sampled steps, the boundary inputs and the parameters named in locals belong to their window only: position j of a scan is another time step in another window. Name in locals any other parameter whose positional entries are per-window (innovations declared outside the scan, a plate of recurrences' draws).
Windows that cover a series one after another, each starting from the previous window's end state, then have the series' log density and gradient: with h_in the state before the series and h_out the state at its last step, two windows reproduce one window over all rows. Gradients flow back through each output into the window that produced it. A prior that a later window computes from its own rows differently (a scale from all its rows) is counted as the first window holding the coordinate computes it.
Use joined_point to pack the window points and joined_value_and_gradient! to evaluate their joint density. window_points recovers each window point with its boundary inputs; joined_coordinates identifies the retained coordinates.
ReactiveKernelsPPL.prepare_marginalized_latents Method
prepare_marginalized_latents(built, plan) -> MarginalizedLatentQueryPrepare the Kalman filter of every recurrence marginalize integrated out of plan, on the graph built (build_kernel of the same binding). q(u) returns a NamedTuple keyed by latent name; each entry holds the filtered mean[t] and var[t] of the state given the first t observations, and the transition x[t] = coef[t] * x[t - 1] + shift[t] + Normal(0, sqrt(innovation_var[t])) (entry 1 holds the seed's law: coef[1] = 0). A recurrence per @plate index holds one such vector per index in each field. A vector state is one entry keyed by its first array: its window's components ((array, j) for array[t - j]), its seed depth lags, and per step the window's filtered mean and cov, and the transition into it, coef and shift with noise covariance innovation_cov (entries up to lags hold seeds). A recurrence a submodel holds is keyed by its author path (Symbol("z.x")). At posterior draws of the parameters these determine each latent's exact conditional posterior; marginalized_latent_draws samples it. A program with no marginalized recurrence is refused.
ReactiveKernelsPPL.prepare_partition Method
prepare_partition(built, plan, observations; by, locality = :error, on_error = nothing,
partitioned = (), u0 = nothing) -> PartitionQueryPrepare the summed log density of ONE partition of the observations named in observations (a name or a collection of names): all cells whose key equals a label, such as one subject's observations, evaluated at an unconstrained point u: q(u, label). by names the key: a supplied data column with one entry per cell of each observation's plate (one row per entry of an elementwise observation, one per iteration of an @plate for loop), either one column name for every observation or, per observation, a named tuple, a dictionary, one observation => column pair or a collection of such pairs. Per observation, by may instead give the labels themselves, observation => labels: a vector with one label per cell, which need not be data of the model and which no statement need read. A key of another length is refused. partition_labels lists the labels.
A partition runs as one compiled pass over its cells (RK plate_partition): each plate loops once over the positions holding the label, and every value the partition's cells read at their rows is computed once per partition at the union of those rows, so
sum(q(u, label) for label in partition_labels(q)) == likelihood of the observationsand one partition costs its share of the whole likelihood. locality is as for prepare_cell_query, with the default :error: the query is prepared only when every value its cells read at rows is computed at those rows; otherwise preparation throws a ReactiveKernels.PartitionLocalityError naming each such value and its statement.
With partitioned, use the same local/shared coordinate declaration and separability check as prepare_partition_sampler, including partitioned = :none when partitions own no parameter. Shared intermediates are cached across labels and local changes, and the strict check applies to the remaining per-partition program. Row-capable calculations stay in that program. u0 is an optional packed exemplar (zeros by default), as for prepare_cell_query. partition_locality(q) reports the executed residual. The original q.kernel continues to supply packed-coordinate footprints including all dependencies through the prefix; call q(u, label) for cached evaluation. Comparing shared coordinates costs O(shared dimension) per call; refreshing the prefix adds its graph's work once per changed shared point. Cache storage is query-owned; prepare one query per concurrent caller. Cached calls preserve AbstractVector{Float64} storage and prepare each argument-type specialization once, without copying the packed point.
The partition's kernels are lowered from u0 and the first label, as a cell query's are from u0: those types decide what is computed at a partition's rows, such as the arm a branch on an element type takes. q.kernel is therefore typed for a Vector{Float64} point and a label of the first label's type; q(u, label) prepares a kernel for any other point or label type once.
For a value-only query's packed-coordinate footprint, call ReactiveKernels.partition_footprint(q.kernel, u, label, nothing).unconstrained, which takes any point and label type. The final nothing supplies the plan port; the footprint kernel computes its own row bookkeeping. A result of :whole means all positions of u. For repeated calls, prepare ReactiveKernels.partition_footprint_kernel(q.kernel) once and call it with (u, label, nothing) through Base.invokelatest; it is typed like q.kernel. This does not prepare AD. For individual cell supports, use the prepare_cell_query footprint recipe: preparing a partition with one label per cell would retain a partition plan for every cell.
ReactiveKernelsPPL.prepare_partition_sampler Method
prepare_partition_sampler(built, plan, observations, u0; by, backend, compact = true,
partitioned = (), locality = :error, on_error = nothing) -> PartitionSamplerprepare_partition, with the same by, plus a prepare_ad gradient; the label stays a constant. u0 is a length-consistent exemplar and backend a DifferentiationInterface backend, as for prepare_sampler.
With compact = true (the default) the gradient is over each partition's footprint, the packed coordinates it reads, computed at preparation for every label from the bound index data (partition_footprint); the active coordinates overlay a read-only packed base as in prepare_compact_cell_sampler, so with native AutoEnzyme Reverse use ordinary Enzyme.Reverse. With compact = false the gradient is over the whole packed vector, nonzero only on the footprint, at the cost of zeroing the whole vector per call.
partitioned is the separability rule: the parameters whose rows belong to one partition each (an NLME unit's effects), named bare when indexed by the key column itself (z[levels(subject)]) or as parameter => labels giving each level's label. Preparation then checks every label: a partition that reads another label's coordinates of those parameters, even genuinely, is refused with a ReactiveKernels.PartitionSeparabilityError naming them.
partitioned = :none declares that partitions own no parameter: every coordinate is shared, so a value with no row form that reads only parameters is computed once and read at each partition's rows. This differs from the default (), which declares nothing and leaves such a value to the locality check. shared = false then has no coordinate to differentiate. A parameter literally named none makes the bare symbol ambiguous, and is refused; (:none,) still names that parameter.
For parameter => labels, the label count is the first constrained dimension (first(parameter_metadata(built)[i].shape)), or the packed count for a scalar. Labels cycle in order over that parameter's packed coordinates. The packed count need not equal or be divisible by the label count. For a whole local coupled transform, repeat its unit's label across that constrained axis: L ~ LKJCholesky(2, eta) takes partitioned = (:L => fill(unit, 2),), even though L has only one packed coordinate. More generally an LKJ factor of width K takes fill(unit, K) to assign all K*(K-1)/2 coordinates to unit. This declaration assigns coordinate ownership; it does not split the transform or its atomic prior/Jacobian factors. A partition query still selects only the requested observations, not those prior/Jacobian terms.
The compiler also cuts out intermediates that structurally read only shared coordinates and bound data. The sampler keeps their values across labels and local-coordinate changes, and recomputes them when a shared coordinate changes. The cache belongs to this sampler; changes are compared by value, including in-place edits to u. Full gradients propagate cotangents through the prefix with the chosen backend. That pullback may recompute its forward work; no backend tape reuse is assumed. shared = false on the gradient call requests only local derivatives. It differentiates a separate compact conditional program, avoiding cotangents for the cached shared frontier and its pullback. Each full gradient call runs that pullback once, so sweeping units one call at a time costs one whole pullback per unit; partition_batch_value_and_gradient! runs it once per batch.
ReactiveKernelsPPL.prepare_predictive Method
prepare_predictive(built, plan) -> PredictiveQueryPrepare posterior-predictive draws of every observation of plan on the graph built (build_kernel of a binding of the same program). plan may leave its responses absent (a prediction design): the laws read only the values the observations' distributions receive, and each draw takes the shape the response would have.
The graph computes each observation's law arguments; drawing happens in ordinary Julia, so it needs using Distributions (the package extension that builds each law). Every response's family maps to its Distributions.jl law, with censored and truncated evidence wrapped as RKPPL observes it (the clamp law and the renormalized law). Mixtures, weighted, interval-censored and packed responses, caller-owned sampling laws and conditioned declarations are refused, naming them.
Call the prepared query with a packed point and an explicit random-number generator. predictive_draws! fills existing response storage, and predictive_laws exposes the corresponding Distributions laws.
ReactiveKernelsPPL.prepare_query Method
Prepare the sum of selected authored density events, callable with a packed point.
sourceReactiveKernelsPPL.prepare_query Method
prepare_query(built, plan, preset::Symbol; on_error = nothing, exemplars = nothing,
inputs = ())Prepare the build_kernel output built for a named workflow preset over the sampler boundary (:unconstrained + data columns, data hoisted via bound=). Thin wrapper over ReactiveKernels.prepare with want = workflow_wants(preset) and the supplied on_error policy. The optional exemplars tuple is forwarded to RK's native type-evidence path. The returned kernel maps an unconstrained float vector to the preset node's value. plan may be any binding that generates the same program as built (other row counts, including zero, parameter extents and data values, or the same source lowered in another gensym-created isolation module); one that generates another program (other levels, data element types, missing entries, another broadcast shape) is refused with a ContractValidationError naming the first difference, since the graph would evaluate the wrong program for it. The preparation itself is world-age safe (callable from compiled functions), but the RAW returned kernel closes over build-time eval'd code: call it from top level, wrap the call in Base.invokelatest, or use SamplerQuery, whose call paths carry the barrier.
Runtime inputs
inputs names data values of plan that each call supplies instead of the binding: q = prepare_query(built, plan, want; inputs = (:x,)) prepares once, and q(u, xx) evaluates at u with xx in place of the bound x, giving what preparing again on a binding with x = xx gives. Values follow u in the order inputs names them. A number the model reads as a value (s) is named as authored. With exemplars, the preparation adds the bound values of the inputs to them.
Each call checks that every input has the type and size of its bound value (ArgumentError otherwise). What binding computes from the inputs (data definitions such as w = f(x) and value matrices) is evaluated again on every call from the call's values, exactly as binding evaluates it, so it never keeps the bound value. Only floating-point values may change: when such a value changes an integer, a Boolean, a label, a range or the size of an array (something that may index, count or size the program), the call throws an ArgumentError and the value must be bound. Values reach the program as given: a call checks their type and size, not the ranges binding checks for observations.
Preparation refuses, with a ContractValidationError naming the reason, an input that is not a data value the binding was given, one that binding checks as an observation or against one (a value observed with | or condition, a statistical response, weights, trials, scales, censoring bounds or cutpoints, or data an observed definition is computed from), a factor's labels, and data other than floating-point numbers and dense Arrays of them (integer and Boolean data index, count, size or select, and binding checks them value by value). Bind such values with bind_data. A value pinned in the model call (model(; x, y)) is data, not an observation, and may be an input.
ReactiveKernelsPPL.prepare_query Method
prepare_query(built, plan, values::Tuple{Vararg{Symbol}}; on_error = nothing,
exemplars = nothing, inputs = ())Prepare the authored values of the model by name, over the same sampler boundary as a preset: a definition (h_out = h[T]), a recurrence's carried array, a per-index output of a @plate (h_out[g] = …). The kernel maps an unconstrained vector to their values, a tuple in that order; one name gives its value itself, as one WANT of ReactiveKernels.prepare does. A workflow preset name is refused (query it with the Symbol method). The same tuple is a prepare_query_ad preset for pullbacks and pushforwards: prepare_query_ad(prepare_ad_pullback, built, plan, (:h_out,), backend, 1.0, u0). inputs leaves data values as call arguments, q(u, xx), exactly as for a preset (see "Runtime inputs" there).
ReactiveKernelsPPL.prepare_query_ad Method
prepare_query_ad(prepare_operator, built, plan, selections::AbstractVector{<:FactorSelection},
backend, exemplars...; coordinates = nothing, kwargs...)Prepare a family of authored density queries in selection order. All selections must come from one catalogue. The batch checks its bound program once, then shares one packed exemplar across preparation. With coordinates = :support, each returned FactorQueryAD owns a compact derivative workspace; fixed row and coordinate metadata use storage proportional to the selected supports. Selections that read the same sites whole share one prepared program, so a query keeps only its own entries, row plan, slots and workspace, never a copy of the model graph. Every selection reads each elementwise (plate) site of the catalogue by cells, with no cells where it selects none, so neither its entries nor which plates the binding has rows in change that program: another binding of the model calls the programs this one compiled. Empty selections return zero-valued queries; an empty batch returns no queries. Single-selection calls retain their bound-program validation.
ReactiveKernelsPPL.prepare_query_ad Method
prepare_query_ad(prepare_operator, built, plan, preset, backend, exemplars...;
on_error = nothing) -> QueryADPrepare a ReactiveKernels derivative operator over the query prepare_query(built, plan, preset), differentiating with respect to the whole unconstrained vector. prepare_operator is the ReactiveKernels preparation to apply — prepare_ad, prepare_ad_pullback, prepare_ad_pushforward, prepare_ad_hvp or prepare_ad_third — and exemplars are that function's arguments after its backend, ending with an unconstrained exemplar u0 of length layout.total.
Choose prepare_ad_hvp with a second-order backend, such as SecondOrder(AutoEnzyme(; mode = Enzyme.Reverse), AutoEnzyme(; mode = Enzyme.Forward)), and evaluate ad_gradient_and_hvp(q, (v,), u) for Hessian-vector products; prepare_ad_pushforward with a forward backend and ad_value_and_pushforward for directional outputs; or prepare_ad_third with a nested backend and ad_gradient_hvp_and_third, whose third output is the gradient of vᵀ H v.
Gradients, Hessian-vector products and third-order derivatives need a scalar preset (:sampler, :likelihood, :prior, :log_jacobian); pullbacks and pushforwards also accept :pointwise, :observations and a tuple of authored value names ((:h_out,), see prepare_query), whose seed has the shape of their values. Directions with disjoint supports over coordinate_names(built.layout) compress block-structured Jacobians, Hessians and third-order contractions (see ReactiveKernels.prepare_ad_hvp and ReactiveKernels.prepare_ad_third). The backend's packages must be loaded in the calling session.
ReactiveKernelsPPL.prepare_sampler Method
prepare_sampler(built, plan, u0::AbstractVector{<:Real}; backend, on_error = nothing, retain = (), warm = false, native_forward_batch = false, nonallocating = :auto) -> SamplerQueryPrepare a reusable SamplerQuery: the :sampler-cut value kernel plus a prepare_ad gradient with active = :unconstrained. u0 is a length-consistent type/shape exemplar (checked against layout.total before any preparation work). The non-allocating sampler (the default, below) also evaluates the density once at u0 to give its operations their buffers: operations that evaluation does not reach, including those after a throw (an ODE that does not integrate at u0, say), allocate on every gradient call, with unchanged values and gradients. A density that throws at u0 is prepared anyway, with a warning naming the error; prepare at a point where the model evaluates, such as a start point, for every buffer to be reused. backend is any DifferentiationInterface.AbstractADType (e.g. AutoEnzyme reverse mode). on_error is forwarded to prepare_query. The backend's package must be loaded in the calling session (using Enzyme for AutoEnzyme); the backend value alone does not load DifferentiationInterface's backend extension, and preparation without it fails loudly naming the missing using.
The sampler passes its converted Vector{Float64} exemplar to native preparation by default. Its public calls convert other real vectors to that type; the prepared native kernel uses the concrete type to infer plate inputs without fixing the vector's length.
retain names further query presets (:pointwise, :likelihood, :prior, :log_jacobian) whose values the gradient's own primal sweep returns through sampler_value_gradient_and_retained!, with no second primal pass. It needs a backend that keeps that sweep's values (reverse-mode AutoEnzyme; see ReactiveKernels.ad_retains_primal_sweep).
warm = true compiles the gradient during preparation (prepare_ad's warm), so sampler_value_and_gradient! with a Vector{Float64} point runs compiled code from its first call.
The sampler preserves an explicitly requested AD mode. Native forward batching is disabled by default. With AutoEnzyme() (no explicit mode), the opt-in native_forward_batch = true may select one batched forward sweep for a pure independent summed plate with one to four active coordinates. It differentiates the unchanged generated kernel, including priors and transforms. Explicit reverse mode, wider, effectful, scan, and retained-output programs keep the ordinary reverse preparation. The opt-in forward preparation keeps a reverse operator for a later input with a different active shape.
The sampler is non-allocating by default. nonallocating = :auto prepares the density and its gradient over ReactiveKernels.prepare_nonallocating unless the request needs the ordinary sampler:
retain: ReactiveKernels does not build retained outputs over a non-allocating kernel yet;native_forward_batch = true: forward batching does not apply;a backend other than reverse-mode
AutoEnzyme: a dual-number backend cannot run the non-allocating gradient;a program with a multi-output recipe (a destructuring assignment), which a non-allocating kernel does not take;
a program whose plates run as matrix products (ReactiveKernels' batched plates), which a non-allocating program runs cell by cell.
nonallocating = true requires it, and those requests then fail; nonallocating = false prepares the ordinary sampler.
The opt-in generated plate reverse (ReactiveKernels.with_plate_reverse) also applies to non-allocating gradients. Eligible summed plates use their generated reverse after cache activity and ownership have been determined; other regions keep the backend's ordinary reverse.
A non-allocating sampler writes every operation with a destination-passing form into a buffer the query owns: an evaluation reuses the same memory instead of allocating fresh observation-length intermediates (matrix-vector products, plate outputs) on every call. Values and gradients equal the ordinary sampler's. The density is usually faster, and loses less when another allocating process shares the CPU core; the reverse gradient is faster on most programs and slower on some, so measure both on the model you fit (nonallocating = false). The query keeps the buffers, which is why a query serves one caller at a time. Its type, like the ordinary sampler's, does not depend on the values of bound numbers: another binding of the same build reuses the compiled density and gradient, and each query still owns its buffers.
A program that factors a sampled covariance (MvNormal with a computed covariance, such as a Gaussian process) keeps a non-allocating density but differentiates the ordinary program, and its gradient allocates what the ordinary gradient does. With every array of that density reused, reverse mode must tape them, because it cannot prove one buffer disjoint from another: the gradient took 1.4 to 3 times the ordinary one.
ReactiveKernelsPPL.prepare_slices Method
prepare_slices(built, plan, observations, u0; by, backend,
partitioned = (), locality = :error, on_error = nothing) -> SliceSamplerPrepare the slices of one bound model: the model restricted to the cells whose label is in a chosen set, with its prior. observations and by are those of prepare_partition_sampler: by gives each observation's cells a label (a column name, or observation => labels), so a slice can be a region of a national binding, a subject group, or a set of observations (an observation not named belongs to no slice). partitioned, locality and on_error pass through to it; u0 is an exemplar packed point.
A slice of the label set S has the log density
the sum of the cells labelled in
S, plusevery authored prior and coordinate-Jacobian term (
density_factors) that owns a packed coordinate those cells reach, with the coordinates those terms read added in turn until nothing new is reached. Each term counts once, however many labels reach it.
Its coordinates, slice_coordinates, are exactly the coordinates that density reads. Nothing outside them is read or differentiated, and cells of other labels are not evaluated. Hyperparameters such as a group scale join the slice through the priors that read them, and a joint law or coupled transform stays whole: if a slice reaches one of its coordinates, all of them join.
For a model whose units nest in the labels, the slice of a label equals the model bound to that label's data alone, in value and gradient, coordinates matched by coordinate_identities. It differs where the whole binding changes a slice's terms: a joint law over every unit, or a data-derived value computed from all rows (for example a frame centred on all sites).
An authored density that owns no coordinate and reads coordinates both inside and outside a slice cannot be assigned to it, and that slice is refused with a ContractValidationError naming the density.
Pass a label or collection of labels to slice_coordinates and slice_value_and_gradient!. The default gradient storage contains only the slice coordinates; compact=false writes into full packed storage.
The binding is prepared once. Another label set uses the same compiled kernels: its cells are another plan of the partition kernels, and its prior terms a factor selection whose rows are data, prepared on the set's first use.
sourceReactiveKernelsPPL.prepare_smc Function
prepare_smc(built, binding, u0; backend, model_id, binding_id, kwargs...)
prepare_smc(make_problem, u0; backend, model_id, binding_id, frame_id)Prepare a reusable SMC posterior target using prepare_sampler. Load SequentialMonteCarlo, WarmupHMC, LogDensityProblems and Random first. model_id identifies the model's source coordinate frame, including frozen preprocessing and caller-owned geometry; binding_id identifies these exact bound data. Use stable strings, and change them when their meanings change. Updates additionally check the packed layout; generated programs may change with the data (for example, a longer scan). Each build must match its own binding. model_id is a caller-supplied identity, not an inferred code hash. Bindings, captured data and code must remain read-only for a target's lifetime. kwargs are forwarded to prepare_sampler.
The two-argument method accepts a zero-argument factory make_problem() returning a prepared LogDensityProblems target with dimension, logdensity and logdensity_and_gradient (capability order at least one). u0 supplies its coordinate dimension, not production particles. The supplied density already includes all priors, coordinate Jacobians and approximation terms: SMC adds none. Its gradient is used directly; backend prepares only the Gaussian reference's derivatives. A gradient returned in reusable storage is copied before retention.
Each factory call must return the same density in the same coordinate frame, with independent mutable workspaces. Preparation calls it once; initialization, tuning, update, resume and additional mutation workers construct owned execution instances. Factories are invoked before launching mutation workers, never once per particle. Read-only data may be shared; do not share mutable solver state. Use () -> deepcopy(problem) only when copying is valid for that problem. Execution instances along one state's continuation may share scratch; do not concurrently advance or checkpoint the same continuation. Separate initializations and resumes have independent problem state.
model_id covers density code and approximation configuration (including any inner-solver settings), binding_id covers exact data, and frame_id covers ordered coordinate meanings, transforms and preprocessing. These stable strings are caller assertions, not inferred hashes. Change them when semantics change. Updates require matching model/frame/dimension; resume and tuning also require the same binding. Checkpoints contain identities and endpoint scores, never the factory or its workspaces. Rebuild with the same code, data and configuration before resume_smc. This adapter does not infer named RKPPL parameter geometry.
ReactiveKernelsPPL.prepare_smc_window Function
prepare_smc_window(built, binding, u0; previous::SMCCarriedReference,
backend, model_id, binding_id, warm=false, coordinates=:all)Prepare a static-parameter target log(previous.reference) + loglikelihood for new observations only. The likelihood and its ordinary AD derivative come from the model's :likelihood query. Original priors and coordinate Jacobians are not added again: the carried reference is already a density in unconstrained coordinates. Parameter transformations in the likelihood remain.
With coordinates=:all, the model/preprocessing identity and packed layout must match previous. Keep fitted preprocessing frozen and pass it through the binding. Retained storage and each evaluation depend on this window, never on elapsed history. Use the filter for latent trajectories whose transitions are evaluated as successive observations arrive.
With coordinates=:auto, the prepared target uses only the old coordinates read by this window's likelihood or fresh priors, and all fresh coordinates. Authored paths and coordinate labels match the previous carry; packed offsets may change. Rebuild and bind the current program when an array extent changes, while keeping model_id and fitted preprocessing fixed. The target is q_old(active) * p(fresh | active) * likelihood(window | active, fresh). Fresh factors include their native transforms and Jacobians once. Dependencies of fresh priors, including old hyperparameters absent from the likelihood, belong to the active set. Joint factors and coupled transforms remain intact. Fresh events are selected by factor_coordinates ownership, never by their read support. A density on a derived expression that owns no coordinates and whose structural support includes fresh ones cannot be assigned automatically and is rejected rather than omitted. This support can conservatively include whole arrays for compound scalar expressions such as z[1]^2; direct scalar index reads use native locality lowering. Fresh-factor discovery inherits density_factors's explicit limitation for stochastic scans inside cells; a top-level scan's prior is one atomic event, so a window cannot take only some of its steps fresh. The likelihood must satisfy native partition locality. Sparse observations selecting elements of simplex/ordered slice-transformed arrays currently lack an observation row lowering and are rejected; their fresh atomic priors are supported. No full-coordinate fallback is performed.
Inspect smc_window_coordinates before supplying a compact initial point, reference or mutation metric. Particle positions and gradients use that compact order. smc_recover draws the inactive old coordinates lazily from their retained conditional; no full joint particle cloud is stored. carry_smc(completed; max_reflections=16, ...) integrates that conditional against the fitted compact Gaussian, flattens the joint covariance and caps its rank at the requested budget. Its full location vector follows the current layout, followed by retained coordinates absent from the current program. Recompression diagnostics report discarded rank and the spectral norm of the discarded covariance correction in the diagonal-whitened frame; this is not a posterior accuracy bound.
Use the ordinary tune_smc, initialize_smc, smc, smc_checkpoint and resume_smc APIs. The default initial reference is the carried prior for :all, or its active marginal with independent standard-normal fresh coordinates for :auto. This proposal does not replace the fresh priors in the target. A checkpoint resumes from the rebuilt window target alone, without old data. Its log normalizer is the new window's predictive normalizer under the approximate carried prior, not exact full-history evidence. Supply each new window once; overlapping windows would count their observations again.
ReactiveKernelsPPL.preprocessing_recipes Method
preprocessing_recipes(plan) -> Vector{Expr}Data design and offset recipes in plan.predictors order. A predictor with broadcast affine operands uses per-block expressions instead of a fused design matrix; absent design and offset blocks emit no recipe.
ReactiveKernelsPPL.reduction_rows Method
The row labels of reduction j in cell, in summand-position order.
ReactiveKernelsPPL.rejuvenate_smc Function
rejuvenate_smc(state; tuning::SMCTuningSchedule, moves::Integer)Attempt recovery or additional exploration using exactly moves fixed-kernel NUTS transitions per particle at state.temperature. tuning must be prepared independently of the production particles, for these exact source/target endpoints and reference. Supply pilot initial positions and RNGs independently; include knots near the temperature needing recovery when calling tune_smc.
There is no weighting, resampling, temperature advance, normalizer update, or movement-based stopping rule. Input state and RNG are preserved. The result owns new positions and RNG, identity ancestors, copied weights/lineage, and the newly validated schedule for subsequent smc stages. The requested moves overrides the selected kernel's move count for this call only. A bounded history entry with kind=:rejuvenate records the actual work and zero normalizer increment; stage still counts tempering stages, so recovery does not spend max_stages. Checkpoint/resume retains the new schedule and exact continuation without retuning.
A still-collapsed result throws SMCDegeneracyError with the input state and the attempt's diagnostics. No automatic retry is made. Distinct output particles do not prove mixing; compare independent fits and posterior diagnostics. Rejuvenation cannot repair errors in normalizer increments accumulated before this call. Zero-dimensional targets perform no transitions and consume no RNG.
For parameter-learning filters:
Attempt fixed-budget particle-Metropolis recovery on the retained window, using exactly moves proposals per member. Prepare tuning independently with tune_filter_smc(state; rng, init, ...); it must name this exact current-window reference. Its final-temperature kernel becomes the stream's fixed kernel; moves overrides that kernel's move count for this recovery call only.
Unlike assimilation replenishment, whose random walk is scaled by the members' own spread, recovery uses the tuned prior-reversible NUTS kernel, so it can move a population whose spread has vanished.
This overload neither resamples nor assimilates an observation. Weights, time, window, records and accumulated normalizer stay unchanged. Rejections retain the old conditional cloud and likelihood estimate. A bounded :rejuvenate history entry records zero score increment and the actual work. Checkpoint and resume retain the replacement kernel and exact continuation without retuning.
SMCDegeneracyError preserves the input and attempt's diagnostics if all members still coincide, or a full window still lacks positive finite marginal scales for rollover. No automatic retry or adaptive stopping occurs. If recovering from a failed filter_step, retry that observation on the returned state: the failed step consumed nothing. Recovery cannot repair past evidence estimates or certify coverage of lost modes.
ReactiveKernelsPPL.rescore_smc_checkpoint Function
rescore_smc_checkpoint(target, checkpoint; previous=nothing, rtol=1e-10)Re-anchor an smc_checkpoint on this host, so resume_smc accepts it here. Use it when a checkpoint written on one host is refused on another only because the two compile the same log density to different machine code, whose sums round differently in their last bits.
Every resume_smc check runs first: checkpoint schema, Julia/package versions, target and previous signatures, positions, weights, bridge state and ancestry. Both endpoint scores are then recomputed for every particle, and each must satisfy abs(new - old) <= rtol * max(abs(old), 1); otherwise an ArgumentError names the largest deviation and its particle. rtol=0 accepts only identical scores.
Returns a new checkpoint carrying this host's scores and a rescored vector with one record per re-anchoring: (; changed, max_abs, max_rel, rtol, codegen), the count of changed scores, the largest absolute and scaled deviations, the tolerance, and this process's code-generation target (Julia's -C option when given, else Sys.CPU_NAME). Earlier records are kept. The input is not modified. Persist the result yourself; every later resume_smc of it on this host keeps the exact check. Checkpoints taken from the resumed state carry no record.
The tolerance is the price of crossing hosts: a change to the data or model that moves no score by more than rtol relative is accepted too. Measured cross-host drift (AVX-512 versus AVX2) was below 4e-16 relative, and a one-count change in one observation moves a score by order one.
ReactiveKernelsPPL.rescore_smc_tuning_checkpoint Function
rescore_smc_tuning_checkpoint(target, partial::SMCTuningPartial;
previous=nothing, rtol=1e-10)
rescore_smc_tuning_checkpoint(target, input_dir::AbstractString;
output_dir=input_dir, previous=nothing, rtol=1e-10)Explicitly re-anchor an adaptive tune_smc continuation on this host. The partial form returns an independent SMCTuningPartial. The directory form reads input_dir/tuning_latest.jls, validates and re-anchors it, then atomically replaces output_dir/tuning_latest.jls and returns the partial. The default updates the input directory; name a different output directory to preserve its checkpoint. Unrelated files are preserved. Validation or re-scoring failure does not replace the destination checkpoint.
Schema, Julia/package versions, target and previous-endpoint identities, phase and completed kernels retain the ordinary resume checks. Re-anchoring uses the saved tuning configuration; resume still checks the caller's keywords. Both endpoint scores at every saved probe must satisfy abs(new-old) <= rtol*max(abs(old),1). rtol must be finite and nonnegative; zero requires numerical equality. An excessive deviation names the endpoint and probe. The returned checkpoint appends a rescored record with changed, max_abs, max_rel, rtol and codegen for these outer scores.
Each active reference or grid pilot is independently re-scored through WarmupHMC.rescore_warmup_checkpoint at its saved temperature, including every active independent-grid pilot. WarmupHMC checks the current evaluation and recomputable retained pointwise gradients, refreshes them, and keeps its own persistent audit. RNG state, counters, completed work and compressed adaptation history remain unchanged. The original partial is never mutated. Requires WarmupHMC 0.2.18 or later.
Resume with the original tuning keywords and resume=anchored, or with checkpoint_dir=output_dir, resume=true. Ordinary resume remains exact; this operation does not certify model/data identity, migrate older package-version checkpoints or promise identical future trajectories across CPUs. Keep the same model, data and coordinate frame. Deserialize only trusted checkpoints and do not concurrently advance or replace the same continuation.
ReactiveKernelsPPL.restore_draws Method
restore_draws(layout::LayoutTable, U::AbstractMatrix{<:Real}) -> NamedTupleRestore constrained parameters from U (layout.total rows × draws columns), with the same nested author paths as constrain. Scalar leaves become length-draws vectors, vector leaves become size × draws matrices, and higher-rank array leaves become vectors of arrays. Empty draws retain those keys and leaf shapes. Each column is constrained independently through constrain, so transforms stay single-sourced.
ReactiveKernelsPPL.rkppl_documentation Function
rkppl_documentation(model_or_plan; path=nothing)Return a fresh vector of immutable RKPPLDocumentation records. Captured models/submodels expose their own authored text; lowered plans also include documentation instantiated from reusable components. Binding, pins and unannotated replacements retain it; an annotated replacement replaces the text at that declaration. A per-cell declaration contributes one record, independent of observation count. Records follow source order within each captured scope, with expanded scopes appended in depth-first use order.
path optionally selects an exact tuple of author names, such as (:fit, :b). Querying documentation never lowers a model, resolves a component, evaluates data, or runs a renderer. In particular it does not inspect Julia's doc registry.
ReactiveKernelsPPL.sampler_value_and_gradient! Method
sampler_value_and_gradient!(q::SamplerQuery, g::AbstractVector, u)Posterior value and gradient at unconstrained u, writing the gradient into g in place. Returns the (value, g) pair. g must be a valid gradient destination for u; u is converted to Vector{Float64} unless it already is one. Where a numerical method cannot evaluate the model (ReactiveKernels.NumericalFailure) the value is -Inf and g is filled with NaN; every other exception propagates.
ReactiveKernelsPPL.sampler_value_gradient_and_retained! Method
sampler_value_gradient_and_retained!(q::SamplerQuery, g::AbstractVector, u)Posterior value and gradient at unconstrained u as sampler_value_and_gradient! computes them, plus the presets named by prepare_sampler(...; retain) evaluated by the same primal sweep. Returns (value, g, retained), where retained is a NamedTuple keyed by those preset names (retained.pointwise has the shape prepare_query(…, :pointwise) returns). Each call returns freshly computed retained values. The retained presets have no value where a numerical method cannot evaluate the model, so this call throws that ReactiveKernels.NumericalFailure instead of answering -Inf.
ReactiveKernelsPPL.sampling_distribution_graph Method
sampling_distribution_graph(constructor, arguments::Tuple)Return a function-shaped KernelSpec, a Julia expression constructing an owned RK distribution object, or nothing when this constructor/arity has no graph mapping. A density KernelSpec receives the sampled value first, then the constructor's positional and keyword arguments. Its complete explicit call boundary composes directly, including keyword ports in declaration order; omitted/default or splatted arguments retain the numerical RHS path. constructor is the resolved Julia binding; arguments contains authored expressions, not evaluated parameter values (keyword syntax is an Expr(:parameters, ...)). An object expression can be composed with .logpdf(value) or with the object's CDF/log-tail endpoints. This structural hook does not choose parameter geometry or evaluate a statistical constructor.
The Distributions extension supplies mappings for supported base families. Caller-owned types may extend this hook with their own graphs, including a locally constructed spec reconstructed by calling the same structural hook; ordinary numerical RHS values retain sampling_logdensity.
ReactiveKernelsPPL.sampling_fragment Method
sampling_fragment(binding) -> RKPPLSubmodel or nothingPublic structural expansion adapter for an external sampling RHS binding. Return an RKPPLSubmodel(name, argument_names, body_ast, defining_module) whose ordinary sampling/definition/plate/scan statements express the external model. The body need not originate in @rkppl. Return a stable fragment, without executing the model or mutating a StructuralPlan. Scope, nesting, conditioning and loop handling are shared with authored RKPPL submodels.
ReactiveKernelsPPL.sampling_geometry Method
sampling_geometry(constructor, argument_expressions::Tuple, declared_shape::Tuple)Return ParameterGeometry for parameter use of an external RHS. This is a structural method: its arguments are the authored Julia expressions, not active parameter values. It must not evaluate the constructor or statistical arguments. Observed use does not call this method. A future generated-only role can use the same RHS without acquiring a sampler layout or invoking these transforms.
ReactiveKernelsPPL.sampling_logdensity Method
sampling_logdensity(rhs, value)The constrained-value log density of a sampling RHS. Extend this function on caller-owned types. A density includes its normalization and support checks; it must be pure and support ordinary backend AD. Model-sized iteration belongs in a visible submodel fragment or an authored plate/scan, not an opaque density. No random generation is performed by this interface.
sourceReactiveKernelsPPL.select_factors Method
select_factors(catalogue; kind = nothing, site = nothing, entries = :)
select_factors(catalogue, factors)Select a set of whole atomic density events. kind and site optionally filter the catalogue; entries selects event indices within each matching site, never coordinates within a joint event. Explicit factors must belong to the catalogue. Duplicate events are counted once. Empty selections sum to zero. Iterate the catalogue to discover the valid authored identities.
ReactiveKernelsPPL.simplex_constrain Method
simplex_constrain(u) -> VectorHost-side stick-breaking simplex transform (thin-layer-owned parameterization — NOT Stan's isometric-log-ratio simplex_constrain; the middle layer owns layout+transforms, the LKJ-factor precedent): break fractions z[j] = σ(u[j] + log(K-j)), stick remainders r[j] = Π_{i<j} (1 - z[i]) (in closed form, exp of the running sum of log1p(-z)), s[j] = r[j]*z[j], s[K] = r[K]. Empty input constrains to [1.0] (the deterministic 1-simplex, as in Stan). The in-graph transform fuses these vector operations into one result buffer and a scalar log-Jacobian.
ReactiveKernelsPPL.simplex_logjac Method
Log-Jacobian of simplex_constrain: Σ [log(r) + log(z) + log1p(-z)] over the K−1 breaks.
ReactiveKernelsPPL.simplex_unconstrain Method
Inverse of simplex_constrain (stick-breaking, not Stan's ILR simplex_free).
ReactiveKernelsPPL.slice_coordinates Method
slice_coordinates(slices, labels) -> Vector{Int}The sorted packed positions, in the whole binding's layout, of the slice of labels (one label, or a collection of them). A compact gradient follows this order. coordinate_identities(built.layout)[slice_coordinates(slices, labels)] names them by meaning, for matching against another binding.
ReactiveKernelsPPL.slice_labels Method
slice_labels(slices) -> VectorThe labels of slices, in first-seen order. A label set is any collection of them; a single label stands for itself.
ReactiveKernelsPPL.slice_problem Method
slice_problem(slices, labels; base = u0) -> SliceProblemThe slice of labels as a log density of its compact coordinates x = u[slice_coordinates(slices, labels)], for an optimizer, Pathfinder or a variational fit. base (default: the exemplar slices was prepared with) is copied. The slice reads none of its other coordinates, so it only completes a packed point. slice_problem(...)(x) is the log density.
ReactiveKernelsPPL.slice_value_and_gradient! Method
slice_value_and_gradient!(slices, g, u, labels; compact = true) -> (value, g)The log density of the slice of labels (one label, or a collection of them) at the packed point u, and its gradient written into g: over slice_coordinates in that order when compact, otherwise over the whole packed vector with zeros outside the slice. u is read only; only its slice coordinates matter. Several labels share one pullback through shared values when the slices were prepared with partitioned.
ReactiveKernelsPPL.smc Function
smc(target; rng, particles=1000, reference=..., options=SMCOptions(), stages=typemax(Int))
smc(state; stages=typemax(Int))Run up to stages complete adaptive stages. A completed state's temperature is exactly 1. Positions are columns in the original unconstrained frame; weights are normalized. log_normalizer estimates the full target integral from the normalized reference. It is model evidence only when the authored density includes the necessary normalizing constants. No input state is mutated. An exactly collapsed positive-dimensional cloud throws SMCDegeneracyError, including when supplied at temperature 1. Reaching temperature 1 does not otherwise certify convergence or adequate exploration.
ReactiveKernelsPPL.smc_checkpoint Function
smc_checkpoint(state)
resume_smc(target, checkpoint; previous=nothing, nthreads=nothing)Copy the completed-stage state into a versioned, data-only checkpoint. Persist it with Julia Serialization in a trusted file. Rebuild the target after a restart and pass it to resume_smc; a data-update checkpoint also needs the old prepared target as previous. IDs, program/layout and endpoint densities are checked. Queries, compiled code and AD caches are never serialized. Exact seeded continuation requires the same Julia/package versions, data, model code and configuration, and a host whose CPU code generation matches the writer's. resume_smc recomputes every particle's log density under both bridge endpoints and requires the stored values bit for bit, and a different instruction set (AVX-512 versus AVX2, for example) can round the same density differently in its last bits. Such a checkpoint is refused with its largest deviation named; rescore_smc_checkpoint re-anchors it on the new host. This API does not write files or promise atomic disk persistence. The caller owns file replacement and model/data retention. pool_smc pools checkpoints of independent clouds directly, without a target. Omitting nthreads preserves the saved worker cap. Pass a positive integer, for example nthreads=Threads.nthreads(), to override only that cap; actual workers remain bounded by available default threads and particle count. Changing it preserves the particle cloud, evidence and RNG stream. History records the workers used at each stage; floating-point reductions in movement and mean-acceptance diagnostics can differ in their last bits across counts. The checkpoint itself is unchanged.
ReactiveKernelsPPL.smc_parameters Method
smc_parameters(carried::SMCCarriedReference, u)Restore the complete selected constrained parameter tuple from a compact unconstrained position. Construct carried with carry_smc(completed; parameters=authored_names, calibration_id) first. Uses the model's native constrain transforms, including dependent static bounds, nested author paths, vector and array geometry. It retains no old latent coordinates or observations. prepare_filter_smc uses this mapping automatically when parameters is omitted.
ReactiveKernelsPPL.smc_recover Function
smc_recover(target_or_state, compact_u; rng::Xoshiro)Draw one full joint unconstrained vector for a selective window, retaining the supplied active and fresh coordinates exactly. Inactive old coordinates are drawn from q_old(inactive | active), including its correlations. The returned order is smc_window_coordinates(target_or_state).joint. The supplied RNG advances; no production RNG is consumed implicitly and the compact point is read only. Full-sized recovery storage is allocated only when requested.
ReactiveKernelsPPL.smc_reference Function
smc_reference(state_or_schedule)Return an owned, data-only normalized reference for an initial bridge, or nothing for a posterior-to-posterior update. An update uses the previous prepared posterior as its source and does not need the original reference. This returns the initial proposal distribution, not posterior moments from a completed cloud. Use carry_smc(completed; basis=:fit, ...) to fit posterior moments before carrying a summary into a new window.
ReactiveKernelsPPL.smc_step Function
smc_step(state)Return the next complete resample/move stage. history holds bounded summaries (temperature, ESS before resampling, log normalizer increment, unique parents, surviving initial ancestors, moves and divergences). ancestors maps the most recent stage to its input cloud, and lineage tracks the initial cloud. Each summary's kernel records the actual scales, step size, moves per particle and depth limit; tuning_index is its schedule knot (zero when untuned). evaluations sums the transition evaluation counts; mean_acceptance averages the transitions' tree acceptance probabilities (nothing for zero dimensions). mean_squared_movement is the mean squared unconstrained displacement from each resampled parent to its final child, after all moves. These describe mutation work and movement, not independent evidence that a posterior has been explored adequately. coordinate_sd gives native unconstrained-coordinate standard deviations of the post-mutation, equally weighted cloud; reference_sd gives the initial Gaussian reference's marginal standard deviations, or nothing for an exact posterior-to-posterior update. These vectors retain O(d*history_limit) values, not historical clouds. Compare spreads across stages and independent runs; neither a large first temperature step nor a high ESS alone diagnoses coverage. nthreads records the number of mutation workers, capped by available default threads and particles (one for a zero-dimensional target). Exact diagnostic replay requires the same available thread count as well as the same options. Failures propagate; the input state and its RNG remain usable. Full spatial collapse is checked before temperature selection and after mutation, including the final stage. It throws SMCDegeneracyError with the preserved input and, for a failed mutation, the rejected stage's diagnostics. Summary kind is :temper for this operation or :rejuvenate for explicit fixed-temperature work.
ReactiveKernelsPPL.smc_window_coordinates Function
smc_window_coordinates(target_or_state)Return an owned coordinate descriptor for a window prepared with coordinates=:auto, or an initialized/completed state from that target. compact contains authored coordinate identities and geometry in particle order; current_indices maps them to the current model's packed frame. active_old gives their old-carry indices, ordered by active_slots in the compact vector. fresh_slots are the remaining compact positions. joint describes the full recovery/carry order (current layout first, then retained old coordinates absent from it); joint_indices locates the compact coordinates in that full order. Indices are one based.
ReactiveKernelsPPL.support_of Method
support_of(family, override) -> SymbolInferred unconstrained support (:real/:positive/:unit/:interval) for a sampled family plus an optional support override (:positive half-Normal/half-Cauchy style, :truncated, :interval, or :upper). :uniform infers :interval from its own literal args and takes no override. Loud on unknown families and inapplicable overrides.
ReactiveKernelsPPL.supports_term Method
supports_term(name) -> BoolStretch handshake: does the thin layer lower the named term kind yet? The emitter fails closed on false (:zscale/:center/:standardize/ :protect until declared here).
ReactiveKernelsPPL.topological_order Method
topological_order(plan) -> Vector{Symbol}Evaluation order over parameters ∪ assignments ∪ derived columns (Kahn's algorithm). Among names whose dependencies are met, the earliest declared comes first, so the same plan always gives the same order. Loud on cycles (and, on bound plans, unknown references — unbound plans defer name resolution to bind). Shared by validation and the generator.
sourceReactiveKernelsPPL.transform_statements Method
transform_statements(entry) -> Vector{Expr}In-graph constrain edge(s) for one layout entry. Coefficient/scan slices read a view; a :identity sampled entry reads its scalar coordinate; a constrained sampled entry (:exp/:logistic) splices the bijector's constrain endpoint, which the planner inlines.
ReactiveKernelsPPL.tune_filter_smc Function
tune_filter_smc(target; rng, init, kwargs...)
tune_filter_smc(state; rng, init, kwargs...)Tune fixed NUTS proposals on the carried reference with the existing independent tune_smc pilot. Pass its schedule as SMCOptions(tuning=schedule) to initialize_filter_smc. The final temperature's kernel is frozen for the stream: its moves sets the proposals per member at each replenishment, and its NUTS settings drive only explicit rejuvenate_smc recovery. That kernel is never adapted from production members, even at a window boundary. Replenishment itself proposes population-scaled random-walk moves; see initialize_filter_smc. This tunes a reference-reversible proposal, not a noisy likelihood. The state overload tunes its current window reference for explicit recovery with rejuvenate_smc(state; tuning, moves). Supply pilot initial positions and RNGs independently of production members. A longer reference pilot alone does not establish exploration of the observed-window posterior.
ReactiveKernelsPPL.tune_smc Function
tune_smc(target; rng::Xoshiro, init, reference=nothing, previous=nothing,
temperatures=(0.0, 1e-6, 1e-5, 1e-4, 1e-3, 0.01, 0.1, 0.5, 1.0),
pilot_steps=64, pilot=:continuous, max_reflections=16,
recording_target=128, pilot_evaluations=1000, reference_inflation=2.0,
options=SMCOptions(), progress=nothing, callback=nothing,
checkpoint_dir=nothing, resume=false, overwrite=false,
grid_start=:sequential)Prepare all mutation tuning before creating a production cloud. init is an explicit finite unconstrained position and rng an explicit independent pilot RNG; both are copied. Do not supply production-derived positions or RNGs. The pilot follows the specified fixed temperature grid, adapting through WarmupHMC's continuous diagonal kernel (pilot=:continuous), then freezes each knot's scale and step size. pilot=:adaptive instead runs ordinary adaptive warm-up at each knot and exports its active bounded-reflection or diagonal scale with that scale's own step size. Each run starts from an explicit diagonal initializer, avoiding a nonportable Pathfinder factor. Its draws are discarded. It does not adapt from production particles.
For pilot=:adaptive, grid_start=:sequential preserves the default: the first grid pilot starts at init, and each later pilot starts at the previous pilot's final position. Opt into grid_start=:independent to start every grid pilot at its own copy of init, with up to options.nthreads concurrent pilots, capped by available default Julia threads and unfinished knots. The reference pilot still finishes first. Each knot's seed is reserved in grid order before launch; private evaluators, sampler state and indexed results make the completed schedule identical across worker counts for the same independent run. The independent and sequential strategies generally learn different schedules. The continuous pilot supports only the sequential strategy. Independent pilots use more live sampler/evaluator memory; speedup depends on grid workload and the serial reference fit, checkpoint and callback costs.
For an initial bridge, supply a normalized SMCReference (default standard Normal). With pilot=:adaptive, reference=:pilot first runs a separate pilot at the full target and learns a normalized Gaussian from its retained draw mean and variances in the active scale's reflection basis. Cross-covariances in that basis are discarded. reference_inflation multiplies the fitted standard deviations (default 2; finite and positive). It applies only to reference=:pilot; 1 uses the uninflated fitted moments, not the active mutation scale. The active mutation scale and its paired step size are exported unchanged by each knot's pilot. The reference is fixed before the grid pilots and production. Fitting costs O(N_d_k) for N retained draws, d coordinates and k bounded reflections (O(N*d) without reflections), with no dense covariance.
Pilot exploration and wider references do not guarantee posterior coverage. schedule.pilot.reference_work records the inflation and native-coordinate draw_sd, alongside pilot work. A proposal reference is not a posterior-moment summary of the production cloud. smc_reference(schedule) returns the resulting data-only reference. For a cumulative-data update pass previous=old_prepared_target and no reference. The returned schedule is valid only for these exact endpoints. Supply it as SMCOptions(tuning=schedule). The production ESS temperature rule remains adaptive; this API does not claim exactly unbiased finite-particle evidence.
temperatures must strictly increase from 0 to 1; pilot_steps is the positive number of continuous adaptive transitions per knot. For pilot=:adaptive it is the retained-draw floor per warm-up, not an exact count; pilot_evaluations sets its first evaluation window, recording_target bounds its retained pool, and max_reflections bounds the learned operator. The schedule retains only scale data, coordinate spread summaries and work records, including each pilot seed; its evaluation counts exclude upstream initialization and the initial step-size search. options supplies the initial diagonal metric, production move count and tree-depth limit; it must not itself contain tuning. The default grid includes near-zero knots. Supply a model-specific grid when its tempering regime needs finer resolution; a finite grid is not an automatic guarantee that the learned kernels explore every intermediate target well.
Adaptive progress, interruption and recovery
The lifecycle keywords apply to pilot=:adaptive. A completed call returns a SMCTuningSchedule; a cooperative stop before completion returns a distinct SMCTuningPartial, which SMCOptions(tuning=...) rejects. The reference pilot must finish before its Gaussian is fitted, and every grid pilot must finish before its kernel is published. Zero-draw initialization stops are supported.
progress is a Treebars parent node. Tuning creates a parent under it and a transient child for the reference pilot or each active grid pilot, with WarmupHMC's own progress underneath. Finished pilot subtrees are detached; the parent reports the current phase, boundary, window, evaluations and completed knots. The inner window counter can restart and is not a total-work percentage. Independent grid callbacks and checkpoint writes are serialized. Event order and the subset finished at a stop can vary with scheduling. After a stop request, other active pilots reach cooperative boundaries and may deliver callbacks; all workers join before the call returns or propagates an error. callback(snapshot, boundary) is observational: only literal true requests a stop. boundary is :init, :window, or :pilot after a completed pilot. The immutable scalar snapshot records phase (:reference/:grid), knot (zero for the reference), temperature, boundary, completed_knots, window, retained_draws and evaluations. The window is zero at :pilot; the evaluation count is for that pilot, with WarmupHMC's initialization exclusions above. A stop at the last completed pilot returns the ready schedule.
Requesting a Treebars interrupt on the supplied parent stops at initialization, an outer warm-up window or between pilots, just like the callback. These are cooperative boundaries, not hard wall-clock guarantees: initialization and a single window may exceed a host deadline. A pre-existing interrupt returns a partial before starting a pilot. Resume under a fresh, uninterrupted node.
With checkpoint_dir=dir, dir/tuning_latest.jls is atomically replaced before each callback and before starting a pilot. It contains the completed reference, completed kernels and work, outer RNG, current pilot seed and WarmupHMC's active checkpoint payload. A failure during a window can restart from the preceding boundary; work since that boundary is not saved. Only this latest outer record is retained. The active payload includes sampler draws and can grow with the active pilot; completed pilots retain no draws. Boundary history is capped by options.history_limit, independently of the finite grid's completed work. Independent-grid checkpoints retain each knot's seed and its active payload or completed kernel/work, plus the grid-start strategy. Their live payloads can therefore occupy memory for several pilots at once.
To resume, rebuild the original target (and previous, for an update), then call tune_smc with the original tuning keywords and either checkpoint_dir=dir, resume=true or resume=partial. The partial can also be serialized and restored in a fresh process. Both paths copy the saved continuation, skip completed pilots, and restore the active sampler through WarmupHMC's public resume API. The required rng argument is ignored on resume: the checkpoint supplies both RNG streams. No callback is repeated at the restored initialization/window boundary. Resuming a completed file returns its schedule without running another pilot or callback. options.nthreads may change on resume; it controls worker allocation, not the saved numerical continuation. Keep grid_start and other tuning settings unchanged. Switching strategy requires a fresh tuning run.
From 0.1.98, custom sampling expressions in coordinate identities use the same generated-namespace normalization as the built program. Rebuilt helper modules therefore need no aliases to the producing process's temporary module names. This does not migrate older checkpoints: keep their original runtime/package versions, and a file that already refers to a missing generated module cannot be recovered merely by rebuilding an equivalent module under a new name.
Resume checks Julia/package and checkpoint versions, target and previous-endpoint identities, binding, coordinate frame, tuning configuration and endpoint scores at saved positions. Caller IDs remain assertions about code/data semantics; finite score probes cannot prove arbitrary functions equivalent. Keep the code, data and non-default tuning settings unchanged. Progress and callback handles are supplied afresh, never serialized. Inputs and a supplied partial stay unchanged. Treat checkpoint arrays as read-only and do not advance/write one continuation concurrently. Deserialize only trusted checkpoints.
A fresh call refuses an existing tuning_latest.jls unless overwrite=true; overwrite cannot combine with resume and replaces only that file, preserving unrelated directory contents. resume=partial optionally writes its continuation to checkpoint_dir, allowing an explicitly selected saved boundary to be forked. Without a directory, an orderly stop still returns an in-memory checkpoint; unexpected exceptions or process loss then have no automatic disk recovery. If another CPU rounds the same scores differently, ordinary resume still refuses. Use rescore_smc_tuning_checkpoint to explicitly re-anchor the outer scores and active sampler payloads before resuming.
ReactiveKernelsPPL.unconstrain Method
unconstrain(layout, constrained) -> VectorInverse of constrain: named values → packed unconstrained vector. Its element type promotes the values' number types with Float64.
ReactiveKernelsPPL.update_smc Function
update_smc(previous, target; options=previous.options, stages=typemax(Int))Bridge a completed posterior cloud to a target for caller-supplied cumulative data in the same model and coordinate frame. The bridge density is (1-beta)*old_posterior + beta*new_posterior in log space, so priors and Jacobians occur once. Every mutation evaluates the required old/new histories from their beginning. This is full-history updating, not constant-cost streaming or a latent-state particle filter. No old terminal scan state is reused. If previous.options contains tuning for its old bridge, the default rejects: supply a freshly prepared update schedule, or explicit untuned SMCOptions.
ReactiveKernelsPPL.validate_data Method
Data checks: columns, eltypes, levels, bounds. Requires a bound plan; bind_data runs this after attaching columns.
ReactiveKernelsPPL.validate_plan Method
validate_plan(plan) -> nothingDefensive thin-side validation of a StructuralPlan (R8): every unknown kind, dangling reference, arity/shape violation, and ordering failure throws ContractValidationError — loud, never silent. Returns nothing on success.
ReactiveKernelsPPL.validate_structure Method
Structure checks: everything provable without data. Runs on bound and unbound plans alike (the macro lowering + emitter-AST path call this).
sourceReactiveKernelsPPL.window_points Method
window_points(joined, x) -> Vector{Vector{Float64}}Each window's packed point at the joined point x: its own and shared coordinates from x, each fed input entry from the previous window's boundary output, unconstrained by the input's support.
ReactiveKernelsPPL.with_cell_batch Method
with_cell_batch(visit, owner, u)Evaluate cells at one copied packed point. owner is a CellQuery, CellFactors, or one of its value operators prepared with partitioned. The shared cache is refreshed once before visit(batch). Inside the callback, value queries and local structural footprints accept batch in place of u, without rescanning shared coordinates. No AD backend is needed. The callback's result is returned.
Prepare the structural footprint once with shared=false. Inside visit, pass the batch to both the value query and footprint kernel for each cell.
A batch belongs to its owner's cache and expires when the callback exits, including on error. Changing a shared coordinate its prefix reads (every shared coordinate when there is no prefix) through another operator invalidates it. A shared coordinate the prefix does not read reaches a cell only through the batch's copied point, so changing it elsewhere leaves the batch valid. Prepare a separate owner per concurrent caller. Input u may be changed after entry; the batch keeps its own point.
ReactiveKernelsPPL.workflow_wants Method
workflow_wants(preset::Symbol)Return the want selection for a named workflow preset (see WORKFLOW_WANTS). Throws ArgumentError naming the valid presets when preset is unknown, so a typo fails loudly rather than planning the wrong cut.
Macros
ReactiveKernelsPPL.@rkppl Macro
Capture a model block and bind caller-scope inputs and pins (a NamedTuple or dict of columns).
ReactiveKernelsPPL.@rkppl Macro
Capture a model block, or define a reusable submodel (@rkppl sm(args...) = begin ... end; see RKPPLSubmodel).
Design-matrix vocabulary (standard-Julia value semantics throughout): bind the matrix once (X = hcat(ones(length(x1)), x1, x2) — the intercept ones(length(x)) plus bare data/derived columns), use it only as a predictor matmul (mu = X * b), and size the coefficient vector with an axes prior (b[axes(X, 2)] .~ Normal.(loc, scale) — scalar args share over elements, literal […] vectors go per element). Declarations are strict: an undeclared coefficient name or vector fails naming the prior to write — nothing is defaulted. Every other matrix position (scales, prior arguments, indexing, arithmetic outside a matmul) fails loudly naming the spelling. Emitter guidance: matrix and affine spellings of one model evaluate bit-identically with identical coefficient labels — emit the matrix form wherever the consumer wants Stan-shaped fused structure (design matrix + coefficients), the affine form otherwise.
Constants and modules
ReactiveKernelsPPL.BIJECTORS Constant
Transform symbol → bijector kernel object (constrained supports only).
sourceReactiveKernelsPPL.COLUMN_ROLES Constant
Column roles: what a bound column IS (CV travel + program transforms read this). Inferred at bind; explicit roles override. Unbound plans carry none.
sourceReactiveKernelsPPL.ColumnData Type
Bound data values: numbers and arrays of any shape. Elementwise observations broadcast over their operands' Julia axes; singleton axes stretch and incompatible dimensions fail. Structured operations such as design-matrix products, schedule slices and level tables retain their own shape requirements. Model-level values have no observation axis.
sourceReactiveKernelsPPL.PPL_NODES Constant
PPL_NODESCanonical node names a generated @kernel program exposes, as a NamedTuple mapping role → node Symbol. Slice-1 subset of the PPLWorkflow.PPL_NODES vocabulary: every program built by build_kernel defines these nodes.
ReactiveKernelsPPL.WORKFLOW_WANTS Constant
WORKFLOW_WANTSPreset want selections over generated programs, as a NamedTuple mapping preset name → the want argument. Prefer workflow_wants, which validates the preset name.
:pointwise returns a NamedTuple keyed by observation name. Elementwise observations retain their array shape; scalar and joint-vector draws return scalars, and broadcast joint draws return one density per slice. In-cell observations use their caller's data-column name and flat data shape. Conditioned declarations contribute here as observations. Summing every field gives :likelihood; prior-only models return an empty NamedTuple.
:observations returns numeric distribution parameters under the same keys. Normal, Student t and LogNormal keep (location = …, scale = …). Bernoulli returns (probability = …, logit = …) for every link, including BernoulliLogit; Exponential returns (scale = …,). These values come from the observation's distribution graph, so the same query supports native evaluation, ordinary AD and js_source.
Other owned distribution objects expose these fields:
| Distribution | Fields |
|---|---|
| Poisson | rate |
| Binomial | trials, probability, logit |
| NegativeBinomial | shape, probability |
| NegativeBinomial2 | mean, dispersion |
| Gamma, Weibull | shape, scale |
| InverseGaussian | mean, shape |
| Beta (mean/precision form) | alpha, beta |
| BetaBinomial | trials, alpha, beta |
| ZeroInflatedPoisson | rate, zero_probability |
| ZeroInflatedBinomial | trials, probability, zero_probability |
Each parameter follows its own broadcast shape, in :pointwise order: a shared scalar stays scalar, a per-index scalar holds one number per index, and a per-entry value in a ragged cell holds one array per index. A new design binding can omit responses when the parameters' inputs supply their axes. Prior-only models return an empty NamedTuple.
The query exposes the underlying distribution's parameters, including for censored or truncated responses; it does not return a draw or a conditional moment of the censored/truncated law. A response without a recognized distribution object (for example a mixture, a sampling-RHS observation, or a conditioned declaration) currently causes ContractValidationError naming the uncovered responses. The direct two-shape Beta form and the specialized logit zero-inflation form of ZeroInflatedBinomial are also uncovered. Other presets remain available.
ReactiveKernelsPPL.ReactiveKernelsPPL Module
ReactiveKernelsPPLThin PPL compiler for ReactiveKernels: consumes a typed structural plan (slice 1: emitted by the BRM-side RK backend) and generates fittable @kernel programs — packed unconstrained layout, transforms, in-graph preprocessing, posterior density — addressable through the canonical sampler-query surface.
External-example style nested package: ReactiveKernels core never depends on it. Slice-1 scope (population GLMs, density+gradient only) is set by the joint BRM–RK backend plan; the emitter→layer input contract lives in src/contract.jl once agreed.
Public names that are not exported
Import these explicitly, for example using ReactiveKernelsPPL: adaptive_centering_problem, or call them qualified. On Julia 1.11 and later their docstrings appear in the sections above. The link enum LinkFunction and its values IdentityLink, LogitLink, LogLink, ProbitLink and CloglogLink are public in the same way.
ReactiveKernelsPPL.LinkFunction Type
Link functions. The enum crosses the boundary; the thin layer owns the inverse-link numerics (R1 counter).
LinkFunction and its values IdentityLink, LogitLink, LogLink, ProbitLink and CloglogLink are public but not exported, because BayesianRegressionModels and GLM.jl export link types with the same names. Import the ones you name, for example using ReactiveKernelsPPL: LinkFunction, LogitLink, or write them qualified.
ReactiveKernelsPPL.adaptive_centering_problem Function
adaptive_centering_problem(built, plan, problem, backend; cells, u0 = nothing,
on_error = nothing)Wrap a packed-coordinate LogDensityProblems target for WarmupHMC's adaptive partial centering. Load WarmupHMC and LogDensityProblems to enable this extension. built and the bound plan describe the same model as problem.
This function is public but not exported, because BayesianRegressionModels exports a different adaptive_centering_problem. Import it with using ReactiveKernelsPPL: adaptive_centering_problem, or call it qualified.
Select whole real-valued latent parameters by their graph names, for example cells = (z = (location = :z_location, log_scale = :z_log_scale),).
Each location and log-scale is either a Real constant shared by the block or a symbol naming a value in the model graph. For example, cells = (z = (location = 0.0, log_scale = :z_log_scale),) needs no named zero in the model. A constant is a runtime input of the endpoint kernel, not part of its code. A named value is a latent or a definition, a scalar (shared by the selected coordinates) or an array with the latent's shape, indexed in Julia's linear order. A definition the model does not have can be appended without editing the model's text, before binding:
merge(model, quote
log_s = log(s)
z_location = a_mean .+ effect
end)A definition that only cells read leaves the sampler's program and the jax_source module unchanged, so it costs the density and its gradient nothing. Named values' numerical work and derivatives stay in the graph, and their arrays are only read. One joint kernel computes all selected endpoints, sharing their common graph work across cells and both affine roles. WarmupHMC 0.2.21 or later evaluates it once per vector and level (below) on a map or inverse, and shares it across scoring candidates. Identity maps do not evaluate the endpoints.
Each cell optionally supplies target and source in [0, 1]: zero is non-centered, one is centered. Both default to 0.0. target describes the model's fixed coordinates; WarmupHMC adapts source. Unselected coordinates pass through, and sampling returns the original model coordinates.
The selected latent must have an identity support transform. This condition concerns coordinates, not prior families (a real ICAR block, for example, can be selected). Locations and log-scales may read unselected latents and the latents of other selected cells, but never their own cell's latent.
A cell whose location or log-scale reads another selected cell's latent is centred about that latent's model-frame value, as in a nested hierarchy:
cells = (z_g = (location = :mu, log_scale = :log_tau_g),
z_u = (location = :unit_location, log_scale = :log_tau_u))with unit_location = mu .+ tau_g .* z_g[group]. The reads order the cells into levels: a cell that reads no selected latent is on level 1, and a cell that reads latents of levels up to k is on level k + 1. WarmupHMC maps the levels in order, so re-centering a parent level keeps the meaning of the coordinates centred on it. The joint kernel runs once per level, after the levels before it are mapped. Cells that read each other's latents, directly or through other cells, form a cycle and are refused. Nested levels need WarmupHMC 0.3.0 or later, whose accessors read earlier pairs at their model values; with WarmupHMC 0.2 they are refused.
Recurrences marked with markov_chains get their WarmupHMC MarkovChains from the same call, with or without cells. A chain's coefficients, drift and step size may not read a cell's latent, and no cell's location or log-scale may read a chain's states.
Construction evaluates each named value once to check its shape, using u0 (default zeros) as a model-coordinate exemplar. The joint execution kernel is independent of the number of latent coordinates.
Additional exports
These exported bindings have no separate docstring. Their definitions are linked below.
| Name | Kind | Source |
|---|---|---|
BernoulliCloglogFam | Kernel or value | module source |
BernoulliLogitFam | Kernel or value | module source |
BernoulliLogitGLMFam | Kernel or value | module source |
BernoulliProbitFam | Kernel or value | module source |
BetaBinomial2Fam | Kernel or value | module source |
BetaLogitFam | Kernel or value | module source |
BetaShapeFam | Kernel or value | module source |
BinomialCloglogFam | Kernel or value | module source |
BinomialLogitFam | Kernel or value | module source |
BinomialProbFam | Kernel or value | module source |
BinomialProbitFam | Kernel or value | module source |
CategoricalFam | Kernel or value | module source |
CategoricalLogitFam | Kernel or value | module source |
CauchyFam | Kernel or value | module source |
CellAccumulator | Type | definition |
CellFactorAD | Type | definition |
CellFactors | Type | definition |
CellPullback | Type | definition |
CensoredAddpropnormalFam | Kernel or value | module source |
ComposedTerm | Kernel or value | module source |
ContinuousTerm | Kernel or value | module source |
ExponentialLogFam | Kernel or value | module source |
FactorQueryAD | Type | definition |
FactorTerm | Kernel or value | module source |
GammaLogFam | Kernel or value | module source |
GammaValueFam | Kernel or value | module source |
GaussianFam | Kernel or value | module source |
HurdlePoissonFam | Kernel or value | module source |
InterceptTerm | Kernel or value | module source |
InverseGaussianFam | Kernel or value | module source |
LatentTerm | Kernel or value | module source |
LogNormalFam | Kernel or value | module source |
MarginalizedLatentQuery | Type | definition |
MatrixTerm | Kernel or value | module source |
MixtureFam | Kernel or value | module source |
MultinomialFam | Kernel or value | module source |
MvNormalCholeskyFam | Kernel or value | module source |
NegativeBinomial2Fam | Kernel or value | module source |
NegativeBinomialFam | Kernel or value | module source |
NormalIDGLMFam | Kernel or value | module source |
OffsetTerm | Kernel or value | module source |
OrderedLogisticFam | Kernel or value | module source |
OrdinalFam | Kernel or value | module source |
PartitionQuery | Type | definition |
PoissonLogFam | Kernel or value | module source |
PoissonLogGLMFam | Kernel or value | module source |
ScanSummandTerm | Kernel or value | module source |
StudentTFam | Kernel or value | module source |
VonMisesFam | Kernel or value | module source |
WeibullFam | Kernel or value | module source |
WeibullValueFam | Kernel or value | module source |
ZeroInflatedBinomialFam | Kernel or value | module source |
ZeroInflatedPoissonFam | Kernel or value | module source |
condition | Function | definition |
filter_parameters | Function | definition |
floored_bijector | Kernel or value | definition |
interval_bijector | Kernel or value | definition |
positive_bijector | Kernel or value | definition |
resume_filter | Function | definition |
resume_smc | Function | definition |
rk_expm | Function | module source |
rk_symmetric_eigvals | Function | module source |
rk_symmetric_eigvecs | Function | module source |
unit_bijector | Kernel or value | definition |
upper_bijector | Kernel or value | definition |