| simfuncs | R Documentation |
Simulation functions provide a unified interface for generating posterior samples from Bayesian GLMs.
These functions are typically used within model fitting routines such as rglmb and rlmb, and
are also suitable for use in Block Gibbs sampling and other simulation-based inference techniques.
simfunction(object, ...)
rNormal_reg(n, y, x, prior_list, offset = NULL, weights = 1,
family = gaussian(), Gridtype = 2, n_envopt = NULL,
use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE,progbar=FALSE)
rNormalGamma_reg(n, y, x, prior_list, offset = NULL, weights = 1, family = gaussian(),
Gridtype = 2,n_envopt = NULL,
use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE,progbar=FALSE)
rindepNormalGamma_reg(n, y, x, prior_list, offset = NULL, weights = 1,
family = gaussian(), Gridtype = 2,n_envopt = NULL,
use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE,
progbar = TRUE)
rGamma_reg(n, y, x, prior_list, offset = NULL, weights = 1, family = gaussian(),
Gridtype = 2,n_envopt = NULL,
use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE,progbar=FALSE)
## S3 method for class 'rGamma_reg'
print(x, digits = max(3, getOption("digits") - 3), ...)
## S3 method for class 'simfunction'
print(x, ...)
rGamma_Conjugate_reg(n, y, x, prior_list, offset = NULL, weights = 1, family = gaussian(),
Gridtype = 2,n_envopt = NULL,
use_parallel = TRUE, use_opencl = FALSE, verbose = FALSE,progbar=FALSE)
rBeta_reg(n, y, x, prior_list, offset = NULL, weights = 1,
family = gaussian(), Gridtype = 2, n_envopt = NULL,
use_parallel = TRUE, use_opencl = FALSE,
verbose = FALSE, progbar = FALSE)
object |
A fitted model object containing a |
n |
Number of draws to generate. If |
y |
A vector of observations of length |
x |
for the simulation functions a design matrix of dimension |
prior_list |
A list with prior parameters (e.g., shape, rate, beta) used in the simulation. |
offset |
Optional numeric vector of length |
weights |
Optional numeric vector of prior weights. |
family |
A description of the error distribution and link function (see |
Gridtype |
Optional integer specifying the method used to construct the envelope function. |
n_envopt |
Effective sample size passed to EnvelopeOpt for grid
construction. Defaults to match |
use_parallel |
Logical. Whether to use parallel processing. |
use_opencl |
Logical. Whether to use OpenCL acceleration. |
verbose |
Logical. Whether to print progress messages. |
progbar |
Logical. Whether to display a progress base during simulation. |
digits |
Number of significant digits to use for printed output. |
... |
Additional arguments passed to or from other methods. |
The low-level simulation functions rNormal_reg(), rNormalGamma_reg(),
rindepNormalGamma_reg(), and rGamma_reg() generate iid samples from posterior
distributions for specific model components. These model functions are used internally by the functions
rglmb() and rlmb() to generate samples.
The simfunction() generic extracts metadata from simulation objects, including the function name, call, and arguments used. This is useful for introspection, reproducibility, and diagnostics.
The lower-level simulation functions generate iid samples from posterior distributions for specific model components.
These functions are used internally by pfamily constructors and model fitting routines.
rNormal_reg(): Produces iid draws for regression coefficients in models with
multivariate normal priors and log-concave likelihood functions. For Gaussian likelihoods,
these are conjugate priors and standard simulation procedures for multivariate normal
distributions are utilized \insertCiteLindleySmith1972,DiaconisYlvisaker1979glmbayes.
For all other families/link functions, the likelihood subgradient approach of
\insertCiteNygren2006glmbayes is used to generate iid samples.
rNormalGamma_reg(): Produces iid draws for regression coefficients and the
dispersion parameter in models with Normal-Gamma priors and Gaussian likelihoods, where
this is a conjugate prior distribution. Standard simulation procedures for gamma and
multivariate normal distributions are utilized
\insertCiteRaiffa1961,LindleySmith1972glmbayes.
rindepNormalGamma_reg(): Produces iid draws for regression coefficients
and the dispersion parameter in models with independent Normal and truncated Gamma priors.
This is a non-conjugate specification but can still be sampled using accept-reject procedures
based on an enveloping approach (see vignette
\insertCiteglmbayesIndNormGammaVignetteglmbayes).
rGamma_reg(): Simulates dispersion parameters for Gaussian and Gamma families
using either standard gamma sampling or accept-reject methods based on likelihood
subgradients \insertCiteChen1979,glmbayesGammaVignetteglmbayes.
simfunction()An object of class "simfunction" containing:
nameCharacter string with the name of the simulation function.
callThe matched call used to generate the simulation.
argsA named list of arguments passed to the simulation function.
rNormal_reg()A list object with classes "rglmb", "glmb", "glm", and "lm".
Elements include:
coefficientsMatrix (n * p) of simulated regression coefficients, with column names from x.
coef.modePosterior mode of the coefficients. Gaussian: from lm.fit; non-Gaussian: BFGS mode shifted by prior mean.
dispersionScalar dispersion used. Poisson/Binomial: 1; otherwise the supplied value. Quasi families: mean residual-based dispersion computed in the wrapper.
PriorList with mean (prior mean vector) and Precision (prior precision matrix P).
prior.weightsVector of prior weights used in the simulation (unscaled).
offsetOffset vector passed to the C++ sampler.
offset2Offset used internally by the wrapper (copy of input or a zero vector).
yResponse vector.
xDesign matrix.
fitFitted/diagnostic object. Gaussian: result of lm.fit (class "lm"). Non-Gaussian: result of glmb.wfit(...).
itersVector of iteration counts per sample. Gaussian: vector of ones; non-Gaussian: counts from the sampler.
EnvelopeEnvelope list used for accept-reject sampling (non-Gaussian); NULL for Gaussian.
familyFamily object describing distribution and link.
famfuncProcessed family functions used internally (e.g., f2, f3).
callMatched call to rNormal_reg().
formulaFormula reconstructed from y and x.
modelModel frame corresponding to formula.
dataData frame combining y and x.
rNormalGamma_reg()A list with class "rglmb" containing:
coefficientsMatrix (n * p) of simulated regression coefficients; row i equals Btilde + IR %*% rnorm(p) * sqrt(dispersion[i]). Column names are set to colnames(x).
coef.modePosterior mean/mode vector Btilde from rNormal_reg.wfit().
dispersionNumeric vector of length n with draws from the inverse-gamma posterior 1/rgamma(shape = shape + nobs/2, rate = rate + 0.5*S).
PriorList with mean (as numeric vector mu) and Precision (matrix P).
offsetOffset vector as supplied.
prior.weightsVector of prior weights wt.
yResponse vector.
xDesign matrix.
fitResult from rNormal_reg.wfit(), including fields such as Btilde, IR, S, and k.
famfuncProcessed family functions for Gaussian models (from glmbfamfunc(gaussian())).
itersNumeric vector (length n) of ones indicating per-draw iteration counts.
EnvelopeNULL; no envelope is constructed in this conjugate setup.
callMatched call to rNormalGamma_reg().
rindepNormalGamma_reg()A list with class "rglmb" containing:
coefficientsMatrix (n * p) of simulated regression coefficients, back-transformed to the original scale; column names set to colnames(x).
coef.modeVector with the conditional posterior mode used for envelope anchoring (from the Gaussian fit).
dispersionNumeric vector of length n with simulated dispersion draws.
PriorList with prior components: mean (prior mean mu), Sigma (prior covariance), shape and rate (Gamma prior for dispersion), Precision (solve(Sigma)).
familyThe gaussian() family object.
prior.weightsVector of prior weights used in the simulation.
yResponse vector.
xDesign matrix.
callMatched call to rindepNormalGamma_reg().
famfuncProcessed family functions for Gaussian models (from glmbfamfunc).
itersVector with per-draw iteration counts returned by the joint sampler.
EnvelopeNULL; envelope diagnostics are not returned by this function.
loglikeNULL; placeholder for log-likelihood values.
weight_outNumeric vector of per-draw weights returned by the C++ routine.
sim_boundsList with low and upp, the dispersion bounds used by the shared envelope.
offset2Offset vector used internally (copy of input or a zero vector).
rGamma_reg()An object of class "rGamma_reg" containing:
coefficientsA 1 * p matrix of assumed regression coefficients.
coef.modeCurrently NULL; reserved for future use.
dispersionA vector of simulated dispersion values.
PriorA list with prior parameters: shape and rate.
prior.weightsVector of prior weights used in the simulation.
yThe response vector.
The simulation framework was developed by Kjell Nygren as part of the glmbayes package. It builds on the likelihood subgradient approach described in \insertCiteNygren2006glmbayes, and extends classical Bayesian GLM sampling techniques.
pfamily, glmb, lmb, rglmb, rlmb
for modeling functions that consume simulation functions.
rNormal_reg, rNormalGamma_reg, rGamma_reg for individual simulation functions.
EnvelopeBuild, EnvelopeEval, EnvelopeSize for envelope construction
and grid evaluation used in likelihood-subgradient sampling.
Theory and implementation narrative: \insertCiteNygren2006glmbayes; \insertCiteglmbayesSimmethods,glmbayesChapterA08glmbayes.
############################### Start of rNormal_reg examples ####################
## During CRAN checks, run examples sequentially.
use_parallel <- identical(Sys.getenv("NOT_CRAN"), "true")
set.seed(333)
## Dobson (1990) Page 93: Randomized Controlled Trial :
counts <- c(18, 17, 15, 20, 10, 20, 25, 13, 12)
outcome <- gl(3, 1, 9)
treatment <- gl(3, 3)
print(d.AD <- data.frame(treatment, outcome, counts))
## Poisson Prior and rNormal_reg call (using Prior_Setup for x, y, and prior values)
ps <- Prior_Setup(counts ~ outcome + treatment, family = poisson(), data = d.AD)
out_pois <- rNormal_reg(
n = 1000,
y = ps$y,
x = ps$x,
prior_list = list(mu = ps$mu, Sigma = ps$Sigma),
family = poisson(link = "log"),
weights = rep(1, nrow(ps$x)),
use_parallel = use_parallel
)
summary(out_pois)
## Menarche Binomial Data Example
data(menarche, package = "MASS")
menarche$Age2 <- menarche$Age - 13
## Logit Prior and rNormal_reg call (use proportion + trial weights)
ps1 <- Prior_Setup(
Menarche / Total ~ Age2,
family = binomial(logit),
data = menarche,
weights = menarche$Total
)
out_logit <- rNormal_reg(
n = 1000,
y = ps1$y,
x = ps1$x,
prior_list = list(mu = ps1$mu, Sigma = ps1$Sigma),
family = binomial(logit),
weights = menarche$Total,
use_parallel = use_parallel
)
summary(out_logit)
## Probit Prior and rNormal_reg call
ps2 <- Prior_Setup(
Menarche / Total ~ Age2,
family = binomial(probit),
data = menarche,
weights = menarche$Total
)
out_probit <- rNormal_reg(
n = 1000,
y = ps2$y,
x = ps2$x,
prior_list = list(mu = ps2$mu, Sigma = ps2$Sigma),
family = binomial(probit),
weights = menarche$Total,
use_parallel = use_parallel
)
summary(out_probit)
## clog-log Prior and rNormal_reg call
ps3 <- Prior_Setup(
Menarche / Total ~ Age2,
family = binomial(cloglog),
data = menarche,
weights = menarche$Total
)
out_cloglog <- rNormal_reg(
n = 1000,
y = ps3$y,
x = ps3$x,
prior_list = list(mu = ps3$mu, Sigma = ps3$Sigma),
family = binomial(cloglog),
weights = menarche$Total,
use_parallel = use_parallel
)
summary(out_cloglog)
## Gamma regression
data(carinsca)
carinsca$Merit <- ordered(carinsca$Merit)
carinsca$Class <- factor(carinsca$Class)
oldopt <- options(contrasts = c("contr.treatment", "contr.treatment"))
psg <- Prior_Setup(
Cost / Claims ~ Merit + Class,
family = Gamma(link = "log"),
data = carinsca,
weights = carinsca$Claims
)
out_gamma <- rNormal_reg(
n = 1000,
y = psg$y,
x = psg$x,
prior_list = list(mu = psg$mu, Sigma = psg$Sigma, dispersion = psg$dispersion),
family = Gamma(link = "log"),
weights = carinsca$Claims,
use_parallel = use_parallel
)
summary(out_gamma)
options(oldopt)
############################### Start of rNormalGamma_reg examples ####################
## During CRAN checks, run examples sequentially.
use_parallel <- identical(Sys.getenv("NOT_CRAN"), "true")
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
ps=Prior_Setup(weight ~ group)
mu <- ps$mu
shape <- ps$shape
rate <- ps$rate
y <- ps$y
x <- as.matrix(ps$x)
prior_list <- list(mu = mu, Sigma = ps$Sigma_0, shape = shape, rate = rate)
ngamma.D9 <- rNormalGamma_reg(n = 1000, y = y, x = x,
prior_list = prior_list, use_parallel = use_parallel)
summary(ngamma.D9)
############################### Start of rindepNormalGamma_reg examples ####################
## During CRAN checks, run examples sequentially.
use_parallel <- identical(Sys.getenv("NOT_CRAN"), "true")
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
p_setup <- Prior_Setup(weight ~ group, family = gaussian())
mu <- p_setup$mu
Sigma_prior <- p_setup$Sigma
dispersion <- p_setup$dispersion
shape <- p_setup$shape
rate <- p_setup$rate
y <- p_setup$y
x <- p_setup$x
prior_list <- list(
mu = mu,
Sigma = Sigma_prior,
dispersion = dispersion,
shape = shape,
rate = rate,
Precision = solve(Sigma_prior),
max_disp_perc = 0.99
)
set.seed(360)
sim2 <- rindepNormalGamma_reg(n = 1000, y, x, prior_list = prior_list,
use_parallel = use_parallel)
summary(sim2)
############################### Start of rGamma_reg examples ####################
## During CRAN checks, run examples sequentially.
use_parallel <- identical(Sys.getenv("NOT_CRAN"), "true")
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17, 5.58, 5.18, 6.11, 4.50, 4.61, 5.17, 4.53, 5.33, 5.14)
trt <- c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69)
group <- gl(2, 10, 20, labels = c("Ctl", "Trt"))
weight <- c(ctl, trt)
## Set up prior hyperparameters (shape/rate) and model matrix via Prior_Setup
ps <- Prior_Setup(weight ~ group, family = gaussian())
y <- ps$y
x <- as.matrix(ps$x)
## rGamma_reg uses a dGamma-style prior on dispersion with fixed beta.
## Use coefficients from Prior_Setup (full-model GLM MLE by default).
prior_list <- list(beta = ps$coefficients, shape = ps$shape, rate = ps$rate)
out <- rGamma_reg(n = 1000, y = y, x = x, prior_list = prior_list,
family = gaussian(), use_parallel = use_parallel)
summary(out)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.