| Title: | PIT-Wasserstein Metrics for Diagnosing Dispersion Miscalibration |
|---|---|
| Description: | Implements the PIT-Wasserstein family of metrics for diagnosing dispersion miscalibration in probabilistic estimators. The package provides three nested metrics—B_pit (baseline), U_pit (bias-adjusted undirected), and D_pit (bias-adjusted signed, detecting overconfidence vs. underconfidence)—each with a significance test based on a large-sample reference distribution for independent predictions. Also provides batch scoring, CRPS calculation, simulation helpers, and diagnostic visualisation tools. |
| Authors: | Rob Challen [aut, cre] (ORCID: <https://orcid.org/0000-0002-5504-7768>) |
| Maintainer: | Rob Challen <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.1 |
| Built: | 2026-11-26 15:43:46 UTC |
| Source: | https://github.com/ai4ci/pit-wasserstein |
Tests the strongest of the three null hypotheses in the PIT-Wasserstein
family: that the predictions are fully probabilistically calibrated, so
that the raw PIT values are i.i.d. — correct location and
correct dispersion and correct shape. The test is one-sided: B_pit is a
distance, so only large values are evidence against calibration.
b_pit_significance(B_pit, n_predictions)b_pit_significance(B_pit, n_predictions)
B_pit |
the baseline (unadjusted) PIT-Wasserstein metric, reported as
|
n_predictions |
the number of predictions each |
Under that null converges to ,
the integrated absolute Brownian bridge, whose c.d.f. is p_l1_bridge().
Nothing is estimated from the data, so the null is exact and fully
analytical.
B_pit rejects when anything is wrong and says nothing about what. Use it
as the omnibus first stage, then d_pit_significance() to test dispersion
free of any location error, and u_pit_significance() for the residual
shape.
a dataframe with one row per input value and columns:
B_pit, n_predictions — as supplied
statistic — , the quantity with a fixed null
expected — the null mean of B_pit,
critical_0.05 — the one-sided 5% critical value of B_pit
p_value — the probability of a B_pit at least this large under full
probabilistic calibration
# a calibrated forecaster sits near the null mean and is not significant res = b_pit_significance(sqrt(2 * pi) / 8 / sqrt(100), 100) testthat::expect_true(res$p_value > 0.3) # the 5% critical value has, by construction, a p value of 0.05 crit = b_pit_significance(0, 100)$critical_0.05 testthat::expect_equal(b_pit_significance(crit, 100)$p_value, 0.05, tolerance = 1e-5) # the critical value scales as 1/sqrt(n) testthat::expect_equal( b_pit_significance(0, 400)$critical_0.05 * 2, b_pit_significance(0, 100)$critical_0.05, tolerance = 1e-6 ) # and is strictly larger than the adjusted test's, which has estimated a # location parameter from the same data testthat::expect_true( b_pit_significance(0, 100)$critical_0.05 > u_pit_significance(0, 100)$critical_0.05 ) # vectorised over both arguments testthat::expect_equal(nrow(b_pit_significance(c(0.02, 0.09), c(76, 76))), 2L)
Predictions whose PIT values are exactly uniform, for a scale family
(gamma4, lnorm4, ...) where location is the median.
calibrated_locations(qfn, median, kappa, n = 100)calibrated_locations(qfn, median, kappa, n = 100)
qfn |
a quantile function parametrised by median and something else |
median |
the median |
kappa |
a spread parameter, typically dispersion (sigma/mu) |
n |
the number of samples (default |
a set of locations for a distribution family that map directly to uniform PIT values.
loc = calibrated_locations(qfn = qgamma4, median = 1, kappa = 0.5) pit_w(1, loc, 0.5, dist = "gamma4", link = "log")$B_pit # ~1e-17loc = calibrated_locations(qfn = qgamma4, median = 1, kappa = 0.5) pit_w(1, loc, 0.5, dist = "gamma4", link = "log")$B_pit # ~1e-17
For a general (non-scale) family, solve it numerically instead:
calibrated_locations_general( pfn, median, kappa, n = 100, interval = c(1e-08, 1e+08) )calibrated_locations_general( pfn, median, kappa, n = 100, interval = c(1e-08, 1e+08) )
pfn |
a CDF parametrised by mean and the spread parameter |
median |
the median |
kappa |
a spread parameter, typically dispersion (sigma/mu) |
n |
the number of samples (default |
interval |
uniroot limits (default |
a set of locations for a distribution family that map directly to uniform PIT values.
Produce a summary plot of a experimental configuration.
configuration_plot(config = i_sim_plot, xlim = c(NA, NA), labels = TRUE, ...)configuration_plot(config = i_sim_plot, xlim = c(NA, NA), labels = TRUE, ...)
config |
dataframe grouped by designed panels - a dataframe with columns:
Any grouping allowed. |
xlim |
limits on the x-axis (default |
labels |
include labels on graphs - too cluttered on mulitple panels (default |
... |
addtionally passed on to |
a ggplot
scoringRules has implementations of common functions but not so much for
re-parametrisations. This detects if a re-parametrisation is available for a
distribution name and remaps the input to a more common distribution that
scoringRules has support for.
crps_fn_generator(dist_name)crps_fn_generator(dist_name)
dist_name |
the name of the distribution, e.g. |
a function which takes 3 parameters: true_value, location, and scale and returns a CRPS for them.
fn=crps_fn_generator("lnorm4")
mapped = fn(1:5,1,2)
tmp = .reparam.lnorm4(1,2)
direct = scoringRules::crps(1:5, tmp$dist, meanlog = tmp$meanlog, sdlog = tmp$sdlog)
testthat::expect_equal(mapped, direct)
Tests the null hypothesis that the predictions are calibrated. D_pit is
signed, so unlike u_pit_significance() this test reports a direction:
positive values indicate overconfidence (predictive distributions too
narrow) and negative values underconfidence (too wide).
d_pit_significance( D_pit, n_predictions, alternative = c("two.sided", "overconfident", "underconfident") )d_pit_significance( D_pit, n_predictions, alternative = c("two.sided", "overconfident", "underconfident") )
D_pit |
the directed PIT-Wasserstein metric, as returned by |
n_predictions |
the number of predictions each |
alternative |
one of |
D_pit is a linear functional of the empirical quantile process, so its
null is exactly Gaussian with a known variance,
. No simulation, bootstrap or
nuisance parameter is required.
The normal approximation to a sum of order statistics converges from above,
so for n_predictions below about 50 the test is mildly anti-conservative
(empirical size around 8% at n = 10, 6% at n = 25, 5.5% at n = 50);
treat small-sample p values as approximate.
a dataframe with one row per input value and columns:
D_pit, n_predictions — as supplied
statistic — the z score,
se — the null standard error,
critical_0.05 — the magnitude of D_pit rejected at 5%
direction — "overconfident", "underconfident" or "calibrated"
p_value — computed against alternative
# a z score of 1.96 is a two sided p of 0.05 res = d_pit_significance(qnorm(0.975) / sqrt(48 * 100), 100) testthat::expect_equal(res$statistic, qnorm(0.975)) testthat::expect_equal(res$p_value, 0.05) testthat::expect_equal(res$direction, "overconfident") # the one sided test is half the two sided test in the expected direction testthat::expect_equal( d_pit_significance(0.01, 100, "overconfident")$p_value, d_pit_significance(0.01, 100)$p_value / 2 ) # and is not fooled by a deviation in the other direction testthat::expect_true(d_pit_significance(-0.03, 100, "overconfident")$p_value > 0.95) # exactly calibrated testthat::expect_equal(d_pit_significance(0, 100)$p_value, 1) testthat::expect_equal(d_pit_significance(0, 100)$direction, "calibrated")
Density, distribution function, quantile function and random
generation for the Beta distribution with parameters shape1 and
shape2 (and optional non-centrality parameter ncp).
dbeta2(x, prob, kappa, log = FALSE)dbeta2(x, prob, kappa, log = FALSE)
x |
vector of quantiles |
prob |
the mean probability (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
log |
logical; if TRUE, probabilities p are given as log(p). |
dbeta gives the density,
pbeta is the cumulative distribution function, and
qbeta is the quantile function of the Beta distribution.
rbeta generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rbeta, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
dbeta2(c(0.25, 0.5, 0.75), 0.5, 0.25)dbeta2(c(0.25, 0.5, 0.75), 0.5, 0.25)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
dcgamma(x, median, kappa = 1/median, log = FALSE)dcgamma(x, median, kappa = 1/median, log = FALSE)
x |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
log |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
dcgamma(seq(0, 4, 0.25), 2, 0.5)dcgamma(seq(0, 4, 0.25), 2, 0.5)
Density function a named distribution
ddist(dist, x, ...)ddist(dist, x, ...)
dist |
the distribution name e.g. |
x |
vector of quantiles |
... |
passed onto named functions |
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
dgamma2(x, mean, sd = sqrt(mean), log = FALSE)dgamma2(x, mean, sd = sqrt(mean), log = FALSE)
x |
vector of quantiles |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
log |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
dgamma2(seq(0, 4, 0.25), 2, 1)dgamma2(seq(0, 4, 0.25), 2, 1)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
dgamma4(x, median, kappa = 1/median, log = FALSE)dgamma4(x, median, kappa = 1/median, log = FALSE)
x |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
log |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
dgamma2(seq(0, 4, 0.25), 2, 1)dgamma2(seq(0, 4, 0.25), 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
dlnorm2(x, mean = 1, sd = sqrt(exp(1) - 1), log = FALSE)dlnorm2(x, mean = 1, sd = sqrt(exp(1) - 1), log = FALSE)
x |
vector of quantiles |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
log |
logical; if TRUE, probabilities p are given as log(p). |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
dlnorm2(seq(0, 4, 0.25), 2, 1)dlnorm2(seq(0, 4, 0.25), 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
dlnorm4(x, median = 1, kappa = 1, log = FALSE)dlnorm4(x, median = 1, kappa = 1, log = FALSE)
x |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
log |
logical; if TRUE, probabilities p are given as log(p). |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
dlnorm4(seq(0, 4, 0.25), 2, 1)dlnorm4(seq(0, 4, 0.25), 2, 1)
The logit-normal distribution has a support of 0 to 1.
dlogitnorm(x, meanlogit = 0, sdlogit = 1, log = FALSE)dlogitnorm(x, meanlogit = 0, sdlogit = 1, log = FALSE)
x |
vector of quantiles |
meanlogit |
the mean on the logit scale |
sdlogit |
the sd on the logit scale |
log |
logical; if TRUE, probabilities p are given as log(p). |
a vector of probabilities, quantiles, densities or samples.
dlogitnorm(seq(0.1, 0.9, 0.1), 0, 1)dlogitnorm(seq(0.1, 0.9, 0.1), 0, 1)
The logit-normal distribution has a support of 0 to 1.
dlogitnorm2(x, prob.0.5 = 0.5, kappa = 1 - exp(-1), log = FALSE)dlogitnorm2(x, prob.0.5 = 0.5, kappa = 1 - exp(-1), log = FALSE)
x |
vector of quantiles |
prob.0.5 |
the median on the true scale |
kappa |
a dispersion parameter from 0 (none) to 1 maximum dispersion |
log |
logical; if TRUE, probabilities p are given as log(p). |
a vector of probabilities, quantiles, densities or samples.
q = seq(0.1, 0.9, 0.1) eps = sqrt(.Machine$double.eps) dlogitnorm2(q, 0.75, 0.2) (plogitnorm2(q + eps, 0.75, 0.2) - plogitnorm2(q - eps, 0.75, 0.2)) / (2 * eps)q = seq(0.1, 0.9, 0.1) eps = sqrt(.Machine$double.eps) dlogitnorm2(q, 0.75, 0.2) (plogitnorm2(q + eps, 0.75, 0.2) - plogitnorm2(q - eps, 0.75, 0.2)) / (2 * eps)
Density, distribution function, quantile function and random
generation for the negative binomial distribution with parameters
size and prob.
dnbinom2(x, mean, sd = sqrt(mean), log = FALSE)dnbinom2(x, mean, sd = sqrt(mean), log = FALSE)
x |
vector of (non-negative integer) quantiles. |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
log |
logical; if TRUE, probabilities p are given as log(p). |
The negative binomial distribution with size and
prob has density
for , and .
This represents the number of failures which occur in a sequence of
Bernoulli trials before a target number of successes is reached.
The mean is and variance .
A negative binomial distribution can also arise as a mixture of
Poisson distributions with mean distributed as a gamma distribution
(see pgamma) with scale parameter (1 - prob)/prob
and shape parameter size. (This definition allows non-integer
values of size.)
An alternative parametrization (often used in ecology) is by the
mean mu (see above), and size, the dispersion
parameter, where prob = size/(size+mu). The variance
is mu + mu^2/size in this parametrization.
If an element of x is not integer, the result of dnbinom
is zero, with a warning.
The case size == 0 is the distribution concentrated at zero.
This is the limiting distribution for size approaching zero,
even if mu rather than prob is held constant. Notice
though, that the mean of the limit distribution is 0, whatever the
value of mu.
The quantile is defined as the smallest value such that
, where is the distribution function.
dnbinom gives the density,
pnbinom is the cumulative distribution function, and
qnbinom is the quantile function of the negative binomial distribution.
rnbinom generates random deviates.
Invalid size or prob will result in return value
NaN, with a warning.
The length of the result is determined by n for
rnbinom, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rnbinom returns a vector of type integer unless generated
values exceed the maximum representable integer when double
values are returned.
dnbinom computes via binomial probabilities, using code
contributed by Catherine Loader (see dbinom).
pnbinom uses pbeta.
qnbinom uses the Cornish–Fisher Expansion to include a skewness
correction to a normal approximation, followed by a search.
rnbinom uses the derivation as a gamma mixture of Poisson
distributions, see Devroye (1986, page 480).
Devroye L (1986). Non-Uniform Random Variate Generation. Springer, New York. doi:10.1007/978-1-4613-8643-8. https://luc.devroye.org/handbooksimulation1.pdf.
Distributions for standard distributions, including
dbinom for the binomial, dpois for the
Poisson and dgeom for the geometric distribution, which
is a special case of the negative binomial.
dnbinom2(0:5, 2, sqrt(2))dnbinom2(0:5, 2, sqrt(2))
Density, distribution function, quantile function and random
generation for the normal distribution with mean equal to mean
and standard deviation equal to sd.
dnorm4(x, median = 0, kappa = 1, log = FALSE)dnorm4(x, median = 0, kappa = 1, log = FALSE)
x |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
log |
logical; if TRUE, probabilities p are given as log(p). |
If mean or sd are not specified they assume the default
values of 0 and 1, respectively.
The normal distribution has density
where is the mean of the distribution and
the standard deviation.
dnorm gives the density,
pnorm is the cumulative distribution function, and
qnorm is the quantile function of the normal distribution.
rnorm generates random deviates.
The length of the result is determined by n for
rnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
For sd = 0 this gives the limit as sd decreases to 0, a
point mass at mu.
sd < 0 is an error and returns NaN.
For pnorm, based on Cody (1993).
For qnorm, the code is based on a C translation of
Wichura (1988)
which provides precise results up to about 16 digits for
log.p=FALSE. For log scale probabilities in the extreme tails,
since R version 4.1.0, extensively since 4.3.0, asymptotic expansions
are used which have been derived and explored in
Mächler (2022).
For rnorm, see RNG for how to select the algorithm and
for references to the supplied methods.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Cody WJ (1993). “Algorithm 715: SPECFUN—A Portable FORTRAN Package of Special Function Routines and Test Drivers.” ACM Transactions on Mathematical Software, 19(1), 22–30. doi:10.1145/151271.151273.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 13.
Mächler M (2022). Asymptotic Tail Formulas for Gaussian Quantiles. Vignette, CRAN package DPQ, https://CRAN.R-project.org/package=DPQ/vignettes/qnorm-asymp.pdf.
Wichura MJ (1988). “Algorithm AS 241: The Percentage Points of the Normal Distribution.” Applied Statistics, 37(3), 477. doi:10.2307/2347330.
Distributions for other standard distributions, including
dlnorm for the log-normal distribution.
require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)
Null distributions always returns NA
dnull(x, ...)dnull(x, ...)
x |
vector of quantiles |
... |
passed onto named functions |
dnull(c(0.25, 0.5, 0.75), 0.5, 0.25)dnull(c(0.25, 0.5, 0.75), 0.5, 0.25)
The wedge distribution has a support of 0 to 1 and has a linear probability density function over that support.
dwedge(x, a, lower.tail = TRUE, log = FALSE)dwedge(x, a, lower.tail = TRUE, log = FALSE)
x |
vector of quantiles |
a |
a gradient from -2 (left skewed) to 2 (right skewed) |
lower.tail |
logical; if TRUE (default), probabilities are |
log |
logical; if TRUE, probabilities p are given as log(p). |
The rwedge can be combined with quantile functions to
skew standard distributions, or introduce correlation or down weight
certain parts of the distribution.
a vector of probabilities, quantiles, densities or samples.
pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )
Scenarios are based on an estimator producing predictions as parametrised
distributions, and the estimator can be characterised in terms of the bias
and sharpness distributions that govern predictions. Predictions are
then expressed as samples from these bias and sharpness distributions and
the associated distribution function (which will be parameterised with
mean = bias and sd = sharpness)
generate_simulation(config = i_sim_config, true_value_fn = NULL)generate_simulation(config = i_sim_config, true_value_fn = NULL)
config |
the simulation configuration - a dataframe with columns:
Any grouping allowed. |
true_value_fn |
a function that generates the true values e.g. a random sampler (default |
a
config = dplyr::tibble(samples = 100) config %>% generate_simulation()config = dplyr::tibble(samples = 100) config %>% generate_simulation()
The limiting null distribution of . For a standard
Brownian bridge , Johnson & Killeen (1983) give the c.d.f. of
as the convergent series
p_l1_bridge(q, terms = 30L) q_l1_bridge(p, terms = 30L)p_l1_bridge(q, terms = 30L) q_l1_bridge(p, terms = 30L)
q |
a vector of quantiles (non-negative) |
terms |
number of terms of the series to sum (default |
p |
a vector of probabilities |
with and
, where is the th zero of
. Terms are suppressed by with
, so the number of terms needed grows with q.
The default is ample over the whole range where the upper tail is
numerically distinguishable from zero; beyond q = 10 the c.d.f. is
returned as exactly 1.
p_l1_bridge() returns the c.d.f. evaluated at q;
q_l1_bridge() returns the quantile function evaluated at p
# the mean of the L1 norm of the bridge is known exactly to be sqrt(2 pi)/8 m = integrate(function(x) 1 - p_l1_bridge(x), 0, 5, subdivisions = 500L)$value testthat::expect_equal(m, sqrt(2 * pi) / 8, tolerance = 1e-5) # a proper distribution function testthat::expect_equal(p_l1_bridge(0), 0) testthat::expect_equal(p_l1_bridge(10), 1) testthat::expect_true(all(diff(p_l1_bridge(seq(0.05, 1, 0.05))) > 0)) # and its inverse testthat::expect_equal(p_l1_bridge(q_l1_bridge(0.95)), 0.95, tolerance = 1e-6)
Density, distribution function, quantile function and random
generation for the Beta distribution with parameters shape1 and
shape2 (and optional non-centrality parameter ncp).
pbeta2(q, prob, kappa, lower.tail = TRUE, log.p = FALSE)pbeta2(q, prob, kappa, lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
prob |
the mean probability (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dbeta gives the density,
pbeta is the cumulative distribution function, and
qbeta is the quantile function of the Beta distribution.
rbeta generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rbeta, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
pbeta2(c(0.25, 0.5, 0.75), 0.5, 0.25)pbeta2(c(0.25, 0.5, 0.75), 0.5, 0.25)
The following conversion describes the parameters mean and kappa
pcgamma(q, median, kappa = 1/median, lower.tail = TRUE, log.p = FALSE)pcgamma(q, median, kappa = 1/median, lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
pcgamma(seq(0, 4, 0.25), 2, 0.5)pcgamma(seq(0, 4, 0.25), 2, 0.5)
Cumulative probability from a named distribution
pdist(dist, q, ...)pdist(dist, q, ...)
dist |
the distribution name e.g. |
q |
vector of quantiles |
... |
passed onto named functions |
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
pgamma2(q, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)pgamma2(q, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
pgamma2(seq(0, 4, 0.25), 2, 1)pgamma2(seq(0, 4, 0.25), 2, 1)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
pgamma4(q, median, kappa = 1/median, lower.tail = TRUE, log.p = FALSE)pgamma4(q, median, kappa = 1/median, lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
pgamma2(seq(0, 4, 0.25), 2, 1)pgamma2(seq(0, 4, 0.25), 2, 1)
An estimator produces multiple parametrised probability distributions, from which we can calculate scores such as CPRS and PIT-W
pit_w( true_value, location, scale, dist = "norm", link = "identity", adjust = c("link", "probit") )pit_w( true_value, location, scale, dist = "norm", link = "identity", adjust = c("link", "probit") )
true_value |
The true value |
location |
The central estimate of the probabilistic prediction |
scale |
The spread estimate of the probabilisitic prediction |
dist |
The distribution name of the prediction (default |
link |
A link function mapping the value space to a linear one, e.g. "identity", "log" (default |
adjust |
adjustment method for constructing the pit value (default |
a one row data frame with:
U_pit an undirected pit-wasserstein
D_pit a directed pit-wasserstein
B_pit raw unadjusted undrected pit-wasserstein
scores = pit_w(0, qnorm(seq(1,199,2)/200, 0, 1), 1, dist = "norm", link="identity") testthat::expect_equal(scores$U_pit, 0) scores = pit_w(1, calibrated_locations(qlnorm4, 1, 1), 1, dist = "lnorm4", link="log") testthat::expect_equal(scores$U_pit, 0) scores = pit_w(1, calibrated_locations(qlnorm4, 1, 1), 1, dist = "lnorm4", link="log") testthat::expect_equal(scores$U_pit, 0) scores = pit_w(1, calibrated_locations(qgamma4, 1, 0.5), 0.5, dist = "gamma4", link="log") testthat::expect_equal(scores$U_pit, 0, tolerance = 10^-5)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
plnorm2(q, mean = 1, sd = sqrt(exp(1) - 1), lower.tail = TRUE, log.p = FALSE)plnorm2(q, mean = 1, sd = sqrt(exp(1) - 1), lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
plnorm2(seq(0, 4, 0.25), 2, 1)plnorm2(seq(0, 4, 0.25), 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
plnorm4(q, median = 1, kappa = 1, lower.tail = TRUE, log.p = FALSE)plnorm4(q, median = 1, kappa = 1, lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
plnorm4(seq(0, 4, 0.25), 2, 1)plnorm4(seq(0, 4, 0.25), 2, 1)
The logit-normal distribution has a support of 0 to 1.
plogitnorm(q, meanlogit = 0, sdlogit = 1, lower.tail = TRUE, log.p = FALSE)plogitnorm(q, meanlogit = 0, sdlogit = 1, lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
meanlogit |
the mean on the logit scale |
sdlogit |
the sd on the logit scale |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
a vector of probabilities, quantiles, densities or samples.
plogitnorm(seq(0.1, 0.9, 0.1), 0, 1)plogitnorm(seq(0.1, 0.9, 0.1), 0, 1)
The logit-normal distribution has a support of 0 to 1.
plogitnorm2( q, prob.0.5 = 0.5, kappa = 1 - exp(-1), lower.tail = TRUE, log.p = FALSE )plogitnorm2( q, prob.0.5 = 0.5, kappa = 1 - exp(-1), lower.tail = TRUE, log.p = FALSE )
q |
vector of quantiles |
prob.0.5 |
the median on the true scale |
kappa |
a dispersion parameter from 0 (none) to 1 maximum dispersion |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
a vector of probabilities, quantiles, densities or samples.
plogitnorm2(seq(0.1, 0.9, 0.1), 0.75, 0.2) plogitnorm2(qlogitnorm2(seq(0.1, 0.9, 0.1), 0.75, 0.2), 0.75, 0.2)plogitnorm2(seq(0.1, 0.9, 0.1), 0.75, 0.2) plogitnorm2(qlogitnorm2(seq(0.1, 0.9, 0.1), 0.75, 0.2), 0.75, 0.2)
Density, distribution function, quantile function and random
generation for the negative binomial distribution with parameters
size and prob.
pnbinom2(q, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)pnbinom2(q, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles. |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The negative binomial distribution with size and
prob has density
for , and .
This represents the number of failures which occur in a sequence of
Bernoulli trials before a target number of successes is reached.
The mean is and variance .
A negative binomial distribution can also arise as a mixture of
Poisson distributions with mean distributed as a gamma distribution
(see pgamma) with scale parameter (1 - prob)/prob
and shape parameter size. (This definition allows non-integer
values of size.)
An alternative parametrization (often used in ecology) is by the
mean mu (see above), and size, the dispersion
parameter, where prob = size/(size+mu). The variance
is mu + mu^2/size in this parametrization.
If an element of x is not integer, the result of dnbinom
is zero, with a warning.
The case size == 0 is the distribution concentrated at zero.
This is the limiting distribution for size approaching zero,
even if mu rather than prob is held constant. Notice
though, that the mean of the limit distribution is 0, whatever the
value of mu.
The quantile is defined as the smallest value such that
, where is the distribution function.
dnbinom gives the density,
pnbinom is the cumulative distribution function, and
qnbinom is the quantile function of the negative binomial distribution.
rnbinom generates random deviates.
Invalid size or prob will result in return value
NaN, with a warning.
The length of the result is determined by n for
rnbinom, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rnbinom returns a vector of type integer unless generated
values exceed the maximum representable integer when double
values are returned.
dnbinom computes via binomial probabilities, using code
contributed by Catherine Loader (see dbinom).
pnbinom uses pbeta.
qnbinom uses the Cornish–Fisher Expansion to include a skewness
correction to a normal approximation, followed by a search.
rnbinom uses the derivation as a gamma mixture of Poisson
distributions, see Devroye (1986, page 480).
Devroye L (1986). Non-Uniform Random Variate Generation. Springer, New York. doi:10.1007/978-1-4613-8643-8. https://luc.devroye.org/handbooksimulation1.pdf.
Distributions for standard distributions, including
dbinom for the binomial, dpois for the
Poisson and dgeom for the geometric distribution, which
is a special case of the negative binomial.
pnbinom2(0:5, 2, sqrt(2))pnbinom2(0:5, 2, sqrt(2))
Density, distribution function, quantile function and random
generation for the normal distribution with mean equal to mean
and standard deviation equal to sd.
pnorm4(q, median = 0, kappa = 1, lower.tail = TRUE, log.p = FALSE)pnorm4(q, median = 0, kappa = 1, lower.tail = TRUE, log.p = FALSE)
q |
vector of quantiles |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
If mean or sd are not specified they assume the default
values of 0 and 1, respectively.
The normal distribution has density
where is the mean of the distribution and
the standard deviation.
dnorm gives the density,
pnorm is the cumulative distribution function, and
qnorm is the quantile function of the normal distribution.
rnorm generates random deviates.
The length of the result is determined by n for
rnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
For sd = 0 this gives the limit as sd decreases to 0, a
point mass at mu.
sd < 0 is an error and returns NaN.
For pnorm, based on Cody (1993).
For qnorm, the code is based on a C translation of
Wichura (1988)
which provides precise results up to about 16 digits for
log.p=FALSE. For log scale probabilities in the extreme tails,
since R version 4.1.0, extensively since 4.3.0, asymptotic expansions
are used which have been derived and explored in
Mächler (2022).
For rnorm, see RNG for how to select the algorithm and
for references to the supplied methods.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Cody WJ (1993). “Algorithm 715: SPECFUN—A Portable FORTRAN Package of Special Function Routines and Test Drivers.” ACM Transactions on Mathematical Software, 19(1), 22–30. doi:10.1145/151271.151273.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 13.
Mächler M (2022). Asymptotic Tail Formulas for Gaussian Quantiles. Vignette, CRAN package DPQ, https://CRAN.R-project.org/package=DPQ/vignettes/qnorm-asymp.pdf.
Wichura MJ (1988). “Algorithm AS 241: The Percentage Points of the Normal Distribution.” Applied Statistics, 37(3), 477. doi:10.2307/2347330.
Distributions for other standard distributions, including
dlnorm for the log-normal distribution.
require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)
Null distributions always returns NA
pnull(q, ...)pnull(q, ...)
q |
vector of quantiles |
... |
passed onto named functions |
pnull(c(0.25, 0.5, 0.75), 0.5, 0.25)pnull(c(0.25, 0.5, 0.75), 0.5, 0.25)
Create a basket of scores for a set of paramtrised probabilistic predictions compared to a known ground truth, predictions are assumed to be distributional and associated with a link function that transforms them to linear space.
prediction_scores(df = i_comparison, summarise = TRUE, threshold = NA_real_)prediction_scores(df = i_comparison, summarise = TRUE, threshold = NA_real_)
df |
input dataframe - a dataframe with columns:
Minimally grouped by: dist + link + calibration + adjust (and other groupings allowed). |
summarise |
produce the results as a groupwise summary or a prediction by prediction metric (default |
threshold |
If given calculates the threshold misclassification probability (default |
a dataframe. columns depend on summarise
qs = seq(1, 199, 2) / 200 df = tidyr::crossing( true_value = 0, location = stats::qnorm(qs, 1, 1), scale = c(1 / 2, 1 / 1.5, 1, 1.5, 2), dist = "norm", link = "identity" ) %>% dplyr::mutate(calibration = scale) %>% dplyr::group_by(dist, link, calibration) df %>% prediction_scores() %>% dplyr::glimpse()qs = seq(1, 199, 2) / 200 df = tidyr::crossing( true_value = 0, location = stats::qnorm(qs, 1, 1), scale = c(1 / 2, 1 / 1.5, 1, 1.5, 2), dist = "norm", link = "identity" ) %>% dplyr::mutate(calibration = scale) %>% dplyr::group_by(dist, link, calibration) df %>% prediction_scores() %>% dplyr::glimpse()
The wedge distribution has a support of 0 to 1 and has a linear probability density function over that support.
pwedge(q, a, log.p = FALSE)pwedge(q, a, log.p = FALSE)
q |
vector of quantiles |
a |
a gradient from -2 (left skewed) to 2 (right skewed) |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The rwedge can be combined with quantile functions to
skew standard distributions, or introduce correlation or down weight
certain parts of the distribution.
a vector of probabilities, quantiles, densities or samples.
pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )
Density, distribution function, quantile function and random
generation for the Beta distribution with parameters shape1 and
shape2 (and optional non-centrality parameter ncp).
qbeta2(p, prob, kappa, lower.tail = TRUE, log.p = FALSE)qbeta2(p, prob, kappa, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities |
prob |
the mean probability (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dbeta gives the density,
pbeta is the cumulative distribution function, and
qbeta is the quantile function of the Beta distribution.
rbeta generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rbeta, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
qbeta2(c(0.25, 0.5, 0.75), 0.5, 0.25)qbeta2(c(0.25, 0.5, 0.75), 0.5, 0.25)
The following conversion describes the parameters mean and kappa
qcgamma(p, median, kappa = 1/median, lower.tail = TRUE, log.p = FALSE)qcgamma(p, median, kappa = 1/median, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
qcgamma(c(0.25, 0.5, 0.75), 2, 0.5)qcgamma(c(0.25, 0.5, 0.75), 2, 0.5)
Quantile function of a named distribution
qdist(dist, p, ...)qdist(dist, p, ...)
dist |
the distribution name e.g. |
p |
vector of probabilities |
... |
passed onto named functions |
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
qgamma2(p, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)qgamma2(p, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
qgamma2(c(0.25, 0.5, 0.75), 2, 1)qgamma2(c(0.25, 0.5, 0.75), 2, 1)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
qgamma4(p, median, kappa = 1, lower.tail = TRUE, log.p = FALSE)qgamma4(p, median, kappa = 1, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
qgamma2(c(0.25, 0.5, 0.75), 2, 1)qgamma2(c(0.25, 0.5, 0.75), 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
qlnorm2(p, mean = 1, sd = sqrt(exp(1) - 1), lower.tail = TRUE, log.p = FALSE)qlnorm2(p, mean = 1, sd = sqrt(exp(1) - 1), lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities. |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
qlnorm2(c(0.25, 0.5, 0.72), 2, 1)qlnorm2(c(0.25, 0.5, 0.72), 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
qlnorm4(p, median = 1, kappa = 1, lower.tail = TRUE, log.p = FALSE)qlnorm4(p, median = 1, kappa = 1, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities. |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
qlnorm4(c(0.25, 0.5, 0.72), 2, 1)qlnorm4(c(0.25, 0.5, 0.72), 2, 1)
The logit-normal distribution has a support of 0 to 1.
qlogitnorm(p, meanlogit = 0, sdlogit = 1, lower.tail = TRUE, log.p = FALSE)qlogitnorm(p, meanlogit = 0, sdlogit = 1, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities |
meanlogit |
the mean on the logit scale |
sdlogit |
the sd on the logit scale |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
a vector of probabilities, quantiles, densities or samples.
qlogitnorm(c(0.25, 0.5, 0.75), 0, 1)qlogitnorm(c(0.25, 0.5, 0.75), 0, 1)
The logit-normal distribution has a support of 0 to 1.
qlogitnorm2( p, prob.0.5 = 0.5, kappa = 1 - exp(-1), lower.tail = TRUE, log.p = FALSE )qlogitnorm2( p, prob.0.5 = 0.5, kappa = 1 - exp(-1), lower.tail = TRUE, log.p = FALSE )
p |
vector of probabilities |
prob.0.5 |
the median on the true scale |
kappa |
a dispersion parameter from 0 (none) to 1 maximum dispersion |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
a vector of probabilities, quantiles, densities or samples.
qlnorm2(c(0.25, 0.5, 0.72), 2, 1)qlnorm2(c(0.25, 0.5, 0.72), 2, 1)
Density, distribution function, quantile function and random
generation for the negative binomial distribution with parameters
size and prob.
qnbinom2(p, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)qnbinom2(p, mean, sd = sqrt(mean), lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities. |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The negative binomial distribution with size and
prob has density
for , and .
This represents the number of failures which occur in a sequence of
Bernoulli trials before a target number of successes is reached.
The mean is and variance .
A negative binomial distribution can also arise as a mixture of
Poisson distributions with mean distributed as a gamma distribution
(see pgamma) with scale parameter (1 - prob)/prob
and shape parameter size. (This definition allows non-integer
values of size.)
An alternative parametrization (often used in ecology) is by the
mean mu (see above), and size, the dispersion
parameter, where prob = size/(size+mu). The variance
is mu + mu^2/size in this parametrization.
If an element of x is not integer, the result of dnbinom
is zero, with a warning.
The case size == 0 is the distribution concentrated at zero.
This is the limiting distribution for size approaching zero,
even if mu rather than prob is held constant. Notice
though, that the mean of the limit distribution is 0, whatever the
value of mu.
The quantile is defined as the smallest value such that
, where is the distribution function.
dnbinom gives the density,
pnbinom is the cumulative distribution function, and
qnbinom is the quantile function of the negative binomial distribution.
rnbinom generates random deviates.
Invalid size or prob will result in return value
NaN, with a warning.
The length of the result is determined by n for
rnbinom, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rnbinom returns a vector of type integer unless generated
values exceed the maximum representable integer when double
values are returned.
dnbinom computes via binomial probabilities, using code
contributed by Catherine Loader (see dbinom).
pnbinom uses pbeta.
qnbinom uses the Cornish–Fisher Expansion to include a skewness
correction to a normal approximation, followed by a search.
rnbinom uses the derivation as a gamma mixture of Poisson
distributions, see Devroye (1986, page 480).
Devroye L (1986). Non-Uniform Random Variate Generation. Springer, New York. doi:10.1007/978-1-4613-8643-8. https://luc.devroye.org/handbooksimulation1.pdf.
Distributions for standard distributions, including
dbinom for the binomial, dpois for the
Poisson and dgeom for the geometric distribution, which
is a special case of the negative binomial.
qnbinom2(c(0.25, 0.5, 0.75), 5, sqrt(5))qnbinom2(c(0.25, 0.5, 0.75), 5, sqrt(5))
Density, distribution function, quantile function and random
generation for the normal distribution with mean equal to mean
and standard deviation equal to sd.
qnorm4(p, median = 0, kappa = 1, lower.tail = TRUE, log.p = FALSE)qnorm4(p, median = 0, kappa = 1, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities. |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
lower.tail |
logical; if |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
If mean or sd are not specified they assume the default
values of 0 and 1, respectively.
The normal distribution has density
where is the mean of the distribution and
the standard deviation.
dnorm gives the density,
pnorm is the cumulative distribution function, and
qnorm is the quantile function of the normal distribution.
rnorm generates random deviates.
The length of the result is determined by n for
rnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
For sd = 0 this gives the limit as sd decreases to 0, a
point mass at mu.
sd < 0 is an error and returns NaN.
For pnorm, based on Cody (1993).
For qnorm, the code is based on a C translation of
Wichura (1988)
which provides precise results up to about 16 digits for
log.p=FALSE. For log scale probabilities in the extreme tails,
since R version 4.1.0, extensively since 4.3.0, asymptotic expansions
are used which have been derived and explored in
Mächler (2022).
For rnorm, see RNG for how to select the algorithm and
for references to the supplied methods.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Cody WJ (1993). “Algorithm 715: SPECFUN—A Portable FORTRAN Package of Special Function Routines and Test Drivers.” ACM Transactions on Mathematical Software, 19(1), 22–30. doi:10.1145/151271.151273.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 13.
Mächler M (2022). Asymptotic Tail Formulas for Gaussian Quantiles. Vignette, CRAN package DPQ, https://CRAN.R-project.org/package=DPQ/vignettes/qnorm-asymp.pdf.
Wichura MJ (1988). “Algorithm AS 241: The Percentage Points of the Normal Distribution.” Applied Statistics, 37(3), 477. doi:10.2307/2347330.
Distributions for other standard distributions, including
dlnorm for the log-normal distribution.
require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)
Null distributions always returns NA
qnull(p, ...)qnull(p, ...)
p |
vector of probabilities |
... |
passed onto named functions |
qnull(c(0.25, 0.5, 0.75), 0.5, 0.25)qnull(c(0.25, 0.5, 0.75), 0.5, 0.25)
The wedge distribution has a support of 0 to 1 and has a linear probability density function over that support.
qwedge(p, a, lower.tail = TRUE, log.p = FALSE)qwedge(p, a, lower.tail = TRUE, log.p = FALSE)
p |
vector of probabilities |
a |
a gradient from -2 (left skewed) to 2 (right skewed) |
lower.tail |
logical; if TRUE (default), probabilities are |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
The rwedge can be combined with quantile functions to
skew standard distributions, or introduce correlation or down weight
certain parts of the distribution.
a vector of probabilities, quantiles, densities or samples.
pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )
A random Bernoulli sample as a logical value
rbern(n, prob)rbern(n, prob)
n |
number of observations |
prob |
the mean probability (vectorised) |
a vector of logical values of size n
table(rbern(100, 0.25))table(rbern(100, 0.25))
Density, distribution function, quantile function and random
generation for the Beta distribution with parameters shape1 and
shape2 (and optional non-centrality parameter ncp).
rbeta2(n, prob, kappa)rbeta2(n, prob, kappa)
n |
number of observations |
prob |
the mean probability (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
dbeta gives the density,
pbeta is the cumulative distribution function, and
qbeta is the quantile function of the Beta distribution.
rbeta generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rbeta, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rbeta2(3, c(0.1, 0.5, 0.9), 0.1)rbeta2(3, c(0.1, 0.5, 0.9), 0.1)
Sampling from the multinomial equivalent of the Bernoulli distribution
rcategorical(n, prob, factor = FALSE)rcategorical(n, prob, factor = FALSE)
n |
a sample size |
prob |
a (optionally named) vector of probabilities that will be normalised to sum to 1 |
factor |
if not FALSE then factor levels will either be taken from the
names of |
a vector of random class labels of length n. Labels come from names
of prob or from a character vector in factor.
prob = c("one" = 0.1, "two" = 0.2, "seven" = 0.7) table(rcategorical(1000, prob)) rcategorical(10, prob, factor = TRUE) rcategorical(10, rep(1, 26), factor = letters)prob = c("one" = 0.1, "two" = 0.2, "seven" = 0.7) table(rcategorical(1000, prob)) rcategorical(10, prob, factor = TRUE) rcategorical(10, rep(1, 26), factor = letters)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
rcgamma(n, median, kappa = 1/median)rcgamma(n, median, kappa = 1/median)
n |
number of observations |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rcgamma(10, 2, 0.5)rcgamma(10, 2, 0.5)
Random sample from a named distribution
rdist(dist, n, ...)rdist(dist, n, ...)
dist |
the distribution name e.g. |
n |
number of observations |
... |
passed onto named functions |
Get a converter that maps an unusual parametrisation to a canonical one.
reparam_fn(dist_name)reparam_fn(dist_name)
dist_name |
the distribution family as a string, e.g. |
a function that takes 2 parameters of the original distrbition and returns a list with the parameters and name of the canonical distribution.
tmp_fn = reparam_fn("lnorm2") tmp_fn(mean = 1, sd = 2)tmp_fn = reparam_fn("lnorm2") tmp_fn(mean = 1, sd = 2)
Randomly sample incident times in an exponentially growing process
rexpgrowth(n, r, t_end, t_start = 0)rexpgrowth(n, r, t_end, t_start = 0)
n |
the number of items to sample |
r |
and exponential growth rate (per unit time) |
t_end |
the end of the observation period |
t_start |
the start of the observation period (default |
a vector of n samples from an exponential growth process
graphics::hist(rexpgrowth(1000, 0.1, 40), breaks = 40) graphics::hist(rexpgrowth(1000, -0.1, 40), breaks = 40)graphics::hist(rexpgrowth(1000, 0.1, 40), breaks = 40) graphics::hist(rexpgrowth(1000, -0.1, 40), breaks = 40)
Randomly sample incident times in an exponentially growing process with initial case load
rexpgrowthI0(I0, r, t_end, t_start = 0)rexpgrowthI0(I0, r, t_end, t_start = 0)
I0 |
the expected number of cases observed in the first day |
r |
an exponential growth rate (per unit time) |
t_end |
the end of the observation period |
t_start |
the start of the observation period (default |
a vector of n samples from an exponential growth process
graphics::hist(rexpgrowthI0(10, 0.1, 20), breaks = 40) graphics::hist(rexpgrowthI0(1000, -0.1, 40), breaks = 40)graphics::hist(rexpgrowthI0(10, 0.1, 20), breaks = 40) graphics::hist(rexpgrowthI0(1000, -0.1, 40), breaks = 40)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
rgamma2(n, mean, sd = sqrt(mean))rgamma2(n, mean, sd = sqrt(mean))
n |
number of observations |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rgamma2(10, 2, 1)rgamma2(10, 2, 1)
Density, distribution function, quantile function and random
generation for the Gamma distribution with parameters shape and
scale.
rgamma4(n, median, kappa = 1/median)rgamma4(n, median, kappa = 1/median)
n |
number of observations |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
dgamma gives the density,
pgamma is the cumulative distribution function, and
qgamma is the quantile function of the Gamma distribution.
rgamma generates random deviates.
Invalid arguments will result in return value NaN, with a warning.
The length of the result is determined by n for
rgamma, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rgamma4(10, 2, 1)rgamma4(10, 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
rlnorm2(n, mean = 1, sd = sqrt(exp(1) - 1))rlnorm2(n, mean = 1, sd = sqrt(exp(1) - 1))
n |
number of observations. If |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
rlnorm2(10, 2, 1)rlnorm2(10, 2, 1)
Density, distribution function, quantile function and random
generation for the log-normal distribution whose logarithm has mean
equal to meanlog and standard deviation equal to sdlog.
rlnorm4(n, median = 1, kappa = 1)rlnorm4(n, median = 1, kappa = 1)
n |
number of observations. If |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
The log-normal distribution has density
where and are the mean and standard
deviation of the logarithm.
The mean is ,
the median is , and the variance
and hence the coefficient of variation is
which is
approximately when that is small (e.g., ).
dlnorm gives the density,
plnorm is the cumulative distribution function, and
qlnorm is the quantile function of the log-normal distribution.
rlnorm generates random deviates.
The length of the result is determined by n for
rlnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
The cumulative hazard
is -plnorm(t, r, lower = FALSE, log = TRUE).
dlnorm is calculated from the definition (in ‘Details’).
[pqr]lnorm are based on the relationship to the normal.
Consequently, they model a single point mass at exp(meanlog)
for the boundary case sdlog = 0.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 14.
Distributions for other standard distributions, including
dnorm for the normal distribution.
rlnorm4(10, 2, 1)rlnorm4(10, 2, 1)
The logit-normal distribution has a support of 0 to 1.
rlogitnorm(n, meanlogit = 0, sdlogit = 1)rlogitnorm(n, meanlogit = 0, sdlogit = 1)
n |
number of observations |
meanlogit |
the mean on the logit scale |
sdlogit |
the sd on the logit scale |
a vector of probabilities, quantiles, densities or samples.
rlogitnorm(10, 0, 1)rlogitnorm(10, 0, 1)
The logit-normal distribution has a support of 0 to 1.
rlogitnorm2(n, prob.0.5 = 0.5, kappa = 1 - exp(-1))rlogitnorm2(n, prob.0.5 = 0.5, kappa = 1 - exp(-1))
n |
number of observations |
prob.0.5 |
the median on the true scale |
kappa |
a dispersion parameter from 0 (none) to 1 maximum dispersion |
a vector of probabilities, quantiles, densities or samples.
mean(rlogitnorm2(10000, 0.75, 0.2))mean(rlogitnorm2(10000, 0.75, 0.2))
Density, distribution function, quantile function and random
generation for the negative binomial distribution with parameters
size and prob.
rnbinom2(n, mean, sd = sqrt(mean))rnbinom2(n, mean, sd = sqrt(mean))
n |
number of observations. If |
mean |
the mean value on the true scale (vectorised) |
sd |
the standard deviation on the true scale (vectorised) |
The negative binomial distribution with size and
prob has density
for , and .
This represents the number of failures which occur in a sequence of
Bernoulli trials before a target number of successes is reached.
The mean is and variance .
A negative binomial distribution can also arise as a mixture of
Poisson distributions with mean distributed as a gamma distribution
(see pgamma) with scale parameter (1 - prob)/prob
and shape parameter size. (This definition allows non-integer
values of size.)
An alternative parametrization (often used in ecology) is by the
mean mu (see above), and size, the dispersion
parameter, where prob = size/(size+mu). The variance
is mu + mu^2/size in this parametrization.
If an element of x is not integer, the result of dnbinom
is zero, with a warning.
The case size == 0 is the distribution concentrated at zero.
This is the limiting distribution for size approaching zero,
even if mu rather than prob is held constant. Notice
though, that the mean of the limit distribution is 0, whatever the
value of mu.
The quantile is defined as the smallest value such that
, where is the distribution function.
dnbinom gives the density,
pnbinom is the cumulative distribution function, and
qnbinom is the quantile function of the negative binomial distribution.
rnbinom generates random deviates.
Invalid size or prob will result in return value
NaN, with a warning.
The length of the result is determined by n for
rnbinom, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
rnbinom returns a vector of type integer unless generated
values exceed the maximum representable integer when double
values are returned.
dnbinom computes via binomial probabilities, using code
contributed by Catherine Loader (see dbinom).
pnbinom uses pbeta.
qnbinom uses the Cornish–Fisher Expansion to include a skewness
correction to a normal approximation, followed by a search.
rnbinom uses the derivation as a gamma mixture of Poisson
distributions, see Devroye (1986, page 480).
Devroye L (1986). Non-Uniform Random Variate Generation. Springer, New York. doi:10.1007/978-1-4613-8643-8. https://luc.devroye.org/handbooksimulation1.pdf.
Distributions for standard distributions, including
dbinom for the binomial, dpois for the
Poisson and dgeom for the geometric distribution, which
is a special case of the negative binomial.
rnbinom2(10, 5, sqrt(5))rnbinom2(10, 5, sqrt(5))
Density, distribution function, quantile function and random
generation for the normal distribution with mean equal to mean
and standard deviation equal to sd.
rnorm4(n, median = 0, kappa = 1)rnorm4(n, median = 0, kappa = 1)
n |
number of observations. If |
median |
the median value on the true scale (vectorised) |
kappa |
a coefficient of variation (sd/mean). where 0 is no variability. |
If mean or sd are not specified they assume the default
values of 0 and 1, respectively.
The normal distribution has density
where is the mean of the distribution and
the standard deviation.
dnorm gives the density,
pnorm is the cumulative distribution function, and
qnorm is the quantile function of the normal distribution.
rnorm generates random deviates.
The length of the result is determined by n for
rnorm, and is the maximum of the lengths of the
numerical arguments for the other functions.
The numerical arguments other than n are recycled to the
length of the result. Only the first elements of the logical
arguments are used.
For sd = 0 this gives the limit as sd decreases to 0, a
point mass at mu.
sd < 0 is an error and returns NaN.
For pnorm, based on Cody (1993).
For qnorm, the code is based on a C translation of
Wichura (1988)
which provides precise results up to about 16 digits for
log.p=FALSE. For log scale probabilities in the extreme tails,
since R version 4.1.0, extensively since 4.3.0, asymptotic expansions
are used which have been derived and explored in
Mächler (2022).
For rnorm, see RNG for how to select the algorithm and
for references to the supplied methods.
Becker RA, Chambers JM, Wilks AR (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.
Cody WJ (1993). “Algorithm 715: SPECFUN—A Portable FORTRAN Package of Special Function Routines and Test Drivers.” ACM Transactions on Mathematical Software, 19(1), 22–30. doi:10.1145/151271.151273.
Johnson NL, Kotz S, Balakrishnan N (1994).
Continuous Univariate Distributions, volume 1.
Wiley, New York.
ISBN 978-0-471-58495-7.
Chapter 13.
Mächler M (2022). Asymptotic Tail Formulas for Gaussian Quantiles. Vignette, CRAN package DPQ, https://CRAN.R-project.org/package=DPQ/vignettes/qnorm-asymp.pdf.
Wichura MJ (1988). “Algorithm AS 241: The Percentage Points of the Normal Distribution.” Applied Statistics, 37(3), 477. doi:10.2307/2347330.
Distributions for other standard distributions, including
dlnorm for the log-normal distribution.
require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)require(graphics) dnorm(0) == 1/sqrt(2*pi) dnorm(1) == exp(-1/2)/sqrt(2*pi) dnorm(1) == 1/sqrt(2*pi*exp(1)) ## Using "log = TRUE" for an extended range : par(mfrow = c(2,1)) plot(function(x) dnorm(x, log = TRUE), -60, 50, main = "log { Normal density }") curve(log(dnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("dnorm(x, log=TRUE)", adj = 0) mtext("log(dnorm(x))", col = "red", adj = 1) plot(function(x) pnorm(x, log.p = TRUE), -50, 10, main = "log { Normal Cumulative }") curve(log(pnorm(x)), add = TRUE, col = "red", lwd = 2) mtext("pnorm(x, log=TRUE)", adj = 0) mtext("log(pnorm(x))", col = "red", adj = 1) ## if you want the so-called 'error function' erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1 ## (see Abramowitz and Stegun 29.2.29) ## and the so-called 'complementary error function' erfc <- function(x) 2 * pnorm(x * sqrt(2), lower = FALSE) ## and the inverses erfinv <- function (x) qnorm((1 + x)/2)/sqrt(2) erfcinv <- function (x) qnorm(x/2, lower = FALSE)/sqrt(2)
Null distributions always returns NA
rnull(n, ...)rnull(n, ...)
n |
number of observations |
... |
passed onto named functions |
rnull(3, c(0.1, 0.5, 0.9), 0.1)rnull(3, c(0.1, 0.5, 0.9), 0.1)
The wedge distribution has a support of 0 to 1 and has a linear probability density function over that support.
rwedge(n, a)rwedge(n, a)
n |
number of observations |
a |
a gradient from -2 (left skewed) to 2 (right skewed) |
The rwedge can be combined with quantile functions to
skew standard distributions, or introduce correlation or down weight
certain parts of the distribution.
a vector of probabilities, quantiles, densities or samples.
pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )
The width and height of images to fit scientific publication standards.
std_sizestd_size
A list with width and height in inches
Tests the weakest of the three null hypotheses in the PIT-Wasserstein
family: that the predictive distributions have the right shape given an
arbitrary location error. The bias adjustment absorbs any common shift, so
a rejection here means the shape of the predictive distribution is wrong —
skew, tail weight, or a mixture of dispersion errors — and not that the
forecasts are merely off-centre. One-sided, as U_pit is a distance.
u_pit_significance(U_pit, n_predictions)u_pit_significance(U_pit, n_predictions)
U_pit |
the bias-adjusted undirected PIT-Wasserstein metric, as
returned by |
n_predictions |
the number of predictions each |
Because the adjustment estimates a parameter from the same data, the null is
not the baseline of b_pit_significance(): it is
the bridge with the estimated direction projected out (see .u_pit_null),
giving a 5% critical value about 0.66 times the baseline one at every n.
Using the baseline null here would be badly conservative. The adjusted null
is still distribution-free — it depends on n and nothing else — but has no
published c.d.f., so it is simulated once per session and cached.
U_pit says nothing about the direction of a dispersion error; pair it
with d_pit_significance(), which does.
a dataframe with one row per input value and columns:
U_pit, n_predictions — as supplied
statistic — , the quantity with a fixed null
expected — the null mean of U_pit
critical_0.05 — the one-sided 5% critical value of U_pit
p_value — the probability of a U_pit at least this large under the
location-free null
# the adjusted null is strictly tighter than the baseline one testthat::expect_lt( u_pit_significance(0, 100)$critical_0.05, b_pit_significance(0, 100)$critical_0.05 ) # the critical value scales as 1/sqrt(n) testthat::expect_equal( u_pit_significance(0, 400)$critical_0.05 * 2, u_pit_significance(0, 100)$critical_0.05, tolerance = 1e-6 ) # a statistic at the null mean is not significant testthat::expect_gt(u_pit_significance(u_pit_significance(0, 100)$expected, 100)$p_value, 0.3) # the 5% critical value returns a p value of about 0.05 crit = u_pit_significance(0, 100)$critical_0.05 testthat::expect_equal(u_pit_significance(crit, 100)$p_value, 0.05, tolerance = 0.005) # vectorised over both arguments testthat::expect_equal(nrow(u_pit_significance(c(0.02, 0.09), c(76, 76))), 2L)
The wedge distribution has a support of 0 to 1 and has a linear probability density function over that support.
n |
number of observations |
x |
vector of quantiles |
q |
vector of quantiles |
p |
vector of probabilities |
log |
logical; if TRUE, probabilities p are given as log(p). |
log.p |
logical; if TRUE, probabilities p are given as log(p). |
lower.tail |
logical; if TRUE (default), probabilities are |
a |
a gradient from -2 (left skewed) to 2 (right skewed) |
The rwedge can be combined with quantile functions to
skew standard distributions, or introduce correlation or down weight
certain parts of the distribution.
a vector of probabilities, quantiles, densities or samples.
pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )pwedge(seq(0, 1, 0.1), a = 1) dwedge(seq(0, 1, 0.1), a = 1) qwedge(c(0.25, 0.5, 0.75), a = -1) stats::cor( stats::qnorm(rwedge(1000, a = 2)), stats::qnorm(rwedge(1000, a = -2)) )