Register a brms Custom Family with the hbsaems Model Registry
Source:R/register-custom-brms.R
register_hbsae_brms_custom.RdWraps a brms::custom_family + stanvars pair into a model
spec usable by hbm and the flexible factory
hbm_flex. The custom likelihood is then available
throughout the package – in run_sae_app, in
sae_predict, in the Shiny application, and so on – as if it
were a built-in family.
Usage
register_hbsae_brms_custom(
key,
custom_family,
stanvars,
response_check = NULL,
response_check_msg = NULL,
supports_mi = FALSE,
discrete = FALSE,
overwrite = FALSE
)Arguments
- key
Character. Unique registry key (e.g.\
"loglogistic").- custom_family
A
brms::custom_familyobject describing the parameters, links, and constraints of the distribution. Typically produced bybrms::custom_family()or by a helper such asbrms_custom_loglogistic.- stanvars
A
brms::stanvarsobject containing the Stan-side function definitions (log-PDF / log-CDF / RNG).- response_check
Optional function
function(y) -> logicalfor response-domain validation (e.g.\ positivity check for the loglogistic).- response_check_msg
Character. Error message if
response_checkfails.- supports_mi
Logical. Whether
brms::mi()can impute the response under this likelihood (defaultFALSE; custom families typically do not supportmi()).- discrete
Logical. Whether the family is discrete (default
FALSE).- overwrite
Logical. If
TRUE, replace an existing entry with the samekey.
Details
After registration, the family is usable in any of the following ways:
# Direct via the registry key
fit <- hbm_flex("loglogistic", response = "y",
auxiliary = c("x1", "x2"),
data = d, area_var = "area")
# Direct via hbm() (canonical):
fit <- hbm(brms::bf(y ~ x1 + x2 + (1 | area)),
data = d,
hb_sampling = "loglogistic")Internally, hbm detects that the registered family is a
brms::custom_family and (i) passes the family object directly to
brms::brm() instead of constructing a built-in
brms::brmsfamily(), and (ii) merges the family's stanvars with
any user-supplied stanvars.
Examples
# \donttest{
library(hbsaems)
library(brms)
# Loglogistic (built in to hbsaems 1.0.0; this just shows the
# registration mechanism). We use a key with a "_user" suffix to
# avoid shadowing the built-in "loglogistic" entry, and unregister
# at the end so re-running this example block keeps the registry
# clean.
ll <- brms_custom_loglogistic()
if ("loglogistic_user" %in% list_hbsae_models()) {
# Idempotent rerun: remove any previous registration first.
rm("loglogistic_user", envir = hbsaems:::.hbsae_model_env)
}
register_hbsae_brms_custom(
key = "loglogistic_user",
custom_family = ll$custom_family,
stanvars = ll$stanvars_family,
response_check = function(y) all(y > 0, na.rm = TRUE),
response_check_msg = "Loglogistic response must be positive."
)
"loglogistic_user" %in% list_hbsae_models()
#> [1] TRUE
# Cleanup so the registry is unchanged after the example runs.
rm("loglogistic_user", envir = hbsaems:::.hbsae_model_env)
# }