Set up a model formula for use in the
bayesnec package, allowing linear
and non-linear (potentially multi-level) concentration-response
models to be defined.
bayesnecformula(formula, ..., env = parent.frame())Either a character string defining an
R formula or an actual formula object. See details.
Unused.
An environment in which to resolve symbols
that formula names but that are not columns of the data — a
variable holding the model set, or an R function needed to transform the
predictor. Only used when formula is a character string, because a
formula object already carries its own environment. Defaults to the calling
environment, so a character formula passed down through a wrapper function
is bound at the last call rather than where the string was written; where
that matters, convert it with bnf(string, env = ...) and pass the
result on.
An object of class bayesnecformula and
formula.
See methods(class = "bayesnecformula") for an overview of
available methods.
General formula syntax
The formula argument accepts formulas of the following syntax:
response | aterms ~ crf(x, model) + glterms
The population-level term: crf
bayesnec uses a special internal
term called crf, which sets the concentration-response equation
to be evaluated based on some x predictor. The equation itself is
defined by the argument "model": a character
vector containing a specific model, a concatenation of specific models,
a single string defining a particular group of models, or a named list of
equation formulas returned by models. Internally
this argument is substituted by an actual brmsformula,
which is then passed onto brm for model fitting.
The model argument may be a variable rather than a literal, so that
the set can be assembled before the formula is written — eqs <-
c("nec3param", "ecxll3"); bnf(y ~ crf(x, eqs)). It is resolved in the
environment the formula was written in, which for a formula supplied as a
character string means the environment given by env. The same applies
on the R side to a function used to transform the predictor inside
crf. Resolving that function in R does not define it in Stan: the
function call must also be valid Stan syntax, either because Stan provides
it or because the corresponding Stan function is supplied through
stanvars. Otherwise, transform the predictor in the data first.
The predictor is read as a model formula reads it. Parentheses around it
and a unary plus are dropped, so crf((log(x))) is
crf(log(x)). A formula operator at its top level, as in
crf(-x), crf(x - 1), crf(log(x) + 1) or
crf(x^2), is refused, because a model formula reads it as formula
syntax, not as arithmetic: the model would be fitted on x, or on
log(x). The operators are +, -, *, /,
:, ^ and %in%. Where arithmetic is meant, write it
inside I(), as in crf(I(x - 1)) or crf(I(-x)), or
compute it into a column of the data. Stan has no I(), so the
formula passed to brms holds the expression inside it, in
parentheses, including where I() is nested inside another call.
An operator inside a function call is arithmetic and is
accepted, as in crf(log(x + 1)).
Group-level terms: glterms
The user has three options to define group-level effects in a
bayesnecformula: 1) a general "offset" group-level effect
defined by the term ogl (as in e.g. ogl(group_variable)). This
adds an additional population-level parameter ogl to the model defined
by crf, analogously to an intercept-only group-level effect
in a classic linear model. 2) A group-level effect applied to all
parameters in a model at once. This is done by the special term pgl,
(as in e.g. pgl(group_variable)), which comes in handy so the user
does not need to know the internal syntax and name of each parameter in the
model. 3) A more classic approach where the user can specify which
specific parameters — NB: that requires prior knowledge on the model
structure and parameter names — to vary according to a grouping variable
(as in e.g. (bot | group_variable)). A term naming a parameter an
equation does not have is left out of that equation, but each equation must
keep at least one group-level term on every grouping variable such a term
names; an ogl() or pgl() term on the variable counts. An
equation that keeps none would be fitted as one curve pooled over the levels
of the variable while the rest of the set fits the curve of a typical level,
so bnec excludes it before fitting, with a message, and records
the reason (see bnec_record). A call from which every equation
is excluded is refused. For example, the parameter bot exists in
model "nec4param" but not in "nec3param", so if the user
specifies model = "nec" in crf, the term
(bot | group_variable) excludes "nec3param", which would keep
no term on group_variable. Under
(bot | group_variable) + (nec | group_variable), "nec3param"
is fitted with the term on nec alone, and "nec4param" with
both.
The grouping inside ogl() and pgl() uses the formula operators
accepted on the right of the bar in a brms group-level term. The terms
are expanded before they are passed to brms. ogl(a/b) fits one
deviation per level of a and a further one per level of b
within each level of a, as (1 | a/b) does. ogl(a:b) fits one per
combination of the two. ogl(a + b) is two separate terms,
(1 | a) + (1 | b), the same as ogl(a) + ogl(b).
ogl(a*b) also includes (1 | a:b).
The grouping inside ogl() and pgl() may also be a
gr call. pgl(gr(plate, by = toxicant)) fits a
separate standard deviation of the plate deviations for each level of
toxicant, which suits a grouping whose levels each belong to one
level of toxicant. A gr() call on the right of the bar in a
(par | group) term is not supported; use pgl() or
ogl().
A grouping whose levels are each observed at a single concentration, such
as the replicate vessels at each concentration, changes how the model
weights are computed: each level is left out whole, rather than each
observation. See the loo_controls argument and Details of
bnec.
The scale a group-level deviation is applied on
brms declares a group-level deviation unconstrained, and under the
"identity" link bnec assigns, the quantity it is added
to often is not. Where the likelihood restricts the range of the mean —
every family except gaussian — the deviation is therefore applied
multiplicatively rather than added, so that no proposal can put the
quantity outside the range in which the model is defined. On a 0 to
1 response it scales the odds and on a positive response it scales the
value itself. This applies to ogl, where the deviation is on the whole
curve, and to a term on top or bot, which are the two
parameters bounded to the support of the mean. A deviation on nec,
ec50, beta, slope, d or f is added, as
none of those is bounded by the likelihood. A pgl term places a
deviation on every parameter at once and so generates a mixture of the two.
The deviation is centred on zero and a deviation of zero leaves the value
unchanged, so top, bot, nec and beta keep their
meanings and their own priors. A deviation on top or bot adds
no population-level term of its own, so the fit has exactly the parameters the
additive form had and bot remains the asymptote the population-level
curve declines towards. A prior the user supplies for top or
bot must bound it to the range the mean is defined on, because the
multiplicative form is defined only inside that range; a prior that does not
is refused with a message naming the bounds to add. What changes is the name the standard deviation
is reported under: a term on bot is summarised as
sd(botgl_Intercept) rather than sd(bot_Intercept), and it is on
the log-odds or log scale rather than on the response scale. The generated
term names ogl, bnecmu, topgl, botgl,
bnectop and bnecbot are refused as data column names, because
brms would resolve a column of that name in place of the generated term.
See vignette("example3").
Dispersion sub-models: disp
By default a fit holds the family's dispersion parameter constant across the
whole concentration-response curve. The special term disp lets that
parameter vary, and takes one of two forms.
disp(~x) models dispersion as a function of the predictor —
an ordinary brms distributional formula, e.g. disp(~log(x)) or
disp(~s(x)). Inside disp() a function call may not be
followed by another term: write disp(~z + s(x)) rather than
disp(~s(x) + z), or compute the term as a column of the data. Form
is descriptive: it says noise is larger at one end of the dose axis.
disp("power") models dispersion as a function of the mean
curve — a variance function in the GLM sense, and a statement about the
measurement process rather than about the dose axis. The functions available,
on the log link every eligible family gives its dispersion parameter, with
m a fixed reference value computed from the response before fitting,
on the scale of mu (a count divided by its number of trials or by its
rate() denominator):
| name | form | families |
"power" | log(dpar) = c0 + c1 * (log(mu) - log(m)) | all eligible |
"twosided" | log(phi) = c0 + c1 * (log(mu) - log(m)) + c2 * (log(1 - mu) - log(1 - m)) | Beta, beta_binomial |
"loglinear" | log(dpar) = c0 + c1 * (mu - m) | all eligible |
Form 2) requires the mean to be modelled on its natural scale; see the
identity-link note in bnec. Form 1) is an ordinary
distributional formula and is valid under any link.
Form 1) may name a column other than the predictor, as in disp(~z),
which fits a dispersion parameter for each level of a factor z, or
one that changes with a numeric z. brms needs z
wherever it predicts, so every prediction grid bayesnec builds holds
it. The fitted curve stored on a fit, ecx,
nec, nsec and ecnsec take
z at one fixed value: the first level of a factor, or the median of
a numeric column. The mean of every family the term can be fitted for does
not involve the dispersion parameter, so that value does not change them.
bnec_newdata writes the same value and marks the column as a
placeholder. posterior_predict and predict
replace a marked column draw by draw with the value of a row sampled from
the data the fit was made from, so a predicted reading is one from the
design's mix of z rather than from its first level. A
newdata without z is refused with a message naming it. The
term is refused for a negbinomial growth component of
bnec_hurdle and for the hurdle_negbinomial family,
whose curves are the mean of the zero-truncated counts, or that mean
multiplied by 1 - hu, and so depend on the shape parameter.
Where the formula also has an ogl() term, mu in form 2) is the
curve before the group-level deviation is applied, not the fitted mean of
the group. The deviation therefore changes the mean of each group without
changing its dispersion parameter. The observation variance can still
change with the fitted mean; for Gamma it is the squared fitted mean divided
by the shape. A deviation on a parameter, as in (bot | group) or
pgl(group), changes the curve itself, and so is included in the
variance function as well. Reading the fitted mean after an ogl()
deviation can produce a second posterior mode at a very low mean when
"power" on a Gamma response has c1 > 1. This occurred
in a fit to the zinc bioluminescence data of the article
Grouping and factor covariates
(https://open-aims.github.io/bayesnec/articles/example8.html).
A dispersion sub-model requires a family with a free dispersion parameter.
For poisson, bernoulli and binomial the variance is a
deterministic function of the mean and there is nothing to model;
over-dispersion there is remedied by changing family (poisson to
negbinomial, binomial to beta_binomial) or by an
observation-level group-level effect. Those are exactly the families the
dispersion diagnostic applies to, so the two are complements
rather than alternatives.
Of the two-block families, hurdle_gamma, zero_inflated_beta
and hurdle_negbinomial take a dispersion sub-model on their positive
block, a Gamma, Beta or zero-truncated negbinomial
distribution, and m is computed from the positive responses; see
bnec. hurdle_poisson has no dispersion parameter to
model.
What the exponent means depends on the family, because each family already imposes its own mean-variance link. The form above is written for the dispersion parameter itself, which is what brms fits:
Writing r = mu / m for the response relative to the reference, and
taking "power" for concreteness:
| family | parameter | implied variance | constant CV at |
gaussian | sigma | (exp(c0) * r^c1)^2 | c1 = 1 |
Gamma | shape | mu^2 / (exp(c0) * r^c1) | c1 = 0 |
negbinomial | shape | mu + mu^2 / (exp(c0) * r^c1) | -- |
Beta, beta_binomial | phi | mu * (1 - mu) / (1 + exp(c0) * r^c1) | -- |
In every case c1 = 0 returns the constant-dispersion model, which is
where the default prior on c1 is centred.
Under "power" that prior is normal(0, 2) restricted to a range
of c1 that depends on the family. The range is derived from a
variance proportional to mu^b with b between 0 and 2, which
runs from a constant variance to a constant coefficient of variation:
| family | range of c1 | at the two ends |
Gamma | 0 to 2 | constant CV; constant variance |
gaussian | 0 to 1 | constant variance; constant CV |
negbinomial | 0 to 1 | overdispersion proportional to mu^2; to mu |
Beta, beta_binomial | unbounded | -- |
Outside the range for a Gamma or gaussian response, the variance function
describes a variance that rises as the mean falls, or a coefficient of
variation that falls as the mean falls. For a negative binomial response
above 1, the overdispersion term would grow more slowly than the Poisson
part of the variance. The beta families are not bounded, because their
variance already falls towards both ends of the unit interval through
mu * (1 - mu), and their precision can plausibly rise in either
direction, which is what "twosided" models. Neither slope of
"twosided" is bounded, nor is the slope of "loglinear", which
is in units of one over the response. A two-block family takes the range of
its positive block's family.
The range is a hard bound on the parameter, as the support of the response
is for top and bot. A posterior for c1 concentrated
against one end of it is evidence that the data do not follow the range; a
prior on c1 supplied through the prior argument of
bnec replaces the default, bounds included. Under
prior_type = "regularizing" the prior is centred on the slope the
replicates show rather than on zero; see bnec.
Both "power" and "twosided" take log(mu), so a fitted
mean that reaches zero is undefined. This rules them out for a response on
the real line — a specific growth rate, yield or increment can be negative —
and bnec refuses the combination rather than failing at
initialisation, pointing at "loglinear" or disp(~x) instead.
Worked guidance — how to decide whether a dispersion sub-model is warranted,
why the covariate is centred, and how the forms differ in practice — is given
in vignette("example1").
Further brms terms (largely untested)
Currently bayesnecformula is quite agnostic about additional
terms that are valid for a brmsformula. These are
aterms and pterms (see ?brmsformula).
The only capability that bayesnecformula does not allow is
the addition of pterms outside of the term crf. Although
pterms can be passed to predictor x within crf, we
strongly discourage their use because those functionalities have not
been tested yet. If this is extremely important to your work, please
raise an issue on bayesnec GitHub, and we will consider further testing and
development.
Currently, the only four aterms that have validated behaviour are:
trials(), which is essential in binomially-distributed data, e.g.
y | trials(trials_variable), 2) weights, e.g.
y | weights(weights_variable), 3) cens() (see below), and
rate() (see below), following brms formula syntax.
Any other aterm is an error rather than a warning: an aterm
bayesnec has not validated cannot be assumed to behave sensibly
through the prior generation, initial-value search and post-processing that
follow.
Rates and exposure
rate(denominator) declares that the response is a count observed over
an exposure — animals per unit time, larvae per unit area — and is valid
for the poisson and negbinomial families only. Any other
family is an error when the family is known, the zero-inflated count
families included: brms cannot place a rate denominator on those, and
under bnec's identity link there is no offset that would do
the same job. The check necessarily needs a family to check against, so it
fires on every path that fits — bnec always supplies one —
but not on a bare make_brmsformula(formula, data) call, which
has no family to validate and builds the formula unchecked.
Because bnec fits on link = "identity", which it
assigns unless a link argument is written, brms
writes the denominator multiplicatively on the response scale rather than as
a log offset on the linear predictor, so the mean is the rate,
"top" and "bot" stay directly interpretable as counts per unit exposure, and
"nec" stays a concentration. The prediction grid holds the denominator at 1, so a fitted curve,
an ecx and an nsec are all read on the rate
scale; plots put the observations on that same scale by dividing through.
offset is deliberately not offered as an alternative — under an
identity link it would be additive on the mean, which is not what is wanted.
The denominator must be a column of the data. An expression such as
rate(hours / 24) is an error, because bayesnec records the
denominator as a plain column and reads that column when it builds the
default priors, pins the prediction grid at a denominator of 1, and puts the
observations on the rate scale for a plot; an expression is not recorded
there, so each of them would divide by hours while brms divided
by the quotient. Compute the column before the call and name it in
rate().
Please note that brms does not implement design weights as in other
standard base functions. From their help page, brms "takes the
weights literally, which means that an observation with weight 2 receives 2
times more weight than an observation with weight 1. It also means that
using a weight of 2 is equivalent to adding the corresponding observation
twice to the data frame". Other aterms might be added, though we
cannot attest to their functionality within
bayesnec, i.e. checks will
be done outside via brm.
Censored responses: cens
A response that is rounded at the recording resolution, reported below a
limit of detection, or deliberately coarsened at a boundary is censored: the
true value is known to lie in an interval rather than at a point. The
cens() aterm states this, e.g.
y | cens(censoring_variable), or
y | cens(censoring_variable, upper_bound) for interval censoring.
censoring_variable is a variable in the data taking the values
"none", "left", "right" or "interval"
(equivalently 0, -1, 1, 2); it is not a constant,
because in a concentration-response dataset only some rows are censored.
The response value carries the bound. For a left-censored row the
number in the response column is the value the truth is known to be at or
below — not zero, and not a substitute for the unknown truth. Because of
this, a censored row is exempt from the boundary shifts that
bnec otherwise applies to zeros in Gamma and Beta responses:
the bound has already been declared and moving it would restate it. A row
declared censored at a value the family excludes — left-censored at 0 under
Gamma or Beta, right-censored at 1 under Beta — is an error rather than a
shift, because the censored likelihood is degenerate there.
In a direct two-block bnec fit, left censoring of the total
response includes the zero outcome. For a survivor known to have a positive
response below the bound, bnec_hurdle records survival
separately. bnec_joint keeps that distinction for a Gamma
refit and refuses a zero-inflated Beta refit with left-censored survivors.
NB: aterms other than trials(), weights() and
cens() are currently omitted from model.frame output. If
you need other aterms as part of that output please raise an issue on
our GitHub page.
Validation of formula
Please note that the function only checks for the input nature of the
formula argument and adds a new class. This function does not
perform any validation on the model nor checks on its adequacy to work with
other functions in the package. For that please refer to the function
check_formula which requires the dataset associated with the
formula.
library(bayesnec)
bayesnecformula(y ~ crf(x, "nec3param"))
#> y ~ crf(x, "nec3param")
#> <environment: 0x5a3a00f83938>
# or use shot alias bnf
bayesnecformula(y ~ crf(x, "nec3param")) == bnf(y ~ crf(x, "nec3param"))
#> [1] TRUE
bnf(y | trials(tr) ~ crf(sqrt(x), "nec3param"))
#> y | trials(tr) ~ crf(sqrt(x), "nec3param")
#> <environment: 0x5a3a00f83938>
bnf(y | trials(tr) ~ crf(x, "nec3param") + ogl(group_1) + pgl(group_2))
#> y | trials(tr) ~ crf(x, "nec3param") + ogl(group_1) + pgl(group_2)
#> <environment: 0x5a3a00f83938>
# dispersion as a function of the predictor
bnf(y ~ crf(x, "nec3param") + disp(~x))
#> y ~ crf(x, "nec3param") + disp(~x)
#> <environment: 0x5a3a00f83938>
# dispersion as a function of the fitted mean
bnf(y ~ crf(x, "nec3param") + disp("power"))
#> y ~ crf(x, "nec3param") + disp("power")
#> <environment: 0x5a3a00f83938>
bnf(y | trials(tr) ~ crf(x, "nec3param") + (nec + top | group_1))
#> y | trials(tr) ~ crf(x, "nec3param") + (nec + top | group_1)
#> <environment: 0x5a3a00f83938>
# \donttest{
# The predictor expression is passed to Stan by brms. Precompute a
# transformation unless its function is also defined for Stan.
try(bnf(y | trials(tr) ~ crf(scale(x, scale = TRUE), "nec3param")))
#> y | trials(tr) ~ crf(scale(x, scale = TRUE), "nec3param")
#> <environment: 0x5a3a00f83938>
# }