| Title: | Bayesian Statistical Modelling with Torch |
|---|---|
| Description: | A probabilistic programming package for Bayesian statistical modelling in R using native R syntax. Models are defined interactively with 'gretaR_array' objects, then compiled to 'torch' tensors for Hamiltonian Monte Carlo and No-U-Turn Sampler inference. Runs on a native 'torch' (libtorch) backend with no Python dependency required. |
| Authors: | Max Moldovan [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-9680-8474>) |
| Maintainer: | Max Moldovan <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.5.2 |
| Built: | 2026-11-27 12:48:45 UTC |
| Source: | https://github.com/max578/gretaR |
Enables indexing into group-level parameters for hierarchical models.
Supports integer vector indexing (e.g., alpha[group_id]).
## S3 method for class 'gretaR_array' x[i, j, ..., drop = TRUE]## S3 method for class 'gretaR_array' x[i, j, ..., drop = TRUE]
x |
A gretaR_array. |
i |
Index: an integer vector or a gretaR_array of integer indices. |
j |
Not supported. Supplying a column index raises an error; only single-index row/element selection is currently implemented. |
... |
Additional arguments (ignored). |
drop |
Logical (ignored; always returns a gretaR_array). |
A new gretaR_array with elements selected by the index.
Overrides base %*% to dispatch to sparse-aware matrix multiplication
when either argument is a gretaR_array.
x %*% yx %*% y
x |
A matrix, gretaR_array, or numeric. |
y |
A matrix, gretaR_array, or numeric. |
A gretaR_array (if either input is gretaR_array) or the base result.
Convert numeric vectors, matrices, or arrays into a
gretaR_array data node for use in model definitions. Data nodes
are fixed (not sampled) during inference.
as_data(x)as_data(x)
x |
A numeric vector, matrix, or array of observed data. |
A gretaR_array representing fixed (observed) data.
## Not run: y <- as_data(iris$Sepal.Length) X <- as_data(matrix(rnorm(30), ncol = 3)) ## End(Not run)## Not run: y <- as_data(iris$Sepal.Length) X <- as_data(matrix(rnorm(30), ncol = 3)) ## End(Not run)
Create a Bernoulli-distributed variable with the specified
probability of success. Support is on {0, 1}.
bernoulli(prob, dim = NULL)bernoulli(prob, dim = NULL)
prob |
Probability of success (numeric or |
dim |
Integer vector of dimensions (default scalar). |
A gretaR_array.
## Not run: z <- bernoulli(0.5) ## End(Not run)## Not run: z <- bernoulli(0.5) ## End(Not run)
Create a beta-distributed variable with the specified shape
parameters. Support is on the interval (0, 1). Named
beta_dist to avoid conflict with base::beta.
beta_dist(alpha, beta, dim = NULL, truncation = NULL)beta_dist(alpha, beta, dim = NULL, truncation = NULL)
alpha |
First shape parameter (positive numeric or |
beta |
Second shape parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array.
## Not run: p <- beta_dist(alpha = 2, beta = 5) ## End(Not run)## Not run: p <- beta_dist(alpha = 2, beta = 5) ## End(Not run)
Create a binomially-distributed variable with the specified number of trials and probability of success per trial.
Named binomial_dist to avoid masking stats::binomial
(the GLM family constructor).
binomial_dist(size, prob, dim = NULL)binomial_dist(size, prob, dim = NULL)
size |
Number of trials (positive integer or |
prob |
Probability of success per trial (numeric or |
dim |
Integer vector of dimensions (default scalar). |
A gretaR_array.
## Not run: y <- binomial_dist(size = 10, prob = 0.3) ## End(Not run)## Not run: y <- binomial_dist(size = 10, prob = 0.3) ## End(Not run)
The Cauchy distribution (Student-t with 1 degree of freedom). Heavy-tailed; useful as a weakly informative prior.
cauchy(location = 0, scale = 1, dim = NULL, truncation = NULL)cauchy(location = 0, scale = 1, dim = NULL, truncation = NULL)
location |
Location parameter. |
scale |
Scale parameter (positive). |
dim |
Dimensions. |
truncation |
Optional length-2 numeric vector |
A gretaR_array.
## Not run: x <- cauchy(0, 1) ## End(Not run)## Not run: x <- cauchy(0, 1) ## End(Not run)
Extract posterior means (for MCMC/VI) or MAP estimates as a named numeric vector.
## S3 method for class 'gretaR_fit' coef(object, ...)## S3 method for class 'gretaR_fit' coef(object, ...)
object |
A |
... |
Ignored. |
A named numeric vector of point estimates.
## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) fit <- opt(m) coef(fit) ## End(Not run)## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) fit <- opt(m) coef(fit) ## End(Not run)
Translate a compiled gretaR_model into Stan code suitable
for use with cmdstanr. The generated code preserves the model structure
defined via the gretaR DSL.
compile_to_stan(model)compile_to_stan(model)
model |
A |
A character string containing valid Stan code.
## Not run: mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) cat(compile_to_stan(m)) ## End(Not run)## Not run: mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) cat(compile_to_stan(m)) ## End(Not run)
Define a distribution with a user-supplied log-probability density function. The function must accept a torch tensor and return a scalar torch tensor. It must be differentiable via torch autograd.
custom_distribution( log_prob_fn, constraint = NULL, dim = NULL, name = "custom" )custom_distribution( log_prob_fn, constraint = NULL, dim = NULL, name = "custom" )
log_prob_fn |
A function |
constraint |
Optional list with |
dim |
Dimensions of the variable. |
name |
Optional name for display purposes. |
A gretaR_array representing a variable with the custom distribution.
## Not run: # Laplace distribution (not built in) x <- custom_distribution( log_prob_fn = function(x) -torch_sum(torch_abs(x)), name = "laplace" ) # Truncated normal (positive only) x <- custom_distribution( log_prob_fn = function(x) { torch_sum(-0.5 * x^2) # kernel of N(0,1) }, constraint = list(lower = 0, upper = Inf), name = "truncated_normal" ) ## End(Not run)## Not run: # Laplace distribution (not built in) x <- custom_distribution( log_prob_fn = function(x) -torch_sum(torch_abs(x)), name = "laplace" ) # Truncated normal (positive only) x <- custom_distribution( log_prob_fn = function(x) { torch_sum(-0.5 * x^2) # kernel of N(0,1) }, constraint = list(lower = 0, upper = Inf), name = "truncated_normal" ) ## End(Not run)
Creates a variable distributed according to the Dirichlet distribution, the multivariate generalisation of the Beta distribution. Values lie on the probability simplex (non-negative, sum to one).
dirichlet(concentration, dim = NULL)dirichlet(concentration, dim = NULL)
concentration |
Concentration parameter vector (positive numeric or gretaR_array). Length determines the dimensionality of the simplex. |
dim |
Dimensions of the variable (inferred from concentration if NULL). |
A gretaR_array with support on the simplex.
Latent (sampled) Dirichlet variables are not yet supported because a
correct simplex transform (stick-breaking or centered softmax with the
matching Jacobian) is not yet implemented. model() will error if a
Dirichlet variable is reachable as a free parameter. The distribution can
still be evaluated (log_prob) and is planned to be sampler-ready in
v0.3.
## Not run: theta <- dirichlet(c(1, 1, 1)) theta <- dirichlet(c(2, 5, 1)) ## End(Not run)## Not run: theta <- dirichlet(c(1, 1, 1)) theta <- dirichlet(c(2, 5, 1)) ## End(Not run)
Retrieve the distribution object associated with a
gretaR_array variable node, or NULL if none is set.
distribution(x)distribution(x)
x |
A |
The GretaRDistribution object, or NULL.
## Not run: mu <- normal(0, 1) distribution(mu) ## End(Not run)## Not run: mu <- normal(0, 1) distribution(mu) ## End(Not run)
Define the likelihood by assigning a distribution to a data
gretaR_array. This registers the distribution as a likelihood
term in the model's log-joint density.
distribution(x) <- valuedistribution(x) <- value
x |
A data |
value |
A distribution |
The data gretaR_array x, invisibly.
## Not run: y <- as_data(rnorm(100)) mu <- normal(0, 10) sigma <- half_cauchy(1) distribution(y) <- normal(mu, sigma) ## End(Not run)## Not run: y <- as_data(rnorm(100)) mu <- normal(0, 10) sigma <- half_cauchy(1) distribution(y) <- normal(mu, sigma) ## End(Not run)
Create an exponentially-distributed variable with the specified rate. Support is on the positive reals.
exponential(rate = 1, dim = NULL, truncation = NULL)exponential(rate = 1, dim = NULL, truncation = NULL)
rate |
Rate parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array.
## Not run: lambda <- exponential(rate = 1) ## End(Not run)## Not run: lambda <- exponential(rate = 1) ## End(Not run)
Create a gamma-distributed variable with the specified shape
and rate. Support is on the positive reals. Named gamma_dist to
avoid conflict with base::gamma.
gamma_dist(shape, rate, dim = NULL, truncation = NULL)gamma_dist(shape, rate, dim = NULL, truncation = NULL)
shape |
Shape parameter (positive numeric or |
rate |
Rate parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array.
## Not run: tau <- gamma_dist(shape = 2, rate = 1) ## End(Not run)## Not run: tau <- gamma_dist(shape = 2, rate = 1) ## End(Not run)
A high-level interface for specifying and fitting generalised linear models (including mixed / hierarchical models) using standard R formula syntax. Internally translates to the gretaR DSL, constructs the model, and runs MCMC inference.
lme4-style random effects are supported via regex parsing (lme4 is not required). Recognised patterns:
(1|group) — random intercepts by group (supported)
(0 + x|group) — independent random slopes, no intercept
(supported)
(x|group) — correlated random intercept + slope
(not yet supported; correct support requires an LKJ
correlation transform planned for v0.3)
As a workaround for correlated intercept + slope, split the term:
(1|group) + (0 + x|group) fits both as independent
random effects.
Multiple random effect terms are permitted, e.g.
y ~ x + (1|site) + (1|year).
A non-centred parameterisation is used by default for superior HMC geometry.
gretaR_glm( formula, data, family = c("gaussian", "binomial", "poisson"), prior = NULL, sampler = c("nuts", "hmc", "vi", "map"), chains = 4L, iter = 2000L, warmup = NULL, formula_style = NULL, verbose = TRUE, ... )gretaR_glm( formula, data, family = c("gaussian", "binomial", "poisson"), prior = NULL, sampler = c("nuts", "hmc", "vi", "map"), chains = 4L, iter = 2000L, warmup = NULL, formula_style = NULL, verbose = TRUE, ... )
formula |
A formula specifying the model (e.g., |
data |
A data frame containing the variables referenced in the formula. |
family |
Distribution family: |
prior |
A named list of gretaR distribution objects for parameter priors.
Recognised names: |
sampler |
Sampler: |
chains |
Number of MCMC chains (default 4). |
iter |
Total iterations per chain (warmup + samples, default 2000). |
warmup |
Number of warmup iterations (default half of iter). |
formula_style |
Optional explicit formula style hint: |
verbose |
Logical; print progress (default TRUE). |
... |
Additional arguments passed to the sampler. |
A gretaR_glm_fit object with components:
Posterior draws (from MCMC or VI).
The compiled gretaR_model.
The original formula.
The family used.
The original data.
The model matrix (fixed effects).
Named mapping of fixed-effect parameters.
List of parsed random effect specifications (NULL for base-style formulas).
## Not run: # Gaussian linear model fit <- gretaR_glm(Sepal.Length ~ Sepal.Width + Petal.Length, data = iris, family = "gaussian") summary(fit$draws) # Logistic regression dat <- data.frame(y = rbinom(100, 1, 0.6), x = rnorm(100)) fit <- gretaR_glm(y ~ x, data = dat, family = "binomial") # Custom priors fit <- gretaR_glm(y ~ x, data = dat, family = "gaussian", prior = list(beta = normal(0, 1), sigma = half_cauchy(1))) # Random intercepts model (lme4-style) sleepstudy <- data.frame( Reaction = rnorm(180, 300, 50), Days = rep(0:9, each = 18), Subject = factor(rep(1:18, times = 10)) ) fit <- gretaR_glm(Reaction ~ Days + (1 | Subject), data = sleepstudy, family = "gaussian") # Random intercept + independent random slope (workaround for (Days|Subject)) fit <- gretaR_glm(Reaction ~ Days + (1 | Subject) + (0 + Days | Subject), data = sleepstudy, family = "gaussian") ## End(Not run)## Not run: # Gaussian linear model fit <- gretaR_glm(Sepal.Length ~ Sepal.Width + Petal.Length, data = iris, family = "gaussian") summary(fit$draws) # Logistic regression dat <- data.frame(y = rbinom(100, 1, 0.6), x = rnorm(100)) fit <- gretaR_glm(y ~ x, data = dat, family = "binomial") # Custom priors fit <- gretaR_glm(y ~ x, data = dat, family = "gaussian", prior = list(beta = normal(0, 1), sigma = half_cauchy(1))) # Random intercepts model (lme4-style) sleepstudy <- data.frame( Reaction = rnorm(180, 300, 50), Days = rep(0:9, each = 18), Subject = factor(rep(1:18, times = 10)) ) fit <- gretaR_glm(Reaction ~ Days + (1 | Subject), data = sleepstudy, family = "gaussian") # Random intercept + independent random slope (workaround for (Days|Subject)) fit <- gretaR_glm(Reaction ~ Days + (1 | Subject) + (0 + Days | Subject), data = sleepstudy, family = "gaussian") ## End(Not run)
Create a half-Cauchy-distributed variable. A popular weakly informative prior for scale parameters (Gelman, 2006), with support on the positive reals.
half_cauchy(scale = 1, dim = NULL, truncation = NULL)half_cauchy(scale = 1, dim = NULL, truncation = NULL)
scale |
Scale parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array with support on the positive reals.
## Not run: sigma <- half_cauchy(1) tau <- half_cauchy(5) ## End(Not run)## Not run: sigma <- half_cauchy(1) tau <- half_cauchy(5) ## End(Not run)
Create a half-normal-distributed variable. The half-normal is the absolute value of a normal distribution, with support on the positive reals.
half_normal(sd = 1, dim = NULL, truncation = NULL)half_normal(sd = 1, dim = NULL, truncation = NULL)
sd |
Scale parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array with support on the positive reals.
## Not run: sigma <- half_normal(1) ## End(Not run)## Not run: sigma <- half_normal(1) ## End(Not run)
Convenience wrapper around mcmc that selects the
static Hamiltonian Monte Carlo sampler.
hmc(model, n_samples = 1000L, warmup = 1000L, chains = 4L, ...)hmc(model, n_samples = 1000L, warmup = 1000L, chains = 4L, ...)
model |
A |
n_samples |
Number of post-warmup samples per chain (default 1000). |
warmup |
Number of warmup (adaptation) iterations per chain (default 1000). |
chains |
Number of independent chains (default 4). |
... |
Additional arguments passed to |
A gretaR_fit object.
## Not run: m <- model(normal(0, 1)) fit <- hmc(m, n_samples = 500, warmup = 500) coef(fit) ## End(Not run)## Not run: m <- model(normal(0, 1)) fit <- hmc(m, n_samples = 500, warmup = 500) coef(fit) ## End(Not run)
Extract a torch-compatible function that evaluates the log
joint density of a compiled gretaR_model at a given parameter
vector in unconstrained space.
joint_density(model)joint_density(model)
model |
A |
A function f(theta) that takes a 1-D torch tensor of
unconstrained parameter values and returns a scalar torch tensor (the
log joint density).
## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3)) distribution(y) <- normal(mu, 1) m <- model(mu) ld <- joint_density(m) ld(torch::torch_zeros(1)) ## End(Not run)## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3)) distribution(y) <- normal(mu, 1) m <- model(mu) ld <- joint_density(m) ld(torch::torch_zeros(1)) ## End(Not run)
Approximate the posterior distribution using a multivariate normal centred at the MAP estimate with covariance equal to the inverse of the negative Hessian of the log-joint density.
laplace(model, map_fit = NULL, ...)laplace(model, map_fit = NULL, ...)
model |
A |
map_fit |
Optional output from |
... |
Additional arguments passed to |
A list with components:
Named numeric vector of posterior means (constrained).
Posterior means in unconstrained space.
Posterior covariance matrix (unconstrained space).
Named numeric vector of posterior standard deviations (unconstrained).
Approximate log marginal likelihood.
The MAP fit used.
## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) la <- laplace(m) la$mean la$sd ## End(Not run)## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) la <- laplace(m) la$mean la$sd ## End(Not run)
The LKJ distribution over correlation matrices (Lewandowski, Kurowicka,
and Joe, 2009). The density is proportional to
where is a correlation matrix. When , the
distribution is uniform over valid correlation matrices.
lkj_correlation(eta = 1, dim = 2L)lkj_correlation(eta = 1, dim = 2L)
eta |
Shape parameter (positive). Values > 1 concentrate mass around the identity matrix; values < 1 favour extreme correlations. |
dim |
Dimension of the correlation matrix (integer >= 2). |
A gretaR_array representing a correlation matrix.
Latent (sampled) LKJ variables are not yet supported because a
correct correlation-matrix transform (LKJ-Cholesky with the matching
Jacobian) is not yet implemented. model() will error if an LKJ
variable is reachable as a free parameter. The distribution can still
be evaluated (log_prob); sampler-ready support is planned for v0.3.
## Not run: R <- lkj_correlation(eta = 2, dim = 3) ## End(Not run)## Not run: R <- lkj_correlation(eta = 2, dim = 3) ## End(Not run)
A variable whose logarithm is normally distributed.
lognormal(meanlog = 0, sdlog = 1, dim = NULL, truncation = NULL)lognormal(meanlog = 0, sdlog = 1, dim = NULL, truncation = NULL)
meanlog |
Mean of the log-scale distribution. |
sdlog |
Standard deviation on the log scale (positive). |
dim |
Dimensions. |
truncation |
Optional length-2 numeric vector |
A gretaR_array with support on the positive reals.
## Not run: x <- lognormal(0, 1) ## End(Not run)## Not run: x <- lognormal(0, 1) ## End(Not run)
Run Hamiltonian Monte Carlo or the No-U-Turn Sampler on a
compiled gretaR_model and return posterior draws in a format
compatible with the posterior and bayesplot packages.
mcmc( model, n_samples = 1000L, warmup = 1000L, chains = 4L, sampler = c("nuts", "hmc"), backend = c("torch", "stan"), step_size = NULL, max_treedepth = 10L, n_leapfrog = 25L, target_accept = NULL, metric = c("diag", "dense"), init_values = NULL, seed = NULL, batched = FALSE, trajectory = c("fixed", "chees"), device = "cpu", verbose = TRUE )mcmc( model, n_samples = 1000L, warmup = 1000L, chains = 4L, sampler = c("nuts", "hmc"), backend = c("torch", "stan"), step_size = NULL, max_treedepth = 10L, n_leapfrog = 25L, target_accept = NULL, metric = c("diag", "dense"), init_values = NULL, seed = NULL, batched = FALSE, trajectory = c("fixed", "chees"), device = "cpu", verbose = TRUE )
model |
A |
n_samples |
Number of post-warmup samples per chain (default 1000). |
warmup |
Number of warmup (adaptation) iterations per chain (default 1000). |
chains |
Number of independent chains (default 4). |
sampler |
Sampler to use: |
backend |
Inference backend: |
step_size |
Initial step size for the leapfrog integrator. If
|
max_treedepth |
Maximum tree depth for NUTS (default 10). |
n_leapfrog |
Safety cap on leapfrog steps per static-HMC iteration
(default 25). HMC integrates for a random time |
target_accept |
Target average acceptance probability (default 0.8 for NUTS, 0.65 for HMC). |
metric |
Mass-matrix metric for the single-chain samplers, estimated
during warmup. |
init_values |
Optional list of initial parameter vectors (one per chain). |
seed |
Optional integer seed for reproducibility. Sets both R and torch random number generators. |
batched |
Logical (default |
trajectory |
Trajectory-length rule for the batched path ( |
device |
Character device for the batched path: |
verbose |
Logical; print progress information (default |
A gretaR_fit object with components:
Posterior draws as posterior::draws_array.
The compiled gretaR_model.
Posterior summary table (mean, sd, quantiles, R-hat, ESS).
List: n_eff, rhat, max_rhat, min_ess, n_divergences.
List of sampling arguments for reproducibility.
Elapsed seconds.
"nuts" or "hmc".
Use coef() for point estimates, summary() for full table,
plot() for diagnostics.
## Not run: # Simple normal model mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) draws <- mcmc(m, n_samples = 500, warmup = 500) summary(draws) ## End(Not run)## Not run: # Simple normal model mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) draws <- mcmc(m, n_samples = 500, warmup = 500) summary(draws) ## End(Not run)
Build an operation node that reduces a gretaR_array to a scalar by
averaging over all elements.
## S3 method for class 'gretaR_array' mean(x, ...)## S3 method for class 'gretaR_array' mean(x, ...)
x |
A |
... |
Ignored. |
A scalar gretaR_array.
Define a finite mixture of distributions. The mixture is marginalised over the discrete component indicator using the log-sum-exp trick, enabling gradient-based inference (HMC/NUTS).
mixture(distributions, weights)mixture(distributions, weights)
distributions |
A list of gretaR distribution objects (e.g.,
|
weights |
A gretaR_array or numeric vector of mixture weights
(must sum to 1). Typically from |
A distribution object suitable for use with distribution().
## Not run: # Two-component Gaussian mixture w <- dirichlet(c(1, 1)) mu1 <- normal(-2, 1); mu2 <- normal(2, 1) sigma <- half_cauchy(1) mix <- mixture( distributions = list(normal(mu1, sigma), normal(mu2, sigma)), weights = w ) y <- as_data(rnorm(100)) distribution(y) <- mix m <- model(w, mu1, mu2, sigma) ## End(Not run)## Not run: # Two-component Gaussian mixture w <- dirichlet(c(1, 1)) mu1 <- normal(-2, 1); mu2 <- normal(2, 1) sigma <- half_cauchy(1) mix <- mixture( distributions = list(normal(mu1, sigma), normal(mu2, sigma)), weights = w ) y <- as_data(rnorm(100)) distribution(y) <- mix m <- model(w, mu1, mu2, sigma) ## End(Not run)
Compile the computation graph defined by the specified target variables into a differentiable log-joint-density function suitable for HMC/NUTS inference.
model(..., precision = c("float32", "float64"))model(..., precision = c("float32", "float64"))
... |
|
precision |
Torch dtype: |
A gretaR_model object with log_prob() and
grad_log_prob() methods.
## Not run: alpha <- normal(0, 10) beta <- normal(0, 5) sigma <- half_cauchy(1) y <- as_data(rnorm(100)) x <- as_data(rnorm(100)) mu <- alpha + beta * x distribution(y) <- normal(mu, sigma) m <- model(alpha, beta, sigma) ## End(Not run)## Not run: alpha <- normal(0, 10) beta <- normal(0, 5) sigma <- half_cauchy(1) y <- as_data(rnorm(100)) x <- as_data(rnorm(100)) mu <- alpha + beta * x distribution(y) <- normal(mu, sigma) m <- model(alpha, beta, sigma) ## End(Not run)
Compile a computation graph into a gretaR_model the same
way model does, but with target parameters, their names, and
the likelihood passed explicitly rather than recovered from the call. This
makes model construction safe to perform programmatically – from
do.call(), a code generator, or another package building gretaR
models from its own representation – and re-entrant, since the likelihood
is scoped to the supplied data nodes instead of the whole session.
model_from_arrays( targets, likelihood = NULL, names = NULL, precision = c("float32", "float64") )model_from_arrays( targets, likelihood = NULL, names = NULL, precision = c("float32", "float64") )
targets |
A list of |
likelihood |
Optional. The data |
names |
Optional parameter names, one entry per element of
|
precision |
Torch dtype: |
model(alpha, beta, sigma) reads the names
"alpha", "beta", "sigma" by deparsing its call. A
programmatic caller has no stable way to reproduce that, and an interactive
one cannot override it. model_from_arrays() takes the targets as a
list and their names as a character vector (or as the names of the list),
so the parameter labels are whatever the caller chooses – the hook a host
package needs to map gretaR's internal names onto its own canonical scheme.
model() additionally folds in every distribution(y) <-
... assignment registered in the session, so two models built in the same
session share each other's likelihood terms unless the environment is reset
between them. model_from_arrays() instead includes only the
likelihood of the data nodes named in likelihood, leaving the global
registry untouched. Independent models can therefore be compiled in
sequence without interference.
The two front-ends delegate to the same internal compiler, so a model built
with model_from_arrays() is indistinguishable from the equivalent
model() call and is accepted everywhere a gretaR_model is –
mcmc, opt, joint_density.
A gretaR_model object, identical in structure to one produced
by model.
model for the interactive front-end.
## Not run: # Programmatic construction — names supplied, not deparsed. mu <- normal(0, 10) sigma <- half_cauchy(1) y <- as_data(rnorm(100, 3)) distribution(y) <- normal(mu, sigma) m <- model_from_arrays( targets = list(mu, sigma), likelihood = y, names = c("mu", "sigma") ) # Re-entrant: a second, independent model in the same session. theta <- normal(0, 1) z <- as_data(rnorm(50)) distribution(z) <- normal(theta, 1) m2 <- model_from_arrays(targets = list(theta), likelihood = z, names = "theta") ## End(Not run)## Not run: # Programmatic construction — names supplied, not deparsed. mu <- normal(0, 10) sigma <- half_cauchy(1) y <- as_data(rnorm(100, 3)) distribution(y) <- normal(mu, sigma) m <- model_from_arrays( targets = list(mu, sigma), likelihood = y, names = c("mu", "sigma") ) # Re-entrant: a second, independent model in the same session. theta <- normal(0, 1) z <- as_data(rnorm(50)) distribution(z) <- normal(theta, 1) m2 <- model_from_arrays(targets = list(theta), likelihood = z, names = "theta") ## End(Not run)
Create a multivariate-normal-distributed variable with the
specified mean vector and covariance matrix. If dim is NULL,
it is inferred from the length of mean.
multivariate_normal(mean, covariance, dim = NULL)multivariate_normal(mean, covariance, dim = NULL)
mean |
Numeric mean vector or |
covariance |
Covariance matrix (positive definite numeric matrix or
|
dim |
Integer vector of dimensions (inferred from |
A gretaR_array.
## Not run: mu <- c(0, 0) Sigma <- diag(2) x <- multivariate_normal(mean = mu, covariance = Sigma) ## End(Not run)## Not run: mu <- c(0, 0) Sigma <- diag(2) x <- multivariate_normal(mean = mu, covariance = Sigma) ## End(Not run)
Parameterised by the number of successes size (r) and the probability
of success prob (p). Models the number of failures before size
successes occur.
negative_binomial(size, prob, dim = NULL)negative_binomial(size, prob, dim = NULL)
size |
Target number of successes (positive numeric or gretaR_array). |
prob |
Probability of success per trial (0 to 1). |
dim |
Dimensions. |
A gretaR_array (discrete, non-negative integers).
## Not run: y <- negative_binomial(size = 5, prob = 0.5) ## End(Not run)## Not run: y <- negative_binomial(size = 5, prob = 0.5) ## End(Not run)
Create a normally-distributed variable with the specified mean and standard deviation. Support is on the entire real line.
normal(mean = 0, sd = 1, dim = NULL, truncation = NULL)normal(mean = 0, sd = 1, dim = NULL, truncation = NULL)
mean |
Mean of the distribution (numeric or |
sd |
Standard deviation (numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array representing a normally-distributed variable.
## Not run: x <- normal(0, 1) beta <- normal(0, 5, dim = c(3, 1)) x_pos <- normal(0, 1, truncation = c(0, Inf)) ## End(Not run)## Not run: x <- normal(0, 1) beta <- normal(0, 5, dim = c(3, 1)) x_pos <- normal(0, 1, truncation = c(0, Inf)) ## End(Not run)
Convenience wrapper around mcmc that selects the
No-U-Turn Sampler (NUTS).
nuts(model, n_samples = 1000L, warmup = 1000L, chains = 4L, ...)nuts(model, n_samples = 1000L, warmup = 1000L, chains = 4L, ...)
model |
A |
n_samples |
Number of post-warmup samples per chain (default 1000). |
warmup |
Number of warmup (adaptation) iterations per chain (default 1000). |
chains |
Number of independent chains (default 4). |
... |
Additional arguments passed to |
A gretaR_fit object.
## Not run: m <- model(normal(0, 1)) fit <- nuts(m, n_samples = 500, warmup = 500) coef(fit) ## End(Not run)## Not run: m <- model(normal(0, 1)) fit <- nuts(m, n_samples = 500, warmup = 500) coef(fit) ## End(Not run)
Optimise the log-joint density using gradient-based methods to find the posterior mode. Uses the Adam optimiser via torch.
opt( model, max_iter = 2000L, learning_rate = 0.01, tolerance = 1e-06, init = NULL, verbose = TRUE, backend = c("torch", "stan"), seed = NULL )opt( model, max_iter = 2000L, learning_rate = 0.01, tolerance = 1e-06, init = NULL, verbose = TRUE, backend = c("torch", "stan"), seed = NULL )
model |
A |
max_iter |
Maximum number of optimisation iterations (default 2000). |
learning_rate |
Adam learning rate (default 0.01). |
tolerance |
Convergence tolerance on relative change in log-prob (default 1e-6). |
init |
Optional initial values (numeric vector in unconstrained space). |
verbose |
Logical; print progress (default TRUE). |
backend |
Inference backend: |
seed |
Optional integer seed for reproducibility. |
A gretaR_fit object (method = "map") with components:
Named numeric vector of MAP estimates (constrained space).
Numeric vector of MAP in unconstrained space.
Log-joint density at the MAP.
List with convergence info.
Number of iterations used.
## Not run: mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) fit <- opt(m) fit$par ## End(Not run)## Not run: mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) fit <- opt(m) fit$par ## End(Not run)
Extracts all (expr | group) terms and classifies them as
"intercept", "slope_only", or "intercept_slope".
parse_re_bars(formula)parse_re_bars(formula)
formula |
A formula potentially containing bar terms. |
A list of parsed random effect specifications. Each element is a
list with components: raw (original text), lhs (left of
bar), group (grouping variable), type (one of
"intercept", "slope_only", "intercept_slope"),
and slope_vars (character vector of slope variable names, may
be empty).
parse_re_bars(y ~ x + (1 | group)) parse_re_bars(y ~ x + (x | group)) parse_re_bars(y ~ x + (0 + x | group)) parse_re_bars(y ~ x + (1 | site) + (1 | year))parse_re_bars(y ~ x + (1 | group)) parse_re_bars(y ~ x + (x | group)) parse_re_bars(y ~ x + (0 + x | group)) parse_re_bars(y ~ x + (1 | site) + (1 | year))
Generate diagnostic plots for MCMC or VI posterior draws.
Requires the bayesplot package.
## S3 method for class 'gretaR_fit' plot(x, type = c("trace", "density", "pairs", "rhat", "neff"), ...)## S3 method for class 'gretaR_fit' plot(x, type = c("trace", "density", "pairs", "rhat", "neff"), ...)
x |
A |
type |
Plot type: |
... |
Additional arguments passed to the bayesplot function. |
A ggplot object.
## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) fit <- mcmc(m, n_samples = 200, warmup = 200, chains = 2) plot(fit, type = "trace") ## End(Not run)## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) fit <- mcmc(m, n_samples = 200, warmup = 200, chains = 2) plot(fit, type = "trace") ## End(Not run)
Create a Poisson-distributed variable with the specified rate.
Named poisson_dist to avoid conflict with stats::poisson.
poisson_dist(rate, dim = NULL)poisson_dist(rate, dim = NULL)
rate |
Rate parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
A gretaR_array.
## Not run: y <- poisson_dist(rate = 5) ## End(Not run)## Not run: y <- poisson_dist(rate = 5) ## End(Not run)
Display a concise summary of the model fit including method, parameter count, convergence diagnostics, and timing.
## S3 method for class 'gretaR_fit' print(x, ...)## S3 method for class 'gretaR_fit' print(x, ...)
x |
A |
... |
Ignored. |
x, invisibly.
Extract and construct smooth terms from a formula containing
s(), te(), ti(), or t2() terms. Requires the mgcv package.
Uses the smooth2random decomposition (same approach as brms) to
convert penalised smooth bases into fixed + random effect components
suitable for HMC/NUTS sampling.
process_smooths(formula, data, knots = NULL)process_smooths(formula, data, knots = NULL)
formula |
A formula potentially containing smooth terms. |
data |
A data frame with the covariates. |
knots |
Optional named list of knot locations. |
A list with components:
The formula with smooth terms removed (parametric part).
Combined fixed-effects design matrix from all smooths (n x p_fixed).
List of random-effects design matrices (each n x p_j).
List of metadata for each smooth (label, type, rank, etc.).
Number of smooth fixed-effect columns.
List of dimensions per random-effect block.
## Not run: library(mgcv) dat <- data.frame(y = rnorm(100), x = rnorm(100)) sm <- process_smooths(y ~ s(x, k = 10), data = dat) str(sm) ## End(Not run)## Not run: library(mgcv) dat <- data.frame(y = rnorm(100), x = rnorm(100)) sm <- process_smooths(y ~ s(x, k = 10), data = dat) str(sm) ## End(Not run)
Construct a grouped random-effect term with an explicit
centring weight that interpolates between the non-centred and centred
parameterisations. The weight controls only the sampling geometry seen by
the HMC/NUTS sampler – the implied prior on the group effects,
, is identical for every
weight – so it is a pure efficiency control for hierarchical models whose
mixing is bottlenecked by the funnel coupling between a group-scale
parameter and its latent effects.
random_effect(group, n_groups, sd, centring = 0, mean = 0)random_effect(group, n_groups, sd, centring = 0, mean = 0)
group |
Integer vector of length |
n_groups |
Number of groups |
sd |
A scalar |
centring |
The centring weight |
mean |
The random-effect mean, a numeric scalar or scalar
|
A centring weight w = 0 gives the non-centred form
with
, which mixes well when groups are weakly informed.
A weight w = 1 gives the centred form
with
, which mixes well when groups are
strongly informed. Intermediate and per-group weights interpolate:
which leaves unchanged. The
informativeness-optimal weight for a balanced group of
observations with residual scale is
; a
data-adaptive sampler estimates it during warmup, but a fixed value may be
supplied directly here.
The returned latent block $latent is the free parameter the sampler
moves and must be passed to model_from_arrays (or
model); the returned $effect is the per-observation
effect to add into the linear predictor. The latent block carries the
group-level names, not the observation-level ones.
A list of class gretaR_random_effect with elements
latentThe -element latent gretaR_array to
include in the model's target list.
effectThe -element per-observation effect
gretaR_array for the linear predictor.
centringThe resolved per-group weight vector.
n_groupsThe number of groups.
model_from_arrays for the programmatic model
front-end the latent block is designed for.
## Not run: # Random-intercept model, near-centred (informative groups). n <- 1000L J <- 20L g <- rep(seq_len(J), length.out = n) x <- rnorm(n) y <- as_data(1.5 - 0.8 * x + rnorm(n)) b0 <- normal(0, 5) b1 <- normal(0, 5) s <- half_normal(5) tau <- half_normal(2) re <- random_effect(g, n_groups = J, sd = tau, centring = 0.9) eta <- b0 + b1 * as_data(x) + re$effect distribution(y) <- normal(eta, s) m <- model_from_arrays( list(b0, b1, s, tau, re$latent), likelihood = y, names = list("b0", "b1", "s", "tau", paste0("u[", seq_len(J), "]")) ) ## End(Not run)## Not run: # Random-intercept model, near-centred (informative groups). n <- 1000L J <- 20L g <- rep(seq_len(J), length.out = n) x <- rnorm(n) y <- as_data(1.5 - 0.8 * x + rnorm(n)) b0 <- normal(0, 5) b1 <- normal(0, 5) s <- half_normal(5) tau <- half_normal(2) re <- random_effect(g, n_groups = J, sd = tau, centring = 0.9) eta <- b0 + b1 * as_data(x) + re$effect distribution(y) <- normal(eta, s) m <- model_from_arrays( list(b0, b1, s, tau, re$latent), likelihood = y, names = list("b0", "b1", "s", "tau", paste0("u[", seq_len(J), "]")) ) ## End(Not run)
Returns the fixed-effects-only formula by stripping all (expr|group)
terms. If reformulas is installed, delegates to
reformulas::nobars(); otherwise falls back to lme4::nobars(),
and finally to regex substitution.
remove_re_bars(formula)remove_re_bars(formula)
formula |
A formula potentially containing bar terms. |
A formula with bar terms removed.
remove_re_bars(y ~ x + (1 | group)) # y ~ xremove_re_bars(y ~ x + (1 | group)) # y ~ x
Clear all tracked nodes, distributions, and reset the node counter. Called automatically on package load; call manually to start a fresh model definition.
reset_gretaR_env()reset_gretaR_env()
Invisible NULL.
## Not run: reset_gretaR_env() ## End(Not run)## Not run: reset_gretaR_env() ## End(Not run)
Create a Student-t-distributed variable with the specified degrees of freedom, location, and scale. Useful as a robust alternative to the normal distribution.
student_t(df = 3, mu = 0, sigma = 1, dim = NULL, truncation = NULL)student_t(df = 3, mu = 0, sigma = 1, dim = NULL, truncation = NULL)
df |
Degrees of freedom (positive numeric or |
mu |
Location parameter (numeric or |
sigma |
Scale parameter (positive numeric or |
dim |
Integer vector of dimensions (default scalar). |
truncation |
Optional length-2 numeric vector |
A gretaR_array.
## Not run: x <- student_t(df = 3, mu = 0, sigma = 1) ## End(Not run)## Not run: x <- student_t(df = 3, mu = 0, sigma = 1) ## End(Not run)
Build an operation node that reduces a gretaR_array to a scalar by
summing over all elements.
## S3 method for class 'gretaR_array' sum(x, ..., na.rm = FALSE)## S3 method for class 'gretaR_array' sum(x, ..., na.rm = FALSE)
x |
A |
... |
Ignored. |
na.rm |
Ignored (no NAs in torch). |
A scalar gretaR_array.
Compute or display detailed posterior summary statistics and convergence diagnostics.
## S3 method for class 'gretaR_fit' summary(object, ...)## S3 method for class 'gretaR_fit' summary(object, ...)
object |
A |
... |
Additional arguments passed to |
A data frame of posterior summaries (from posterior::summarise_draws()),
or a list for MAP/Laplace fits.
## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) fit <- mcmc(m, n_samples = 200, warmup = 200, chains = 2) summary(fit) ## End(Not run)## Not run: mu <- normal(0, 10) y <- as_data(rnorm(50, 3, 1)) distribution(y) <- normal(mu, 1) m <- model(mu) fit <- mcmc(m, n_samples = 200, warmup = 200, chains = 2) summary(fit) ## End(Not run)
Create a uniformly-distributed variable on the interval
[lower, upper].
uniform(lower = 0, upper = 1, dim = NULL)uniform(lower = 0, upper = 1, dim = NULL)
lower |
Lower bound (numeric). |
upper |
Upper bound (numeric). |
dim |
Integer vector of dimensions (default scalar). |
A gretaR_array.
## Not run: p <- uniform(0, 1) ## End(Not run)## Not run: p <- uniform(0, 1) ## End(Not run)
Create an unconstrained or constrained variable without a distributional prior. Useful for deterministic transformations or parameters that do not require a prior.
variable(lower = -Inf, upper = Inf, dim = NULL)variable(lower = -Inf, upper = Inf, dim = NULL)
lower |
Lower bound (default |
upper |
Upper bound (default |
dim |
Integer vector of dimensions (default |
A gretaR_array variable node.
## Not run: x <- variable() x_pos <- variable(lower = 0) x_bounded <- variable(lower = 0, upper = 1) ## End(Not run)## Not run: x <- variable() x_pos <- variable(lower = 0) x_bounded <- variable(lower = 0, upper = 1) ## End(Not run)
Fit a model using Automatic Differentiation Variational Inference. Approximates the posterior with a multivariate Gaussian in unconstrained parameter space.
variational( model, n_samples = 1L, max_iter = 5000L, learning_rate = 0.01, tolerance = 1e-04, method = c("meanfield", "fullrank"), init_from_map = TRUE, seed = NULL, verbose = TRUE )variational( model, n_samples = 1L, max_iter = 5000L, learning_rate = 0.01, tolerance = 1e-04, method = c("meanfield", "fullrank"), init_from_map = TRUE, seed = NULL, verbose = TRUE )
model |
A |
n_samples |
Number of Monte Carlo samples per ELBO gradient estimate (default 1). |
max_iter |
Maximum number of optimisation iterations (default 5000). |
learning_rate |
Adam learning rate (default 0.01). |
tolerance |
Convergence tolerance on relative ELBO change (default 1e-4). |
method |
Variational family: |
init_from_map |
Logical; initialise from MAP estimate (default TRUE). |
seed |
Optional integer seed for reproducibility. Sets both R and torch random number generators. |
verbose |
Logical; print progress (default TRUE). |
A gretaR_fit object (method = "vi") with standard fields plus:
Named vector of posterior means (constrained space).
Named vector of posterior SDs (unconstrained space).
Posterior covariance matrix (unconstrained, fullrank only).
Vector of ELBO values per iteration.
A posterior::draws_array of samples from the variational posterior.
Logical; did the optimiser converge?
## Not run: mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) fit <- variational(m) coef(fit) ## End(Not run)## Not run: mu <- normal(0, 10) sigma <- half_cauchy(2) y <- as_data(rnorm(50, 3, 1.5)) distribution(y) <- normal(mu, sigma) m <- model(mu, sigma) fit <- variational(m) coef(fit) ## End(Not run)
The Wishart distribution over positive-definite matrices. Used as a prior for covariance or precision matrices.
wishart(df, scale_matrix)wishart(df, scale_matrix)
df |
Degrees of freedom (must be >= dimension of scale matrix). |
scale_matrix |
Scale matrix (positive definite, p x p). |
A gretaR_array representing a positive-definite matrix.
Latent (sampled) Wishart variables are not yet supported because a
correct positive-definite-matrix transform (Cholesky factor with
positive diagonal plus the matching Jacobian) is not yet implemented.
model() will error if a Wishart variable is reachable as a free
parameter. The distribution can still be evaluated (log_prob);
sampler-ready support is planned for v0.3.
## Not run: Sigma <- wishart(df = 5, scale_matrix = diag(3)) ## End(Not run)## Not run: Sigma <- wishart(df = 5, scale_matrix = diag(3)) ## End(Not run)