| Title: | Core C++ Sampling Engine for 'lmebayes' |
|---|---|
| Description: | Core C++ engine for lmebayes: envelope-based iid samplers, two-block Gibbs mixed-model engines, and optional OpenCL acceleration. Full-featured developer backend for lmebayes and extensions. End users should use lmebayes for lmer/glmer-style mixed-model workflows. |
| Authors: | Kjell Nygren [aut, cre], The R Core Team [ctb, cph] (R Mathlib sources, R stats modeling code, and derived/adapted routines), The R Foundation [cph] (Portions of R Mathlib and R source code), Ross Ihaka [ctb, cph] (R Mathlib and original R modeling infrastructure), Robert Gentleman [ctb, cph] (Portions of R Mathlib), Simon Davies [ctb] (Original R glm implementation), Morten Welinder [ctb, cph] (Portions of R Mathlib), Martin Maechler [ctb] (Portions of R Mathlib) |
| Maintainer: | Kjell Nygren <[email protected]> |
| License: | GPL-2 |
| Version: | 0.1.0 |
| Built: | 2026-10-03 13:43:11 UTC |
| Source: | https://github.com/knygren/lmebayesCore |
Core C++ engine for envelope-based iid samplers, two-block Gibbs mixed-model engines, and optional OpenCL acceleration. Full-featured developer backend for lmebayes and related extensions. End users should install lmebayes for lmer/glmer-style mixed-model workflows.
Low-level entry points include envelope construction
(EnvelopeBuild, EnvelopeOrchestrator),
registered simulation pipelines (rNormalGLM_std,
rIndepNormalGammaReg_std), matrix-input samplers
(rglmb, rlmb), the two-block Gibbs
mixed-model engines (rlmerb, rglmerb), and
OpenCL kernel loaders. Formula interfaces lmerb and glmerb
live in lmebayes; lmebayesCore supplies the sampling engine.
The Chapter-B* vignettes document the engine itself: the theory it
implements, the routes it selects between, and the diagnostics it emits.
They assume the reader has met the models already, for which see the
Chapter-00 to Chapter-13 curriculum in lmebayes.
vignette("Chapter-B00")Roadmap, notation, and the correspondence to lme4.
vignette("Chapter-B01")The two-block architecture: replicate chains, the sweep loop, and the call stack.
vignette("Chapter-B02")Ergodicity and total-variation
convergence; the rate and the rank conditions.
vignette("Chapter-B03")Calibrating m_convergence
from tv_tol, and the pilot-versus-main cost trade-off.
vignette("Chapter-B04")The known-vcov Gaussian route and the exact iid sampler.
vignette("Chapter-B05")Estimated variance components
(dIndependent_Normal_Gamma Block 2).
vignette("Chapter-B06")The extended local rate diagnostic.
vignette("Chapter-B07")Per-group measurement dispersion.
vignette("Chapter-B08")Design, identifiability and rank conditions.
vignette("Chapter-B09")Row-block engines.
vignette("Chapter-B10")Sweep history and convergence plots.
The Chapter-C* vignettes take one model class each and work through
its posterior algebra, the eigenvalue calculation behind the convergence
rate , and simulation results with convergence
plots. Where the B series describes what the engine does, the C series
derives why it is correct and then shows the numbers.
vignette("Chapter-C01")The Gaussian running example: data, model, design, rank restriction and calibrated priors, shared by every Gaussian chapter in the series.
vignette("Chapter-C02")The exact Gaussian iid sampler:
known and , closed-form
posterior, no Markov chain.
vignette("Chapter-C03")Total variation distances between multivariate normal densities: Nygren (2020) reproduced in full — the generalized error functions, Lemmas 1–2, Theorems 1–3, Claims 1–4, Corollary 1 and their proofs. Model-free.
vignette("Chapter-C04")The same Gaussian model via the two-block Gibbs sampler: the Chapter-C03 rate and sweep budget instantiated on the running design, sweep history, and variance-convergence diagnostics.
The Chapter-A* vignettes shipped in the sources are inherited iid
GLM reference material from glmbayes and are not built into the
package tarball.
In interactive sessions, attaching the package with library(lmebayesCore)
may emit a short packageStartupMessage when glmbayesCore_has_opencl()
is FALSE but a GPU or OpenCL stack appears available on the host.
Set options(glmbayes.quiet_opencl_startup = TRUE) to suppress attach
notes (recommended for CI and R CMD check).
Maintainer: Kjell Nygren [email protected]
Other contributors:
The R Core Team (R Mathlib sources, R stats modeling code, and derived/adapted routines) [contributor, copyright holder]
The R Foundation (Portions of R Mathlib and R source code) [copyright holder]
Ross Ihaka (R Mathlib and original R modeling infrastructure) [contributor, copyright holder]
Robert Gentleman (Portions of R Mathlib) [contributor, copyright holder]
Simon Davies (Original R glm implementation) [contributor]
Morten Welinder (Portions of R Mathlib) [contributor, copyright holder]
Martin Maechler (Portions of R Mathlib) [contributor]
There are no references for Rd macro \insertAllCites on this help page.
lmebayes for the end-user modelling package.
Test whether group random effects lie in widetilde B(delta_2).
beta_in_marginal_safe_set(b, beta_set)beta_in_marginal_safe_set(b, beta_set)
b |
Group effects as a |
beta_set |
A |
Logical scalar: TRUE if .
rNormal_reg_group_safe,
rNormalGLM_reg_group_safe
Finds the Newton mode of the gamma-integrated marginal
posterior on stacked group coefficients. Reusable input for
beta_marginal_safe_set and group_precision_floor.
beta_marginal_mode( design, pfamily_list, family, dispprior_list = NULL, offset = NULL, weights = NULL, tol = 1e-10, maxit = 200L )beta_marginal_mode( design, pfamily_list, family, dispprior_list = NULL, offset = NULL, weights = NULL, tol = 1e-10, maxit = 200L )
design |
A |
pfamily_list |
Block~2 prior list from |
family |
A |
dispprior_list |
Optional Block~1 dispersion prior for |
offset, weights
|
Observation |
tol, maxit
|
Newton controls (unused beyond initial solve). |
An object of class "beta_marginal_mode" with beta,
hessian, f_mode, engine, prior_int,
group_data, P_b, and family.
beta_marginal_safe_set, group_precision_floor
Build the beta-safe set at fixed from
beta_marginal_mode. Does not compute data-precision floors;
use group_precision_floor for .
beta_marginal_safe_set( design = NULL, pfamily_list = NULL, family = NULL, delta_2 = 0.01, beta_mode = NULL, dispprior_list = NULL, offset = NULL, weights = NULL, tol = 1e-10, maxit = 200L, verbose = FALSE )beta_marginal_safe_set( design = NULL, pfamily_list = NULL, family = NULL, delta_2 = 0.01, beta_mode = NULL, dispprior_list = NULL, offset = NULL, weights = NULL, tol = 1e-10, maxit = 200L, verbose = FALSE )
design |
A |
pfamily_list |
Block~2 prior list (used if |
family |
A |
delta_2 |
Tail mass budget in |
beta_mode |
Optional result of |
dispprior_list, offset, weights
|
Passed to |
tol, maxit
|
Passed to |
verbose |
If |
An object of class "beta_marginal_safe_set" with level,
beta_mode, delta_2, P_b, and certification metadata.
beta_marginal_mode, group_precision_floor,
gamma_beta_tv_certificate
Computes the EM fixed point , the mode profile
, and the spectrum-calibrated restricted-chain
multiplier .
certificate( design, pfamily_list, family = gaussian(), delta = 0.01, dispprior_list = NULL, estep = c("exact", "aghq", "mc"), acceleration = c("none", "squarem"), icm_init = TRUE, icm_tol = 1e-08, icm_maxit = 200L, n = 10000L, mc_seed = NULL, tol = NULL, em_tol = 1e-10, maxit = 200L )certificate( design, pfamily_list, family = gaussian(), delta = 0.01, dispprior_list = NULL, estep = c("exact", "aghq", "mc"), acceleration = c("none", "squarem"), icm_init = TRUE, icm_tol = 1e-08, icm_maxit = 200L, n = 10000L, mc_seed = NULL, tol = NULL, em_tol = 1e-10, maxit = 200L )
design |
A |
pfamily_list |
Block~2 prior list from |
family |
A |
delta |
Tail / escape probability budget in |
dispprior_list |
Optional Block~1 dispersion prior for |
estep |
E-step tier: |
acceleration |
|
icm_init |
If |
icm_tol |
ICM convergence tolerance on |
icm_maxit |
Maximum ICM iterations. |
n |
Number of |
mc_seed |
Optional seed for the MC E-step (first iteration only). |
tol |
If supplied, compute a sweep count |
em_tol |
EM convergence tolerance passed to |
maxit |
Maximum EM iterations. |
The certificate applies to the restricted Gibbs chain on
, not necessarily the production sampler; see
inst/CHAPTER_C05_IMPLEMENTATION.md section 8. Set sizing inverts
the weighted- escape tail on the coupling spectrum at
(section 4A.3). Outside Gaussian closure the exact
escape mass may differ from delta.
An object of class "minorization_certificate".
population_mode,
epsilon, deficiency_spectrum,
gamma_beta_tv_certificate
Runs the "two-step identifiability assessment" used internally by
model_setup: a Level~1 (within-group) rank/estimability
check on the level-1 design D, followed by a Level~2 (across-group)
rank check on the level-2 design matrices W, restricted to the
Level-1-estimable groups. Takes the same D/group/W
matrix inputs (and the same conventions – see Details) as
rLMM_reg/rGLMM_reg, so it can be run directly
on hand-built matrices from those matrix-level workflows, or on
model_setup()'s design$D/design$group/
design$W directly, without requiring a full lmer/glmer
reference fit.
check_identifiability( y, D, group, W, family = gaussian(), group_name = attr(group, "group_name"), verbose = FALSE )check_identifiability( y, D, group, W, family = gaussian(), group_name = attr(group, "group_name"), verbose = FALSE )
y |
Response vector of length |
D |
Level-1 design matrix ( |
group |
Grouping factor of length |
W |
Named list of group-level design matrices ( |
family |
A |
group_name |
Display name of the grouping factor (e.g.
|
verbose |
If |
Level 1 (within-group). For each group , the within-group
submatrix (D[group == , ]) is checked for
full column rank (groupef.rank). A rank-deficient group has too few
distinct observations to estimate all random slopes independently.
Algebraically full-rank groups are then additionally checked for
estimability (groupef.estimable, with per-group detail in
groupef.glm_check), with the specific check depending on
family:
binomial(), poisson(), Gamma(): a classical
glm(y ~ D_j - 1, family) fit is attempted; a group can be full
column rank yet have no finite MLE under complete or quasi-complete
separation (binomial), an all-zero count response
(poisson), or a non-positive response (Gamma) –
Gamma groups are additionally required to have n_j > p_j
so the dispersion/shape parameter is estimable.
gaussian(): no fit is attempted (the OLS coefficient MLE
always exists given full column rank), but the group must still have
n_j > p_j so the residual variance/dispersion is estimable
(otherwise the group achieves a perfect/saturated fit with zero
residual degrees of freedom).
other families: groupef.estimable is set equal to
groupef.rank (no additional check yet).
Level 2 (across-group). Restricting to the estimable
groups from Level 1 (groupef.estimable), each level-2 design matrix
W[[k]] is checked for full column rank (popef.rank), using
only the rows at the estimable positions (row of W[[k]]
corresponds to levels(group)[j], exactly as in
rLMM_reg). Rank deficiency at this level means the level-2
hyperparameters are not identified by the data, even as the number of
estimable groups grows. The scalar popef.rank_ok is TRUE
only when every popef.rank entry is TRUE.
Inputs must already be consistently keyed. This function does not infer or coerce missing names – it validates them up front and errors immediately on a mismatch, rather than risking a silently wrong match deeper in the rank/estimability computation:
D must have unique, non-empty colnames(D): these are
the random-effect coefficient names used to key W (there is no
separate groupef.names argument to override them, matching
rLMM_reg).
group must be a factor (not coerced from a character
vector); levels(group) fixes the row order assumed by
W (there is no separate group_levels argument).
W must be a named list, with names matching
colnames(D) exactly (as sets; no missing, empty, or duplicate
names), and each W[[k]] must have exactly
length(levels(group)) rows.
group_name, used only for error/verbose messages, must be
resolvable from either the group_name argument or
attr(group, "group_name").
A list with:
groupef.rankNamed logical, one entry per group (names
levels(group)): TRUE if is full column
rank.
groupef.estimableNamed logical, same names as
groupef.rank: TRUE if the group is additionally
estimable (see Details).
groupef.glm_checkPer-group diagnostic data frame for
binomial()/poisson()/Gamma()/gaussian(),
or NULL for other families.
popef.rankNamed logical, one entry per RE coefficient
(names colnames(D)): TRUE if W[[k]] is full
column rank when restricted to groupef.estimable groups.
popef.deficientNegation of popef.rank.
popef.rank_okScalar TRUE only when every
popef.rank entry is TRUE.
group_levelslevels(group), i.e. the exact
names used on groupef.rank/groupef.estimable.
group_nameThe resolved grouping-factor display name.
model_setup,
rLMM_reg,
rGLMM_reg,
extract_re_hyper_matrices
Inverts the Gaussian-reference escape tail on -weights,
then sets d = r^2/2 (equivalently 2d = r^2) and
set_cut = exp(-d).
deficiency_calibrate(delta, spectrum)deficiency_calibrate(delta, spectrum)
delta |
Tail / escape probability budget in |
spectrum |
A list from |
Weighted- tails for general spectra use
CompQuadForm::imhof() when the suggested package CompQuadForm
is installed, otherwise mgcv::psum.chisq() if mgcv is available.
A list with r2, r, d, delta,
escape_mass, set_cut, and spectrum.
Returns symmetrized coupling eigenvalues and
deficiency weights with
, ,
(spectrally; matrix product only when and
share eigenvectors). Computed at the terminal conditional-mean
E-step of population_mode.
deficiency_spectrum(mode)deficiency_spectrum(mode)
mode |
A |
Limits: ;
.
A list with kappa, weights, kappa_max,
rho, q, and method.
Generic for constructing a named list of dGamma prior
objects from a prior-specification object. For mixed models, one
dGamma per group level supplies observation-level
priors for lmerb(..., group.dispersion = ...).
dGamma_list(object, ...)dGamma_list(object, ...)
object |
A prior-specification object. |
... |
Additional arguments passed to methods (e.g.
|
Where pfamily_list configures the between-group
variance components , dGamma_list() configures the
within-group observation variance. It returns one
dGamma prior per group level, so each group
gets its own rather than sharing a pooled value.
Each element places a Gamma prior on the precision
(hence Inv_Dispersion = TRUE) and carries a
truncation window disp_lower/disp_upper calibrated from
that group's own data. Because groups differ in size and in residual
scatter, the windows differ across groups – often by an order of
magnitude – which is the point of the per-group treatment.
For Prior_Setup_GLMM with a per-group dispformula,
each group's dGamma() uses shape_ING/rate from
object$group.ing_prior (Part VI calibration; see
inst/DGAMMA_LIST_MARGINAL_AND_BOUNDS.md). Truncation bounds are
posterior-shape quantiles at that group's max_disp_perc.
For dGamma_list(), an object of class
"dGamma_list" (also inherits from "list"): a named
list of "pfamily" objects (one per group). Attributes such
as window_diagnostics and measurement_prior_group
are retained for downstream use but are not shown by
print.dGamma_list(). For print.dGamma_list(),
x invisibly.
dGamma, Prior_Setup_GLMM,
pfamily_list, rLMM_reg
Combines the mode profile eps_star with the reference radius
r(delta) and deficiency d = r^2/2 from the -spectrum
weights at mode. Produces
eps_d = exp(-d) eps_star and eps = eps_d Q(C_tilde_d) with
Q(C_tilde_d) at Pr(sum kappa_i Z_i^2 <= r^2).
epsilon(eps_star, delta, mode)epsilon(eps_star, delta, mode)
eps_star |
Mode profile |
delta |
Tail budget used to calibrate |
mode |
A |
Weighted- tails for general coupling spectra require suggested
package CompQuadForm (preferred) or mgcv.
A list with eps_star, d, r, r2,
eps_d, Q_mass_lb, eps, spectrum, kappa,
cal, and route.
Solves the convex program of Chapter C05 Definition 5 at the EM fixed
point: minimize over destination , with
the kernel integral over uses an exact Gaussian convolution when
family = gaussian(), otherwise Monte Carlo draws from
.
epsilon_optimize( mode, n = NULL, mc_seed = NULL, gamma_prime_start = NULL, control = list(maxit = 200L), ... )epsilon_optimize( mode, n = NULL, mc_seed = NULL, gamma_prime_start = NULL, control = list(maxit = 200L), ... )
mode |
Object returned by |
n |
Number of |
mc_seed |
Optional seed for the cached |
gamma_prime_start |
Initial destination |
control |
A list passed to |
... |
Ignored. |
A list with eps_star, method, certified,
g_opt, gamma_prime, optim, and n.
Mode profile epsilon(gamma*) for the restricted Gibbs certificate.
epsilon_star(mode, method = c("closure", "optimize"), ...)epsilon_star(mode, method = c("closure", "optimize"), ...)
mode |
Object returned by |
method |
|
... |
Passed to |
A list with eps_star, method, and certified.
Forms
and returns .
Rosenthal drift constants are computed separately by
rosenthal_drift_constants.
floor_coupling_eigenvalues(mode, floor)floor_coupling_eigenvalues(mode, floor)
mode |
A |
floor |
A |
A list with kappa_lb, kappa_max_lb, S_lb, and
q.
rosenthal_drift_constants, rosenthal_tv_bound
Backward-compatible wrapper combining eigenvalues and drift constants.
floor_coupling_spectrum(mode, beta_set)floor_coupling_spectrum(mode, beta_set)
mode |
A |
beta_set |
A |
List from floor_coupling_eigenvalues plus Rosenthal
drift fields from rosenthal_drift_constants.
Orchestrates categories 1–8: population_mode,
epsilon_star, beta_marginal_mode,
beta_marginal_safe_set, group_precision_floor,
floor_coupling_eigenvalues, and
optimal_rosenthal_tv_bound.
gamma_beta_tv_certificate( design, pfamily_list, family = gaussian(), delta_2 = 0.01, dispprior_list = NULL, k = NULL, tol = NULL, inner_tol = NULL, total_tol = NULL, alpha = NULL, display_mode = c("sharp", "general"), include_full_pi_gamma = TRUE, estep = c("exact", "aghq", "mc"), kappa_method = c("laplace", "crude", "none"), acceleration = c("none", "squarem"), n = 10000L, mc_seed = NULL, icm_init = TRUE, icm_tol = 1e-08, icm_maxit = 200L, em_tol = 1e-10, maxit = 200L, delta = NULL, optimize_alpha = TRUE, verbose = FALSE )gamma_beta_tv_certificate( design, pfamily_list, family = gaussian(), delta_2 = 0.01, dispprior_list = NULL, k = NULL, tol = NULL, inner_tol = NULL, total_tol = NULL, alpha = NULL, display_mode = c("sharp", "general"), include_full_pi_gamma = TRUE, estep = c("exact", "aghq", "mc"), kappa_method = c("laplace", "crude", "none"), acceleration = c("none", "squarem"), n = 10000L, mc_seed = NULL, icm_init = TRUE, icm_tol = 1e-08, icm_maxit = 200L, em_tol = 1e-10, maxit = 200L, delta = NULL, optimize_alpha = TRUE, verbose = FALSE )
design |
A |
pfamily_list |
Block~2 prior list from |
family |
A |
delta_2 |
Asymptotic tail allowance for the full marginal. |
dispprior_list |
Optional Block~1 dispersion prior for |
k |
If set, evaluate at this sweep count only. |
tol |
Alias for |
inner_tol |
Target for the inner Rosenthal bound. |
total_tol |
Target for full |
alpha |
If set, skip alpha optimization. |
display_mode |
|
include_full_pi_gamma |
If |
estep |
E-step tier: |
kappa_method |
Passed to |
acceleration |
|
n |
Number of |
mc_seed |
Optional seed for the MC E-step (first iteration only). |
icm_init |
If |
icm_tol |
ICM convergence tolerance on |
icm_maxit |
Maximum ICM iterations. |
em_tol |
EM convergence tolerance passed to |
maxit |
Maximum EM iterations. |
delta |
Tail budget for |
optimize_alpha |
If |
verbose |
If |
An object of class "gamma_beta_tv_certificate".
certificate, optimal_rosenthal_tv_bound
Computes the C05 EM E-step: per-group conditional means
(and posterior covariances ) at a
supplied population location fixef. For gaussian() with
estep = "exact" and no beta_set, the posterior mean is closed
form. Otherwise means are Monte Carlo averages.
group_effects_conditional_mean( design = NULL, pfamily_list = NULL, family = NULL, fixef = NULL, mode = NULL, dispprior_list = NULL, beta_set = NULL, estep = c("exact", "aghq", "mc"), n = 10000L, mc_seed = NULL )group_effects_conditional_mean( design = NULL, pfamily_list = NULL, family = NULL, fixef = NULL, mode = NULL, dispprior_list = NULL, beta_set = NULL, estep = c("exact", "aghq", "mc"), n = 10000L, mc_seed = NULL )
design |
A |
pfamily_list |
Block~2 prior list (required if |
family |
A |
fixef |
Named list of population fixed effects ( |
mode |
Optional result of |
dispprior_list |
Optional Block~1 dispersion prior for |
beta_set |
Optional |
estep |
|
n |
Target number of accepted joint draws when |
mc_seed |
Optional RNG seed for the MC E-step. |
When beta_set () is supplied, means are
Monte Carlo averages of accepted joint draws from
rNormal_reg_group_safe or
rNormalGLM_reg_group_safe (by family).
An object of class "group_effects_conditional_mean" with
b_mean, V_list, b_mc_se (when MC is used),
fixef, estep, n, n_target, n_tried,
accept_rate (when beta_set is set), beta_set,
restricted, and model context (design, family,
p11).
population_mode, beta_marginal_safe_set,
rNormal_reg_group_safe, rNormalGLM_reg_group_safe
Compute per-group lower-bound data precision matrices on a
certified beta level set. Typically used after
beta_marginal_mode and beta_marginal_safe_set.
group_precision_floor( design = NULL, pfamily_list = NULL, family = NULL, beta_mode = NULL, beta_set = NULL, epsilon = 0.01, dispprior_list = NULL, offset = NULL, weights = NULL, kappa_method = c("crude", "laplace", "none"), union_over = c("groups", "functionals"), mode_method = c("marginal_newton", "icm"), level_method = c("prop2_groups", "prop2_functionals", "r_gauss_joint"), tol = 1e-10, maxit = 200L, verbose = FALSE )group_precision_floor( design = NULL, pfamily_list = NULL, family = NULL, beta_mode = NULL, beta_set = NULL, epsilon = 0.01, dispprior_list = NULL, offset = NULL, weights = NULL, kappa_method = c("crude", "laplace", "none"), union_over = c("groups", "functionals"), mode_method = c("marginal_newton", "icm"), level_method = c("prop2_groups", "prop2_functionals", "r_gauss_joint"), tol = 1e-10, maxit = 200L, verbose = FALSE )
design |
Used when |
pfamily_list |
Block~2 prior list. |
family |
A |
beta_mode |
Result of |
beta_set |
Result of |
epsilon |
Escape budget when building levels without |
dispprior_list |
Optional Block~1 dispersion prior for |
offset, weights
|
Observation |
kappa_method |
|
union_over |
|
mode_method |
Default |
level_method |
Default |
tol, maxit
|
Newton controls (unused beyond initial solve). |
verbose |
If |
An object of class "group_precision_floor".
beta_marginal_safe_set, floor_coupling_eigenvalues
Wrapper around lmer or glmer for
models with exactly one grouping factor. Design matrices come from
formula (including cross-level RE moderation terms). Random-effect
and residual variance components (Psi, dispersion) come
from the same reference lmer/glmer fit on formula, so
printed summaries match summary(lmer(...)) on that formula.
model_setup( formula, data = NULL, family = gaussian(), REML = TRUE, control = NULL, start = NULL, verbose = 0L, subset, weights, na.action, offset, contrasts = NULL, devFunOnly = FALSE, fit_mer = TRUE, dispformula = ~1, ... )model_setup( formula, data = NULL, family = gaussian(), REML = TRUE, control = NULL, start = NULL, verbose = 0L, subset, weights, na.action, offset, contrasts = NULL, devFunOnly = FALSE, fit_mer = TRUE, dispformula = ~1, ... )
formula |
A two-sided linear formula, as in |
data |
An optional data frame containing the variables named in
|
family |
As in |
REML |
Logical scalar, as in |
control |
|
start |
Optional starting values, passed to the reference
|
verbose |
Integer scalar passed to the reference |
subset |
An optional expression indicating the subset of rows of
|
weights |
An optional vector of prior weights, as in |
na.action |
A function indicating what should happen when |
offset |
An optional a priori known component to include in the
linear predictor, as in |
contrasts |
An optional list of contrasts (see the
|
devFunOnly |
Logical, as in |
fit_mer |
If |
dispformula |
As in |
... |
Ignored. |
Uncorrelated random effects (||).
The sampler treats Sigma_ranef as diagonal (no off-diagonal
covariance). Multi-coefficient random terms must use ||, e.g.
(1 + x || group) rather than (1 + x | group). A single
random intercept may use (1 | group); (1 || group) is not
supported by lme4.
Fixed-effect constraints.
model_setup accepts the same formula language as
lmer, subject to one structural rule: every fixed
effect that does not correspond to a random-slope term must be a
group-constant (level-2) covariate—a predictor whose value is the
same for every observation within a given group. School-level attributes
such as private_school or title1 satisfy this constraint.
Student-level covariates that vary within groups may appear as fixed
main effects only when they also appear as random slopes (they then
represent the population mean slope , e.g.,
distracted_ppvt). Cross-level interactions of the form
level2_var:random_slope (e.g.,
free_reduced_lunch:distracted_a1) are additionally permitted; they
moderate the prior mean of the corresponding random slope across groups (see
extract_re_hyper_matrices). Fixed terms that are none of
these three types—level-2 covariate, population mean slope, or cross-level
moderation interaction—are rejected with an informative error.
Two-step identifiability assessment.
After fitting lmer/glmer, model_setup calls
check_identifiability to assess whether the model is
empirically identified at both the within-group (groupef.rank,
groupef.estimable, groupef.glm_check) and across-group
(popef.rank, popef.deficient, popef.rank_ok) levels,
and copies its fields onto the returned design object – see
check_identifiability for the full algorithm description
(including the family-specific estimability checks and how
popef.rank_ok is derived). Non-estimable groups are flagged but
retained in the lmer/glmer fit;
Prior_Setup_GLMM excludes them when calibrating priors,
and requires popef.rank_ok = TRUE to derive default hyperpriors
automatically.
The example uses big_word_club from bayesrules
(see ?bayesrules::big_word_club) and the same
formula as the full lmerb() demo in lmebayes
(demo("Ex_12_lmerb_BigWordClub", package = "lmebayes")).
Object of class "model_setup" with:
yResponse vector, length nrow(D).
weightsNumeric prior-weight vector of length
length(y) (ones when unspecified), aligned with y/
D/group after subset/na.action.
offsetNumeric offset vector of length length(y)
(zeros when unspecified and no formula offset()), aligned
with y/D/group.
DGroup-effects model matrix (n_obs x
p_re): per-observation loadings on the within-group
group-effect coefficient vector (columns groupef.names).
groupFactor of length nrow(D) for block
subsetting; levels(group) fixes group order used elsewhere.
Also carries attr(group, "group_name") (same value as
group_name) so group alone can be passed to sampler
engine functions without a separate group_name argument.
group_nameGrouping factor name.
groupef.namesGroup-effect coefficient names from
lme4; always identical to names(W) (and to
colnames(D)).
WNamed list of group-level hyper-design matrices (one
per groupef.names entry, one row per group level).
popef.moderationCross-level moderation metadata; see
extract_re_hyper_matrices.
formulaThe formula argument, as supplied.
familyThe normalized family
object.
callThe matched call.
termsThe terms object for
formula, as in lm/glm (and
glmbayes::glmb/lmb).
dataThe data argument, as supplied (NULL
when omitted), as in lm/glm (and
glmbayes::glmb/lmb).
dispformulaThe dispformula argument, as
supplied.
lmer / glmer
The reference
lmer (Gaussian) or glmer
(otherwise) fit on formula; NULL when
fit_mer = FALSE.
varcorrThe raw VarCorr object from
the reference fit.
PsiNamed numeric vector (names groupef.names) of
group-effect variances.
dispersionResidual (measurement) variance from the reference fit.
glmmTMB_fitNULL when dispformula = ~1 or
fit_mer = FALSE; otherwise a glmmTMB
fit on formula with the same dispformula (Gaussian
models only), fit via the same data/REML/
control-derived arguments as lmer. This is
additive: lmer/glmer are never replaced by a
glmmTMB fit. Prior_Setup_GLMM and
lmerb() (in lmebayes) reuse glmmTMB_fit as their
per-group-dispersion calibration reference instead of fitting
glmmTMB a second time.
groupef.rankNamed logical (names levels(group)):
TRUE if that group's is full column rank; see
check_identifiability.
groupef.estimableNamed logical, same names as
groupef.rank: TRUE if the group is additionally
estimable (family-specific MLE/dispersion check); see
check_identifiability.
groupef.glm_checkPer-group diagnostic data frame from
check_identifiability (family-dependent; may be
NULL).
popef.rankNamed logical (names groupef.names):
TRUE if W[[k]] is full column rank when restricted to
groupef.estimable groups.
popef.deficientNegation of popef.rank.
popef.rank_okScalar TRUE only when every
popef.rank entry is TRUE; required by
Prior_Setup_GLMM to derive default hyperpriors
automatically.
check_identifiability,
extract_re_hyper_matrices
Computes d = 0.5 * qchisq(1 - delta, q). This equal-weight route is
retained for reference only; epsilon and
certificate use deficiency_calibrate on the
coupling spectrum from deficiency_spectrum instead.
mvn_calibrate(q, delta)mvn_calibrate(q, delta)
q |
Hyperparameter dimension. |
delta |
Tail / escape probability budget in |
A list with r2, r, d, and set_cut = exp(-d).
Optimize Rosenthal TV bound over alpha and/or sweep count k.
optimal_rosenthal_tv_bound( mode, eigenvalues, eps, k = NULL, alpha = NULL, inner_tol = NULL, total_tol = NULL, delta_2 = 0, include_full_pi_gamma = TRUE, optimize_alpha = TRUE, display_mode = c("sharp", "general"), d = NULL, V_sup = NULL )optimal_rosenthal_tv_bound( mode, eigenvalues, eps, k = NULL, alpha = NULL, inner_tol = NULL, total_tol = NULL, delta_2 = 0, include_full_pi_gamma = TRUE, optimize_alpha = TRUE, display_mode = c("sharp", "general"), d = NULL, V_sup = NULL )
mode |
A |
eigenvalues |
Output of |
eps |
Minorization constant for the bound. |
k |
If set, evaluate at this sweep count only. |
alpha |
If set, skip alpha optimization. |
inner_tol |
Target for the inner Rosenthal bound. |
total_tol |
Target for full |
delta_2 |
Asymptotic tail allowance for the full marginal. |
include_full_pi_gamma |
If |
optimize_alpha |
If |
display_mode |
|
d |
Deficiency level for |
V_sup |
Override for |
A list of class "optimal_rosenthal_tv_bound".
rosenthal_tv_bound, gamma_beta_tv_certificate
Generic for converting a prior-setup object into a named list of
pfamily objects (class "pfamily_list") for block or
mixed-model samplers.
pfamily_list(object, ptypes = NULL, ...)pfamily_list(object, ptypes = NULL, ...)
object |
A prior-setup object. Dispatch is method-specific; see Methods and linked help pages for required classes and arguments. |
ptypes |
Prior-family name(s) per component; meaning depends on the
active method (for row-block setup see |
... |
Passed to methods (unused for |
For a Prior_Setup_GLMM object, each group-effect
coefficient uses parameters from
object$pop.prior_list[[k]]:
"dNormal": dNormal(mu, Sigma, dispersion) with
group-effect variance from
pop.prior_list[[k]]$dispersion (A12 §3.3.4 marginal
hyper-regression center for Gaussian models; classical VarCorr in
pop.dispersion.ref).
"dIndependent_Normal_Gamma": the same mu and
Sigma, plus a Gamma prior on precision
from object$pop.ing_prior[[k]] (calibrated by
Prior_Setup_GLMM via pop.dispersion.pwt /
pop.dispersion.nprior, mean-matched at that same marginal
). With effective prior sample size
and population predictors for component
,
Requires (equivalently
pop.dispersion.pwt ). Truncation bounds
disp_lower / disp_upper come from the limiting
posterior window stored on pop.ing_prior; see
inst/ING_TRUNCATION_WINDOW.md.
This is separate from observation-level priors: those
use dGamma_list (per-group dispformula) or a
single dGamma built from
object$group.ing_prior when dispersion is pooled.
For pfamily_list(), an object of class "pfamily_list"
(also inherits from "list"): a named list of pfamily objects.
Attribute "ptypes" records the resolved prior-family name per
component when the method sets it. For print.pfamily_list(),
x invisibly.
Prior_SetupGroup, Prior_Setup_GLMM,
pfamily,
dNormal, dNormal_Gamma,
dIndependent_Normal_Gamma
Tracks convergence of the Block~2 fixed-effects (hyperparameter) posterior
mean across inner Gibbs sweeps as a single combined chart (all
traces overlaid on one axis), the mean-side counterpart of
plot_var_convergence's variance-side Claim~3 chart. Per the
two-block Gibbs ergodicity result's Claim~1, the cross-chain mean bias
decays like (linear in l,
vs. Claim~3's for variance). Each coefficient's per-sweep
deviation from its reference mean is standardized by that same sweep's
cross-chain SD, , so coefficients on very different scales can be overlaid
on one chart and Z(l) is expected to shrink toward 0 as l
grows.
plot_mean_convergence(hist, ...) ## Default S3 method: plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), design = NULL, measurement_prior_list = NULL, whitened = FALSE, engine = c("base", "ggplot"), n_chains = NULL, conf_level = 0.95, stage_label = hist$stage, split = c("auto", "none"), max_whitened = 4L, ... ) ## S3 method for class 'rLMMNormal_reg' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rlmerb' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rGLMM_reg' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rglmerb' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... )plot_mean_convergence(hist, ...) ## Default S3 method: plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), design = NULL, measurement_prior_list = NULL, whitened = FALSE, engine = c("base", "ggplot"), n_chains = NULL, conf_level = 0.95, stage_label = hist$stage, split = c("auto", "none"), max_whitened = 4L, ... ) ## S3 method for class 'rLMMNormal_reg' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rlmerb' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rGLMM_reg' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rglmerb' plot_mean_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... )
hist, coef_focus, component, engine, n_chains, conf_level, split, max_whitened
|
Same meaning as in |
... |
Passed to methods; see |
design, measurement_prior_list
|
When both are supplied, the exact
reference mean is resolved automatically via
|
whitened |
When |
stage_label |
Defaults to the resolved |
stage |
|
The x-axis is the inner Gibbs sweep index , and each point is a
cross-chain statistic computed over the n_chains
independent replicate chains, all of which sit at sweep
simultaneously. Nothing here is a running statistic along a single
chain.
The plotted quantity is the standardized deviation
which divides out the scale of each coefficient so that an intercept
measured in hundreds and a slope measured in tenths can share one axis.
A converged run shows every trace scattered around 0 with no trend; a
systematic drift toward or away from 0 means the sweep budget is too
small. Supplying n_chains adds a naive band that separates
Monte Carlo noise from genuine bias.
mean_ref is the exact posterior mean when design and
measurement_prior_list are supplied (only possible when
and the RE variance components are all fixed), and
otherwise the empirical last-sweep mean. As with
plot_var_convergence, the empirical fallback cannot detect a
run that never converged, because the reference is drawn from the same
unconverged distribution.
This chart is the location-side counterpart of
plot_var_convergence, which tracks spread. The variance
converges at twice the rate of the mean, so this is the slower — and
therefore the more informative — of the two when deciding whether
m_convergence is large enough. A fit whose variance ratios have
settled at 1 while these traces still drift has converged in spread but
not in location.
Because every replicate chain starts at the posterior mean, the bias
begins at zero on Gaussian fits with fixed variance components: expect a
flat chart from sweep 1 there. Read a non-flat one as evidence that
something upstream — an estimated variance component, or a start at the
mode rather than the mean — has moved the starting point off the target
mean. vignette("Chapter-B02", package = "lmebayesCore") derives
the two rates.
As for plot_var_convergence: the exact route runs no sweeps
to record, some Gaussian paths do not export per-sweep cross-chain
statistics, and whitened = TRUE needs slots that only the
sweep-recording engines populate. See that topic, which also explains
how to obtain n_chains from a fitted object.
hist invisibly.
plot_var_convergence,
lmerb_posterior_mean
Tracks convergence of the Block~2 fixed-effects (hyperparameter) posterior
variance across inner Gibbs sweeps as a single combined chart (all traces
overlaid on one axis, following lmebayes::Ex_16's style), per the
two-block Gibbs ergodicity result (Claim~3 of the package's ergodicity
reference, inst/BLOCK_GIBBS_ERGODICITY.md): after l sweeps,
the cross-chain covariance satisfies
for a convergent (symmetric, eigenvalues in ) matrix .
Var(l) / Var_ref ratios are therefore bounded above by 1 and
increase toward it as l grows.
plot_var_convergence(hist, ...) ## Default S3 method: plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), design = NULL, measurement_prior_list = NULL, whitened = FALSE, engine = c("base", "ggplot"), n_chains = NULL, conf_level = 0.95, stage_label = hist$stage, split = c("auto", "none"), max_whitened = 4L, ... ) ## S3 method for class 'rLMMNormal_reg' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rlmerb' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rGLMM_reg' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rglmerb' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... )plot_var_convergence(hist, ...) ## Default S3 method: plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), design = NULL, measurement_prior_list = NULL, whitened = FALSE, engine = c("base", "ggplot"), n_chains = NULL, conf_level = 0.95, stage_label = hist$stage, split = c("auto", "none"), max_whitened = 4L, ... ) ## S3 method for class 'rLMMNormal_reg' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rlmerb' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rGLMM_reg' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... ) ## S3 method for class 'rglmerb' plot_var_convergence( hist, coef_focus = NULL, component = c("fixef", "precision"), whitened = FALSE, engine = c("base", "ggplot"), n_chains, conf_level = 0.95, stage = c("main", "pilot"), stage_label = NULL, ... )
hist |
Object of class |
... |
Passed to methods (e.g. |
coef_focus |
Optional list of length-2 character vectors
|
component |
|
design, measurement_prior_list
|
When both are supplied, the exact
reference covariance is resolved automatically via
|
whitened |
When |
engine |
|
n_chains |
Optional integer, the number of independent chains each
plotted
Not series-specific (a single band, not one per coefficient/eigenvalue)
since it depends only on |
conf_level |
Confidence level for the |
stage_label |
Defaults to the resolved |
split |
|
max_whitened |
Maximum number of eigenvalue series per chart when
|
stage |
|
The x-axis is the inner Gibbs sweep index , not the stored-draw
index: these charts diagnose convergence within the burn-in that
precedes each stored draw. Each point is a cross-chain statistic
at sweep — the variance across the n_chains independent
replicate chains, all of which are at sweep simultaneously — not
a running statistic along a single chain. This is why the sweep-outer
loop order matters: it is what makes "the sampler's distribution after
sweeps" an observable quantity.
The y-axis is the ratio Var(l) / Var_ref. Under Claim 3 that ratio
is bounded above by 1 and rises toward it, so a converged run shows every
trace flattening just below 1. Traces that are still climbing at the last
sweep indicate the sweep budget is too small; traces that overshoot 1
substantially are Monte Carlo noise, and n_chains draws the band
that says how much overshoot is expected.
Var_ref is the exact posterior variance when design and
measurement_prior_list are both supplied (only possible when
and the RE variance components are all fixed), and
otherwise the empirical last-sweep variance. The empirical fallback
cannot detect a run that has not converged at all, since the
denominator is then drawn from the same unconverged distribution; prefer
the exact reference whenever the model allows it.
Location and spread converge at different speeds, and the two plotting
functions separate them: plot_mean_convergence tracks the
mean, plot_var_convergence the variance. The variance converges
at twice the rate, so the mean chart settles later and is usually the one
that decides whether the sweep budget is adequate. A run whose variance
ratios sit at 1 while its standardized mean deviations still drift has
converged in spread but not in location.
Because every chain starts at the posterior mean, the mean chart is flat
from sweep 1 on well-behaved Gaussian fits, leaving the variance chart to
carry the information. vignette("Chapter-B02", package =
"lmebayesCore") derives the two rates.
sweep_history is recorded only when all chains advance together,
one sweep at a time, so that the cross-chain spread at sweep is
meaningful. Two situations produce no history:
The exact route (fixed , all components
dNormal, sim_method = "DEFAULT") runs no sweeps at all,
because the draws are already exact. There is nothing to diagnose.
Passing sim_method = "TWO_BLOCK_GIBBS" forces the iterative
path on the same target if you want a history anyway.
Some Gaussian paths run sweeps but do not export per-sweep
cross-chain statistics; fit$sweep_history is then NULL.
whitened = TRUE additionally requires cov_by_sweep and
coef_index, which only the sweep-outer engines above populate, and
component = "precision" additionally requires disp_table,
which requires at least one ING Block 2 component.
n_chains is not stored on hist itself, so it must be
supplied from the fitted object that produced it: for the main-stage
history (fit$sweep_history) use nrow(fit$popef[[k]]) for
any RE component k (all have the same number of rows, the n
passed to the _run_with_pilot() call); for the pilot-stage history
(fit$pilot$draws$sweep_history) use fit$pilot$n.
hist invisibly.
plot_mean_convergence,
lmerb_posterior_covariance
Finds the fixed point of the conditional-mean map (Chapter C05 Stage 1). Uses conditional means for Block~1, not modes.
population_mode( design, pfamily_list, family = gaussian(), dispprior_list = NULL, beta_set = NULL, estep = c("exact", "aghq", "mc"), acceleration = c("none", "squarem"), n = 10000L, mc_seed = NULL, icm_init = TRUE, icm_tol = 1e-08, icm_maxit = 200L, icm_screen = NULL, mc_alpha = 0.05, mc_stable = 2L, tol = 1e-10, maxit = 200L, verbose = FALSE )population_mode( design, pfamily_list, family = gaussian(), dispprior_list = NULL, beta_set = NULL, estep = c("exact", "aghq", "mc"), acceleration = c("none", "squarem"), n = 10000L, mc_seed = NULL, icm_init = TRUE, icm_tol = 1e-08, icm_maxit = 200L, icm_screen = NULL, mc_alpha = 0.05, mc_stable = 2L, tol = 1e-10, maxit = 200L, verbose = FALSE )
design |
A |
pfamily_list |
Block~2 prior list from |
family |
A |
dispprior_list |
Optional Block~1 dispersion prior for |
beta_set |
Optional |
estep |
E-step tier: |
acceleration |
|
n |
Number of |
mc_seed |
Optional seed for the MC E-step (first iteration only). |
icm_init |
If |
icm_tol |
ICM convergence tolerance on |
icm_maxit |
Maximum ICM iterations. |
icm_screen |
If |
mc_alpha |
Two-sided level for the MC fixed-point screen and EM stop
( |
mc_stable |
Number of consecutive MC fixed-point passes required at the
same |
tol |
Convergence tolerance on the Mahalanobis change in |
maxit |
Maximum EM iterations. |
verbose |
If |
In the restricted certificate, the EM E-step uses conditional means under
the -truncated target on . Pass
Pass beta_set from beta_marginal_safe_set; routes to
rNormal_reg_group_safe (Gaussian) or
rNormalGLM_reg_group_safe (non-Gaussian).
A list with fixef (), gamma_star,
b_mean, b_mc_se (terminal MC standard errors when
estep = "mc"), V_list, n, model context
(design, family, measurement_prior_list, p11),
refresh objects (P11, Sigma_star), tilde_J,
kappa_spectrum, weights, kappa, rho,
Sigma_pi, eps_star_closure,
icm and icm_screen diagnostics, EM diagnostics
(tol_eff, mc_delta_floor, em_route, em_trace),
beta_set,
restricted, and related fields.
group_effects_conditional_mean,
rNormal_reg_group_safe,
rNormalGLM_reg_group_safe
S3 generic for distribution-sampler style display of groupef draws
(long data frame), parallel to print() for population coefficients.
Filters by grouping levels and optional RE columns. Methods are registered
for rLMMNormal_reg, rLMMindepNormalGamma_reg,
rGLMM_reg, rlmerb, and rglmerb; the
default method accepts any list-like object with a usable
groupef data frame.
print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## Default S3 method: print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rLMMNormal_reg' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rlmerb' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rGLMM_reg' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rglmerb' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... )print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## Default S3 method: print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rLMMNormal_reg' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rlmerb' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rGLMM_reg' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... ) ## S3 method for class 'rglmerb' print_groupef( x, groups = NULL, components = NULL, draws = NULL, digits = max(3, getOption("digits") - 3), ... )
x |
An object with a |
groups |
|
components |
|
draws |
|
digits |
Number of significant digits for printed numeric values. |
... |
further arguments passed to or from other methods. |
Population coefficients () and group coefficients
() are stored in different shapes, which is why they have
different printers. popef is a named list of matrices, one
per random-effect component, each n draws by level-2
predictors — printed by the print() methods. groupef is a
single long-format data frame with one row per
(draw, group level) pair:
draw |
integer draw index, 1:n |
| grouping column | the group level, named after the grouping
factor ("Subject", "state", ...) |
| one column per RE coefficient | "(Intercept)" and any
random slopes
|
So a fit with n = 1000 draws over 20 groups produces 20,000 rows.
Printing it whole is rarely what anyone wants, which is the reason this
function exists.
The three filters are independent and compose; all of them are
print-only, and x is never modified.
draws — integer indices into 1:n, or a logical mask
of length n. Filters rows by the draw column.
groups — level names as characters, or integer indices
into the unique levels present in groupef (which is the
ordering the fit used, not necessarily levels() of the original
factor). Filters rows by the grouping column.
components — names or integer indices selecting which
random-effect columns to show. The draw and grouping
columns are always kept and are never counted in the indexing.
print_groupef(fit, draws = 1:5, groups = 1:3) is the usual idiom:
the first few draws for the first few groups, enough to confirm the
sampler is producing sensible numbers without flooding the console. An
empty result after filtering prints a placeholder rather than erroring.
Numeric columns are formatted to digits significant figures for
display only; the stored values keep full precision.
All registered methods share the default implementation — they
exist so that the generic dispatches cleanly on every sampler return class
rather than falling through, and so that class-specific layouts can be
added later without changing call sites. The default method works
on any list-like object carrying a usable groupef data frame, which
includes intermediate objects produced during route dispatch.
Point-estimate fits (simulate = FALSE) have no groupef at
all; use groupef.mode directly for those.
No return value, called for side effects.
rLMM_reg, rGLMM_reg,
rlmerb, rglmerb
population_mode_em_trace object.Print a population_mode_em_trace object.
## S3 method for class 'population_mode_em_trace' print(x, ...)## S3 method for class 'population_mode_em_trace' print(x, ...)
x |
A |
... |
Ignored. |
x, invisibly.
Calibrates priors for the level-2 fixed effects (fixef) of a
hierarchical mixed model using the reference lmer/glmer fits
on all groups (from model_setup). Per-group design
rank (groupef.rank) and estimability (groupef.estimable –
classical-glm MLE existence for family =
binomial()/poisson()/Gamma(), residual degrees of freedom
for family = gaussian()) are diagnostic checks computed by
model_setup and do not subset the data or the reference
glmer fit. Random-effect variances are
treated as fixed at their mixed-model estimates. The returned object
organizes calibrated priors as two independent blocks:
Prior_Setup_GLMM( formula, data, family = gaussian(), REML = TRUE, control = NULL, start = NULL, verbose = 0L, subset, weights, na.action, offset, contrasts = NULL, dispformula = ~1, pop.pwt = NULL, pop.pwt_default_low = 0.01, pop.pwt_default_high = 0.05, pop.nprior = NULL, pop.sd = NULL, pop.dispersion.pwt = NULL, pop.dispersion.nprior = NULL, pop.max_disp_perc = 0.99, pop.intercept_source = c("null_model", "full_model"), pop.effects_source = c("null_effects", "full_model"), pop.mu = NULL, group.dispersion.pwt = NULL, group.dispersion.nprior = NULL, group.alpha_target = 0.01, group.max_disp_perc = 0.99 )Prior_Setup_GLMM( formula, data, family = gaussian(), REML = TRUE, control = NULL, start = NULL, verbose = 0L, subset, weights, na.action, offset, contrasts = NULL, dispformula = ~1, pop.pwt = NULL, pop.pwt_default_low = 0.01, pop.pwt_default_high = 0.05, pop.nprior = NULL, pop.sd = NULL, pop.dispersion.pwt = NULL, pop.dispersion.nprior = NULL, pop.max_disp_perc = 0.99, pop.intercept_source = c("null_model", "full_model"), pop.effects_source = c("null_effects", "full_model"), pop.mu = NULL, group.dispersion.pwt = NULL, group.dispersion.nprior = NULL, group.alpha_target = 0.01, group.max_disp_perc = 0.99 )
formula |
Mixed-model formula passed to |
data |
Data frame containing all variables in |
family |
Model |
REML |
Logical scalar passed to |
control |
Optional |
start |
Optional starting values passed to |
verbose |
Integer scalar passed to |
subset, na.action
|
Optional arguments passed through to
|
weights, offset
|
Optional arguments passed through to
Not fully active for mixed-model sampling yet. They affect the
classical reference fit used for prior calibration. Low-level
|
contrasts |
Optional contrast list passed to
|
dispformula |
One-sided formula selecting the Block~1 measurement-
dispersion structure: |
pop.pwt |
Prior weight(s) in |
pop.pwt_default_low |
Scalar in |
pop.pwt_default_high |
Scalar in |
pop.nprior |
Optional absolute effective prior sample
size(s), in group units ( |
pop.sd |
Optional prior standard deviation(s), on the coefficient
scale of |
pop.dispersion.pwt |
Optional relative prior weight(s) in
|
pop.dispersion.nprior |
Optional absolute effective prior
sample size(s) (in group units) for the Block~2 |
pop.max_disp_perc |
Scalar in |
pop.intercept_source |
Character string controlling the prior mean for
the global intercept hyperparameter |
pop.effects_source |
Character string controlling the prior mean for
all other Block~2 hyperparameters (including population-mean slopes
stored as |
pop.mu |
Optional prior mean override(s) for the population-level
(Block~2, |
group.dispersion.pwt |
Optional relative prior weight(s) in |
group.dispersion.nprior |
Optional positive scalar: absolute effective
prior sample size for the Block~1 |
group.alpha_target |
Scalar in |
group.max_disp_perc |
Scalar in |
Block 1 (per-group, independent):
when family = gaussian(). For non-Gaussian families there is no
observation-level dispersion; Block~1 uses dNormal with
ddef = TRUE (see dNormal).
Block 2 (per-RE coefficient , independent):
Naming convention. Top-level fields use pop.* for Block~2
(population / , ) and group.* for Block~1
(within-group / observation , RE covariance ).
Nested entries in pop.prior_list[[k]] use glmbayes-style
mu, Sigma, and dispersion (where dispersion
is the plug-in RE variance ).
Why default calibration depends on classical estimates.
Prior_Setup_GLMM scales Block~2 covariances from
vcov(fit_ref) by and plugs in
RE variances from the full reference fit, where fit_ref is the
pooled lmer/glmer fit when dispformula = ~1, or an
equivalent glmmTMB fit with the same dispformula when
per-group dispersion is requested (see calibration_source and
mer_fit above). By default the global intercept
prior mean comes from a random-intercept-only null fit; all other prior
means are zero (pop.effects_source = "null_effects"). This requires:
Converged reference lmer/glmer fit from
model_setup on the full formula (and a random-intercept-only
null fit when pop.intercept_source = "null_model").
Fits with lme4 checkConv failures (e.g.\ large
max|grad|) are rejected.
Every X_hyper[[k]] column maps to a fixef(fit_ref) term.
Each RE variance from the reference fit is strictly positive.
Object of class "Prior_Setup_GLMM" with fields:
formulaModel formula.
familyFamily object.
pop.pwtPrior weight(s) used: the scalar as supplied, the
canonical named list of per-predictor weight vectors when a list was
supplied, or the dimension-adaptive default list (one weight per
Block~2 predictor, per RE component) when pop.pwt was
NULL.
pop.npriorNamed list with one named numeric vector per
random-effect component – the effective prior sample size (group
units) actually implied, , whether
derived from pop.pwt/pop.sd (the usual case) or
overridden via pop.nprior. Always present, and in the same
shape the pop.nprior argument expects, so it can be
inspected from a first call and fed back in (after editing) as
pop.nprior to a second call.
pop.sdNamed list with one named numeric vector per
random-effect component – the effective coefficient-scale prior
standard deviations actually used
(), whether
derived from pop.pwt/pop.nprior (the usual case) or
overridden via pop.sd. Always present, and in the same
shape the pop.sd argument expects, so it can be inspected
from a first call and fed back in (after editing) as pop.sd
to a second call.
pop.muNamed list with one named numeric vector per
random-effect component – the prior means actually used
(mu), whether derived from
pop.intercept_source/pop.effects_source (the usual
case) or overridden via pop.mu. Always present, and in the
same shape the pop.mu argument expects, so it can be
inspected from a first call and fed back in (after editing) as
pop.mu to a second call.
pop.dispersion.pwtNamed per-component vector of relative
dispersion prior weights (always present; consistent with
pop.dispersion.nprior via ).
pop.dispersion.npriorNamed per-component vector of
effective prior sample sizes for the Block~2 dispersion prior
(always present; used by
pfamily_list() to
calibrate dIndependent_Normal_Gamma components).
group.dispersion.pwtGaussian models only: scalar or length-
vector of relative prior weights for Block~1 – a
scalar unless a per-group vector was supplied or
group.alpha_target calibration was active, in which case it
is the resolved length- vector (see dGamma_list()).
group.dispersion.npriorGaussian models only: effective prior
sample size for Block~1 , on the same pooled-vs.-vector
basis as group.dispersion.pwt (a scalar on the observation scale, or a
named length- vector of per-group
reflecting the group.alpha_target-calibrated group.dispersion.pwt
when calibration was active; see group.pwt_calibration).
group.alpha_targetThe value used, or NULL
if calibration was not active.
group.pwt_calibrationNULL unless
calibration was active; otherwise a per-group diagnostics
data.frame (group, n_j, pwt_floor,
pct_outside_before, w_star, clipped_at_ceiling,
w_final, floor_binds, pct_outside_after) from
the search described under group.alpha_target.
group.max_disp_percGaussian models only: scalar or
length- vector of the tail probability used for the Block~1
truncation window (group.ing_prior) – the
scalar as supplied, or the resolved length- vector when a
vector was supplied.
pop.max_disp_percNamed length-
vector of resolved per-component values used for the Block~2
truncation windows in pop.ing_prior (always
present).
pop.intercept_sourceHow the global intercept prior mean
was chosen ("null_model" or "full_model").
pop.effects_sourceHow other Block~2 prior means were
chosen ("null_effects" or "full_model").
block_formulaWithin-group Block~1 formula: response
regressed on the random-coefficient structure only (columns of
design$groupef.names); level-2 hyper covariates are excluded.
Used by dGamma_list().
group.tau_sdNamed vector sqrt(Psi) from the reference
fit; shared population RE standard deviations for per-group calibration.
dataData frame passed to Prior_Setup_GLMM()
(reference for dGamma_list() diagnostics).
designFull model_setup object (all groups),
including length-n weights and offset vectors
aligned with design$y.
mer_fitReference lmer/glmer fit on all
groups (the full-formula fit from model_setup), always
present regardless of dispformula (backs
group.dispersion and x$lmer/x$glmer in
lmerb()/glmerb()).
fit_refThe calibration reference for Block~2
(fixef/) and the per-group Block~1 inputs
(group.tau_sd, BLUP coefficients): identical to mer_fit when
dispformula = ~1; otherwise an equivalent glmmTMB
fit with the same dispformula (Gaussian models only). See
calibration_source.
group.dispersion.fitNULL when dispformula = ~1;
otherwise the same glmmTMB object as fit_ref.
group.dispersion.refNULL when dispformula = ~1;
otherwise a named length- vector of per-group observation-level
dispersion read from fit_ref's dispersion linear predictor
(glmmTMB::predict(fit_ref, type = "disp"), aggregated by
group). Diagnostic only – not the value fed to the sampler; compare
against group.ing_prior's sigma2_hat.
calibration_source"lme4" or "glmmTMB";
which reference fit produced fit_ref (and therefore
pop.prior_list, pop.ing_prior, group.tau_sd, and
group.ing_prior).
group.dispersionFor Gaussian models: resolved Block~1
observation used to mean-match the Gamma prior.
When dispformula = ~1, the pooled A12 §3.3.4 aggregate
(Part VI
Omega_j included); classical lmer residual in
attr(., "classical"). When dispformula is per-group,
a named length- vector of per-group
group.ing_prior[[j]]$sigma2_hat. attr(., "source")
records provenance. NULL for non-Gaussian families.
Pass to rlmerb()/rglmerb() as
group.dispersion for fixed- routes.
group.SigmaDiagonal RE covariance matrix (Block~1),
classical reference-fit diagonals.
pop.dispersion.refNamed vector of classical reference-fit
(VarCorr / Psi) before the A12 §3.3.4
hyper-regression remargin; compare to
pop.prior_list[[k]]$dispersion.
pop.prior_listNamed Block~2 prior list per RE coefficient.
For Gaussian models dispersion is the A12 §3.3.4 marginal
hyper-regression center for (not the raw VarCorr
plug-in; see pop.dispersion.ref).
pop.ing_priorNamed per-component list of the prospective
dIndependent_Normal_Gamma calibration: Gamma precision-prior
shape and rate
(the lmebayesCore default
calibration with pop.dispersion.nprior; since
rate , the implied
inverse-Gamma prior on has mean exactly
), where is the A12 §3.3.4
marginal hyper-regression center in
pop.prior_list[[k]]$dispersion, and the default
truncation window disp_lower / disp_upper: the
/
quantiles of the limiting posterior
– the weak-prior
() limit of the Block~2 posterior Gamma for the
precision (lmebayesCore Chapter A12, Theorem 2; inverted to a
interval). This window is identical for all
, covers
of the exact posterior for every prior strength, and keeps the
envelope sampler's cost stable as priors weaken; see
inst/ING_TRUNCATION_WINDOW.md. Used by
pfamily_list() when
ptypes = "dIndependent_Normal_Gamma"; ignored for
dNormal priors.
group.ing_priorGaussian models only; NULL
for non-Gaussian models. Shape depends on dispformula:
dispformula = ~1 (pooled)A single list: prospective
dGamma() group.dispersion calibration for Block~1
ING (observation shared across all group
levels) – mean-matched shape / rate with
,
, and =
group.dispersion (pooled A12 §3.3.4 aggregate of
per-group by default; same ING algebra
as pop.ing_prior for ; requires
group.dispersion.pwt ),
plus disp_lower / disp_upper as the central
prior-mass
interval from the same calibrated shape/rate
(always the pooled/scalar group.max_disp_perc value,
even when a per-group vector was supplied). Pass these fields
to dGamma().
dispformula requesting per-group dispersionA named
list (one entry per group level) of per-group dGamma()
density calibration (sigma2_hat, shape_ING,
rate, rate_gamma, n_prior, n_j,
n_combined, disp_lower, disp_upper,
max_disp_perc, omega_j, ...).
shape_ING/rate already fold in the Part VI
model-derived Omega_j (fixed-effect/gamma
uncertainty about b_j's prior mean, propagated through
group j's hyper-design row and
pop.prior_list[[k]]$Sigma), so this marginal
integrates out both random effects (b_j) and fixed
effects (gamma); see
inst/DGAMMA_LIST_MARGINAL_AND_BOUNDS.md Part VI.
disp_lower/disp_upper are /
quantiles of Gamma(shape_ING + n_j/2, rate_post), where
rate_post is sigma2_hat mean-matched at that same
inflated shape ( added only for the window, so it
reflects the posterior spread the sampler's own envelope
machinery actually draws from – see
EnvelopeDispersionBuild.cpp's shape2 = Shape + n_w/2
fallback – while shape_ING/rate themselves, the
values actually fed to the sampler as the Gamma prior, are
unchanged); is this group's own resolved
group.max_disp_perc value (stored per-group as
max_disp_perc). Used directly by
dGamma_list().
Which shape is returned is fully determined by dispformula;
see dGamma_list() for how consumers tell the two
apart.
dispformulaThe dispformula supplied.
x invisibly.
model_setup, Prior_Setup,
build_mu_all,
pfamily_list, dGamma_list
Runs Prior_Setup on each block subset of the data.
Typical callers are rNormal_reg_group /
rNormalGLM_reg_group or the lmbBlock / glmbBlock
wrappers in lmebayes.
Prior_SetupGroup( formula, group, family = gaussian(), data = NULL, weights = NULL, subset = NULL, na.action = na.fail, offset = NULL, contrasts = NULL, pwt = NULL, pwt_default_low = 0.01, pwt_default_high = 0.05, n_prior = NULL, sd = NULL, dispersion = NULL, intercept_source = c("null_model", "full_model"), effects_source = c("null_effects", "full_model"), mu = NULL, k = 1, ... )Prior_SetupGroup( formula, group, family = gaussian(), data = NULL, weights = NULL, subset = NULL, na.action = na.fail, offset = NULL, contrasts = NULL, pwt = NULL, pwt_default_low = 0.01, pwt_default_high = 0.05, n_prior = NULL, sd = NULL, dispersion = NULL, intercept_source = c("null_model", "full_model"), effects_source = c("null_effects", "full_model"), mu = NULL, k = 1, ... )
formula |
A |
group |
Group partition: |
family |
a description of the error distribution and link function to be used in the model. |
data |
an optional data frame, list or environment (or object
coercible by |
weights |
an optional vector of ‘prior weights’ to be used
in the fitting process. Should be |
subset |
an optional vector specifying a subset of observations to be used in the fitting process. (See additional details about how this argument interacts with data-dependent bases in the ‘Details’ below.) |
na.action |
how |
offset |
this can be used to specify an a priori known
component to be included in the linear predictor during fitting.
This should be |
contrasts |
an optional list. See the |
pwt, n_prior, sd, mu, dispersion, k
|
Each of these six calibration
arguments (passed to
The two forms may be mixed freely across the six arguments in one call. |
pwt_default_low |
Default prior weight used when |
pwt_default_high |
Default prior weight used when |
intercept_source |
Specifies the method through which the prior mean for the intercept term is set. Options are based on the null intercept only model (null_model) or full_models. The default is the null model which is safer if variables are not centered. |
effects_source |
Specifies the method through which the prior means for the effects terms are set. Options are null_effects (prior means set to zero) or full_model (effect means set to match maximum likelihood estimates). |
... |
Not used. |
Prior_SetupGroup() calls Prior_Setup once per block,
on that block's rows only, and returns the results as a named list keyed by
block ID.
Prior_Setup_GLMM calibrates a
hierarchical prior (one reference lmer/glmer fit,
Block~2 hyperpriors, cross-group shrinkage). Prior_SetupGroup()
calibrates independent priors per row block with no shared
or ; row-block engines draw blocks iid.
Names for per-block calibration lists must match normalize_group
block IDs exactly.
After calibration, convert to sampler-ready pfamily objects with
pfamily_list(x, ptypes = ...) (see Prior families via
pfamily_list() below for ptypes and allowed families).
A named list of class "Prior_SetupGroup". Each element is a
Prior_Setup result for one block.
x invisibly.
An object of class "pfamily_list": a named list of
pfamily objects with attribute "ptypes".
Prior_Setup, multi_prior_setup,
normalize_group, pfamily_list,
rNormal_reg_group, rNormalGLM_reg_group,
Prior_Setup_GLMM
rglmerb draws from the posterior of a Bayesian generalized linear
mixed model — Poisson, binomial, Gamma, or Gaussian — with a single
grouping factor and uncorrelated random effects, given a design from
model_setup and priors for the population level
(pfamily_list) and, for Gaussian responses only, the residual
variance (dispprior_list).
rglmerb( n, design, pfamily_list, family = poisson(), dispprior_list = NULL, offset = NULL, weights = 1, gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, collect_block1 = TRUE, verbose = TRUE, progbar = FALSE, sim_method = "DEFAULT", simulate = TRUE )rglmerb( n, design, pfamily_list, family = poisson(), dispprior_list = NULL, offset = NULL, weights = 1, gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, collect_block1 = TRUE, verbose = TRUE, progbar = FALSE, sim_method = "DEFAULT", simulate = TRUE )
n |
Integer. Number of independent chains in the main stage.
Required when |
design |
A |
pfamily_list |
Named list of Block~2 |
family |
A |
dispprior_list |
Block~1 observation-dispersion prior, in the same
shapes as the |
offset, weights
|
Observation offset and prior weights, as in
|
gap_tol |
Legacy mode–mean gap for deriving the pilot chain count when
|
tv_tol |
Total variation tolerance for convergence calibration.
Inner Gibbs sweeps and pilot chain counts are derived internally.
Ignored when |
mode_gap_max |
Pilot inner-sweep calibration (non-Gaussian and
Gaussian+ING only). Ignored when |
collect_block1 |
Collect |
verbose |
Print stage headers and diagnostics. |
progbar |
Progress bars when |
sim_method |
Simulation method for |
simulate |
Logical (default |
The returned sample is n mutually independent draws, one per
replicate chain, taken at that chain's final sweep. It is analyzed like an
iid sample rather than like an MCMC trace.
This is the matrix-level interface; for a formula interface use
glmerb() in lmebayes. rlmerb is the
Gaussian-only counterpart.
rglmerb estimates the same two-stage structure as
rlmerb, with a link function between the linear predictor
and the response mean. For group with link :
The across-group stage is unchanged and remains Gaussian: group
coefficients scatter around a population expectation
with diagonal covariance
. What changes is the within-group
stage and, with it, the interpretation of , which now lives
on the link scale — log rates for poisson(), log-odds for
binomial(). Summaries that are meaningful on the response scale
need the inverse link applied to the draws.
Supported families are gaussian(), poisson(),
binomial(), and Gamma() with their standard links. The
restriction is log-concavity of the likelihood, which the sampler
requires (Nygren and Nygren 2006).
designA model_setup object built with the
matching family. For non-Gaussian responses its estimability
report matters more than usual: a group with no variation in the
response (all-zero counts, a single binomial outcome level) has no
finite maximum likelihood estimate, and is reported separately from
the rank check. See
vignette("Chapter-B08", package = "lmebayesCore").
pfamily_listThe population-level prior, one component per
random-effect coefficient, declaring whether each between-group
variance is known (dNormal) or estimated
(dIndependent_Normal_Gamma).
dispprior_listOnly meaningful for gaussian(),
where it gives the residual variance. poisson() and
binomial() have no free dispersion parameter, so it must be
NULL.
As in rlmerb, rglmerb runs n independent
replicate chains and stores one draw from each, taken at the final sweep,
so the n draws are mutually independent and ordinary Monte Carlo
standard errors apply. There is nothing to thin and no autocorrelation to
diagnose.
The strength of the accompanying guarantee is weaker here than in the
Gaussian case, and the difference is worth understanding rather than
glossing over. The calibration behind m_convergence is derived for
Gaussian targets. A Poisson or binomial posterior is not Gaussian, so the
engine applies the same calibration at curvature evaluated near the
posterior mode. The sweep count is therefore a well-motivated
budget rather than a certificate, and tv_tol should be
read in that spirit. Only family = gaussian() with fixed
and all-dNormal components yields exact draws.
A second difference follows from the same fact. Because the posterior mode
is not the posterior mean when the target is skewed, chains started at the
mode begin at an unknown distance from the target. rglmerb
therefore runs a short pilot stage first and uses its cross-chain
mean as the starting point for the main chains, which shortens the main
stage. Pilot draws are diagnostic only and are discarded — they are
never part of the returned sample.
vignette("Chapter-B03", package = "lmebayesCore") covers the
trade-off between pilot size and main-stage length.
simulate = FALSE returns the joint posterior mode by iterated
conditional modes (or the exact mean for gaussian()), at fixed
variance-component plug-ins. No sweeps run and no RNG is consumed, so the
result is deterministic — useful while iterating on model
specification. All draw, pilot, and convergence slots are NULL.
An object of class c("rglmerb", "list"), with the same
layout as rlmerb. Each draw slot holds one row per
replicate chain, taken at that chain's final sweep.
popefNamed list of population draws , one
n matrix per random-effect coefficient, on
the link scale. popef.means and popef.mode are the
draw mean and the posterior mode.
groupefLong-format data frame of group coefficients
(n rows: draw, the
grouping factor, then one column per coefficient), also on the link
scale. groupef.mode is the mode matrix.
Collected only when collect_block1 = TRUE.
popef.dispersionDraws of the between-group variances
; constant for dNormal components, varying for
estimated ones. popef.dispersion.mean is the column mean.
group.dispersionResidual variance, Gaussian responses
only; absent for poisson() and binomial().
m_convergence, convergence_info
Sweeps run per
chain and the calibration behind that count (method,
lambda_star, draw_engine,
sim_method_used, icm_info).
pilotPresent when a pilot stage ran, holding its size
n, the chisq calibration constant, and its
draws. Diagnostic only — these are not posterior draws.
Inputs are echoed back in design, family, n,
call, pfamily_list, dispprior_list,
prior.weights and offset, alongside the packed
prior and thin Prior summaries.
When simulate = FALSE, every draw, pilot and convergence slot is
NULL and only the mode fields are populated.
Nygren K~N, Nygren L~M (2006). “Likelihood Subgradient Densities.” Journal of the American Statistical Association, 101(475), 1144–1156. doi:10.1198/016214506000000357.
rlmerb, rglmerb_point,
rLMMNormal_reg_known_vcov,
rLMMNormal_reg_estimated_vcov,
rLMMindepNormalGamma_reg_known_vcov,
rLMMindepNormalGamma_reg_estimated_vcov, rGLMM_reg,
Prior_Setup_GLMM
## rglmerb() — matrix-level GLMM sampler (binomial) on book_banning ## ## Probability that a challenged book is removed, with a random intercept and ## a `violent` slope by state. Restricted to the eight largest states so the ## example stays quick under R CMD check. Requires suggested package ## bayesrules. For the formula interface see lmebayes::glmerb(). if (requireNamespace("bayesrules", quietly = TRUE)) { data(book_banning, package = "bayesrules") dat <- book_banning[, c("state", "removed", "violent")] dat <- dat[stats::complete.cases(dat), ] dat$removed_i <- as.integer(dat$removed == 1L | dat$removed == "1") dat$violent_i <- as.integer( dat$violent == TRUE | dat$violent == 1L | dat$violent == "TRUE" ) dat$state <- factor(dat$state) keep <- names(sort(table(dat$state), decreasing = TRUE))[seq_len(8L)] dat <- droplevels(subset(dat, state %in% keep)) form <- removed_i ~ violent_i + (1 + violent_i || state) design <- model_setup(form, data = dat, family = binomial()) ps <- Prior_Setup_GLMM(form, data = dat, family = binomial(), pop.pwt = 0.01) ## Point estimates only: joint posterior mode by ICM, no sampling. pt <- rglmerb( design = design, pfamily_list = pfamily_list(ps), family = binomial(), simulate = FALSE, verbose = FALSE ) pt$popef.mode ## Draws. Non-Gaussian families always run a pilot stage before the main ## chains, and dispprior_list must stay NULL for binomial(). set.seed(1) fit <- rglmerb( n = 10L, design = design, pfamily_list = pfamily_list(ps), family = binomial(), verbose = FALSE, progbar = FALSE ) print_groupef(fit, draws = 1:3, groups = 1:3) }## rglmerb() — matrix-level GLMM sampler (binomial) on book_banning ## ## Probability that a challenged book is removed, with a random intercept and ## a `violent` slope by state. Restricted to the eight largest states so the ## example stays quick under R CMD check. Requires suggested package ## bayesrules. For the formula interface see lmebayes::glmerb(). if (requireNamespace("bayesrules", quietly = TRUE)) { data(book_banning, package = "bayesrules") dat <- book_banning[, c("state", "removed", "violent")] dat <- dat[stats::complete.cases(dat), ] dat$removed_i <- as.integer(dat$removed == 1L | dat$removed == "1") dat$violent_i <- as.integer( dat$violent == TRUE | dat$violent == 1L | dat$violent == "TRUE" ) dat$state <- factor(dat$state) keep <- names(sort(table(dat$state), decreasing = TRUE))[seq_len(8L)] dat <- droplevels(subset(dat, state %in% keep)) form <- removed_i ~ violent_i + (1 + violent_i || state) design <- model_setup(form, data = dat, family = binomial()) ps <- Prior_Setup_GLMM(form, data = dat, family = binomial(), pop.pwt = 0.01) ## Point estimates only: joint posterior mode by ICM, no sampling. pt <- rglmerb( design = design, pfamily_list = pfamily_list(ps), family = binomial(), simulate = FALSE, verbose = FALSE ) pt$popef.mode ## Draws. Non-Gaussian families always run a pilot stage before the main ## chains, and dispprior_list must stay NULL for binomial(). set.seed(1) fit <- rglmerb( n = 10L, design = design, pfamily_list = pfamily_list(ps), family = binomial(), verbose = FALSE, progbar = FALSE ) print_groupef(fit, draws = 1:3, groups = 1:3) }
Posterior draws for Bayesian generalized linear mixed models, given
design matrices y, D, W and population priors
pfamily_list. The model is the two-stage structure documented in
rLMM_reg with a link function applied within groups; see
rglmerb for the model statement and for how to read the
returned draws.
These are the engine-level entry points, normally reached through
rglmerb (or glmerb() in lmebayes). Gaussian
responses use the rLMM_reg engines instead. Each returned
draw is one replicate chain's state at its final sweep.
## S3 method for class 'rGLMM_reg' print( x, digits = max(3, getOption("digits") - 3), components = NULL, draws = NULL, ... ) rGLMM_reg_known_vcov( n, y, D, group, W, pfamily_list, dispprior_list, icm_tol = 1e-10, icm_maxit = 200L, offset = NULL, weights = 1, family = gaussian(), gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, Gridtype = 2, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE, stage_verbose = FALSE, rate_calibration = NULL, collect_block1 = TRUE ) rGLMM_reg_estimated_vcov( n, y, D, group, W, pfamily_list, dispprior_list, icm_tol = 1e-10, icm_maxit = 200L, offset = NULL, weights = 1, family = gaussian(), gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, Gridtype = 2, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE, stage_verbose = FALSE, rate_calibration = NULL, collect_block1 = TRUE ) rGLMM_reg( n, y, D, group, W, pfamily_list, dispprior_list, icm_tol = 1e-10, icm_maxit = 200L, offset = NULL, weights = 1, family = gaussian(), gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, Gridtype = 2, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE, stage_verbose = FALSE, rate_calibration = NULL, collect_block1 = TRUE )## S3 method for class 'rGLMM_reg' print( x, digits = max(3, getOption("digits") - 3), components = NULL, draws = NULL, ... ) rGLMM_reg_known_vcov( n, y, D, group, W, pfamily_list, dispprior_list, icm_tol = 1e-10, icm_maxit = 200L, offset = NULL, weights = 1, family = gaussian(), gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, Gridtype = 2, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE, stage_verbose = FALSE, rate_calibration = NULL, collect_block1 = TRUE ) rGLMM_reg_estimated_vcov( n, y, D, group, W, pfamily_list, dispprior_list, icm_tol = 1e-10, icm_maxit = 200L, offset = NULL, weights = 1, family = gaussian(), gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, Gridtype = 2, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE, stage_verbose = FALSE, rate_calibration = NULL, collect_block1 = TRUE ) rGLMM_reg( n, y, D, group, W, pfamily_list, dispprior_list, icm_tol = 1e-10, icm_maxit = 200L, offset = NULL, weights = 1, family = gaussian(), gap_tol = 0.0196, tv_tol = 0.01, mode_gap_max = 1, Gridtype = 2, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE, stage_verbose = FALSE, rate_calibration = NULL, collect_block1 = TRUE )
x |
For |
digits |
Number of significant digits for printed numeric values. |
components |
For |
draws |
For |
... |
further arguments passed to or from other methods. |
n |
Number of stored main-stage draws. If |
y |
Response vector of length |
D |
Level-1 design matrix ( |
group |
Grouping factor of length |
W |
Named list of group-level design matrices ( |
pfamily_list |
Named list of population |
dispprior_list |
Observation-dispersion prior container:
|
icm_tol, icm_maxit
|
ICM convergence controls for the internal population start. |
offset, weights
|
Observation offset and prior weights (glmbayes-style
formals: |
family |
Likelihood family (length- |
gap_tol |
Legacy mode–mean gap for pilot chain count when |
tv_tol |
Total-variation tolerance for Theorem~3 calibration.
|
mode_gap_max |
Pilot inner-sweep calibration when a pilot stage runs. |
Gridtype, n_envopt, use_parallel, use_opencl
|
Reserved (not yet forwarded). |
verbose |
Print stage headers and convergence calibration lines. |
progbar |
Progress bars during sampling. |
stage_verbose |
Print pilot chi-squared and post-pilot UB diagnostics. |
rate_calibration |
Optional rate object for |
collect_block1 |
Collect |
An object of class c("<route>", "rGLMM_reg", "list"), where
<route> is "rGLMM_reg_known_vcov" or
"rGLMM_reg_estimated_vcov". Components use package
group/population names (see ‘inst/notation.md’),
in glm/glmbayes-style order:
groupefDraws of non-centered group coefficients
(when collect_block1 is TRUE): grouping
column plus one column per colnames(D).
groupef.mode matrix of ICM group
coefficients . Not lme4's mean-zero
.
groupef.itersOptional group-level envelope iteration counts.
popefNamed list of n x q_k matrices of population
coefficient draws .
popef.mode, popef.init
ICM population point estimates and main-stage starts.
popef.dispersion, popef.iters
Optional population per-draw diagnostics when produced by the sampler.
pfamily_list, dispprior_list
Population and observation-dispersion priors that were used.
prior.weights, offset, offset2
Normalized
copies of the weights/offset arguments (glmbayes
naming). Not yet consumed by sampling.
any_non_normalWhether any population component is not
dNormal.
family, design, n
Likelihood family, matrix
inputs (including echoed weights/offset), and chain
count.
callMatched call.
m_convergenceInner Gibbs sweeps per stored main-stage draw.
convergence_infoTheorem~3 / UB calibration details,
including draw_engine and icm_info.
pilotWhen a pilot ran: list with n,
m_convergence, chisq, and draws; otherwise
NULL.
sweep_historyMain-stage sweep history when collected.
rGLMM_reg_known_vcov(): All population components dNormal (known
). Non-Gaussian: pilot always (unless n_pilot = 0L);
standard fixed-dispersion eigenvalue rate bounds (no ING
disp_lower path).
rGLMM_reg_estimated_vcov(): ING population components (estimated ).
Non-Gaussian: pilot always (unless n_pilot = 0L); conservative
disp_lower eigenvalue bounds and pilot-updated starts.
rGLMM_reg(): Route by population pfamily_list to known or
estimated simulation routes.
Callers never name a route. Given a non-Gaussian family, the only
remaining modelling decision is whether the between-group variances
are known or estimated:
|
Engine |
all known (every component dNormal) |
rGLMM_reg_known_vcov |
any estimated (an dIndependent_Normal_Gamma component) |
rGLMM_reg_estimated_vcov
|
A gaussian() family is handled by the rLMM_reg
engines instead.
Because the observation-level dispersion is fixed by the family for
poisson() and binomial(), there is no residual-variance
decision to make: the second axis present in rLMM_reg
collapses.
Three properties hold for every GLMM route and are worth knowing before interpreting the output:
The posterior is never jointly Gaussian, so there is no closed form to sample from. Draws always come from the final sweep of a calibrated chain.
popef.mode is a mode, not a meanWith a skewed posterior the two differ, so the reported mode should not be read as a posterior mean the way it can be on the exact Gaussian route.
The calibration is
derived for Gaussian targets and is applied here at local curvature
near the mode. It is a well-motivated approximation;
convergence_info$method records which flavour was used.
The same fact — mode mean — is why a short pilot stage
always runs first: its cross-chain average provides a starting point
closer to the target than the mode is, which shortens the main stage.
Pilot draws are discarded and are never part of the returned sample.
See vignette("Chapter-B03", package = "lmebayesCore") and
vignette("Chapter-B06", package = "lmebayesCore").
rGLMM_sweep, rLMM_reg,
rglmerb, print_groupef
glmbayes Simulation Functions
rGLMM_Re_Draw(),
rGLMM_sweep(),
rLMMNormal_joint_iid(),
rLMM_reg,
two_block_optimize_pilot_cost(),
two_block_rNormal_reg(),
two_block_rate(),
two_block_tv_bound()
## rGLMM_reg_known_vcov() — binomial, dNormal population priors on book_banning ## ## Same data / formula path as lmebayes demo ## demo("Ex_16_glmerb_book_banning", package = "lmebayes"), restricted to the ## eight largest states so the example stays quick under R CMD check. ## Requires suggested package bayesrules. if (requireNamespace("bayesrules", quietly = TRUE)) { data(book_banning, package = "bayesrules") dat <- book_banning[, c("state", "removed", "violent")] dat <- dat[stats::complete.cases(dat), ] dat$removed_i <- as.integer(dat$removed == 1L | dat$removed == "1") dat$violent_i <- as.integer( dat$violent == TRUE | dat$violent == 1L | dat$violent == "TRUE" ) dat$state <- factor(dat$state) ## Keep the largest states (avoids singular glmer fits on tiny subsets). keep <- names(sort(table(dat$state), decreasing = TRUE))[seq_len(8L)] dat <- droplevels(subset(dat, state %in% keep)) form <- removed_i ~ violent_i + (1 + violent_i || state) design <- model_setup(form, data = dat, family = binomial()) ps <- Prior_Setup_GLMM(form, data = dat, family = binomial(), pop.pwt = 0.01) pf <- pfamily_list(ps) design$y set.seed(1) fit <- rGLMM_reg_known_vcov( n = 10L, y = design$y, D = design$D, group = design$group, W = design$W, pfamily_list = pf, dispprior_list = list(), family = binomial(), progbar = FALSE, verbose = FALSE ) print(fit, draws = 1:5) print_groupef(fit, draws = 1:5, groups = 1:3) }## rGLMM_reg_known_vcov() — binomial, dNormal population priors on book_banning ## ## Same data / formula path as lmebayes demo ## demo("Ex_16_glmerb_book_banning", package = "lmebayes"), restricted to the ## eight largest states so the example stays quick under R CMD check. ## Requires suggested package bayesrules. if (requireNamespace("bayesrules", quietly = TRUE)) { data(book_banning, package = "bayesrules") dat <- book_banning[, c("state", "removed", "violent")] dat <- dat[stats::complete.cases(dat), ] dat$removed_i <- as.integer(dat$removed == 1L | dat$removed == "1") dat$violent_i <- as.integer( dat$violent == TRUE | dat$violent == 1L | dat$violent == "TRUE" ) dat$state <- factor(dat$state) ## Keep the largest states (avoids singular glmer fits on tiny subsets). keep <- names(sort(table(dat$state), decreasing = TRUE))[seq_len(8L)] dat <- droplevels(subset(dat, state %in% keep)) form <- removed_i ~ violent_i + (1 + violent_i || state) design <- model_setup(form, data = dat, family = binomial()) ps <- Prior_Setup_GLMM(form, data = dat, family = binomial(), pop.pwt = 0.01) pf <- pfamily_list(ps) design$y set.seed(1) fit <- rGLMM_reg_known_vcov( n = 10L, y = design$y, D = design$D, group = design$group, W = design$W, pfamily_list = pf, dispprior_list = list(), family = binomial(), progbar = FALSE, verbose = FALSE ) print(fit, draws = 1:5) print_groupef(fit, draws = 1:5, groups = 1:3) }
rlmerb draws from the posterior of a Bayesian linear mixed model
with a single grouping factor and uncorrelated random effects, given a
design from model_setup and priors for the population level
(pfamily_list) and the residual variance (dispprior_list).
rlmerb( n, design, pfamily_list, dispprior_list, offset = NULL, weights = 1, tv_tol = 0.01, progbar = TRUE, verbose = TRUE, print_icm_table = TRUE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, sim_method = "DEFAULT", simulate = TRUE )rlmerb( n, design, pfamily_list, dispprior_list, offset = NULL, weights = 1, tv_tol = 0.01, progbar = TRUE, verbose = TRUE, print_icm_table = TRUE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, sim_method = "DEFAULT", simulate = TRUE )
n |
Integer. Number of stored draws (each draw is one full pass through
|
design |
A |
pfamily_list |
Named list of Block~2 |
dispprior_list |
Block~1 observation-dispersion prior, in the same
shapes accepted by the |
offset, weights
|
Observation offset and prior weights, as in
|
tv_tol |
Single numeric in |
progbar |
Logical. Show a text progress bar during sampling.
Default |
verbose |
Logical. Print the reference-vs-ICM table and the convergence
calibration line. Default |
print_icm_table |
Logical. When |
gap_tol |
Legacy mode–mean gap tolerance for the pilot stage when
any population component uses |
mode_gap_max |
Pilot inner-sweep calibration for ING population models
(default |
diag_sweeps |
Diagnostic flag for ING population models with a pilot stage.
When |
sim_method |
Simulation method: |
simulate |
Logical (default |
The returned sample is n mutually independent draws — one per
replicate chain, taken at that chain's final sweep, where the number of
sweeps is calibrated in advance so the final sweep is within
tv_tol of the target posterior. It is therefore analyzed like an
iid sample rather than like an MCMC trace.
This is the matrix-level interface. For a formula interface, use
lmerb() in lmebayes. The Poisson/binomial/Gamma counterpart
is rglmerb, and the non-hierarchical analogue is
rlmb.
rlmerb estimates the two-stage Gaussian mixed model in a
centered (Lindley–Smith) parameterization
(Lindley and Smith 1972). For group
:
Read the second line as the model for how groups differ: each group's own
coefficient vector is drawn around a population expectation
, with measuring how far groups
scatter from it. The estimand is therefore the pair
at the population level together with all
group vectors , and for the residual scale.
What distinguishes this from the lme4 presentation is that the
full coefficient appears in the likelihood, not a
mean-zero deviation. Marginalizing recovers the familiar form with
, , and
, so corresponds to
lme4's fixed effects and to its random effects. The
practical consequence is that groupef holds directly
(comparable to lme4::coef()), not .
is diagonal, , because model_setup accepts only
uncorrelated (||) random-effect terms and a single grouping factor.
There is no random-effect correlation parameter to estimate.
Three arguments carry the statistical content; the rest are controls.
designA model_setup object, which fixes
, , the grouping factor, and the level-2 design
. It also reports whether the data can identify
the model at all; see
vignette("Chapter-B08", package = "lmebayesCore").
pfamily_listThe prior on the population level, one
component per random-effect coefficient. This is where you declare
whether the between-group variance is
known (dNormal, treating the supplied dispersion as
fixed) or estimated (dIndependent_Normal_Gamma,
placing a Gamma prior on the precision ).
dispprior_listThe prior on the residual variance
: a fixed value (scalar, or one per group), a single
dGamma() to estimate one pooled
, or a named list of dGamma() objects to estimate
a separate per group.
Both priors are normally produced from one
Prior_Setup_GLMM object, via pfamily_list()
and either ps$group.dispersion or dGamma_list(ps).
Those two choices are also what determine which internal engine runs.
You never name an engine; it follows from the priors. The statistically
meaningful consequence is that when is fixed and every
component is dNormal, the posterior is exactly multivariate
normal and can be sampled directly; every other combination requires
iterative sampling. See
vignette("Chapter-B01", package = "lmebayesCore") for the full
mapping and vignette("Chapter-B04", package = "lmebayesCore")
for the exact route.
This is the part most likely to differ from other samplers, and it governs how the output should be analyzed.
rlmerb runs n independent replicate chains and
keeps one draw from each — the state after that chain's final
sweep. It does not run one long chain and thin it. Two consequences:
The n draws are mutually independent. They are a
genuine iid sample, not an autocorrelated series. Ordinary Monte Carlo
standard errors apply directly; there is no effective sample size to
compute, nothing to thin, and no trace plot or to
inspect on the returned sample.
Each draw comes from a distribution deliberately made
close to the target. The sweep count m_convergence is not a
burn-in guess. It is calibrated before sampling so that the
distribution reached at the final sweep is within tv_tol of the
exact posterior in total variation. tv_tol is a per-draw
guarantee, and it is reported on the fit.
So n and tv_tol control different errors and can be set
independently: n controls Monte Carlo noise, tv_tol controls
the residual bias of each draw. To certify the whole n-draw sample
jointly at level , pass tv_tol = alpha / n; because
cost grows only logarithmically in tv_tol, this typically
adds a few sweeps.
In the exactly-Gaussian case (fixed , all dNormal)
the draws are exact rather than approximate: m_convergence is
1 and no approximation is involved.
How m_convergence is derived, and what to do when a warning
reports strong cross-block coupling, is covered in
vignette("Chapter-B02", package = "lmebayesCore") and
vignette("Chapter-B03", package = "lmebayesCore").
simulate = FALSE returns only the posterior mean of
at fixed variance-component plug-ins, computed by
iterated conditional modes. No sweeps run and no RNG is consumed, so the
result is deterministic and fast — useful when iterating on model
specification. All draw and convergence slots are NULL. This same
quantity is where the replicate chains start when simulate = TRUE,
which is why it is always computed.
An object of class c("rlmerb", "list"). Each draw slot holds
one row (or one value) per replicate chain, taken at that chain's final
sweep; see the "What the returned draws are" section above.
Population level (, the analogue of lme4
fixed effects):
popefNamed list, one entry per random-effect
coefficient. Entry is an n matrix of
draws, columns named by colnames(design$W[[k]]).
popef.means, popef.mode
Named lists in the same
shape: the mean of the draws, and the posterior mode used to start
every chain. popef.init records the starting values.
Group level (, one vector per group):
groupefData frame in long format with
n rows: a draw index, a column named
for the grouping factor, then one column per random-effect
coefficient. These are full coefficients, comparable to
lme4::coef(), not mean-zero deviations.
groupef.mode matrix of posterior
modes, rows named by group level.
Variance components:
popef.dispersionn matrix of
between-group variance draws . Constant down a column
for a dNormal component (the value was treated as known);
varying for an dIndependent_Normal_Gamma component.
popef.dispersion.mean is the column mean.
group.dispersionResidual variance : a
fixed scalar or per-group vector, or draws when a dGamma
measurement prior was used. group.dispersion.mean is the
corresponding mean.
Convergence reporting:
m_convergenceInteger sweeps run per chain; 1 on
the exact route.
convergence_infoList with method
("exact_iid" when the draws are exact), lambda_star
and eigenvalues (the contraction rate behind the sweep
count), draw_engine, sim_method_used, and
icm_info for the mode solve. convergence is the same
list.
Inputs echoed back: design, family, n,
call, pfamily_list, dispprior_list,
prior.weights, offset, plus the packed prior and
thin Prior summaries.
When simulate = FALSE, every draw and convergence slot is
NULL and only the mode fields are populated.
Lindley DV, Smith AFM (1972). “Bayes Estimates for the Linear Model.” Journal of the Royal Statistical Society. Series B (Methodological), 34(1), 1–41. doi:10.1111/j.2517-6161.1972.tb00899.x.
rglmerb, rlmerb_point,
rLMMNormal_reg_known_vcov,
rLMMNormal_reg_estimated_vcov,
rLMMindepNormalGamma_reg_known_vcov,
rLMMindepNormalGamma_reg_estimated_vcov,
Prior_Setup_GLMM,
rlmb
## rlmerb() — matrix-level Gaussian LMM sampler on lme4::sleepstudy ## ## Reaction time versus centered days of sleep deprivation, with a random ## intercept and slope by Subject. lmebayesCore requires uncorrelated ## random-effect terms, hence the `||` form. For the formula interface see ## lmebayes::lmerb(), which wraps this function. data(sleepstudy, package = "lme4") dat <- sleepstudy dat$Days_c <- dat$Days - mean(dat$Days) form <- Reaction ~ Days_c + (1 + Days_c || Subject) design <- model_setup(form, data = dat) ps <- Prior_Setup_GLMM(form, data = dat, pop.pwt = 0.01) ## Point estimates only: exact joint Gaussian posterior mean, no sampling. pt <- rlmerb( design = design, pfamily_list = pfamily_list(ps), dispprior_list = list(dispersion = ps$group.dispersion), simulate = FALSE, verbose = FALSE, print_icm_table = FALSE ) pt$popef.mode ## Draws: fixed sigma^2 and known tau^2_k, so the joint posterior is exactly ## multivariate normal and sim_method = "DEFAULT" samples it directly (iid). set.seed(1) fit <- rlmerb( n = 20L, design = design, pfamily_list = pfamily_list(ps), dispprior_list = list(dispersion = ps$group.dispersion), progbar = FALSE, verbose = FALSE, print_icm_table = FALSE ) fit$convergence_info$sim_method_used print_groupef(fit, draws = 1:5, groups = 1:3)## rlmerb() — matrix-level Gaussian LMM sampler on lme4::sleepstudy ## ## Reaction time versus centered days of sleep deprivation, with a random ## intercept and slope by Subject. lmebayesCore requires uncorrelated ## random-effect terms, hence the `||` form. For the formula interface see ## lmebayes::lmerb(), which wraps this function. data(sleepstudy, package = "lme4") dat <- sleepstudy dat$Days_c <- dat$Days - mean(dat$Days) form <- Reaction ~ Days_c + (1 + Days_c || Subject) design <- model_setup(form, data = dat) ps <- Prior_Setup_GLMM(form, data = dat, pop.pwt = 0.01) ## Point estimates only: exact joint Gaussian posterior mean, no sampling. pt <- rlmerb( design = design, pfamily_list = pfamily_list(ps), dispprior_list = list(dispersion = ps$group.dispersion), simulate = FALSE, verbose = FALSE, print_icm_table = FALSE ) pt$popef.mode ## Draws: fixed sigma^2 and known tau^2_k, so the joint posterior is exactly ## multivariate normal and sim_method = "DEFAULT" samples it directly (iid). set.seed(1) fit <- rlmerb( n = 20L, design = design, pfamily_list = pfamily_list(ps), dispprior_list = list(dispersion = ps$group.dispersion), progbar = FALSE, verbose = FALSE, print_icm_table = FALSE ) fit$convergence_info$sim_method_used print_groupef(fit, draws = 1:5, groups = 1:3)
Posterior draws for Bayesian linear mixed models, given design matrices
y, D, W and population priors pfamily_list.
The model is stated under “Model and notation” below.
These are the engine-level entry points, normally reached through
rlmerb (or lmerb() in lmebayes), which is also
where the returned object is documented field by field. Each returned
draw is one independent replicate chain's state at its final sweep,
except on the fully-known-variance route, where draws are exact.
## S3 method for class 'rLMMNormal_reg' print( x, digits = max(3, getOption("digits") - 3), components = NULL, draws = NULL, ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' print( x, digits = max(3, getOption("digits") - 3), components = NULL, draws = NULL, ... ) rLMMNormal_reg( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, sim_method = "DEFAULT" ) rLMMNormal_reg_known_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, sim_method = "DEFAULT" ) rLMMNormal_reg_known_vcov_iid( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMNormal_reg_known_vcov_two_bg( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMNormal_reg_estimated_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, stage_verbose = FALSE, sim_method = "DEFAULT" ) rLMMindepNormalGamma_reg( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMindepNormalGamma_reg_known_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMindepNormalGamma_reg_estimated_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, stage_verbose = FALSE ) rLMMindepNormalGamma_reg_known_vcov_v2( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMindepNormalGamma_reg_estimated_vcov_v2( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, stage_verbose = FALSE )## S3 method for class 'rLMMNormal_reg' print( x, digits = max(3, getOption("digits") - 3), components = NULL, draws = NULL, ... ) ## S3 method for class 'rLMMindepNormalGamma_reg' print( x, digits = max(3, getOption("digits") - 3), components = NULL, draws = NULL, ... ) rLMMNormal_reg( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, sim_method = "DEFAULT" ) rLMMNormal_reg_known_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, sim_method = "DEFAULT" ) rLMMNormal_reg_known_vcov_iid( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMNormal_reg_known_vcov_two_bg( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMNormal_reg_estimated_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, stage_verbose = FALSE, sim_method = "DEFAULT" ) rLMMindepNormalGamma_reg( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMindepNormalGamma_reg_known_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMindepNormalGamma_reg_estimated_vcov( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, stage_verbose = FALSE ) rLMMindepNormalGamma_reg_known_vcov_v2( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE ) rLMMindepNormalGamma_reg_estimated_vcov_v2( n, y, D, group, W, pfamily_list, dispprior_list, offset = NULL, weights = 1, icm_tol = 1e-10, icm_maxit = 200L, tv_tol = 0.01, progbar = TRUE, verbose = FALSE, gap_tol = 0.0196, mode_gap_max = 1, diag_sweeps = FALSE, stage_verbose = FALSE )
x |
For |
digits |
Number of significant digits for printed numeric values. |
components |
For |
draws |
For |
... |
further arguments passed to or from other methods. |
n |
Number of stored draws. If |
y |
Response vector of length |
D |
Level-1 design matrix ( |
group |
Grouping factor of length |
W |
Named list of group-level design matrices ( |
pfamily_list |
Named list of population |
dispprior_list |
Observation-dispersion prior:
|
offset, weights
|
Observation offset and prior weights (glmbayes-style
formals: |
icm_tol, icm_maxit
|
ICM convergence controls for the internal population start. |
tv_tol |
Total-variation tolerance in |
progbar |
Show a text progress bar during sampling. |
verbose |
Print convergence calibration / ICM lines. |
sim_method |
Simulation method for |
gap_tol, mode_gap_max, diag_sweeps, stage_verbose
|
Pilot-stage controls for
|
An object of class c("<route>", "rLMMNormal_reg", "list")
(or c("rLMMindepNormalGamma_reg", "list") for the legacy outer-loop
engine), where <route> is the specific export that ran (e.g.
"rLMMNormal_reg_known_vcov"). Components use package
group/population names (see ‘inst/notation.md’),
in glm/glmbayes-style order:
groupefDraws of non-centered group coefficients
: a data frame with the grouping column plus one column
per colnames(D). Each row is one group in one stored draw.
groupef.mode matrix of ICM (or
exact posterior-mean) group coefficients ; rows
are levels(group), columns are colnames(D).
Not lme4's mean-zero .
groupef.itersOptional group-level envelope iteration counts.
popefNamed list of n x q_k matrices of population
coefficient draws .
popef.mode, popef.init
ICM (or exact) population point estimates and main-stage starts.
popef.dispersion, popef.iters
Optional population per-draw diagnostics when produced by the sampler.
group.dispersionObservation residual variance
/ when present (fixed scalar/vector or
draws under a Gamma measurement prior). Optional
group.dispersion.mean / group.dispersion.iters.
Distinct from popef.dispersion ().
pfamily_list, dispprior_list
Population
(pfamily_list) and observation-dispersion (dispprior_list)
priors that were used.
prior.weights, offset, offset2
Normalized
copies of the weights/offset arguments (glmbayes
naming). Not yet consumed by sampling.
any_non_normalWhether any population component is not
dNormal.
family, design, n
Likelihood family, matrix
inputs (y, D, group, W,
groupef.names, group_name, plus echoed
weights/offset), and chain count.
callMatched call.
m_convergenceInner Gibbs sweeps per stored draw
(always 1L for the exact-iid known-vcov route).
convergence_infoCalibration details, including
draw_engine, sim_method_used, icm_info, and
optional pilot UB fields.
pilotWhen a pilot ran: list with n,
m_convergence, chisq, and draws; otherwise
NULL.
sweep_historyMain-stage sweep history when collected.
rLMMNormal_reg(): Dispatcher for fixed : routes to
rLMMNormal_reg_known_vcov or
rLMMNormal_reg_estimated_vcov by population pfamily_list.
rLMMNormal_reg_known_vcov(): Fixed ; all population components
dNormal (known ). Dispatches on sim_method:
"DEFAULT" draws directly from the exact multivariate-normal
posterior via rLMMNormal_reg_known_vcov_iid (no Gibbs
sweeps, no burn-in, no autocorrelation between draws);
"TWO_BLOCK_GIBBS" runs
rLMMNormal_reg_known_vcov_two_bg instead (two-block Gibbs
with Theorem~3 rate calibration – the only option available for
rLMMNormal_reg_estimated_vcov and the GLMM routes).
rLMMNormal_reg_known_vcov_iid(): Fixed ; all population components
dNormal; exact iid draws from the closed-form multivariate-normal
posterior via rLMMNormal_joint_iid
(sim_method = "DEFAULT" route of
rLMMNormal_reg_known_vcov).
rLMMNormal_reg_known_vcov_two_bg(): Fixed ; all population components
dNormal (known ). Exact Theorem~3 rate calibration;
two-block Gibbs sweeps (sim_method = "TWO_BLOCK_GIBBS" route of
rLMMNormal_reg_known_vcov).
rLMMNormal_reg_estimated_vcov(): Fixed ; ING population components
(estimated ). Optional pilot stage; conservative
disp_lower rate bound. sim_method is accepted but has no
effect: variance components are estimated here, so the joint posterior
is not exactly Gaussian and only two-block Gibbs sampling is
implemented.
rLMMindepNormalGamma_reg(): Legacy outer-loop sampler: draws via
rGamma_reg, then calls rLMMNormal_reg each
replicate. Prefer rLMMindepNormalGamma_reg_known_vcov or
rLMMindepNormalGamma_reg_estimated_vcov for the ING
observation-dispersion path used by rlmerb.
rLMMindepNormalGamma_reg_known_vcov(): Random (pooled or per-group ING
observation prior, drawn jointly with group coefficients); all population
components dNormal. Used by rlmerb when
group.dispersion is dGamma() / dGamma_list() and
population priors are all dNormal.
rLMMindepNormalGamma_reg_estimated_vcov(): Random (pooled or per-group ING
observation prior, drawn jointly with group coefficients); ING population
components. Pilot/UB calibration via the sweep-outer sampler. Default path
for rlmerb with dGamma() / dGamma_list()
group.dispersion and ING population priors.
rLMMindepNormalGamma_reg_known_vcov_v2(): v2 (stub). Random (pooled or
per-group), but drawn with the population block; group block is
Gaussian at fixed . Same formals as
rLMMindepNormalGamma_reg_known_vcov. Sampling not yet
implemented; see ‘inst/DERIVATION_sigma2_with_block2_v2.md’.
rLMMindepNormalGamma_reg_estimated_vcov_v2(): v2 (stub). Random with the
population block (and ING population components). Same formals as
rLMMindepNormalGamma_reg_estimated_vcov. Sampling not yet
implemented; see ‘inst/DERIVATION_sigma2_with_block2_v2.md’.
For group (length(group_levels)),
with observations in group and
ncol(D) group-varying coefficients:
Likelihood (group level):
Hierarchical prior (population level):
The full, non-centered coefficient vector – not a mean-zero
deviation – appears directly in the likelihood. This is a centered
parameterization in the sense of (Lindley and Smith 1972):
is the group parameter, the population
(hyper-mean) parameter, and the population covariance.
is block-diagonal across the
coefficient dimensions,
and each coefficient may have its own number of level-2 predictors
(no padding needed, unlike a 3-index array).
Correspondence to these functions' arguments/return values:
(row-stacked )D: the
level-1 design matrix, one row per observation; is the
submatrix D[group == , ].
Assembled on demand from W: block
is row of W[[k]], so W is
list(), one
matrix per RE column .
popef/popef.mode in the returned object
(one entry per RE column, named by colnames(W[[k]])).
The group- row of groupef/
groupef.mode – not lme4's mean-zero
(see below).
Diagonal, , one plug-in per pfamily_list
component (see pfamily_list below); is the
internally-derived group prior precision P.
group (levels(group) fixes the
order ).
Correspondence to lme4/Laird-Ware: marginalizing (substituting
the population equation into the group likelihood) recovers the standard
lme4 form
where is the mean-zero deviation
lme4 calls . itself has no single lme4
counterpart: it is the common ancestor of both (fixed-effects
design, after right-multiplying by ) and
(random-effects design, used as-is). corresponds to
lme4's (fixed effects), and to the per-group
block of lme4's matrix (); the
functions documented here never materialize / –
is sampled directly against at every group-level Gibbs update (the
per-group/shared- conjugate updates for and
are the /-lettered formulas in
lmebayes_posterior_icm, with and
there). When every is
intercept-only ( for all , i.e. no level-2 predictors),
the model reduces to a standard random-intercept/random-slope lmer
model: should then recover lme4's fixed effects and
should track lme4::coef() (lme4::ranef()
tracks ), giving a natural automated
equivalence check.
For the full write-up (including the block-diagonal Gibbs full-conditional
derivation) see notation.md in system.file(package =
"lmebayesCore") (source: inst/notation.md).
Callers never name a route. It follows from two modelling decisions, and the decisions — not the routing — are what matter statistically.
1. Is the residual variance known or estimated?
Supplying a positive scalar (or one value per group) treats it as
known and conditions on it. Supplying a
dGamma() prior — one pooled, or a
dGamma_list with one per group — estimates it.
2. Are the between-group variances known or
estimated? A dNormal component treats as
known; a single dIndependent_Normal_Gamma component
anywhere in pfamily_list makes that variance a parameter to be
estimated.
The cross of the two selects one of four engines:
|
|
Engine |
| known | all known | rLMMNormal_reg_known_vcov |
| known | any estimated | rLMMNormal_reg_estimated_vcov |
| estimated | all known | rLMMindepNormalGamma_reg_known_vcov |
| estimated | any estimated | rLMMindepNormalGamma_reg_estimated_vcov
|
The consequence that shows up in the output is exactness. When both
variances are known the posterior is exactly multivariate normal, so
draws are exact, popef.mode is the true posterior mean, and
m_convergence is 1. As soon as either variance is
estimated the posterior is no longer Gaussian: draws come from the final
sweep of a calibrated chain, popef.mode is a conditional mode
rather than a mean, and a short pilot stage runs first.
sim_method is therefore meaningful only in the fully-known case,
the one route offering a choice between drawing directly from the closed
form ("DEFAULT") and running the sweep loop on the same target
("TWO_BLOCK_GIBBS", which exists mainly to cross-check the two
against each other). Elsewhere the argument is ignored.
The rLMMindepNormalGamma_reg_*_v2 functions are stubs for the same
priors with updated alongside the population parameters;
they are not yet implemented.
One input you cannot supply: the group prior precision
. It is always derived from pfamily_list, and a
caller-supplied P/Sigma is rejected, so it cannot silently
disagree with the population priors. See
vignette("Chapter-B01", package = "lmebayesCore") for the engine
map and vignette("Chapter-B04", package = "lmebayesCore") for the
exact route.
rLMMNormal_reg and rLMMindepNormalGamma_reg
validate inputs and delegate to the appropriate route (or, for the legacy
outer-loop rLMMindepNormalGamma_reg, draw then call
rLMMNormal_reg).
Lindley DV, Smith AFM (1972). “Bayes Estimates for the Linear Model.” Journal of the Royal Statistical Society. Series B (Methodological), 34(1), 1–41. doi:10.1111/j.2517-6161.1972.tb00899.x.
rGLMM_reg, rlmerb, print_groupef,
rindepNormalGamma_reg,
lmebayes_posterior_icm
glmbayes Simulation Functions
rGLMM_Re_Draw(),
rGLMM_reg(),
rGLMM_sweep(),
rLMMNormal_joint_iid(),
two_block_optimize_pilot_cost(),
two_block_rNormal_reg(),
two_block_rate(),
two_block_tv_bound()
## rLMMNormal_reg_known_vcov_iid() — exact iid draws on big_word_club ## ## Same data / formula path as the Ex_10 / Ex_13b demos; uses only the ## fixed-dispersion, known-vcov iid sampler. Requires suggested package ## bayesrules. if (requireNamespace("bayesrules", quietly = TRUE)) { data(big_word_club, package = "bayesrules") dat <- big_word_club dat$school_id <- factor(dat$school_id) dat <- subset( dat, !is.na(score_ppvt) & !is.na(invalid_ppvt) & invalid_ppvt == 0L & complete.cases(dat[, c( "score_ppvt", "distracted_a1", "distracted_ppvt", "private_school", "title1", "free_reduced_lunch", "school_id" )]) ) form_lmer <- score_ppvt ~ private_school + title1 + free_reduced_lunch + distracted_ppvt + distracted_a1 + free_reduced_lunch:distracted_a1 + (1 + distracted_ppvt + distracted_a1 || school_id) design <- model_setup(form_lmer, data = dat) ps <- Prior_Setup_GLMM(form_lmer, data = dat, pop.pwt = 0.01) pf <- pfamily_list(ps) ## Exact iid draws (fixed sigma^2, known tau^2_k / all dNormal). ## design$group already carries attr(*, "group_name"). set.seed(1) fit <- rLMMNormal_reg_known_vcov_iid( n = 20L, y = design$y, D = design$D, group = design$group, W = design$W, pfamily_list = pf, dispprior_list = list(dispersion = ps$group.dispersion), progbar = FALSE, verbose = FALSE ) ## Print a few population draws (object unchanged). print(fit, draws = 1:5) print_groupef(fit, draws = 1:5, groups = 1:3) }## rLMMNormal_reg_known_vcov_iid() — exact iid draws on big_word_club ## ## Same data / formula path as the Ex_10 / Ex_13b demos; uses only the ## fixed-dispersion, known-vcov iid sampler. Requires suggested package ## bayesrules. if (requireNamespace("bayesrules", quietly = TRUE)) { data(big_word_club, package = "bayesrules") dat <- big_word_club dat$school_id <- factor(dat$school_id) dat <- subset( dat, !is.na(score_ppvt) & !is.na(invalid_ppvt) & invalid_ppvt == 0L & complete.cases(dat[, c( "score_ppvt", "distracted_a1", "distracted_ppvt", "private_school", "title1", "free_reduced_lunch", "school_id" )]) ) form_lmer <- score_ppvt ~ private_school + title1 + free_reduced_lunch + distracted_ppvt + distracted_a1 + free_reduced_lunch:distracted_a1 + (1 + distracted_ppvt + distracted_a1 || school_id) design <- model_setup(form_lmer, data = dat) ps <- Prior_Setup_GLMM(form_lmer, data = dat, pop.pwt = 0.01) pf <- pfamily_list(ps) ## Exact iid draws (fixed sigma^2, known tau^2_k / all dNormal). ## design$group already carries attr(*, "group_name"). set.seed(1) fit <- rLMMNormal_reg_known_vcov_iid( n = 20L, y = design$y, D = design$D, group = design$group, W = design$W, pfamily_list = pf, dispprior_list = list(dispersion = ps$group.dispersion), progbar = FALSE, verbose = FALSE ) ## Print a few population draws (object unchanged). print(fit, draws = 1:5) print_groupef(fit, draws = 1:5, groups = 1:3) }
Like rNormal_reg_group, but when beta_set is supplied
draws independent unrestricted joint samples via rNormal_reg_group,
stacks group coefficients, and keeps only draws with
beta_in_marginal_safe_set. Additional batches use the
observed acceptance rate until n accepted joint draws are collected.
rNormal_reg_group_safe( n, y, x, group, prior_list = NULL, prior_lists = NULL, beta_set = NULL, offset = NULL, weights = 1, max_tries = NULL, mc_seed = NULL, Gridtype = 2L )rNormal_reg_group_safe( n, y, x, group, prior_list = NULL, prior_lists = NULL, beta_set = NULL, offset = NULL, weights = 1, max_tries = NULL, mc_seed = NULL, Gridtype = 2L )
n |
Number of iid draws per group ( |
y |
Response vector of length |
x |
Design matrix |
group |
Group partition: |
prior_list |
Single prior specification recycled to all groups, or with
|
prior_lists |
Optional list of length |
beta_set |
Optional |
offset |
Optional numeric vector (length |
weights |
Optional weights; same recycling and blocking as |
max_tries |
Maximum attempts when |
mc_seed |
Optional RNG seed. |
Gridtype |
Passed to each group's sampler (Armadillo Gridtype). |
Like rNormal_reg_group, plus safe-set fields
n_accepted, n_target, n_tried, accept_rate,
restricted, beta_set, and coefficients_all when
n > 1 accepted draws.
rNormalGLM_reg_group_safe,
beta_in_marginal_safe_set
Non-Gaussian counterpart of rNormal_reg_group_safe using
rNormalGLM_reg_group for each unrestricted joint attempt,
then joint rejection on beta_set.
rNormalGLM_reg_group_safe( n, y, x, group, prior_list = NULL, prior_lists = NULL, family, beta_set = NULL, offset = NULL, weights = 1, max_tries = NULL, mc_seed = NULL, Gridtype = 2L, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE )rNormalGLM_reg_group_safe( n, y, x, group, prior_list = NULL, prior_lists = NULL, family, beta_set = NULL, offset = NULL, weights = 1, max_tries = NULL, mc_seed = NULL, Gridtype = 2L, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE )
n |
Number of iid draws per group ( |
y |
Response vector of length |
x |
Design matrix |
group |
Group partition: |
prior_list |
Single prior specification recycled to all groups, or with
|
prior_lists |
Optional list of length |
family |
GLM |
beta_set |
Optional |
offset |
Optional numeric vector (length |
weights |
Optional weights; same recycling and blocking as |
max_tries |
Maximum attempts when |
mc_seed |
Optional RNG seed. |
Gridtype |
Passed to each group's sampler (Armadillo Gridtype). |
n_envopt |
Passed to each group; defaults to |
use_parallel, use_opencl, verbose, progbar
|
Passed to each group's GLM sampler. |
Like rNormalGLM_reg_group, plus safe-set metadata
(see rNormal_reg_group_safe).
rNormal_reg_group_safe,
beta_in_marginal_safe_set
Foster / Rosenthal drift constants from floor coupling eigenvalues.
rosenthal_drift_constants( eigenvalues, gamma_0 = NULL, mode = NULL, display_mode = c("sharp", "general"), d = NULL, V_sup = NULL )rosenthal_drift_constants( eigenvalues, gamma_0 = NULL, mode = NULL, display_mode = c("sharp", "general"), d = NULL, V_sup = NULL )
eigenvalues |
Output of |
gamma_0 |
Start state for |
mode |
Optional |
display_mode |
|
d |
Deficiency level for |
V_sup |
Override for |
A list with kappa_lb, lambda_lb, b_drift,
C_beta_plus, U, drift numerator/denominator, and Lyapunov
values.
rosenthal_tv_bound, floor_coupling_eigenvalues
Evaluates the Rosenthal (1995) bound at sweep count k, minorization
eps, floor eigenvalues, and fixed alpha. To optimize
alpha or k, use optimal_rosenthal_tv_bound.
rosenthal_tv_bound( k, alpha, eps, eigenvalues, drift = NULL, gamma_0 = NULL, mode = NULL, display_mode = c("sharp", "general"), d = NULL, V_sup = NULL )rosenthal_tv_bound( k, alpha, eps, eigenvalues, drift = NULL, gamma_0 = NULL, mode = NULL, display_mode = c("sharp", "general"), d = NULL, V_sup = NULL )
k |
Number of Gibbs sweeps ( |
alpha |
Tuning parameter in |
eps |
Minorization constant (typically |
eigenvalues |
Output of |
drift |
Optional output of |
gamma_0 |
Start state for |
mode |
Optional |
display_mode |
|
d |
Deficiency level for |
V_sup |
Override for |
A list with bound, minorization, drift,
k, alpha, eps, and drift_constants.
Draw from groupwise full conditionals when the posterior factorizes across
observation groups. rNormal_reg_group uses the Gaussian
rNormalReg() path per group; rNormalGLM_reg_group uses
the GLM envelope path per group. Typical use is block Gibbs
(n = 1 per outer step); n > 1 gives iid draws from the product
conditional.
rNormalGLM_reg_group( n, y, x, group, prior_list = NULL, prior_lists = NULL, offset = NULL, weights = 1, family = gaussian(), Gridtype = 2L, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE ) rNormal_reg_group( n, y, x, group, prior_list = NULL, prior_lists = NULL, offset = NULL, weights = 1, Gridtype = 2L )rNormalGLM_reg_group( n, y, x, group, prior_list = NULL, prior_lists = NULL, offset = NULL, weights = 1, family = gaussian(), Gridtype = 2L, n_envopt = NULL, use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE, progbar = FALSE ) rNormal_reg_group( n, y, x, group, prior_list = NULL, prior_lists = NULL, offset = NULL, weights = 1, Gridtype = 2L )
n |
Number of iid draws per group ( |
y |
Response vector of length |
x |
Design matrix |
group |
Group partition: |
prior_list |
Single prior specification recycled to all groups, or with
|
prior_lists |
Optional list of length |
offset |
Optional numeric vector (length |
weights |
Optional weights; same recycling and blocking as |
family |
GLM |
Gridtype |
Passed to each group's sampler (Armadillo Gridtype). |
n_envopt |
Passed to each group; defaults to |
use_parallel, use_opencl, verbose, progbar
|
Passed to each group's GLM sampler. |
Output layout: coefficients and coef.mode are matrices with
rows = groups and columns = predictors.
Per-group prior mean: pass prior_list$mu as an l1 x k
matrix (one column per group).
Dispersion: must be supplied via prior_list$dispersion (residual
variance ).
For rNormalGLM_reg_group, a list with class
"rNormalGLM_reg_group" including coefficients,
coef.mode, group_info, and group_results.
A list with class "rNormal_reg_group" including
coefficients, coef.mode, dispersion, and
group_info.
rNormal_reg_group_safe, rNormalGLM_reg_group_safe
## rNormalGLM_reg_group() — independent Poisson GLMs by group (toy) set.seed(1) group <- factor(rep(c("A", "B"), each = 15L)) x <- cbind(1, rnorm(length(group))) colnames(x) <- c("(Intercept)", "x1") eta <- x %*% c(-0.5, 0.3) + ifelse(group == "A", 0, 0.4) y <- rpois(length(group), exp(eta)) prior_list <- list( mu = rep(0, ncol(x)), P = diag(10, ncol(x)), dispersion = 1 ) out <- rNormalGLM_reg_group( n = 1L, y = y, x = x, group = group, prior_list = prior_list, family = poisson(), use_parallel = FALSE ) out$coefficients out$coef.mode ## rNormal_reg_group() — independent Gaussian regressions by group (toy) set.seed(42) n_groups <- 3L n_per <- 10L school <- rep(seq_len(n_groups), each = n_per) x <- cbind(1, rnorm(n_groups * n_per)) colnames(x) <- c("(Intercept)", "X1") b_true <- matrix(c(5, 0.5, 3, -0.2, 7, 0.3), nrow = n_groups, byrow = TRUE) sigma2 <- 1.5 y <- rowSums(x * b_true[school, ]) + rnorm(nrow(x), sd = sqrt(sigma2)) l1 <- ncol(x) prior_list <- list( mu = rep(0, l1), Sigma = diag(100, l1), dispersion = sigma2, ddef = FALSE ) out <- rNormal_reg_group( n = 1L, y = y, x = x, group = school, prior_list = prior_list ) out$coefficients out$coef.mode## rNormalGLM_reg_group() — independent Poisson GLMs by group (toy) set.seed(1) group <- factor(rep(c("A", "B"), each = 15L)) x <- cbind(1, rnorm(length(group))) colnames(x) <- c("(Intercept)", "x1") eta <- x %*% c(-0.5, 0.3) + ifelse(group == "A", 0, 0.4) y <- rpois(length(group), exp(eta)) prior_list <- list( mu = rep(0, ncol(x)), P = diag(10, ncol(x)), dispersion = 1 ) out <- rNormalGLM_reg_group( n = 1L, y = y, x = x, group = group, prior_list = prior_list, family = poisson(), use_parallel = FALSE ) out$coefficients out$coef.mode ## rNormal_reg_group() — independent Gaussian regressions by group (toy) set.seed(42) n_groups <- 3L n_per <- 10L school <- rep(seq_len(n_groups), each = n_per) x <- cbind(1, rnorm(n_groups * n_per)) colnames(x) <- c("(Intercept)", "X1") b_true <- matrix(c(5, 0.5, 3, -0.2, 7, 0.3), nrow = n_groups, byrow = TRUE) sigma2 <- 1.5 y <- rowSums(x * b_true[school, ]) + rnorm(nrow(x), sd = sqrt(sigma2)) l1 <- ncol(x) prior_list <- list( mu = rep(0, l1), Sigma = diag(100, l1), dispersion = sigma2, ddef = FALSE ) out <- rNormal_reg_group( n = 1L, y = y, x = x, group = school, prior_list = prior_list ) out$coefficients out$coef.mode
These functions are methods for class rlmerb,
rglmerb, or summary.rlmerb objects, following the layout of
summary.rglmb extended to the two-block mixed
model: Block~2 (population/level-2) tables are reported per random-effects
component, and Block~1 (group-level) effects are summarized in aggregate.
## S3 method for class 'rlmerb' summary(object, groups = NULL, ...) ## S3 method for class 'summary.rlmerb' print(x, digits = max(3, getOption("digits") - 3), ...) ## S3 method for class 'rglmerb' summary(object, groups = NULL, ...)## S3 method for class 'rlmerb' summary(object, groups = NULL, ...) ## S3 method for class 'summary.rlmerb' print(x, digits = max(3, getOption("digits") - 3), ...) ## S3 method for class 'rglmerb' summary(object, groups = NULL, ...)
object |
An object of class |
groups |
Optional character vector of grouping levels for which to
include a per-group Block~1 detail table. When |
x |
An object of class |
digits |
The number of significant digits to use when printing. |
... |
Additional optional arguments. |
Like summary.rglmb, which fits its own
glm maximum-likelihood reference, this method computes
its reference comparison internally from the model_setup
object carried on the fit — nothing needs to be supplied by the caller.
The reference is the lmer fit built by model_setup(), whose
fixed effects are on a different footing from the Block~2 hyperparameters:
is indexed by (random-effect component, level-2 parameter),
whereas lmer reports one flat coefficient vector. The two are put on
a common footing before being tabulated (see
‘Reference correspondence’ below), so the lmer column is the
coefficient that estimates the same quantity, not merely one with a similar
name.
summary.rlmerb returns an object of class
"summary.rlmerb", a list with components:
call, formula
|
The originating call and model formula. |
n |
Integer number of stored draws. |
sim_method_used, method, draw_engine
|
Character labels for the engine that produced the draws. |
m_convergence, lambda_star
|
Sweeps per stored draw, and the
convergence rate |
n_obs, n_groups, group_name, groupef.names
|
Design dimensions. |
varcor |
The reference |
popef |
Named list, one entry per random-effect component, each a
list of matrices |
popef_prior_overview, popef_overview, popef_percentiles_overview
|
The same three tables stacked across components, with rows named
|
tau2_prior_overview, tau2_overview, tau2_percentiles_overview
|
Block~2 variance components |
sigma2_group_overview |
Per-group |
groupef_overview |
Distribution of the Block~1 posterior modes across groups, per component. |
groupef_groups |
Per-group detail for the levels named in
|
any_non_normal |
|
print.summary.rlmerb returns its argument invisibly and is called
for the side effect of printing.
Writing for the random-effect component and for the level-2
parameter within that component, maps to an lmer
fixed effect as follows:
and both the interceptthe lmer intercept.
the intercept, a slopethe main effect : the
average of the random slope across groups.
the intercept, a covariatethe main effect :
a group-level predictor of the random intercept.
and slopesthe cross-level interaction
, since moderates the random slope . The
interaction column recorded in
model_setup()$popef.moderation is used when available, and the
/ orderings are tried otherwise.
Coefficients with no counterpart are reported as NA rather than
matched approximately.
rlmerb, rglmerb,
model_setup, Prior_Setup_GLMM,
summary.rglmb
Computes the eigenvalues of
for the
joint Gaussian posterior targeted by two_block_rNormal_reg
with family = gaussian() and fixed variance components. The
maximal eigenvalue is the geometric contraction rate of
the two-block Gibbs sampler ((Nygren 2020),
Claim 2 / Remark 8 / Corollary 1): the total variation distance between
the -step kernel and the target decays like .
two_block_rate( x, group, x_hyper, prior_list_block1, prior_list_block2, weights = NULL, family = gaussian(), group_levels = levels(group), warn_slow = TRUE ) ## S3 method for class 'two_block_rate' print(x, tols = c(0.01, 0.001, 1e-06), ...) two_block_rate_from_pfamily_list( x, group, x_hyper, prior_list_block1, pfamily_list, weights = NULL, family = gaussian(), group_levels = levels(group), warn_slow = TRUE ) two_block_rate_ing( x, group, x_hyper, prior_list_block1, prior_list_block2, lambda_ing = NULL, omega_ing = NULL, weights = NULL, family = gaussian(), group_levels = levels(group), warn_slow = TRUE ) ## S3 method for class 'two_block_rate_ing' print(x, ...)two_block_rate( x, group, x_hyper, prior_list_block1, prior_list_block2, weights = NULL, family = gaussian(), group_levels = levels(group), warn_slow = TRUE ) ## S3 method for class 'two_block_rate' print(x, tols = c(0.01, 0.001, 1e-06), ...) two_block_rate_from_pfamily_list( x, group, x_hyper, prior_list_block1, pfamily_list, weights = NULL, family = gaussian(), group_levels = levels(group), warn_slow = TRUE ) two_block_rate_ing( x, group, x_hyper, prior_list_block1, prior_list_block2, lambda_ing = NULL, omega_ing = NULL, weights = NULL, family = gaussian(), group_levels = levels(group), warn_slow = TRUE ) ## S3 method for class 'two_block_rate_ing' print(x, ...)
x |
Level-1 RE design matrix |
group |
Grouping factor or row-group partition of length |
x_hyper |
Named list of group-level design matrices |
prior_list_block1 |
Block 1 prior: |
prior_list_block2 |
Named list of Block 2 prior lists (each with
|
weights |
Optional per-observation working weights (length 1 or
|
family |
Response family (default |
group_levels |
Character vector defining group order (default
|
warn_slow |
If |
tols |
For |
... |
Ignored by the print methods. |
pfamily_list |
Named list of |
lambda_ing |
For |
omega_ing |
For |
Block convention: the paper's (the block updated second in
each sweep) is the Block 2 hyper vector of dimension
; the paper's is the Block 1
random-effect stack. is therefore and is
computed without ever forming the
Block 1 precision: per group only solves
are needed, followed by a single symmetric
eigendecomposition.
For non-Gaussian families the joint posterior is not normal; supplying
IRLS-style weights evaluated at the posterior mode (via the internal
two_block_mode_weights() helper used by rGLMM_reg) yields a
local-Gaussian heuristic rate (no theorem applies).
For two_block_rate() / two_block_rate_from_pfamily_list(),
an object of class "two_block_rate": a list with
lambda_star (the Remark 8 rate), eigenvalues (full
spectrum in ),
m_for_tol (function: iterations needed so that
tol), S
(), P11, dims,
re_names, gamma_names, group_levels,
family, weights_source, and call.
For two_block_rate_ing(), see the value description under that
function below.
print(two_block_rate): Print a "two_block_rate" object
(eigenvalues, , and implied sweeps for common TV
tolerances).
two_block_rate_from_pfamily_list(): Convergence rate from a pfamily_list
Block~2 spec: thin wrapper that accepts Block~2 priors as pfamily
objects. For dNormal components the fixed dispersion is
used; for dIndependent_Normal_Gamma components the conservative
disp_lower plug-in is used (the rate is then an upper bound over
the truncated tau^2 range).
two_block_rate_ing(): Extended -aware
local rate diagnostic (not a certified TV bound). Computes the
Remark~8-style eigenvalues twice from the same
prior_list_block1/prior_list_block2 inputs
two_block_rate() would use: once as the plain
(,)-only eigenvalues_base/
lambda_star_base, and once with the joint
Hessian extension of inst/BLOCK_GIBBS_ERGODICITY_ING.md
(Sections 5–6 / 14) as eigenvalues/lambda_star.
The extended matrix is evaluated at a single reference state
(lambda_ing/omega_ing) and is state-dependent; it does
not set sampler m_convergence. Not exported; call via
lmebayesCore:::two_block_rate_ing(). Returns an object of class
"two_block_rate_ing" with lambda_star/eigenvalues
(extended), lambda_star_base/eigenvalues_base (plain),
extended S/P11/P12/P21/P22,
ext_names, n_lambda, n_omega, lambda_names,
omega_scope, and the usual metadata fields.
print(two_block_rate_ing): Print a "two_block_rate_ing" object
(base vs extended and their difference).
alone gives only the geometric proxy
tol, which is loose because it waits for the
slowest eigendirection while ignoring that the others converged sweeps
earlier. The sampler instead inverts the exact Theorem 3 bound, which sums
closed-form per-eigendirection terms over the full spectrum
returned in eigenvalues:
capped at 1, with the eigenvalues taken in ascending order (Lemma 2) and
the squared standardized distance of the chain start from the
posterior mean. Because rlmerb starts every replicate chain at the
exact ICM posterior mean, and the mean term vanishes
identically; only the variance-convergence sum has to be certified.
The pipeline is therefore
two_block_rate()
two_block_tv_bound()
two_block_l_for_tv(), and the sampler adds one sweep
to the result: the bound applies to the block updated second in each sweep
(the hyper vector ), and the stored Block 1 draw lags by a
half-step. Calling print() on the returned object shows all three
answers — geometric proxy, Corollary 1 envelope, and Theorem 3 — side
by side for a range of tolerances.
Cost grows only logarithmically in tol, so certifying an
entire n-draw sample at level (pass
tol = alpha / n) usually costs a handful of extra sweeps. When
chains cannot start at the posterior mean — non-Gaussian families, or
sampled variance components — a pilot stage supplies a start whose
is certified from the pilot size; see
two_block_optimize_pilot_cost and
vignette("Chapter-B03", package = "lmebayesCore").
Nygren KN (2020). “On the Total Variation Distance Between Multivariate Normal Densities with Applications to Two-Block Gibbs Samplers.” Working manuscript. Claims 1–3, Theorem 3, Remarks 3, 5, 8 and 17, and Corollary 1 are cited throughout the lmebayesCore two-block ergodicity code and vignettes.
two_block_tv_bound, two_block_rNormal_reg,
two_block_optimize_pilot_cost;
vignette("Chapter-B02", package = "lmebayesCore") for the
derivation and vignette("Chapter-B03", package = "lmebayesCore")
for the sweep calibration.
glmbayes Simulation Functions
rGLMM_Re_Draw(),
rGLMM_reg(),
rGLMM_sweep(),
rLMMNormal_joint_iid(),
rLMM_reg,
two_block_optimize_pilot_cost(),
two_block_rNormal_reg(),
two_block_tv_bound()
## two_block_rate() — Remark 8 contraction rate for a balanced ## random-intercept model, where lambda* has a closed form. ## ## For J groups of n_j observations each, p_re = q = 1, and a diffuse Block 2 ## prior, lambda* = sigma^2 / (sigma^2 + n_j * tau^2). J <- 12L n_j <- 8L sigma2 <- 1.0 tau2 <- 0.5 group <- factor(rep(seq_len(J), each = n_j)) Z <- matrix(1, J * n_j, 1L, dimnames = list(NULL, "(Intercept)")) x_hyper <- list("(Intercept)" = matrix( 1, J, 1L, dimnames = list(levels(group), "(Intercept)") )) rate <- two_block_rate( x = Z, group = group, x_hyper = x_hyper, prior_list_block1 = list(Sigma = matrix(tau2), dispersion = sigma2), prior_list_block2 = list("(Intercept)" = list(mu = 0, Sigma = matrix(100))) ) c(computed = rate$lambda_star, closed_form = sigma2 / (sigma2 + n_j * tau2)) ## print() adds the sweeps implied by each bound: the geometric (lambda*)^m ## proxy, the Corollary 1 envelope, and the exact Theorem 3 terms the sampler ## actually uses. rate ## Larger groups carry more likelihood precision and mix faster; the rate does ## not depend on the number of groups. lambda_for <- function(n_j) { g <- factor(rep(seq_len(J), each = n_j)) two_block_rate( x = matrix(1, J * n_j, 1L, dimnames = list(NULL, "(Intercept)")), group = g, x_hyper = list("(Intercept)" = matrix( 1, J, 1L, dimnames = list(levels(g), "(Intercept)") )), prior_list_block1 = list(Sigma = matrix(tau2), dispersion = sigma2), prior_list_block2 = list("(Intercept)" = list(mu = 0, Sigma = matrix(100))) )$lambda_star } round(vapply(c(2L, 8L, 32L), lambda_for, numeric(1)), 4)## two_block_rate() — Remark 8 contraction rate for a balanced ## random-intercept model, where lambda* has a closed form. ## ## For J groups of n_j observations each, p_re = q = 1, and a diffuse Block 2 ## prior, lambda* = sigma^2 / (sigma^2 + n_j * tau^2). J <- 12L n_j <- 8L sigma2 <- 1.0 tau2 <- 0.5 group <- factor(rep(seq_len(J), each = n_j)) Z <- matrix(1, J * n_j, 1L, dimnames = list(NULL, "(Intercept)")) x_hyper <- list("(Intercept)" = matrix( 1, J, 1L, dimnames = list(levels(group), "(Intercept)") )) rate <- two_block_rate( x = Z, group = group, x_hyper = x_hyper, prior_list_block1 = list(Sigma = matrix(tau2), dispersion = sigma2), prior_list_block2 = list("(Intercept)" = list(mu = 0, Sigma = matrix(100))) ) c(computed = rate$lambda_star, closed_form = sigma2 / (sigma2 + n_j * tau2)) ## print() adds the sweeps implied by each bound: the geometric (lambda*)^m ## proxy, the Corollary 1 envelope, and the exact Theorem 3 terms the sampler ## actually uses. rate ## Larger groups carry more likelihood precision and mix faster; the rate does ## not depend on the number of groups. lambda_for <- function(n_j) { g <- factor(rep(seq_len(J), each = n_j)) two_block_rate( x = matrix(1, J * n_j, 1L, dimnames = list(NULL, "(Intercept)")), group = g, x_hyper = list("(Intercept)" = matrix( 1, J, 1L, dimnames = list(levels(g), "(Intercept)") )), prior_list_block1 = list(Sigma = matrix(tau2), dispersion = sigma2), prior_list_block2 = list("(Intercept)" = list(mu = 0, Sigma = matrix(100))) )$lambda_star } round(vapply(c(2L, 8L, 32L), lambda_for, numeric(1)), 4)