| Type: | Package |
| Title: | Probability Distributions with Certain or Uncertain Parameters |
| Version: | 0.1.0 |
| Description: | Represents probability distributions with fixed or potentially uncertain parameters, with tools to discretise, convolve, sample from and summarise them. |
| License: | MIT + file LICENSE |
| URL: | https://epiforecasts.io/distspec/ |
| BugReports: | https://github.com/epiforecasts/distspec/issues |
| Depends: | R (≥ 3.5.0) |
| Imports: | cli, lifecycle, methods, primarycensored, rlang, stats, truncnorm, utils |
| Suggests: | covr, ggplot2, knitr, rmarkdown, spelling, testthat |
| VignetteBuilder: | knitr |
| Encoding: | UTF-8 |
| Language: | en-GB |
| RoxygenNote: | 7.3.3 |
| NeedsCompilation: | no |
| Packaged: | 2026-07-30 09:56:28 UTC; eidesfun |
| Author: | Sebastian Funk |
| Maintainer: | Sebastian Funk <sebastian.funk@lshtm.ac.uk> |
| Repository: | CRAN |
| Date/Publication: | 2026-08-07 16:50:06 UTC |
distspec: Probability Distributions with Certain or Uncertain Parameters
Description
Represents probability distributions with fixed or potentially uncertain parameters, with tools to discretise, convolve, sample from and summarise them.
Author(s)
Maintainer: Sebastian Funk sebastian.funk@lshtm.ac.uk (ORCID)
Authors:
James M. Azam james.azam@lshtm.ac.uk (ORCID)
Sam Abbott sam.abbott@lshtm.ac.uk (ORCID)
See Also
Useful links:
Creates a delay distribution as the sum of two other delay distributions.
Description
Creates a delay distribution as the sum of two other delay distributions.
Usage
## S3 method for class 'dist_spec'
e1 + e2
Arguments
e1 |
The first delay distribution (of type <dist_spec>) to combine. |
e2 |
The second delay distribution (of type <dist_spec>) to combine. |
Value
A delay distribution representing the sum of the two delays
Examples
# A fixed lognormal distribution with mean 5 and sd 1.
dist1 <- LogNormal(
meanlog = 1.6, sdlog = 1, max = 20
)
dist1 + dist1
# An uncertain gamma distribution with shape and rate normally distributed
# as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- Gamma(
shape = Normal(3, 0.5),
rate = Normal(2, 0.5),
max = 20
)
dist1 + dist2
Compares two delay distributions
Description
Compares two delay distributions
Usage
## S3 method for class 'dist_spec'
e1 == e2
## S3 method for class 'dist_spec'
e1 != e2
Arguments
e1 |
The first delay distribution (of type <dist_spec>) to combine. |
e2 |
The second delay distribution (of type <dist_spec>) to combine. |
Value
TRUE or FALSE
Examples
Fixed(1) == Normal(1, 0.5)
Beta distribution
Description
A beta distribution as a <dist_spec>, given either by its shape parameters
shape1/shape2 or by its mean/sd. It is not discretised.
Usage
Beta(shape1, shape2, mean, sd, ...)
Arguments
shape1, shape2 |
Shape parameters of the beta distribution. |
mean, sd |
Mean and standard deviation of the distribution, as an
alternative to |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
Beta(shape1 = 2, shape2 = 5)
Beta(mean = 0.3, sd = 0.15)
Dirichlet prior for a nonparametric distribution
Description
A Dirichlet prior over the weights of a nonparametric probability mass
function, used to specify an uncertain NonParametric() distribution whose
PMF is left uncertain given the Dirichlet prior. Give either alpha
directly, or a reference prior PMF together with a concentration.
Usage
Dirichlet(alpha, prior, concentration, ...)
Arguments
alpha |
A positive numeric vector of concentration parameters. |
prior |
Either a numeric PMF vector (zero-indexed, i.e. the
first entry represents probability mass at zero) or a
|
concentration |
A positive scalar controlling how tightly
the Dirichlet prior concentrates around the supplied PMF.
The Dirichlet alpha vector is computed as
|
... |
Not used. |
Value
A <dist_spec>.
See Also
NonParametric() to use the prior, and Distributions for an
overview.
Examples
Dirichlet(c(1, 1, 1, 1))
Dirichlet(prior = c(0.1, 0.3, 0.4, 0.2), concentration = 10)
Probability distributions
Description
distspec represents probability distributions (typically epidemiological
delays, such as generation times or reporting delays) as <dist_spec>
objects. Each supported distribution has its own constructor: LogNormal(),
Gamma(), Normal(), Exponential(), Weibull(), Beta(), Fixed(),
NonParametric() and Dirichlet().
Details
A parameter can be given either as a fixed numeric value or as an uncertain
value (another <dist_spec>); currently only normally distributed uncertain
parameters (from Normal()) are supported.
Each distribution has a "natural" (canonical) parameterisation, such as
shape and rate for Gamma() or meanlog and sdlog for LogNormal().
It can sometimes also be specified using other parameters, such as its mean
and standard deviation, which are then converted to the natural parameters
(propagating any uncertainty with a first-order delta-method approximation).
See Also
discretise() and collapse() to discretise and convolve
distributions, sample_dist() to draw samples, and get_parameters() /
get_pmf() to inspect them.
Exponential distribution
Description
An exponential distribution as a <dist_spec>, given either by its rate or
by its mean.
Usage
Exponential(rate, mean, ...)
Exp(...)
Arguments
rate |
vector of rates. |
mean |
Mean of the distribution, as an alternative to |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
Exponential(rate = 1)
Exponential(mean = 4)
Fixed (point-mass) distribution
Description
A fixed (delta) distribution as a <dist_spec>, placing all of its mass on a
single value.
Usage
Fixed(value, ...)
Arguments
value |
Value of the fixed (delta) distribution. |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
Fixed(value = 3)
Fixed(value = 3.5)
Gamma distribution
Description
A gamma distribution as a <dist_spec>, given either by its natural
parameters shape/rate (or shape/scale) or by its mean/sd.
Usage
Gamma(shape, rate, scale, mean, sd, ...)
Arguments
shape, scale |
shape and scale parameters. Must be positive,
|
rate |
an alternative way to specify the scale. |
mean, sd |
Mean and standard deviation of the distribution, as an
alternative to |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
Gamma(mean = 4, sd = 1)
Gamma(shape = 16, rate = 4)
Gamma(shape = Normal(16, 2), rate = Normal(4, 1))
Lognormal distribution
Description
A lognormal distribution as a <dist_spec>, given either by its natural
parameters meanlog/sdlog or by its mean/sd.
Usage
LogNormal(meanlog, sdlog, mean, sd, ...)
Arguments
meanlog, sdlog |
mean and standard deviation of the distribution
on the log scale with default values of |
mean, sd |
Mean and standard deviation of the distribution, as an
alternative to |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
LogNormal(mean = 4, sd = 1)
LogNormal(mean = 4, sd = 1, max = 10)
# Uncertain parameters must be given as the natural parameters
LogNormal(meanlog = Normal(1.5, 0.5), sdlog = 0.25, max = 10)
Nonparametric distribution
Description
A nonparametric distribution as a <dist_spec>, defined directly by its
probability mass function. The PMF can instead be left uncertain by
passing a Dirichlet() prior.
Usage
NonParametric(pmf, ...)
Arguments
pmf |
Probability mass function, as a zero-indexed numeric vector (the
first entry is the mass at zero) or a |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
NonParametric(c(0.1, 0.3, 0.2, 0.4))
# With a Dirichlet prior (PMF left uncertain)
NonParametric(pmf = Dirichlet(c(1, 1, 1, 1)))
Normal distribution
Description
A normal distribution as a <dist_spec>, given by its mean and sd. Also
used to give an uncertain parameter of another distribution.
Usage
Normal(mean, sd, ...)
Arguments
mean, sd |
Mean and standard deviation of the distribution. |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
Normal(mean = 4, sd = 1)
Normal(mean = 4, sd = 1, max = 10)
Weibull distribution
Description
A Weibull distribution as a <dist_spec>, given either by its
shape/scale or by its mean/sd.
Usage
Weibull(shape, scale, mean, sd, ...)
Arguments
shape, scale |
shape and scale parameters, the latter defaulting to 1. |
mean, sd |
Mean and standard deviation of the distribution, as an
alternative to |
... |
Limits of the distribution, passed to |
Value
A <dist_spec>.
See Also
Distributions for an overview and the other distributions.
Examples
Weibull(shape = 1, scale = 1)
Weibull(shape = 1, scale = 1, max = 10)
Weibull(mean = 4, sd = 1)
Define bounds of a <dist_spec>
Description
Set the bounds that constrain a distribution when it is discretised: max
truncates the support at that value, while cdf_cutoff trims the tail by
keeping the distribution only up to its cdf_cutoff quantile. Either bound
drops the mass beyond it and renormalises the remaining PMF to sum to one.
Usage
bound_dist(x, max = Inf, cdf_cutoff = 1)
Arguments
x |
A |
max |
Numeric, maximum value of the distribution. The distribution will
be truncated at this value. Default: |
cdf_cutoff |
Numeric in |
Value
a <dist_spec> with relevant attributes set that define its bounds
See Also
discretise(), which applies these bounds when producing a PMF.
Examples
# Truncate a gamma distribution at 20
bound_dist(Gamma(mean = 5, sd = 1), max = 20)
# Keep it up to its 99.9th percentile
bound_dist(Gamma(mean = 5, sd = 1), cdf_cutoff = 0.999)
Combines multiple delay distributions for further processing
Description
This combines the given distributions into a single composite <dist_spec>
holding multiple delay distributions.
Note that distributions that already are combinations of other distributions cannot be combined with other combinations of distributions.
Usage
## S3 method for class 'dist_spec'
c(...)
Arguments
... |
The delay distributions to combine |
Value
Combined delay distributions (with class <dist_spec>)
Examples
# A fixed lognormal distribution with mean 5 and sd 1.
dist1 <- LogNormal(
meanlog = 1.6, sdlog = 1, max = 20
)
dist1 + dist1
# An uncertain gamma distribution with shape and rate normally distributed
# as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- Gamma(
shape = Normal(3, 0.5),
rate = Normal(2, 0.5),
max = 20
)
c(dist1, dist2)
Check that a numeric PMF or weight vector is valid
Description
A numeric probability mass function or weight vector must be numeric, contain only finite, non-negative values, and not be all zero, so that it can be normalised to sum to one. Raises an informative error otherwise. An un-normalised vector is allowed (it is treated as weights and normalised by the caller) but warns.
Usage
check_pmf_values(x, arg = "pmf")
Arguments
x |
A numeric vector. |
arg |
The name of the calling argument, used in the messages. |
Value
x, invisibly, if it is valid; otherwise an error is raised.
Check that PMF tail is not sparse
Description
Checks if the tail of a PMF vector has more than span
consecutive values smaller than tol and throws a warning if so.
Usage
check_sparse_pmf_tail(pmf, span = 5, tol = 1e-06)
Arguments
pmf |
A probability mass function vector |
span |
The number of consecutive indices in the tail to check |
tol |
The value which to consider the tail as sparse |
Value
Called for its side effects.
Collapse nonparametric distributions in a <dist_spec>
Description
This convolves any consecutive nonparametric distributions contained in the <dist_spec>.
Usage
## S3 method for class 'dist_spec'
collapse(x, ...)
Arguments
x |
A |
... |
ignored |
Value
A <dist_spec> where consecutive nonparametric distributions
have been convolved
See Also
discretise() to produce the nonparametric components this
convolves. The vignette("distspec") shows the full
get_pmf(collapse(discretise(d1 + d2))) pipeline.
Examples
# A fixed gamma distribution with mean 5 and sd 1.
dist1 <- Gamma(mean = 5, sd = 1, max = 20)
# An uncertain lognormal distribution with meanlog and sdlog normally
# distributed as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- LogNormal(
meanlog = Normal(3, 0.5),
sdlog = Normal(2, 0.5),
max = 20
)
# The sum of two distributions
collapse(discretise(dist1 + dist2, strict = FALSE))
Convert mean and sd to log mean for a log normal distribution
Description
Convert from mean and standard deviation to the log mean of the
lognormal distribution. Useful for defining a LogNormal() distribution
from a mean and standard deviation on the natural scale.
Usage
convert_to_logmean(mean, sd)
Arguments
mean |
Numeric, mean of a distribution |
sd |
Numeric, standard deviation of a distribution |
Value
The log mean of a lognormal distribution
Examples
convert_to_logmean(2, 1)
Convert mean and sd to log standard deviation for a log normal distribution
Description
Convert from mean and standard deviation to the log standard deviation of the
lognormal distribution. Useful for defining a LogNormal() distribution
from a mean and standard deviation on the natural scale.
Usage
convert_to_logsd(mean, sd)
Arguments
mean |
Numeric, mean of a distribution |
sd |
Numeric, standard deviation of a distribution |
Value
The log standard deviation of a lognormal distribution
Examples
convert_to_logsd(2, 1)
Internal function for converting parameters to natural parameters.
Description
Preprocessing before generating a dist_spec: converts a distribution's
parameters to its natural parameters via the per-type to_natural() method,
re-attaching uncertainty where parameters are uncertain.
When any of the supplied parameters are uncertain the uncertainty is
propagated to the natural parameters using a first-order (delta-method)
approximation. The uncertain parameters are treated as independent normals;
the natural parameters are evaluated at their means and their variances are
obtained from the Jacobian of the transformation, computed by central finite
differences. Each natural parameter is returned as a Normal() with that
mean and standard deviation.
Usage
convert_to_natural(x)
Arguments
x |
A |
Value
A named list of natural parameters.
Residual limitation
The delta method represents each natural parameter's marginal uncertainty but
discards the correlation between natural parameters induced by the shared
unnatural parameters (for example, shape and rate of a gamma both depend
on the uncertain mean). Specify the distribution directly in terms of its
natural parameters when that correlation matters.
Delta-method standard deviations of the natural parameters
Description
First-order (delta-method) standard deviations of a distribution's natural
parameters, propagated from uncertain unnatural parameters. The uncertain
unnatural parameters are treated as independent normals with standard
deviations sds, and for each natural parameter the propagated standard
deviation is sqrt(sum_i J[j, i]^2 * sds[i]^2), where the Jacobian
J[j, i] = d(natural_j) / d(param_i) is estimated by central finite
differences. Estimating the Jacobian numerically lets this work uniformly for
every distribution type, including the Weibull, whose to_natural() solves
for the shape numerically.
Usage
delta_method_sd(x, sds, natural, h_rel = 1e-04)
Arguments
x |
A single |
sds |
Numeric; the standard deviation of each unnatural parameter, in
|
natural |
The natural-parameter list evaluated at the means. |
h_rel |
Numeric; the relative step of the central finite difference. For
parameter |
Value
A named numeric vector of standard deviations, one per natural parameter.
Discretised probability mass function
Description
This function returns the probability mass function of a discretised and truncated distribution defined by distribution type, maximum value and model parameters.
Usage
discrete_pmf(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to methods. The default method takes
|
Value
A vector representing a probability distribution.
Methodological details
The probability mass function is computed using the {primarycensored}
package, which provides double censored PMF calculations. This correctly
represents the probability mass function of a double censored distribution
arising from the difference of two censored events.
The probability mass function of the discretised probability distribution is a vector where the first entry corresponds to the integral over the (0,1] interval of the corresponding continuous distribution (probability of integer 0), the second entry corresponds to the (0,2] interval (probability mass of integer 1), the third entry corresponds to the (1, 3] interval (probability mass of integer 2), etc.
The maximum value truncates the distribution: mass beyond it is dropped and
the remaining PMF is renormalised to sum to one. A cdf_cutoff below 1
additionally trims the tail, keeping the distribution only up to its
cdf_cutoff quantile.
Fixed distributions
A Fixed() (point-mass) distribution is not discretised through a CDF but by
its own method: an integer value places all of the mass on that integer,
while a fractional value splits the mass proportionally across the two
adjacent integers. For example Fixed(2.25) places 0.75 on 2 and 0.25 on 3.
References
Charniga, K., et al. “Best practices for estimating and reporting epidemiological delay distributions of infectious diseases using public health surveillance and healthcare data”, arXiv e-prints, 2024. doi:10.48550/arXiv.2405.08841 Park, S. W., et al., "Estimating epidemiological delay distributions for infectious diseases", medRxiv, 2024. doi:10.1101/2024.01.12.24301247 Abbott S., et al., "primarycensored: Primary Event Censored Distributions", 2025. doi:10.5281/zenodo.13632839
Discretise a <dist_spec>
Description
Discretise a <dist_spec>
Usage
## S3 method for class 'dist_spec'
discretise(x, strict = TRUE, remove_trailing_zeros = TRUE, ...)
discretize(x, ...)
Arguments
x |
A |
strict |
Logical; If |
remove_trailing_zeros |
Logical; If |
... |
ignored |
Value
A <dist_spec> where all distributions with constant parameters are
nonparametric. Extract the resulting PMF vector with get_pmf().
Methodological details
The probability mass function is computed using the {primarycensored}
package, which provides double censored PMF calculations. This correctly
represents the probability mass function of a double censored distribution
arising from the difference of two censored events.
The probability mass function of the discretised probability distribution is a vector where the first entry corresponds to the integral over the (0,1] interval of the corresponding continuous distribution (probability of integer 0), the second entry corresponds to the (0,2] interval (probability mass of integer 1), the third entry corresponds to the (1, 3] interval (probability mass of integer 2), etc.
The maximum value truncates the distribution: mass beyond it is dropped and
the remaining PMF is renormalised to sum to one. A cdf_cutoff below 1
additionally trims the tail, keeping the distribution only up to its
cdf_cutoff quantile.
Fixed distributions
A Fixed() (point-mass) distribution is not discretised through a CDF but by
its own method: an integer value places all of the mass on that integer,
while a fractional value splits the mass proportionally across the two
adjacent integers. For example Fixed(2.25) places 0.75 on 2 and 0.25 on 3.
References
Charniga, K., et al. “Best practices for estimating and reporting epidemiological delay distributions of infectious diseases using public health surveillance and healthcare data”, arXiv e-prints, 2024. doi:10.48550/arXiv.2405.08841 Park, S. W., et al., "Estimating epidemiological delay distributions for infectious diseases", medRxiv, 2024. doi:10.1101/2024.01.12.24301247 Abbott S., et al., "primarycensored: Primary Event Censored Distributions", 2025. doi:10.5281/zenodo.13632839
See Also
collapse() to convolve the discretised components of a composite
distribution into a single PMF, and sample_dist() to draw random samples.
The vignette("distspec") shows the full
get_pmf(collapse(discretise(d1 + d2))) pipeline.
Examples
# A fixed gamma distribution with mean 5 and sd 1, discretised to a PMF.
dist1 <- Gamma(mean = 5, sd = 1, max = 20)
get_pmf(discretise(dist1))
# An uncertain lognormal distribution cannot be discretised, so with
# `strict = FALSE` it is returned unchanged.
dist2 <- LogNormal(
meanlog = Normal(3, 0.5),
sdlog = Normal(2, 0.5),
max = 20
)
discretise(dist2, strict = FALSE)
# A fractional fixed value splits its mass across the two adjacent integers.
get_pmf(discretise(Fixed(2.25)))
Extract parameter names
Description
Internal function for extracting given parameter names of a distribution
from the environment. Called by new_dist_spec
Usage
extract_params(params, distribution)
Arguments
params |
Given parameters (obtained using |
Value
A character vector of parameters and their values.
Extract a single element of a composite <dist_spec>
Description
Extract a single element of a composite <dist_spec>
Usage
extract_single_dist(x, i)
Arguments
x |
A composite |
i |
The index to extract |
Value
A single dist_spec object
Fix the parameters of a <dist_spec>
Description
If the given <dist_spec> has any uncertainty, it is removed and the
corresponding distribution converted into a fixed one.
Call this before sample_dist() or get_pmf() on an uncertain
distribution, as neither can operate on a distribution that still carries a
prior.
Usage
## S3 method for class 'dist_spec'
fix_parameters(x, strategy = c("mean", "sample"), ...)
Arguments
x |
A |
strategy |
Character; either "mean" (use the mean estimates of the
mean and standard deviation) or "sample" (randomly sample mean and
standard deviation from uncertainty given in the |
... |
ignored |
Value
A <dist_spec> object without uncertainty
Examples
# An uncertain gamma distribution with shape and rate normally distributed
# as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist <- Gamma(
shape = Normal(3, 0.5),
rate = Normal(2, 0.5),
max = 20
)
fix_parameters(dist)
Get the distribution of a <dist_spec>
Description
Get the distribution of a <dist_spec>
Usage
get_distribution(x, id = NULL)
Arguments
x |
A |
id |
Integer; the id of the distribution to use (if x is a composite
distribution). If |
Value
A character string naming the distribution (or "nonparametric")
Examples
dist <- Gamma(shape = 3, rate = 2, max = 10)
get_distribution(dist)
Extracts an element of a <dist_spec>
Description
Extracts an element of a <dist_spec>
Usage
get_element(x, id = NULL, element)
Arguments
x |
A |
id |
Integer; the id of the distribution to use (if x is a composite
distribution). If |
element |
The element, i.e. "parameters", "pmf" or "distribution". |
Value
The id to use.
Get parameters of a parametric distribution
Description
Generic function to extract the distribution parameters (e.g. shape and
rate for Gamma) from a dist_spec object.
Usage
get_parameters(x, ...)
## S3 method for class 'dist_spec'
get_parameters(x, id = NULL, ...)
Arguments
x |
A |
... |
Additional arguments passed to methods |
id |
Integer; the id of the distribution to use (if x is a composite
distribution). If |
Value
A list of parameters of the distribution.
Examples
dist <- Gamma(shape = 3, rate = 2)
get_parameters(dist)
Get the probability mass function of a nonparametric distribution
Description
Get the probability mass function of a nonparametric distribution
Usage
get_pmf(x, id = NULL)
Arguments
x |
A |
id |
Integer; the id of the distribution to use (if x is a composite
distribution). If |
Details
An uncertain (Dirichlet-backed) nonparametric distribution has no concrete
PMF, so calling get_pmf() on one is an error. Resolve it to a fixed PMF
first with fix_parameters() (e.g. strategy = "mean").
Value
The pmf of the distribution
Examples
dist <- discretise(Gamma(shape = 3, rate = 2, max = 10))
get_pmf(dist)
Check whether a <dist_spec> is uncertain
Description
A distribution is uncertain when it carries a prior: a parametric
distribution with a <dist_spec> (rather than numeric) parameter, or a
nonparametric distribution whose PMF is given by a <dist_spec> (a
Dirichlet() prior) rather than a numeric vector.
Usage
has_uncertainty(x, id = NULL)
Arguments
x |
A |
id |
Integer; the id of the distribution to use (if x is a composite
distribution). If |
Value
TRUE if the (component) distribution is uncertain.
Examples
has_uncertainty(Gamma(shape = 1, rate = 1))
has_uncertainty(Gamma(shape = Normal(1, 0.5), rate = 1))
Check if a <dist_spec> is constrained, i.e. has a finite maximum or nonzero CDF cutoff.
Description
Check if a <dist_spec> is constrained, i.e. has a finite maximum or nonzero CDF cutoff.
Usage
## S3 method for class 'dist_spec'
is_constrained(x, ...)
Arguments
x |
A |
... |
ignored |
Value
Logical; TRUE if x is constrained
Examples
# A fixed gamma distribution with mean 5 and sd 1.
dist1 <- Gamma(mean = 5, sd = 1, max = 20)
# An uncertain lognormal distribution with meanlog and sdlog normally
# distributed as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- LogNormal(
meanlog = Normal(3, 0.5),
sdlog = Normal(2, 0.5),
max = 20
)
# both distributions are constrained and therefore so is the sum
is_constrained(dist1 + dist2)
Get the lower bounds of the parameters of a distribution
Description
This is used to avoid sampling parameter values that have no support.
Usage
lower_bounds(x)
Arguments
x |
A |
Value
A numeric vector, the lower bounds.
Examples
lower_bounds(LogNormal(meanlog = 0, sdlog = 1))
# a distribution type can also be given by name
lower_bounds("lognormal")
Returns the maximum of one or more delay distribution
Description
This works out the maximum of all the (parametric / nonparametric) delay distributions combined in the passed <dist_spec> (ignoring any uncertainty in parameters)
Usage
## S3 method for class 'dist_spec'
max(x, ...)
Arguments
x |
The <dist_spec> to use |
... |
Not used |
Value
A numeric vector of maxima, one per component.
Examples
# A fixed gamma distribution with mean 5 and sd 1.
dist1 <- Gamma(mean = 5, sd = 1, max = 20)
max(dist1)
# An uncertain lognormal distribution with meanlog and sdlog normally
# distributed as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- LogNormal(
meanlog = Normal(3, 0.5),
sdlog = Normal(2, 0.5),
max = 20
)
max(dist2)
# The max the sum of two distributions
max(dist1 + dist2)
Returns the mean of one or more delay distribution
Description
This works out the mean of all the (parametric / nonparametric) delay distributions combined in the passed <dist_spec>.
Usage
## S3 method for class 'dist_spec'
mean(x, ..., ignore_uncertainty = FALSE)
Arguments
x |
The |
... |
Not used |
ignore_uncertainty |
Logical; whether to ignore any uncertainty in parameters. If set to FALSE (the default) then the mean of any uncertain parameters will be returned as NA. |
Value
A numeric vector of means, one per component of the <dist_spec>;
NA for any component with uncertain parameters unless
ignore_uncertainty = TRUE.
Examples
# A fixed lognormal distribution with mean 5 and sd 1.
dist1 <- LogNormal(mean = 5, sd = 1, max = 20)
mean(dist1)
# An uncertain gamma distribution with shape and rate normally distributed
# as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- Gamma(
shape = Normal(3, 0.5),
rate = Normal(2, 0.5),
max = 20
)
mean(dist2)
# The mean of the sum of two distributions
mean(dist1 + dist2)
Get the names of the natural parameters of a distribution
Description
These are the natural (canonical) parameters of a distribution, such as
shape and rate for a gamma distribution or meanlog and sdlog for a
lognormal distribution. All other parameter representations (for example a
mean and standard deviation) are converted to these using
convert_to_natural().
Usage
natural_params(x)
Arguments
x |
A |
Value
A character vector, the natural parameters.
Examples
natural_params(Gamma(shape = 1, rate = 1))
# a distribution type can also be given by name
natural_params("gamma")
Calculate the number of distributions in a <dist_spec>
Description
Calculate the number of distributions in a <dist_spec>
Usage
ndist(x)
Arguments
x |
A |
Value
The number of distributions.
Examples
ndist(Gamma(mean = 5, sd = 1))
ndist(Gamma(mean = 5, sd = 1) + Exponential(rate = 1))
Internal function for generating a dist_spec given parameters and a
distribution.
Description
This will convert all parameters to natural parameters before generating
a dist_spec. If they are uncertain the uncertainty is propagated to the
natural parameters with a first-order (delta-method) approximation (see
convert_to_natural()).
Usage
new_dist_spec(params, distribution, max = Inf, cdf_cutoff = 1)
Arguments
params |
Parameters of the distribution (including |
distribution |
Character; the distribution type (e.g. |
max |
Numeric, maximum value of the distribution. The distribution will
be truncated at this value. Default: |
cdf_cutoff |
Numeric in |
Value
A dist_spec of the given specification.
Examples
new_dist_spec(
params = list(mean = 2, sd = 1),
distribution = "normal"
)
Build PMF data for the nonparametric branch of plot.dist_spec
Description
For a fixed nonparametric delay returns a single row per bin
(the stored PMF). For a Dirichlet-backed uncertain delay, draws
samples PMFs from the alpha vector via rdirichlet() and
returns one row per sample-bin pair so the calling plot can
render an uncertainty band.
Usage
nonparametric_pmf_data(x, i, samples)
Arguments
x |
The |
i |
Index of the nonparametric component within |
samples |
Number of PMFs to draw when alpha is present. |
Value
A data.frame with columns sample, x, p,
distribution.
Plot PMF and CDF for a dist_spec object
Description
This function takes a <dist_spec> object and plots its probability mass
function (PMF) and cumulative distribution function (CDF) using {ggplot2}.
Usage
## S3 method for class 'dist_spec'
plot(x, samples = 50L, res = 1, cumulative = TRUE, ...)
Arguments
x |
A |
samples |
Integer; Number of samples to generate for distributions with uncertain parameters (default: 50). |
res |
Numeric; Resolution of the PMF and CDF (default: 1, i.e. integer
discretisation). This applies only to components discretised from a
continuous distribution; a nonparametric component is already discretised
on its integer support and is unaffected by |
cumulative |
Logical; whether to plot the cumulative distribution in addition to the probability mass function |
... |
ignored |
Details
A component must have a finite range to be plotted. One with no finite max
and no cdf_cutoff of its own raises an error; bound it first (e.g. with
bound_dist()).
Value
A {ggplot2} object showing the PMF (and, if cumulative = TRUE,
the CDF) of each component, faceted by distribution.
Examples
# A fixed lognormal distribution with mean 5 and sd 1.
dist1 <- LogNormal(mean = 1.6, sd = 0.5, max = 20)
# Plot discretised distribution with 1 day discretisation window
plot(dist1)
# Plot discretised distribution with 0.01 day discretisation window
plot(dist1, res = 0.01, cumulative = FALSE)
# An uncertain gamma distribution with shape and rate normally distributed
# as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- Gamma(
shape = Normal(3, 0.5),
rate = Normal(2, 0.5),
max = 20
)
plot(dist2)
# Multiple distributions with 0.1 discretisation window and do not plot the
# cumulative distribution
plot(dist1 + dist2, res = 0.1, cumulative = FALSE)
Prints the parameters of one or more delay distributions
Description
This displays the parameters of the uncertain and probability mass functions of fixed delay distributions combined in the passed <dist_spec>.
Usage
## S3 method for class 'dist_spec'
print(x, ...)
Arguments
x |
The |
... |
Not used |
Value
invisible
Examples
#' # A fixed lognormal distribution with mean 5 and sd 1.
dist1 <- LogNormal(mean = 1.5, sd = 0.5, max = 20)
print(dist1)
# An uncertain gamma distribution with shape and rate normally distributed
# as Normal(3, 0.5) and Normal(2, 0.5) respectively
dist2 <- Gamma(
shape = Normal(3, 0.5), rate = Normal(2, 0.5), max = 20
)
print(dist2)
Draw a single sample from a Dirichlet
Description
Base R does not provide an rdirichlet(). We use the
gamma-normalisation method also used by the Stan model:
draw an independent Gamma(alpha_i, 1) per bin and rescale by
the segment sum. Bins with alpha == 0 stay at zero so
structural zeros (e.g. the t = 0 generation-time bin) are
preserved.
Usage
rdirichlet(alpha)
Arguments
alpha |
A non-negative numeric vector of concentration parameters. |
Value
A numeric vector the same length as alpha, summing
to 1 over the positive-alpha entries.
References
Stan discourse, "Ragged array of simplexes", https://discourse.mc-stan.org/t/ragged-array-of-simplexes/1382/21.
Sample from a distribution
Description
Draws random samples from a <dist_spec> whose parameters are fixed numbers,
using the base-R random-generation function for its family (e.g. rgamma()
for a gamma distribution). A discretised distribution is sampled on its
integer support.
Only distributions with fixed parameters can be sampled. If any parameter is itself a distribution (a prior), there is no single distribution to sample from and an error is raised.
A composite (multi-component) distribution is sampled per component, in
keeping with mean()/sd(), which also return one value per component. Use
rowSums() on the result to obtain samples of the combined (convolved)
distribution.
Usage
sample_dist(x, n, ...)
## S3 method for class 'dist_spec'
sample_dist(x, n, ...)
## S3 method for class 'multi_dist_spec'
sample_dist(x, n, ...)
Arguments
x |
A |
n |
The number of samples to draw. |
... |
Not used. |
Value
For a single distribution, a numeric vector of n samples. For a
composite distribution of k components, an n by k matrix, one column
of n samples per component (rowSums() gives n samples of the combined
distribution).
See Also
fix_parameters() to resolve an uncertain distribution to fixed
parameters before sampling, and discretise() to obtain a PMF instead.
Examples
# Samples from a fixed gamma distribution
sample_dist(Gamma(shape = 2, rate = 1), 10)
# Samples from a discretised distribution, drawn on its integer support
sample_dist(discretise(Gamma(shape = 2, rate = 1, max = 20)), 10)
# A fixed distribution always returns the same value
sample_dist(Fixed(3), 5)
# A composite: an n-by-k matrix, one column per component
sample_dist(Gamma(shape = 2, rate = 1) + Gamma(shape = 3, rate = 1), 10)
Returns the standard deviation of one or more delay distribution
Description
This works out the standard deviation of all the (parametric /
nonparametric) delay distributions combined in the passed <dist_spec>.
If any of the parameters are themselves uncertain then NA is returned.
Usage
sd(x, ...)
## S3 method for class 'dist_spec'
sd(x, ...)
Arguments
x |
The <dist_spec> to use |
... |
Not used |
Value
A vector of standard deviations.
Examples
# A fixed lognormal distribution with mean 5 and sd 1.
dist1 <- LogNormal(mean = 5, sd = 1, max = 20)
sd(dist1)
# A gamma distribution with mean 3 and sd 2
dist2 <- Gamma(mean = 3, sd = 2)
sd(dist2)
# The sd of the sum of two distributions
sd(dist1 + dist2)
Numerically stable convolution function for two pmf vectors
Description
Unlike stats::convolve(), this function does not use the FFT algorithm,
which can generate negative numbers when below machine precision.
Usage
stable_convolve(a, b)
Arguments
a |
Numeric vector, the first sequence. |
b |
Numeric vector, the second sequence. |
Value
A numeric vector representing the convolution of a and b.
Convert a distribution's parameters to its natural parameters (per-type)
Description
Per-type conversion of a distribution's parameters to its natural parameters.
Dispatched on the distribution type; each method reads the parameter means
from ux and returns the natural parameters as a named list (see e.g.
to_natural.gamma). The shared pre- and post-processing lives in
convert_to_natural(), which computes ux once and passes it in.
Usage
to_natural(x, ux)
Arguments
x |
A single |
ux |
The parameter means, as returned by |
Value
A named list of natural parameters.
Validate the structure of a <dist_spec>
Description
Asserts the structural invariants of a <dist_spec>: its class, the shape of
its parameters, and its max/cdf_cutoff attributes. Called by every
constructor on the object it builds, so a <dist_spec> from the package is
always well-formed. A composite is valid when each of its components is.
Usage
validate_dist_spec(x)
Arguments
x |
A |
Value
x, invisibly, if it is valid; otherwise an error is raised.