Package {epidist}


Title: Estimate Epidemiological Delay Distributions with 'brms'
Version: 1.0.0
Description: Understanding and accurately estimating epidemiological delay distributions is important for public health policy. These estimates influence epidemic situational awareness, control strategies, and resource allocation. This package provides methods to address the key challenges in estimating these distributions, including truncation, interval censoring, and dynamical biases, following Park et al. (2024) <doi:10.1101/2024.01.12.24301247> and Charniga et al. (2024) <doi:10.1371/journal.pcbi.1012520>. These issues are frequently overlooked, resulting in biased conclusions. Built on top of 'brms', it allows for flexible modelling including time-varying and spatial effects and partially pooled estimates of demographic characteristics.
License: MIT + file LICENSE
URL: https://epidist.epinowcast.org/, https://github.com/epinowcast/epidist/
BugReports: https://github.com/epinowcast/epidist/issues/
Depends: R (≥ 4.1.0)
Imports: brms (≥ 2.23.0), checkmate, cli, dplyr, lubridate, primarycensored (≥ 1.6.0), purrr, rstan (≥ 2.26.0), stats, tibble, tidyr, utils
Suggests: MASS, bayesplot, bookdown, collapse, distspec (≥ 0.2.0), flexsurv, ggplot2, knitr, loo, marginaleffects, patchwork, posterior, priorsense, reformulas, roxyglobals, scales, spelling, testthat (≥ 3.0.0), tidybayes, withr
Config/Needs/website: r-lib/pkgdown, epinowcast/enwtheme
Config/testthat/edition: 3
Config/roxyglobals/filename: globals.R
Config/roxyglobals/unique: FALSE
LazyData: true
VignetteBuilder: knitr
Encoding: UTF-8
Language: en-GB
Config/roxygen2/version: 8.1.0
NeedsCompilation: no
Packaged: 2026-09-29 18:46:17 UTC; lshsa2
Author: Adam Howes ORCID iD [aut], Sang Woo Park ORCID iD [aut], Sam Abbott ORCID iD [aut, cre, cph], Sebastian Funk ORCID iD [ctb]
Maintainer: Sam Abbott <contact@samabbott.co.uk>
Repository: CRAN
Date/Publication: 2026-10-13 14:40:02 UTC

epidist: Estimate Epidemiological Delay Distributions with 'brms'

Description

logo

Understanding and accurately estimating epidemiological delay distributions is important for public health policy. These estimates influence epidemic situational awareness, control strategies, and resource allocation. This package provides methods to address the key challenges in estimating these distributions, including truncation, interval censoring, and dynamical biases, following Park et al. (2024) doi:10.1101/2024.01.12.24301247 and Charniga et al. (2024) doi:10.1371/journal.pcbi.1012520. These issues are frequently overlooked, resulting in biased conclusions. Built on top of 'brms', it allows for flexible modelling including time-varying and spatial effects and partially pooled estimates of demographic characteristics.

Author(s)

Maintainer: Sam Abbott contact@samabbott.co.uk (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Add a default grid cutoff to summary estimates

Description

The grid used to compute the implied summaries of an unbiased estimand must be finite. Where the study adjusted for right truncation there is no observation time to use, so a cutoff is derived from the reported values. A lognormal is matched to what each study reported by .estimates_lnorm_match(), and the cutoff is the delay beyond which one percent of its second moment lies, which for parameters meanlog and sdlog is exp(meanlog + 2 * sdlog^2 + sdlog * qnorm(0.99)). This is the same yardstick as the short cutoff check of .estimates_short_cutoff(), which fires at two percent, so the default never trips it. The cutoff is rounded up to a whole number of secondary windows with a floor of ten. Where nothing can be matched, which is a study reporting a single quantile or a mean with a standard error, the cutoff is five times the largest reported value.

Usage

.add_default_max_delay(data)

Arguments

data

A data.frame containing study, type, value, p and swindow columns.

Value

The input with an added max_delay column.


Add delay_min column to data

Description

Resolves the delay_min argument into a column on the data frame. If NULL, uses an existing delay_min column or defaults to 0. If numeric, uses that scalar. If character, looks up the named column.

Usage

.add_delay_min(data, delay_min = NULL)

Arguments

data

A data frame

delay_min

NULL, a numeric scalar, or a column name string

Value

The data frame with a delay_min column


Additional distributional parameter information for brms families

Description

Includes additional information (link functions and parameter bound) about the distributional parameters of a brms family which are not the conditional mean mu.

Usage

.add_dpar_info(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

The family with other_links and other_bounds elements added.


Add the distributional parameters a primary event distribution needs

Description

Also records the distribution on the family so that the post-processing functions built from it use the same one.

Usage

.add_primary_dpars(family, data)

Arguments

family

A brms family object.

data

An epidist data object.

Value

The family with any primary event parameters added.


Add weights to a data frame

Description

Helper function to add weights to a data frame, either from an existing column or defaulting to 1.

Usage

.add_weights(data, weight = NULL)

Arguments

data

A data frame to add weights to

weight

A column name to use for weighting. If NULL, weights default to 1. Internally this is used to define the 'n' column of the returned object.

Value

The data frame with an added 'n' column containing the weights


Analytic delay summaries for the families that have them

Description

Each gives the brms parameters of the family and functions of them returning the mean, the standard deviation, the quantile function and the density of the delay distribution, built by .analytic_family().

Usage

.analytic_delay_summaries(name)

Arguments

name

The name of a delay distribution family.

Value

A list of solutions, or NULL when the family has none.


Build the analytic delay summaries of a family

Description

Build the analytic delay summaries of a family

Usage

.analytic_family(dpars, dist, natural, mean, sd)

Arguments

dpars

The brms parameters of the family.

dist

The distribution function name, as used by .pdist().

natural

A function of the brms parameters returning the named arguments of the distribution's R functions.

mean, sd

Functions of the brms parameters returning the mean and the standard deviation.

Value

A list with dpars and the functions mean(d), sd(d), quantile(d, p) and density(d, x) of the brms parameters d.


Add summaries from an analytic solution

Description

Add summaries from an analytic solution

Usage

.analytic_summaries(data, analytic, probs = NULL)

Arguments

data

A data.frame of draws of the distributional parameters, as returned by delay_parameter_draws().

analytic

A list of analytic solutions, as returned by .analytic_delay_summaries().

probs

A numeric vector of probabilities to add quantiles of the delay distribution for. If NULL, the default, no quantiles are added.

Value

The input with summary columns added.


Check that the distributional parameters of a family are present

Description

Check that the distributional parameters of a family are present

Usage

.assert_dpars(data, name, dpars)

Arguments

data

A data.frame of draws of the distributional parameters, as returned by delay_parameter_draws().

name

The name of a delay distribution family.

dpars

The distributional parameters the family needs.

Value

The input, invisibly.


Check the parameters a study reported for its fitted distribution

Description

Check the parameters a study reported for its fitted distribution

Usage

.assert_estimates_parameters(family, parameters)

Arguments

family

The distribution the study fitted.

parameters

A named numeric vector of the reported parameters.

Value

The parameters, ordered as the family expects.


Check the covariance matrices of an epidist_estimates_data object

Description

Each matrix must cover the rows sharing its mvn_id, be symmetric, and be positive definite, so that it has a Cholesky factor and defines a proper multivariate normal.

Usage

.assert_estimates_vcov(data)

Arguments

data

An epidist_estimates_data object.

Value

NULL, invisibly.


Check that a fit is a meta model fitted with epidist()

Description

Check that a fit is a meta model fitted with epidist()

Usage

.assert_meta_fit(fit)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

Value

NULL, invisibly.


Assert that the group rows of an epidist_meta_model object are consistent

Description

A group row stands for several summaries reported by one study and indexes them in the flat member arrays. This checks that every index lands inside those arrays, that each kind of group has the members its likelihood needs, and that a set of quantiles is a partition of the delay axis.

Usage

.assert_meta_groups(data)

Arguments

data

An epidist_meta_model object.

Value

NULL, invisibly.


Check that a covariance matrix has a usable Cholesky factor

Description

A set of quantities that are deterministic functions of fewer underlying parameters has a covariance of the rank of those parameters, not of its own dimension. Five summaries of a two parameter fit are the common case. The message says so, because the alternative reading, that a column is constant or repeated, is usually not what happened. The rank is judged on the correlation matrix against .multivariate_eigen_floor(), because a covariance that is singular only up to the curvature of the map from parameters to summaries still has a Cholesky factor.

Usage

.assert_multivariate_definite(vcov)

Arguments

vcov

A covariance matrix.

Value

NULL, invisibly.


Refuse a primary event distribution for a summaries only meta model

Description

The summaries only methods of as_epidist_meta_model() pass their extra arguments here. A primary among them would be silently ignored otherwise, since summary rows take their tilt from the growth_rate metadata.

Usage

.assert_no_meta_primary(...)

Arguments

...

The extra arguments of a summaries only method.

Value

NULL, invisibly.


Check that a family is one the epidist helpers support

Description

Check that a family is one the epidist helpers support

Usage

.assert_supported_family(family)

Arguments

family

A brmsfamily object.

Value

The family, invisibly. Errors when the family is not supported.


Reject a grouped data.frame

Description

The ⁠as_epidist_*()⁠ constructors that build a model or aggregate object from epidist_linelist_data number rows or count observations in ways that go wrong silently on a grouped data.frame, for example dplyr::row_number() restarting within each group. Grouped input is rejected here rather than accepted and mishandled.

Usage

.assert_ungrouped(data)

Arguments

data

An object to check.

Value

NULL, invisibly. Called for the side effect of raising an error when data is a grouped data.frame.


Check a reporting window argument

Description

Accepts a single value or one value per observation, and recycles a single value so the caller can treat them the same.

Usage

.assert_window(window, n, name)

Arguments

window

The reporting window argument to check.

n

The number of observations it has to cover.

name

The argument name, used in error messages.

Value

The window as a vector of length n.


Bin the delays of each stratum

Description

Bin the delays of each stratum

Usage

.bin_delays(delays, binwidth = 1, keep = NULL)

Arguments

delays

A tibble of delays with their .stratum, as returned by .draw_strata().

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

keep

A character vector of columns of delays to keep, which must be constant within a stratum.

Value

A tibble with one row per stratum and bin, holding the lower edge of the bin as delay, the weighted count n, the proportion of the stratum p and the density density.


The delay families whose brms post-processing epidist replaces

Description

The delay families whose brms post-processing epidist replaces

Usage

.brms_delay_families()

Value

A character vector of brms family names.


The stats distribution of a brms delay family

Description

Replaces the family specific parts of the brms internals ⁠log_lik_<family>()⁠ and ⁠posterior_predict_<family>()⁠ for the delay families brms provides and epidist supports. brms gives mu as the mean of the gamma, Weibull and exponential families and as the mean of the log delay for the lognormal family.

Usage

.brms_family_dist(family, prep, i)

Arguments

family

The name of a brms family, for example "lognormal".

prep

A brms prepared predictions object.

i

The index of the observation.

Value

A list with the stats distribution name dist, for example "lnorm", and its arguments args for observation i.


The post-processing functions of a delay family

Description

Gives the functions with the signatures brms expects of a custom family, for a delay family brms provides. Other families get functions that error when called, so a model can still be fitted with them.

Usage

.brms_family_fn(prefix, family)

Arguments

prefix

One of "log_lik", "posterior_predict" or "posterior_epred".

family

The name of a brms family, for example "lognormal".

Value

A function.


The log likelihood of a brms delay family

Description

Replaces the brms internals ⁠log_lik_<family>()⁠, log_lik_censor() and log_lik_truncate(). Observation i may be left (cens of -1), right (1) or interval (2) censored, with the upper end of the interval in rcens, and truncated to lie between lb and ub.

Usage

.brms_family_log_lik(family, i, prep)

Arguments

family

The name of a brms family, for example "lognormal".

i

The index of the observation.

prep

A brms prepared predictions object.

Value

The log likelihood of observation i for every draw.


The mean of a brms delay family

Description

Replaces the brms internals ⁠posterior_epred_<family>()⁠.

Usage

.brms_family_posterior_epred(family, prep)

Arguments

family

The name of a brms family, for example "lognormal".

prep

A brms prepared predictions object.

Value

The mean delay for every draw and observation.


Draw from a brms delay family

Description

Replaces the brms internals ⁠posterior_predict_<family>()⁠ and rcontinuous(). When observation i is truncated to lie between lb and ub the delays are drawn by inverting the distribution function.

Usage

.brms_family_posterior_predict(family, i, prep)

Arguments

family

The name of a brms family, for example "lognormal".

i

The index of the observation.

prep

A brms prepared predictions object.

Value

A delay for observation i for every draw.


Expand variables into a grid and add the variables a model needs

Description

Used by the epidist_newdata() methods. Any epidist class is dropped before expanding so that the class methods documented in epidist_data do not warn about an object that was never meant to stay in its class.

Usage

.build_newdata(data, ..., .cols, .supplied = character())

Arguments

data

An epidist data object.

...

Variables to expand into a grid, passed to tidyr::expand().

.cols

A named list of the variables to add, each of which is crossed with the grid.

.supplied

Names of the method's own arguments that the user gave, usually intersect(names(match.call()), names(formals())). A name that was both expanded and supplied is an error. Names passed through ... are not included, so setting a column with the tidyr::expand() syntax, such as pwindow = 1:2, still works.

Value

A tibble::tibble() of newdata.


Capture the environment variables rstan leaks when compiling a model

Description

The rstan backend compiles through inline::cxxfunction(), which sets PKG_CPPFLAGS and PKG_LIBS and never restores them. The leaked flags make the next pkgbuild::has_build_tools() check fail, which prints a spurious compiler error before the model compiles and fits successfully. Restore them with .restore_compile_env() after a fit.

Usage

.capture_compile_env()

Value

A named character vector of the current values, NA where unset.


Check an object against the requirements of a single epidist class

Description

Check an object against the requirements of a single epidist class

Usage

.check_epidist_class(data, class)

Arguments

data

An object to check.

class

A character string giving the epidist class to check against.

Value

NULL if data meets the requirements of class, or if class has no assert_epidist() method, and otherwise the message explaining why it does not.


Check that ggplot2 is installed

Description

ggplot2 is a suggested package, so the plot functions check for it before they use it.

Usage

.check_ggplot2()

Value

NULL, invisibly.


Model specific checks of user supplied prior distributions

Description

Dispatches on the class of data so that a model can reject or warn about prior distributions it does not support. By default no checks are made.

Usage

.check_model_prior(data, prior)

Arguments

data

An object with class corresponding to an implemented model.

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

Value

NULL, invisibly, called for the messages it may raise.


Check user supplied prior distributions for latent models

Description

The latent model reparameterises the event windows so that pwindow_raw and swindow_raw are on the unit interval. A non uniform prior on swindow_raw is not supported and a non uniform prior on pwindow_raw is only partially supported.

Usage

## S3 method for class 'epidist_latent_model'
.check_model_prior(data, prior)

Arguments

data

An object with class corresponding to an implemented model.

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

Value

NULL, invisibly, called for the messages it may raise.


Find the bins the data or the predictions put mass in

Description

Find the bins the data or the predictions put mass in

Usage

.delay_bins_with_mass(observed, predicted)

Arguments

observed

The binned observed delays, as returned by .bin_delays().

predicted

The binned predicted delays, as returned by .predicted_delays().

Value

A tibble of the .stratum and delay of each bin to draw.


Draw the binned delays of each stratum as columns

Description

Draw the binned delays of each stratum as columns

Usage

.delay_column_plot(plot_data, legend, binwidth)

Arguments

plot_data

The binned delays, as returned by .bin_delays().

legend

The legend title, or NULL for none.

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

Value

A ggplot object.


Evaluate the density of the delay distribution at each draw

Description

Uses the density of the family when there is an analytic solution, and otherwise simulates delays from each draw with .simulate_delays() and estimates their density with stats::density().

Usage

.delay_density_grid(family, dpars, max_delay = NULL, n_grid = 101, nsim = 1000)

Arguments

family

A delay distribution family as returned by .resolve_delay_family(), a list with the family name and its distributional parameters dpars.

dpars

A named list of distributional parameter vectors.

max_delay

The largest delay to evaluate the delay distribution at when type = "delay". If NULL, the default, the posterior median of the 99% quantile of the delay distribution is used.

n_grid

The number of delays to evaluate the density at.

nsim

The number of delays to simulate per row of data. Defaults to 1000. Only used when simulating.

Value

A list with delays, the delays the density is evaluated at, and density, a matrix with one row per draw and one column per delay.


The delay distribution family of a fitted model

Description

The families epidist builds are brms custom families named after the model and the delay distribution, such as latent_lognormal. This returns the delay distribution part, which is what the summaries and the simulation need.

Usage

.delay_family(family)

Arguments

family

A brms family.

Value

A list with the delay distribution name and its distributional parameters dpars.


Find the minimum delay the datasets record

Description

Find the minimum delay the datasets record

Usage

.delay_min_of(datasets)

Arguments

datasets

A list of epidist_linelist_data objects.

Value

The single minimum delay the datasets record, or NULL when they do not all record the same one.


Label the axes of a delay plot and theme it

Description

Label the axes of a delay plot and theme it

Usage

.delay_plot_labs(p)

Arguments

p

A ggplot object.

Value

A ggplot object.


Draw the predicted delays over the observed delays

Description

Draw the predicted delays over the observed delays

Usage

.delay_predictive_layers(predicted, single)

Arguments

predicted

The binned predicted delays, as returned by .predicted_delays().

single

A logical, TRUE when there is a single stratum.

Value

A list of ggplot2 layers.


Draw a reference delay distribution over the observed delays

Description

Draw a reference delay distribution over the observed delays

Usage

.delay_reference_layer(reference, family, plot_data, binwidth)

Arguments

reference

A named numeric vector of the distributional parameters of a delay distribution to draw over the columns, as c(mu = 1.8, sigma = 0.5) for a lognormal delay. If NULL, the default, no distribution is drawn.

family

A brms family, or the name of one, giving the delay distribution reference holds the parameters of. Defaults to "lognormal".

plot_data

The binned delays, as returned by .bin_delays().

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

Value

A ggplot2 layer.


Label the strata of the observed delays of one or more datasets

Description

Takes the observed delay of each case, labels it with the dataset it came from, and hands the labelling to .draw_strata(). A single dataset with no by has one stratum, and a list of datasets is stratified by its names.

Usage

.delay_strata(datasets, by = NULL)

Arguments

datasets

A named list of epidist_linelist_data objects.

by

A string naming a column of x to stratify the delays by.

Value

A list as returned by .draw_strata(), holding the observed delay of each case, its weight n and its .stratum.


Describe prior distributions for use in messages

Description

Gives each prior as its distribution followed by the parameter it applies to, dropping the matching columns which are empty. Braces are escaped so that the result can be passed to cli.

Usage

.describe_prior(prior)

Arguments

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

Value

A character vector with one entry per prior.


The functions of a primarycensored distribution name

Description

.pdist() gives the distribution function, .ddist() the density and .qdist() the quantile function, all found by swapping the leading p of the name.

Usage

.dist_fn(dist, type)

.pdist(dist)

.ddist(dist)

.qdist(dist)

Arguments

dist

A primarycensored distribution function name, for example "plnorm".

type

One of "p", "d" or "q".

Value

The function of that name from the package that provides the distribution.


The distspec constructor and natural parameters of a delay family

Description

Maps the name of a delay distribution family to the distspec constructor that represents it and to a function turning draws of its brms parameters into draws of the natural parameters of that constructor.

Usage

.dist_spec_family(name)

Arguments

name

The name of a delay distribution family, as returned by .delay_family().

Value

A list with the family name, the constructor name, the brms parameters dpars it needs, and a function natural taking a list of draws of them and returning a named list of draws of the natural parameters.


Summarise draws of the delay parameters into a ⁠<dist_spec>⁠

Description

Summarise draws of the delay parameters into a ⁠<dist_spec>⁠

Usage

.dist_spec_from_draws(draws, family, max = Inf, cdf_max = 1)

Arguments

draws

A data.frame of draws of the brms parameters of the delay distribution for a single row of newdata, as one group of the result of delay_parameter_draws().

family

A list describing the family, as returned by .dist_spec_family().

max

The maximum of the delay distribution, passed to distspec::bound_dist(). Defaults to Inf, which is no maximum.

cdf_max

The cumulative probability to keep the delay distribution up to, passed to distspec::bound_dist(). Defaults to 1, which keeps the whole distribution.

Value

A ⁠<dist_spec>⁠.


Natural scale bounds of a distributional parameter

Description

Replaces brms:::dpar_bounds() for the non-mixture families that epidist supports. Guarantees a list with character elements lb and ub giving the lower and upper bound of dpar on the natural scale, where "" means unbounded. A custom family, such as gengamma(), records its own bounds, which are returned as brms does. Unlike the brms internal, an unrecognised parameter is an error rather than NULL, because epidist cannot generate Stan code without a bound.

Usage

.dpar_bounds(dpar, family = NULL)

Arguments

dpar

A character string naming a distributional parameter.

family

A brmsfamily object, whose bounds are used when it is a custom family. Otherwise unused and kept so that the signature matches the brms internal this helper replaces.

Value

A list with character elements lb and ub.


Draws of each distributional parameter in a long data.frame

Description

Draws of each distributional parameter in a long data.frame

Usage

.dpar_draws(object, newdata = NULL, ...)

Arguments

object

A model fit with epidist().

newdata

A data.frame of data to predict for. If NULL, the default, the data the model was fitted to is used. The brms models epidist fits need the model variables as well as the predictors, so build newdata with epidist_strata() rather than from the predictors alone.

...

Additional arguments passed to brms::prepare_predictions(), such as ndraws or re_formula.

Value

A data.frame with columns .row, .chain, .iteration, .draw and one column per distributional parameter.


Chain and iteration index of each posterior draw

Description

brms stores draws ordered by chain, so the chain and iteration of a draw follow from its position. A subset of draws cannot be placed this way, so both are NA in that case, as they are in tidybayes.

Usage

.draw_chain_iteration(object, pp)

Arguments

object

A model fit with epidist().

pp

A brmsprep object from brms::prepare_predictions().

Value

A list with chain and iteration elements.


Label the strata of a data.frame of draws

Description

Label the strata of a data.frame of draws

Usage

.draw_strata(object, by = NULL)

Arguments

by

A character vector of columns of object that define the strata to colour by. If NULL, the default, the variables recorded on object are used. See the details.

Value

A list with data, an ungrouped tibble of the draws with a .stratum factor column, by, the columns the strata are defined by or NULL when there is a single stratum, and legend, a legend title.


Drop the epidist_delay_draws class from an object

Description

Drop the epidist_delay_draws class from an object

Usage

.drop_delay_draws_class(data)

Arguments

data

An object to drop the class from.

Value

data without the epidist_delay_draws class.


Drop epidist classes from an object

Description

Removes class from data, and also removes the shared epidist_data class once no specific epidist class is left.

Usage

.drop_epidist_class(data, class = NULL)

Arguments

data

An object to drop classes from.

class

A character vector of epidist classes to drop. Defaults to NULL, in which case all epidist classes are dropped.

Value

data with the requested classes removed.


Remove one study from the model data of a meta model

Description

An epidist_meta_model object is subset through the epidist_data methods, which check the result, and then transformed with epidist_transform_data() so that its rows are summarised as they were for the full fit. The plain model data stored in a fit has already been transformed, so it is subset directly.

Usage

.drop_study(data, study, fit)

Arguments

data

An epidist_meta_model object or the model data of a meta model fit, with a study column.

study

The label of the study to remove.

fit

The fit whose family and formula the transform uses.

Value

The model data without the rows of study.


Extract the specific epidist classes of an object

Description

Extract the specific epidist classes of an object

Usage

.epidist_classes(data)

Arguments

data

An object.

Value

A character vector of the epidist classes of data, excluding the shared epidist_data class.


The discrete colour scale the package plots use

Description

Uses .epidist_palette() when it holds enough colours and the viridis scale otherwise. The scale covers both the colour and the fill aesthetic, so that a variable mapped to each gets one legend.

Usage

.epidist_colour_scale(n)

Arguments

n

The number of levels to colour.

Value

A ggplot2 scale.


The families epidist defines itself

Description

brms names a custom family "custom" and keeps its own name in name, so these are looked up by that name where brms would be asked for one of its own families.

Usage

.epidist_families()

Value

A named list of family constructors.


The colour palette the package plots use

Description

The Okabe-Ito palette, ordered so that the first two colours are the blue and green the vignettes use for the primary and secondary events. It is colour blind friendly and holds eight colours.

Usage

.epidist_palette()

Value

A character vector of colours.


The theme the package plots use

Description

ggplot2::theme_minimal() with the legend below the plot, as the package documentation draws its plots.

Usage

.epidist_plot_theme()

Value

A ggplot2 theme.


A column of an epireview table, or NA where it is absent

Description

A column of an epireview table, or NA where it is absent

Usage

.epireview_column(data, names)

Arguments

data

A tibble of epireview records.

names

The names the column may have, tried in order.

Value

The first of the columns present, or a vector of NA with one entry per record where none is.


The default as_epidist_estimates_data() assumes for a metadata column

Description

Reads from .estimates_default_values so the fallback matches .fill_estimates_defaults() without restating each value here.

Usage

.epireview_default(col, meta)

Arguments

col

The column.

meta

The metadata of each record, as built by .epireview_metadata().

Value

A vector with one default per record.


The family epidist calls a distribution epireview names

Description

The family epidist calls a distribution epireview names

Usage

.epireview_family(type)

Arguments

type

A character vector of epireview distribution types.

Value

A character vector of families, NA where the family is not one epidist_estimates_parameters() supports.


Resolve the study metadata of each epireview record

Description

Starts from the metadata shared by every record, replaces it with the values metadata gives for each study, and fills the studies a column leaves blank with the default as_epidist_estimates_data() would assume. A column no study has a value for is left out, so that as_epidist_estimates_data() assumes it and messages once. The studies filled are reported by .epireview_report_gaps() once the records kept are known, so that a dropped record is not named.

Usage

.epireview_metadata(studies, n, metadata, shared)

Arguments

studies

A character vector naming the study of each record.

n

A numeric vector of the sample size of each record.

metadata

A data.frame of study metadata, or NULL.

shared

A named list of metadata applied to every record.

Value

A list holding meta, a tibble with one row per record and the study, n and metadata columns that were given, and filled, a list with one logical vector per column filled marking the records filled.


The metadata columns epidist_estimates_epireview() takes

Description

The metadata columns epidist_estimates_epireview() takes

Usage

.epireview_metadata_cols()

Value

A character vector of column names.


The parameter name epidist uses for a parameter type epireview names

Description

The parameter name epidist uses for a parameter type epireview names

Usage

.epireview_parameter_name(type)

Arguments

type

A character vector of epireview parameter types.

Value

A character vector of parameter names, NA where the type is not recognised. A mean is "mean" and a standard deviation "sd", which are the moments a fit is often recorded by rather than natural parameters.


The natural parameters of the distribution an epireview record fitted

Description

The natural parameters of the distribution an epireview record fitted

Usage

.epireview_parameters(data)

Arguments

data

A tibble of epireview records.

Value

A list with one element per record, NULL where the record does not report a supported family by a supported set of parameters, and otherwise a list holding the family and the named parameters.


Message about the epireview records that were dropped

Description

Message about the epireview records that were dropped

Usage

.epireview_report_dropped(studies, reason)

Arguments

studies

A character vector naming the study of each record.

reason

A character vector giving the reason each record was dropped, NA for a record that was kept.

Value

NULL, invisibly, called for the message it may raise.


Message about the studies a metadata column left blank

Description

A study assumed to have adjusted for right truncation is warned about, as as_epidist_estimates_data() warns.

Usage

.epireview_report_gaps(meta, filled, kept)

Arguments

meta

The metadata of each record, as built by .epireview_metadata().

filled

A list with one logical vector per column filled, as built by .epireview_metadata().

kept

A logical vector marking the records kept.

Value

NULL, invisibly, called for the messages it may raise.


The rows of the long format one epireview record contributes

Description

The rows of the long format one epireview record contributes

Usage

.epireview_row(record, type, value, se = NA_real_, p = NA_real_)

Arguments

record

The index of the record.

type

The summary type of each row.

value

The reported value of each row.

se

The reported standard error of each row.

p

The probability of each quantile row.

Value

A data.frame with one row per value.


Map each epireview record to the rows of the long format

Description

Map each epireview record to the rows of the long format

Usage

.epireview_rows(data, meta)

Arguments

data

A tibble of epireview records.

meta

The metadata of each record, as built by .epireview_metadata().

Value

A data.frame with a .record column indexing the records and the type, value, se and p of each row.


The standard deviation an epireview record reports alongside its mean

Description

The standard deviation an epireview record reports alongside its mean

Usage

.epireview_sd(data, i, spread, spread_type)

Arguments

data

A tibble of epireview records.

i

The record.

spread

The single uncertainty value of each record.

spread_type

The single uncertainty type of each record.

Value

The standard deviation, or NA where none is reported. A standard deviation of zero is treated as not reported by the caller, because as_epidist_estimates_data() rejects it.


Check the shared study metadata passed to epidist_estimates_epireview()

Description

Check the shared study metadata passed to epidist_estimates_epireview()

Usage

.epireview_shared_metadata(...)

Arguments

...

Study metadata applied to every record.

Value

A named list with one value per metadata column given.


Escape braces so that cli does not interpolate them

Description

Messages from checkmate contain braces, which cli would otherwise treat as glue interpolation.

Usage

.escape_braces(x)

Arguments

x

A character vector.

Value

x with each brace doubled.


Advise on summary estimates the meta model will fit poorly

Description

Runs the advisory checks on a freshly built epidist_estimates_data object and messages about each study they flag. They run once, here, when the object is first built, rather than in assert_epidist(), so that passing the finished object on to as_epidist_meta_model() does not repeat them. The pointer to the Checks section of as_epidist_estimates_data.data.frame(), which describes the checks, prints once after the messages when at least one check fired.

Usage

.estimates_advise(data)

Arguments

data

An epidist_estimates_data object.

Value

NULL, invisibly, called for the messages it may raise.


Bind coerced contributions into one epidist_estimates_data object

Description

Covariance matrices are keyed by mvn_id, so a key used by two contributions is renamed before the rows are bound.

Usage

.estimates_bind(parts)

Arguments

parts

A list of epidist_estimates_data objects.

Value

An epidist_estimates_data object.


The pointer that follows the advisory messages

Description

The pointer that follows the advisory messages

Usage

.estimates_checks_pointer()

Value

A named character vector for cli::cli_inform().


Studies whose quadrature nodes are far apart relative to their delays

Description

The number of quadrature intervals of .estimates_n_quad() is capped, so a study whose grid cutoff is very long relative to the spread it reported is left with nodes further apart than a quarter of that spread. This covers a study that did not adjust for right truncation and used a continuous adjustment (cens_adjusted of 1, 2 or 4), a study that did adjust but whose primary events were not uniform within their window (cens_adjusted of 2 or 4 with a non zero or estimated growth_rate), and the quantile members of a covariance matrix group, which are read off the same nodes.

Usage

.estimates_coarse_quadrature(data)

Arguments

data

An epidist_estimates_data object.

Value

A character vector of study identifiers whose quadrature is coarse.


Studies reporting quantiles on a coarse delay grid

Description

The studies flagged by .estimates_coarse_rows().

Usage

.estimates_coarse_quantiles(data)

Arguments

data

An epidist_estimates_data object.

Value

A character vector of study identifiers reporting quantiles on a coarse grid.


The smallest quantile of each study on a coarse delay grid

Description

A study that summarised interval censored delays without adjusting for censoring (cens_adjusted of 0 or 3) reports quantiles of a discrete distribution, which the model interpolates through the mid points of its cells. The reported value is still rounded to that grid, and what the interpolation leaves behind does not shrink with the study sample size. It is a few percent once a reported quantile sits a few tens of cells above the smallest delay the study counted, and tens of percent when it sits within about ten. A study is flagged on its smallest reported quantile, the one nearest that edge of the grid, because the residual on that quantile is what biases the fitted spread even when the larger quantiles of the same study sit well up the grid. A reported mean and standard deviation of the same delays do not carry this residual, so they should be fitted in preference where the study gives them.

Usage

.estimates_coarse_rows(data)

Arguments

data

An epidist_estimates_data object.

Value

A logical vector, one entry per row, marking the smallest reported quantile of each flagged study.


Default values as_epidist_estimates_data() assumes for metadata columns

Description

Shared by .fill_estimates_defaults() and .epireview_default() so the two stay in step.

Usage

.estimates_default_values

A numerical Jacobian of the map from parameters to summaries

Description

Uses a central difference with a step relative to each parameter, held away from zero so that a parameter reported as zero still moves. The step of a parameter constrained to be positive is held below half its value, so the lower evaluation stays inside the support.

Usage

.estimates_delta_jacobian(fn, x, positive)

Arguments

fn

A function of the parameter vector returning the summaries.

x

The reported parameters.

positive

A logical vector marking the parameters constrained to be positive.

Details

A numerical Jacobian is used because the derivative of a quantile with respect to the shape of a gamma or a weibull has no closed form.

Value

A matrix with one row per summary and one column per parameter.


Build an epidist_estimates_data object from one study's summaries

Description

Build an epidist_estimates_data object from one study's summaries

Usage

.estimates_from_summaries(study, value, type, p, se, n, ...)

Arguments

study

A string naming the study.

value

A numeric vector of reported summaries.

type

A character vector of summary types, one per value.

p

A numeric vector of quantile probabilities, one per value.

se

A numeric vector of reported standard errors, or NULL.

n

The number of delays the study summarised, or NULL.

...

Study metadata.

Value

An epidist_estimates_data object.


The grid cutoff implied by a set of summary estimates

Description

Studies that did not adjust for right truncation are evaluated on a grid running to their observation time. Studies that did are evaluated on a grid running to max_delay.

Usage

.estimates_grid_cutoff(data)

Arguments

data

An epidist_estimates_data object.

Value

A numeric vector of grid cutoffs.


Which summary estimates estimate their growth rate

Description

A study whose growth_rate is NA, or which reported it with a positive growth_rate_sd, takes its rate from the pgrowth distributional parameter of the meta model rather than from a number. See as_epidist_estimates_data().

Usage

.estimates_growth_estimated(data)

Arguments

data

An epidist_estimates_data object, or a data frame with its growth_rate and growth_rate_sd columns.

Value

A logical vector, one entry per row.


Which summary estimates have a tilted primary event

Description

The primary event is uniform within its window only for a known growth rate of zero. A non zero rate tilts it, and an estimated rate is taken to tilt it whatever value the parameter holds, so that the choice of path does not depend on a parameter.

Usage

.estimates_growth_tilted(data)

Arguments

data

An epidist_estimates_data object, or a data frame with its growth_rate and growth_rate_sd columns.

Value

A logical vector, one entry per row.


Reported standard deviations with a heavy tailed sampling error

Description

The sampling standard error of a reported standard deviation is \sigma \sqrt{(\kappa - 1) / (4 n)}, with \kappa the kurtosis of the delays. The normal approximation behind it holds while that relative standard error is below about a quarter. Above it the sampling distribution of a sample standard deviation is far from normal, the asymptotic standard error overstates its spread by up to two times, and the joint likelihood of a mean and standard deviation pair is biased by about a standard error. The kurtosis is taken from the reported mean and standard deviation under a lognormal delay, which is a plausible tail for a delay of that coefficient of variation.

Usage

.estimates_heavy_tail_rows(data)

Arguments

data

An epidist_estimates_data object.

Value

A logical vector, one entry per row, marking each reported standard deviation with a heavy tailed sampling error.


Studies whose reported standard deviation has a heavy tailed sampling error

Description

The studies flagged by .estimates_heavy_tail_rows().

Usage

.estimates_heavy_tail_sd(data)

Arguments

data

An epidist_estimates_data object.

Value

A character vector of study identifiers.


A lognormal matched to the summaries a study reported

Description

Matches a lognormal to a reported mean and standard deviation by its moments. Where the study reported only quantiles, its median is the location and its largest quantile above the median, at the level the study reported it, sets the scale. A study reporting neither pair, or one whose quantiles do not increase, gives NULL.

Usage

.estimates_lnorm_match(data, rows)

Arguments

data

An epidist_estimates_data object.

rows

A logical vector selecting the rows of one study.

Value

A list with meanlog and sdlog elements, or NULL.


The moments a reported fit is summarised by

Description

The moments a reported fit is summarised by

Usage

.estimates_moments(moments, probs)

Arguments

moments

Which moments to report.

probs

A numeric vector of probabilities to report quantiles at.

Value

The moments, ordered as the summary vector expects.


What each element of a multivariate representation reports

Description

What each element of a multivariate representation reports

Usage

.estimates_multivariate_types(params)

Arguments

params

The parameter names of an epidist_multivariate object.

Value

A list with the type and p of each element.


Summarise draws of a study's fitted parameters

Description

Summarise draws of a study's fitted parameters

Usage

.estimates_mvn_summarise(data, family, moments, probs, ...)

Arguments

data

An epidist_multivariate object holding draws of the natural parameters of a fitted distribution.

family

The distribution the study fitted.

moments

Which moments to report.

probs

A numeric vector of probabilities to report quantiles at.

...

Study metadata, used for the range the summaries are taken over.

Value

A list with the type, p, value and vcov of the summaries.


The number of quadrature intervals each summary row is evaluated on

Description

The moments and distribution function of a continuous estimand that is truncated at the grid cutoff are computed by Simpson's rule on equally spaced intervals running from delay_min to the cutoff, so the node spacing is set by the cutoff and not by the scale of the delay. A fixed number of intervals leaves a narrow delay unresolved on a wide grid, which pins its implied kurtosis at its floor and can put its implied standard deviation out by a factor of two. The number is therefore chosen per study so that the spacing is at most a quarter of the spread the study reported, see .estimates_spread(), with options(epidist.meta_n_quad) as its floor and .meta_n_quad_max() as its cap unless the option is set above it. It is even, because the quadrature uses Simpson's rule.

Usage

.estimates_n_quad(data)

Arguments

data

An epidist_estimates_data object.

Details

Every row gets a number, including rows on the discrete grid, which do not use it.

Value

An integer vector of interval counts, one per row.


The primarycensored distribution function name of a reported family

Description

The primarycensored distribution function name of a reported family

Usage

.estimates_parameter_dist(family)

Arguments

family

The distribution the study fitted.

Value

A distribution function name.


Which reported parameters are constrained to be positive

Description

Which reported parameters are constrained to be positive

Usage

.estimates_parameter_positive(names)

Arguments

names

The names of the reported parameters.

Value

A logical vector, one entry per parameter.


The parameterisations supported for a reported distribution

Description

Each family lists the sets of parameter names a study may report it with. The first set of each family is the one used internally.

Usage

.estimates_parameter_sets()

Value

A named list of character vectors of parameter names.


The summaries a reported distribution implies

Description

The summaries a reported distribution implies

Usage

.estimates_parameter_summary(
  family,
  parameters,
  moments,
  probs,
  lower = 0,
  cutoff = Inf
)

Arguments

family

The distribution the study fitted.

parameters

A named numeric vector of the reported parameters.

moments

Which moments to report, any of "mean" and "sd", in that order.

probs

A numeric vector of probabilities to report quantiles at.

lower

The smallest delay the study counted.

cutoff

The largest delay the study could have seen, or Inf where it adjusted for right truncation.

Value

A numeric vector of summaries, the moments first.


The largest reported quantile a set of summary estimates can support

Description

A quantile reported at or beyond the top of the estimand's support has an implied cumulative probability of one and an implied density of zero, so the delta method conversion of a delay scale standard error hits its floor and the row contributes a constant to the likelihood instead of information. The limit is the top of the discrete grid for a study that did not adjust for censoring, allowing for the half cell the continuity correction adds and for the half window midpoint imputation shifts by, and the grid cutoff otherwise.

Usage

.estimates_quantile_limit(data)

Arguments

data

An epidist_estimates_data object.

Value

A numeric vector of limits, one per row.


The range of delays a study's reported distribution describes

Description

A study that fitted a distribution to right truncated data without correcting for the truncation reported a distribution with more spread than the delays it saw, because its family carries a tail beyond the point its data stop. Summaries of the reported distribution are therefore taken over the range of delays the study could have seen, which is the same range the meta model computes its implied summaries over. The metadata that gives that range is already on its way onto the returned rows, so it is read from there rather than asked for again.

Usage

.estimates_reported_support(...)

Arguments

...

The metadata columns passed to epidist_estimates_parameters().

Value

A list with the study's lower and cutoff delays.


Label flagged summary rows by study and position in the input

Description

Label flagged summary rows by study and position in the input

Usage

.estimates_row_labels(data, rows)

Arguments

data

An epidist_estimates_data object.

rows

A logical vector selecting the rows to label.

Value

A character vector such as ⁠"A" (row 2)⁠, one entry per selected row.


Attach reported covariance matrices to an epidist_estimates_data object

Description

The matrices are held alongside the data rather than in it, because a covariance matrix spans several rows. They are keyed by the mvn_id column, which names the multivariate object the rows came from, so one study may contribute more than one. Their Cholesky factors are built once by as_epidist_meta_model() and passed to Stan, so the sampler never decomposes them.

Usage

.estimates_set_vcov(data, vcov)

Arguments

data

An epidist_estimates_data object.

vcov

A named list of covariance matrices, or NULL.

Details

Only as_epidist_estimates_data.epidist_multivariate() writes to this.

Value

The input with the matrices attached.


Studies whose grid cutoff is short relative to their reported tail

Description

The implied summaries of a study that did not adjust for censoring but did adjust for right truncation are computed on a grid running to max_delay. A cutoff that the delay distribution has not decayed by biases them downwards, and the standard deviation most, because the tail beyond the cutoff carries a share of the second moment out of all proportion to its mass. A lognormal is matched to what each study reported, through its mean and standard deviation, or its median and largest quantile above the median where it reported only quantiles, and the study is flagged when more than 2% of the second moment of that lognormal lies beyond the cutoff. That is where the standard deviation on the grid falls about 1% short, and the shortfall grows with the share. Studies reporting neither pair are not checked.

Usage

.estimates_short_cutoff(data)

Arguments

data

An epidist_estimates_data object.

Value

A character vector of study identifiers with a short cutoff.


The spread each study reported, as a proxy for its delay standard deviation

Description

The quadrature a summary row uses has to resolve the delay distribution, whose scale is only known once the model is fitted. The spread the study itself reported stands in for it. That is its reported standard deviation where it gave one, the range of its reported quantiles divided by the same range of a standard normal where it gave two or more, and otherwise a quarter of the smallest location it reported, which is the coefficient of variation below which a delay is narrow. The proxy only has to be within a factor of two or so, because the resolution is chosen well inside where Simpson's rule converges.

Usage

.estimates_spread(data)

Arguments

data

An epidist_estimates_data object.

Value

A numeric vector of spreads, one per row.


The reported covariance matrices of an epidist_estimates_data object

Description

The reported covariance matrices of an epidist_estimates_data object

Usage

.estimates_vcov(data)

Arguments

data

An epidist_estimates_data object.

Value

A named list of covariance matrices, empty when no study reported one.


Which rows of an epidist_estimates_data object have a covariance matrix

Description

Which rows of an epidist_estimates_data object have a covariance matrix

Usage

.estimates_vcov_rows(data)

Arguments

data

An epidist_estimates_data object.

Value

A logical vector, one entry per row.


The unit the advisory messages count a study's censoring windows in

Description

The unit the advisory messages count a study's censoring windows in

Usage

.estimates_window_unit(swindow)

Arguments

swindow

The secondary censoring windows of the flagged rows.

Value

"days" for daily windows, "weeks" for weekly ones, and "censoring windows" otherwise.


Expand a dot in a model formula

Description

Replaces the part of brms:::expand_dot_formula() that epidist needs. A formula containing . on the right hand side is expanded against data, keeping the attributes of the original formula.

Usage

.expand_dot_formula(formula, data = NULL)

Arguments

formula

A formula object.

data

A data.frame used to expand ..

Value

The expanded formula.


Extract distributional parameter terms from a brms formula

Description

This function extracts all unique terms from the right-hand side of all distributional parameters in a brms formula.

Usage

.extract_dpar_terms(formula)

Arguments

formula

A brms formula object.

Value

A character vector of unique terms.


Build the Stan functions block shared by the marginal and meta models

Description

Both models read a functions.stan chunk with the same placeholders (family, dist_id, dpars_A, dpars_B, and the pair ⁠primary_id, primary_params⁠), filled in with the target distribution's details and the primary event distribution. dpars_B is the parameter order of primarycensored, which a family may record as pcd_param where it differs from the order of its Stan density. Used within epidist_stancode() methods for the marginal and meta models, which differ only in the chunk path, the family name prefix, and any further placeholders they need substituted.

Usage

.family_functions_stanvar(
  chunk_path,
  family,
  family_prefix,
  primary = .primary_spec("uniform"),
  extra = character()
)

Arguments

chunk_path

Path within the ⁠stan/⁠ folder to the functions chunk.

family

The epidist family object.

family_prefix

The model specific prefix stripped from family$name, for example "marginal_" or "meta_".

primary

A primary event registry entry, as returned by .primary_spec(). Defaults to the uniform primary event.

extra

A named character vector of further placeholder substitutions, applied after the shared ones.

Value

A brms stanvars object holding the substituted functions chunk.


The name of a delay distribution family

Description

A family built with brms::custom_family(), such as gengamma(), is named "custom" for brms to dispatch on and records its own name in name. Every other family is named by family.

Usage

.family_name(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

A character string.


Stan functions a family defines itself

Description

A family brms does not have, such as gengamma(), carries the Stan density and distribution function brms and the latent model call. They are read from the ⁠stan/family/⁠ folder of the installed package.

Usage

.family_stanvars(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

A brms stanvars object, or NULL for a brms family.


Fill in the optional columns of an epidist_estimates_data object

Description

Applies the documented defaults for study metadata that was not supplied, informing the user about each assumption made on their behalf.

Usage

.fill_estimates_defaults(data)

Arguments

data

A data.frame containing at least study, type and value.

Value

The input with all of .estimates_required_cols() present.


Description

brms::custom_family() recycles a single link over every parameter, and a family such as brms::brmsfamily()'s Gamma carries no link for its other parameters, so a link appended for a further parameter would be matched to the wrong one. The missing links are filled with the link of mu, which is what the recycling gives.

Usage

.fill_other_links(family)

Arguments

family

A brms family object.

Value

The family with one entry of other_links per parameter after mu.


The name of the brms family a fit was made with

Description

The families epidist builds are custom families named after the model and the delay distribution, such as meta_lognormal.

Usage

.fit_family_name(fit)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

Value

A string.


Default newdata for a fitted model

Description

Expands the variables in the distributional parameter formulas into a grid with epidist_newdata(), so there is one row per unique combination of the predictors with no censoring and no truncation. brms keeps the data a model was fitted to as a plain data.frame, so the epidist class is restored from the family name first.

Usage

.fit_newdata(object)

Arguments

object

A model fit with epidist().

Value

A tibble::tibble() of newdata.


Take the observed delays of a fitted model

Description

Reads the response and the case weights of the model data, and the strata to colour by, which default to the variables in the distributional parameter formulas as they do in epidist_strata().

Usage

.fitted_delays(x, by = NULL)

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

by

A character vector of columns of the model data that define the strata to colour by. If NULL, the default, the variables in the distributional parameter formulas are used, as epidist_strata() does.

Value

A list with data, a tibble of the observed delay of each case, its weight n and the columns in by, and by, the columns the strata are defined by or NULL when there are none.


Round to the nearest multiple

Description

This function rounds an input x down to the nearest multiple of some number f. For example, if f = 0.2 and x = 1.5 then the output would be 1.4. If f = 1 then floor_mult behaves as floor. If f = 0 then x is returned.

Usage

.floor_mult(x, f = 1)

Arguments

x

A number to be rounded down.

f

A positive number specifying the multiple to be rounded down to

Value

x rounded down to the nearest multiple of f.


The Stacy parameters of a brms prep object for gengamma()

Description

The Stacy parameters of a brms prep object for gengamma()

Usage

.gengamma_dpars(prep, i = NULL)

Arguments

prep

A brms prep object.

i

The observation index, or NULL for every observation.

Value

A named list of shape, scale and k.


The brms post-processing functions of the gengamma() family

Description

The brms post-processing functions of the gengamma() family

Usage

.gengamma_log_lik(i, prep)

.gengamma_posterior_predict(i, prep, ...)

.gengamma_posterior_epred(prep)

Arguments

i

The observation index, or NULL for every observation.

prep

A brms prep object.

...

Not used.

Value

The log likelihood of observation i for every draw, a delay drawn for observation i for every draw, and the mean of the delay for every draw and observation.


The mean and standard deviation of the generalised gamma distribution

Description

From the raw moments E[T^r] = scale^r \Gamma(k + r / shape) / \Gamma(k) of the Stacy form.

Usage

.gengamma_mean(scale, shape, k)

.gengamma_sd(scale, shape, k)

Arguments

scale, shape, k

Parameters of flexsurv::dgengamma.orig().

Value

A numeric vector.


Convert the generalised gamma from the Prentice to the Stacy form

Description

primarycensored and flexsurv::dgengamma.orig() use the Stacy (1962) form with shape, scale and k. It has no counterpart for Q of zero or below, which is why gengamma() keeps Q positive.

Usage

.gengamma_stacy(mu, sigma, Q)

Arguments

mu, sigma, Q

Parameters of flexsurv::dgengamma().

Value

A named list of shape, scale and k.


Get the post-processing function of a family by prefix

Description

Gets the function brms would call for a family, such as log_lik or posterior_predict. A family epidist defines itself, such as gengamma(), carries these functions, so they are taken from it, whether it is given as the family or as a model family built on it. For a brms family they come from .brms_family_fn().

Usage

.get_brms_fn(prefix, family)

Arguments

prefix

Character string prefix of the brms function to get (e.g. "log_lik")

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

The requested function


Check for a non uniform prior on a latent model event window

Description

Check for a non uniform prior on a latent model event window

Usage

.has_non_uniform_window_prior(prior, parameter)

Arguments

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

parameter

The name of the event window parameter to check.

Value

A logical, TRUE if a non uniform prior has been supplied.


Are the infinite values of data all observation times?

Description

Are the infinite values of data all observation times?

Usage

.inf_is_obs_time_only(data)

Arguments

data

A data.frame, or NULL.

Value

TRUE when data holds at least one infinite value and every column holding one is an .obs_time_cols() column, and FALSE otherwise.


The brms warning about infinite values in the data

Description

A substring of the message brms:::validate_data() warns with, which brms::prepare_predictions() reaches through brms:::validate_newdata(). Matching a substring rather than the whole message keeps the match narrow enough not to catch another warning, while surviving a change to the rest of the sentence. A reworded message brings the warning back rather than muffling something else.

Usage

.infinite_data_warning()

Value

A string to match against a warning message.


Inform users about data summarisation

Description

This function informs users when data has been summarised by unique combinations of variables, providing information about the variables used and the reduction in number of rows.

Usage

.inform_data_summarised(data, trans_data, required_cols)

Arguments

data

The original data before summarisation

trans_data

The transformed/summarised data

required_cols

Character vector of required column names

Value

Nothing, called for side effects only


Combine the model and family specific prior distributions

Description

Model specific priors from epidist_model_prior() overwrite family specific priors from epidist_family_prior(). The result is then restricted to the parameters brms recognises, so that priors for parameters which are not in the model are dropped.

Usage

.internal_prior(data, family, formula, default)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model created using epidist_family().

formula

A symbolic description of the model to be fitted created using epidist_formula().

default

The default prior distributions from brms::default_prior().

Value

A brmsprior object, or NULL when there are no internal priors.


Identify manually specified brms priors

Description

Manual priors are written using the parameter ~ distribution syntax and are passed through to the Stan model block unchanged. They cannot be matched on parameter metadata in the way that standard brms priors can.

Usage

.is_manual_prior(prior)

Arguments

prior

One or more prior distributions in the class brmsprior.

Value

A logical vector flagging the manually specified priors.


Attach the model's predictors from newdata to a comparison

Description

study in out already names the held out study, so a study predictor in newdata, such as one built with epidist_newdata(meta, study), is excluded to avoid a second column of the same name.

Usage

.leave_one_out_bind_predictors(out, newdata, formula)

Arguments

out

The comparison, as returned by .leave_one_out_compare(), with study and .row columns.

newdata

The newdata the comparison was built from.

formula

The brms formula of the fit, used to find its predictors.

Value

out with any predictors of formula present in newdata, other than study, added after .row.


Compare the summaries of leave one out refits with the full fit

Description

Compare the summaries of leave one out refits with the full fit

Usage

.leave_one_out_compare(held, full)

Arguments

held

A tibble of summaries of the refits, as returned by .leave_one_out_summaries(), with a study column naming the held out study.

full

The summaries of the full fit, as returned by .leave_one_out_summaries().

Value

held with the full fit values added as full_estimate, full_lower and full_upper, and the refit's median and interval minus the full fit's median as difference, difference_lower and difference_upper.


The cores of each leave-one-out refit

Description

brms does not store the cores a model was fitted with, so this gives cores, else the mc.cores option, else one core per chain.

Usage

.leave_one_out_cores(cores, chains)

Arguments

cores

The number of cores each refit uses. If NULL, the default, the mc.cores option where it is set, and otherwise one core per chain, so the chains of each refit run in parallel.

chains

The number of chains of each refit.

Value

An integer.


The model data used to hold each study out of a meta model fit

Description

The model data used to hold each study out of a meta model fit

Usage

.leave_one_out_data(fit, data = NULL)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

data

The epidist_meta_model object fit was fitted to. Only needed when fit$data has no study column, which happens when the formula does not use study. If NULL, the default, the model data stored in fit is used.

Value

The epidist_meta_model object given as data, or the plain data.frame of model data stored in fit.


The default newdata for comparing leave one out refits

Description

A single row giving the population level delay with no censoring and no truncation. epidist_newdata() only reads its data argument to expand variables, so a copy of the model data carrying the class is enough.

Usage

.leave_one_out_newdata(fit)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

Value

A tibble::tibble() of one row.


The studies of a meta model to hold out

Description

The studies of a meta model to hold out

Usage

.leave_one_out_studies(data, studies = NULL)

Arguments

data

An epidist_meta_model object or the model data of a meta model fit, with a study column.

studies

A character vector of the studies to hold out, one refit each. If NULL, the default, every study is held out in turn. Holding out a few studies, such as the largest, keeps the cost down when a model has many.

Value

A character vector of study labels, in order of first appearance, or studies in the order given.


Posterior summaries of the delay mean and standard deviation of a fit

Description

Posterior summaries of the delay mean and standard deviation of a fit

Usage

.leave_one_out_summaries(fit, newdata, re_formula = NA, width)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

newdata

A data.frame of data to predict the delay for, passed to delay_summary_draws(). Always an already resolved data.frame, never NULL.

re_formula

Passed to brms::prepare_predictions() through delay_summary_draws(). The default NA switches off any study level term, so the summaries are of the population level delay.

width

The width of the central posterior intervals. Defaults to 0.95.

Value

A tibble with one row per row of newdata and summary, with columns .row, summary, estimate (the posterior median), lower and upper.


Apply observation weights to a log likelihood

Description

Replaces brms:::log_lik_weight(). Multiplies x by the weight of observation i, if the model has weights, and returns x unchanged otherwise.

Usage

.log_lik_weight(x, i, prep)

Arguments

x

A numeric vector of log likelihood values.

i

The index of the observation.

prep

A brms prepared predictions object.

Value

The weighted log likelihood values.


Include implicit intercepts in brms formula as explicit

Description

This function detects the distributional parameters in a brms formula object, and alters to formula to include explicit intercept parameters for them i.e. ~ 1.

Usage

.make_intercepts_explicit(formula)

Arguments

formula

A brms formula object.

Value

The formula with an explicit intercept for every distributional parameter that had none.


Extract the parameter name of a manually specified brms prior

Description

Extract the parameter name of a manually specified brms prior

Usage

.manual_prior_parameter(prior)

Arguments

prior

One or more manually specified prior distributions in the class brmsprior.

Value

A character vector of parameter names.


The density of a continuous estimand under an accrual design

Description

The distribution function is interpolated linearly between quadrature nodes, so its slope on the interval containing the reported value is the density there.

Usage

.meta_accrual_density(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  cens_adjusted,
  growth_rate,
  n_quad = .meta_n_quad()
)

Arguments

y

The reported quantile value.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A density on the delay scale.


Whether accrual weighting applies to a summary row

Description

The truncation design only matters for a study that did not adjust for right truncation, because a study that did has already removed the effect the design would have had.

Usage

.meta_accrual_flag(trunc_adjusted, trunc_design)

Arguments

trunc_adjusted

1 if the study adjusted for right truncation, 0 otherwise.

trunc_design

0 for a cohort design, 1 for an accrual design.

Value

1 if the accrual weight applies, 0 otherwise.


The accrual weighted distribution function on the quadrature grid

Description

The weight is offset by half a primary window for the uniform single interval approximation, matching .meta_pcens_trunc_moments(), so that the reported quantile and the reported moments describe the same estimand.

Usage

.meta_accrual_nodes(
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  cens_adjusted,
  growth_rate,
  n_quad = .meta_n_quad()
)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A distribution function at n_quad + 1 equally spaced nodes.


The distribution function of a continuous estimand under an accrual design

Description

Interpolates the accrual weighted distribution function of .meta_accrual_nodes() linearly at the reported value.

Usage

.meta_accrual_prob(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  cens_adjusted,
  growth_rate,
  n_quad = .meta_n_quad()
)

Arguments

y

The reported quantile value.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A probability.


Reweight a distribution function for an accrual design

Description

Weights the probability mass between consecutive quadrature nodes by the follow up available at the midpoint of the interval, then renormalises, so that the returned distribution function is that of the delays a study collecting up to a calendar stop would have seen. The midpoint is used rather than a node because it makes the quadrature second order accurate.

Usage

.meta_accrual_reweight(cdf, lower, cutoff, growth_rate, weight_offset = 0)

Arguments

cdf

The distribution function at equally spaced nodes running from lower to cutoff.

lower

The study's minimum delay (its left truncation point).

cutoff

The length of the collection window.

growth_rate

The exponential growth rate of primary events.

weight_offset

The amount by which the quantity being weighted overstates the time from the primary event's censoring window to the secondary event.

Details

The follow up available to a primary event depends on the calendar time of the event itself, which is only known to within its censoring window. Where the quantity being weighted already includes the offset of the primary event within that window, as it does for the uniform single interval approximation, weight_offset shifts the weight so that it is evaluated at the underlying primary event time. Averaging over the window makes the shift half its width. Without it the follow up is systematically half a window short, which biases the implied summaries downwards.

Value

A distribution function at the same nodes, running from zero to one.


The follow up available to a delay under an accrual design, up to a constant

Description

Every use of the accrual weight renormalises afterwards, so the weights are returned relative to their largest value to avoid overflow. A growth rate of zero makes the follow up linear in the delay, which is taken directly rather than through the log scale form.

Usage

.meta_accrual_weight(d, window, growth_rate)

Arguments

d

A numeric vector of delays.

window

The length of the collection window.

growth_rate

The exponential growth rate of primary events.

Value

A numeric vector of relative weights with a maximum of one.


Add the pgrowth parameter a summary row with an estimated growth rate needs

Description

A summary row whose growth rate is estimated reads the pgrowth distributional parameter, which the family only carries where the individual level rows use an exponential growth primary event. It is added here otherwise, with the link and bounds of that primary event, while the primary event of the individual level rows is left as it is.

Usage

.meta_add_growth_dpar(family, data)

Arguments

family

A brms family object, after .add_primary_dpars().

data

An epidist_meta_model object.

Value

The family with pgrowth among its distributional parameters where a summary row needs it.


Add an independent uniform primary window to a set of summaries

Description

The uniform single interval approximation leaves the primary interval uncorrected, so the study effectively summarised the delay plus an independent draw from a uniform distribution over the primary window. This convolution is exact when the study also adjusted for right truncation and the primary events were uniform within their window.

Usage

.meta_add_uniform(moments, pwindow)

Arguments

moments

A summary vector from .meta_moment_vector().

pwindow

The primary censoring window width.

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


Assign summary estimates to joint likelihood groups

Description

Summaries reported by the same study are fitted jointly, so they must be collected into groups before the model rows are built. Two summaries share a group only when they agree on every column other than the summary itself, that is on the study, its metadata, and any covariates the user supplied. This keeps the grouping correct for any brms formula, because a linear predictor built from those columns cannot vary within a group.

Usage

.meta_assign_groups(estimates, mvn = NULL)

Arguments

estimates

An epidist_estimates_data object.

mvn

A logical vector marking the rows covered by a reported covariance matrix.

Details

A study with a continuous estimand (cens_adjusted 1, 2 or 4) has every kind of summary in one group, because the sampling covariance of its mean, standard deviation and quantiles is available from the implied distribution. See .meta_joint_covariance(). On the discrete grid (cens_adjusted 0 or 3) the mean and standard deviation group together and the quantiles group together, but the two are not mixed because the quantiles are fitted as discrete statistics, so such a study is counted twice where it reports both kinds. A study reporting more than one mean, or more than one standard deviation, with otherwise identical metadata has the repeats split into further groups. A summary with its own reported standard error is left on its own, because that standard error replaces the sampling uncertainty the joint likelihood would derive.

The summaries covered by one covariance matrix are one group, whatever their types, because the matrix is what ties them together. They are identified by their shared mvn_id, so one study may contribute more than one such group.

Value

An integer vector of group identifiers, one per row.


The half width of the band of counts the forward pass keeps

Description

The forward pass of .meta_grid_box_ll() sums over the counts within six standard deviations and eight counts of the most likely path, plus the stride of the grid that path was found on. The mass beyond six standard deviations is below 1e-9 of the total for every binomial, including the Poisson like tail of a step with a small mean, which the eight counts cover. Matches meta_family_band_half_width() in Stan.

Usage

.meta_band_half_width(variance, stride)

Arguments

variance

The variance of the count.

stride

The stride of the coarse grid from .meta_box_stride().

Value

An integer number of counts.


The counts of a coarse grid within a box

Description

The box boundaries and every multiple of the stride between them, so that a most likely count sitting on a boundary is on the grid.

Usage

.meta_box_grid(lower, upper, stride)

Arguments

lower, upper

The box.

stride

The stride of the grid from .meta_box_stride().

Value

An increasing integer vector of counts.


The most likely path of the constrained chain of cumulative counts

Description

A Viterbi pass over the coarse grid of .meta_box_grid() at every edge, which finds the counts a study most probably had at each edge given every box, to within a stride. The forward pass of .meta_grid_box_ll() is then kept to a band around them. Centring on the counts the boxes pull the chain to, rather than on the counts the parameters expect at each edge, is what keeps the pass accurate where a later quantile forces an earlier count far from its mean. The distribution function is rounded to 2^{-20} by .meta_fixed_point() first, as Stan must to keep the search off the autodiff stack. Matches meta_family_box_mode_path() in Stan.

Usage

.meta_box_mode_path(study_n, cdf, lower, upper, stride)

Arguments

study_n

The number of delays the quantiles were computed from.

cdf

The grid distribution function at the edges.

lower, upper

The boxes at the edges.

stride

The stride of the grid from .meta_box_stride().

Value

An integer vector of counts, one per edge, or NULL when no path satisfies every box.


One step of the forward pass over the cumulative counts

Description

Carries the log probabilities of the counts in one band to the counts in the next, through the binomial step of the chain. The step is a matrix product of .meta_step_kernel() with the exponentiated source vector, each scaled so that the arithmetic stays in range, and a sum on the log scale over every pair of counts where the kernel would underflow at the most likely step. Both give the same probabilities. Matches meta_family_box_step() in Stan.

Usage

.meta_box_step(alpha, a, b, a2, b2, r, study_n, m_prev, m, lg)

Arguments

alpha

The log probabilities of the source counts a:b.

a, b

The first and last source count.

a2, b2

The first and last target count.

r

The step probability from .meta_step_prob().

study_n

The number of delays the quantiles were computed from.

m_prev, m

The most likely source and target counts from .meta_box_mode_path().

lg

The log factorials, lg[d + 1] being ⁠log(d!)⁠.

Value

The log probabilities of the target counts a2:b2.


The stride of the coarse grid of counts the forward pass centres on

Description

The most likely path of the constrained chain of counts is found on a grid of every strideth count, about half a standard deviation of a binomial apart, so that a search over it costs about four times the sample size per edge. Matches meta_family_box_stride() in Stan.

Usage

.meta_box_stride(study_n)

Arguments

study_n

The number of delays the quantiles were computed from.

Value

An integer stride of at least one.


The smallest probability a multinomial cell is given

Description

A cell whose implied probability underflows to zero while the study saw delays in it would give a log likelihood of -Inf. Stan differences log distribution functions and so keeps a tiny mass in such a cell, where R differences them on the natural scale and gets exactly zero. Both floor the cell here, so that a single badly misfitting draw is rejected in practice but leaves loo() a finite value.

Usage

.meta_cell_floor()

Value

A probability.


The censoring adjustment whose estimand a code is built on

Description

Two adjustment codes are another code's estimand moved along the delay axis by a fixed amount, because the study replaced an event time with the midpoint of its window. Midpoint imputation of the secondary interval (code 3) moves the naive discrete grid of code 0. Midpoint imputation of the primary event (code 4) moves the primary censored estimand of code 2. Both are evaluated by calling the base code and moving the result, so each estimand is implemented once.

Usage

.meta_cens_base(cens_adjusted)

Arguments

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

Details

Matches meta_family_cens_base in inst/stan/meta_model/functions.stan.

Value

The code whose estimand is evaluated.


The left truncation point of the base estimand a midpoint code is built on

Description

delay_min is the smallest delay a study counted on the scale it reported, so a midpoint code that moved its estimand along the delay axis dropped the records whose moved delay fell below it. The base estimand is therefore left truncated at delay_min moved back by the same shift. A delay_min of zero means the study counted every delay and is left alone, because it is the sentinel that selects the untruncated formulas, even for code 4 whose reported delays can be negative.

Usage

.meta_cens_lower(lower, cens_adjusted, pwindow, swindow)

Arguments

lower

The study's minimum delay (its left truncation point).

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

pwindow, swindow

The primary and secondary censoring window widths.

Details

The right truncation point is not moved, because the observation time bounds the underlying event, not the midpointed value.

Matches meta_family_cens_lower in inst/stan/meta_model/functions.stan.

Value

The left truncation point of the base estimand.


The delay a midpoint imputation moves the base estimand by

Description

Midpoint imputation of the secondary interval (code 3) assigns each delay to the centre of the interval it was seen in, moving it up by half a secondary window. Midpoint imputation of the primary event (code 4) anchors the delay at the centre of the primary window rather than at its lower edge, moving it down by half a primary window. Every other code leaves its estimand where it is.

Usage

.meta_cens_shift(cens_adjusted, pwindow, swindow)

Arguments

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

pwindow, swindow

The primary and secondary censoring window widths.

Details

Matches meta_family_shift in inst/stan/meta_model/functions.stan.

Value

A signed delay.


The slots of the base estimand a midpoint code is built on

Description

Replaces the censoring adjustment code by the code it is built on and moves the left truncation point with it. See .meta_cens_base() and .meta_cens_lower().

Usage

.meta_cens_slots(slots)

Arguments

slots

The output of .meta_row_slots().

Value

The slots of the base estimand.


A central difference of the implied distribution function

Description

Used where the density of the biased estimand has no closed form, which is the primary censored delay of a study whose primary events were not uniform within their window.

Usage

.meta_central_difference(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  trunc_adjusted,
  cens_adjusted,
  growth_rate,
  trunc_design = 0L,
  n_quad = .meta_n_quad()
)

Arguments

y

The reported quantile value.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

trunc_adjusted

1 if the study adjusted for right truncation, 0 otherwise.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

trunc_design

0 for a cohort design, 1 for an accrual design.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A density on the delay scale.


Summarise a distribution from its first four raw moments

Description

Summarise a distribution from its first four raw moments

Usage

.meta_central_from_raw(moments)

Arguments

moments

A numeric vector of the first four raw moments.

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The flat Cholesky factors of an epidist_meta_model object

Description

A group covered by a covariance matrix has the Cholesky factor of that matrix stored here, in column major order, and its row indexes into this vector with chol_start. Factoring once here rather than inside the likelihood keeps the matrix out of every gradient evaluation.

Usage

.meta_chol(data)

Arguments

data

An epidist_meta_model object.

Value

A numeric vector of Cholesky factor entries.


Analytic summaries of a delay distribution

Description

The mean and standard deviation mirror the formulas used by add_summaries(). A draw wide enough to overflow a moment, such as a lognormal whose exp(4 * sdlog^2) is infinite, is returned as .meta_moment_failure() so that the row is rejected rather than carrying a NaN into its standard error. Matches the reject in meta_family_moments() in inst/stan/meta_model/functions.stan, where an infinite intermediate would otherwise leave a finite density with a non finite gradient.

Usage

.meta_continuous_moments(dist, args)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The box constraints a set of integer day quantiles puts on a study

Description

A type 1 quantile at probability p of n delays is their \lceil n p \rceilth smallest, so two reported at probabilities that name the same order statistic cannot land on different days. Such a group would give every parameter a log likelihood of -Inf, so it is refused here with a message that says why.

Usage

.meta_crossing_box(estimates, study_n)

Arguments

estimates

The quantile rows of an epidist_estimates_data object making up one group, in increasing probability.

study_n

The number of delays the quantiles were computed from.

Value

A list of the count and lower member columns of .meta_member_table().


The order statistics a set of type 1 quantiles stand for

Description

A type 1 quantile at probability p of n delays is the \lceil n p \rceilth smallest of them. A quantile of integer day delays reported as day y therefore says the study saw fewer than that many delays below y and at least that many at or below it, which are the box constraints .meta_grid_box_ll() fits. The rounding guard matches .meta_grid_crossing_ll(), so that n p landing on an integer up to floating point error is not pushed up a count.

Usage

.meta_crossing_counts(p, study_n)

Arguments

p

A vector of quantile probabilities in increasing order.

study_n

The number of delays the quantiles were computed from.

Value

An integer vector of counts.


Whether a delay is certainly below the cut of the distribution function

Description

Decided from a closed form bound on the parameters rather than from the distribution function, because in Stan the distribution function must not be evaluated where it underflows: its autodiff partial is then 0 / 0, and Stan's reverse pass chains every node on the stack, so the NaN poisons the gradient even when the value is discarded. The bounds are Phi(z) < exp(-100) for z < -14 for the lognormal, P(a, x) <= x^a / Gamma(a + 1) for the gamma and 1 - exp(-y) <= y for the weibull. The generalised gamma uses the gamma bound at x = (q / scale)^shape with a = k. Mirrors meta_family_deep_tail() in Stan.

Usage

.meta_deep_tail(q, dist, args)

Arguments

q

A numeric vector of delays.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

Value

A logical vector.


Deep lower tail bounds of the delay distributions

Description

One per family with a closed form bound, see .meta_deep_tail(). They mirror the Stan functions of the same name in inst/stan/meta_model/functions.stan.

Usage

.meta_deep_tail_lognormal(q, args)

.meta_deep_tail_gamma(q, args)

.meta_deep_tail_weibull(q, args)

.meta_deep_tail_gengamma(q, args)

Arguments

q

A numeric vector of positive delays.

args

A named list of distribution parameters.

Value

A logical vector.


The distribution function of the delay, severed deep in its lower tail

Description

The distribution function of the delay, severed deep in its lower tail

Usage

.meta_dist_cdf(q, dist, args)

Arguments

q

A numeric vector of delays.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

Value

A numeric vector of cumulative probabilities, zero at or below a delay of zero, where .meta_deep_tail() holds, and below the cut of .meta_log_cdf_floor().


The largest number of entries the implied summary cache holds

Description

The cache is bounded so that it cannot grow without limit over a long session. Passing the limit clears it rather than evicting one entry, which keeps the bookkeeping to a single check. Each entry holds one summary vector per posterior draw, so the limit is small.

Usage

.meta_draw_cache_limit()

Value

An integer number of entries.


The slots of one meta model row for one posterior draw

Description

A row with an estimated growth rate holds one rate per draw, see .meta_row_slots(), and the implied summaries of a draw are computed from the rate of that draw. A row with a known rate is returned as it is.

Usage

.meta_draw_slots(slots, draw)

Arguments

slots

The output of .meta_row_slots().

draw

The posterior draw index.

Value

The slots with a single growth_rate.


Implied summaries shared by meta model rows with the same study design

Description

Holds one entry per study design, each a list of the parameter draws it was built from and the summaries they imply. It lives in the package namespace, so it is never written into a fitted model object. See .meta_row_draw_moments().

Usage

.meta_draws

Format

An environment.


An empty table of grouped summary members

Description

An empty table of grouped summary members

Usage

.meta_empty_members()

Value

A zero row tibble with the member columns.


Build the summary estimate rows of an epidist_meta_model object

Description

One row is built per group from .meta_assign_groups(). A group of one is a single reported summary, and a larger group is fitted with the joint likelihood of its members. The members of a group are held in flat arrays that the row indexes with group_start and group_len, because a study may report any number of quantiles and a row has a fixed number of slots. Row order is irrelevant to the index, so aggregating or reordering rows later cannot break it.

Usage

.meta_estimate_rows(estimates)

Arguments

estimates

An epidist_estimates_data object.

Value

A list with a tibble of summary rows using the meta model slots, a tibble of their members, and the flat chol vector of Cholesky factors for the groups covered by a covariance matrix.


A number as a multiple of a power of two, for a data only scaling

Description

The forward pass scales each step around the expected size of the step, and centres its bands on the most likely path, both of which depend on the parameters. Stan can only build data from integers, so each is carried as the integer part of 2^{20} times the number, found there by bisection on comparisons. Neither has to be exact: the result of a step does not depend on its scaling, and the bands are wide. Matches meta_family_fixed_point() in Stan.

Usage

.meta_fixed_point(x)

Arguments

x

A number.

Value

An integer vector within \pm 2^{29}.


The joint log likelihood of several quantiles of integer day delays

Description

Each quantile reported at probability p and landing on day y says that the empirical distribution function crossed p between the day below and the day itself, N_{\le y - w_s} \le \lceil n p \rceil - 1 and N_{\le y} \ge \lceil n p \rceil, with N_{\le y} the number of delays at or below y. The counts at the integer edges the reported quantiles name form a Markov chain,

N_{e_{i+1}} \mid N_{e_i} \sim N_{e_i} + \text{Binomial}\left(n - N_{e_i}, \frac{G_0(e_{i+1}) - G_0(e_i)}{1 - G_0(e_i)}\right),

with G_0 the uncorrected grid distribution function, and the likelihood is the probability that every count fell in its box. It is a forward pass over the counts on the log scale, one step of .meta_box_step() per edge, kept to a band of .meta_band_half_width() counts around the most likely path of .meta_box_mode_path(), so its cost grows like the number of edges times the sample size to the power one and a half rather than squared. Two quantiles reported at the same value are two constraints at one edge, and reporting the same count at two values is a box no chain can satisfy, which gives -Inf.

Usage

.meta_grid_box_ll(y, upper, lower, study_n, dist, args, slots)

Arguments

y

A vector of reported quantile values in non decreasing order.

upper

The largest count of delays below each reported day.

lower

The smallest count of delays at or below each reported day.

study_n

The number of delays the quantiles were computed from.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

Details

This is the joint form of .meta_grid_crossing_ll(), which it reduces to for a single quantile. Like it, the information it carries saturates as the study grows, and at a thousand delays it is close to an indicator of the parameters that put the population quantiles in the reported cells, a box rather than a peak. The multinomial of .meta_quantile_set_ll() on the continuity corrected grid keeps sharpening with the sample size instead, so it is not used for such a study.

Matches meta_family_grid_box_ll() in Stan.

Value

A log probability mass.


The uncorrected grid distribution function at a set of cells

Description

The number of delays a study saw at or below a grid cell is binomial on the grid distribution function at that cell, which is the mass of the cells up to and including it. A cohort grid is normalised by the mass it holds, so only the cells asked for, the top of the grid and its first cell are evaluated, as in .meta_grid_edges(). An accrual grid reweights every cell before renormalising, so it is built in full by .meta_grid_pmf().

Usage

.meta_grid_cdf(
  cell,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  growth_rate,
  accrual = 0L
)

Arguments

cell

An integer vector of grid cell indices, counting from zero.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

growth_rate

The exponential growth rate of primary events.

accrual

1 to apply the accrual weight, 0 otherwise.

Value

The grid distribution function at each cell, or infinities if the grid mass underflows to zero.


The log likelihood of a single quantile of integer day delays

Description

A quantile of delays counted in whole censoring windows is a discrete statistic. "The median is 5 days" says that the empirical distribution function crossed one half between 4 and 5 days, that is N_{\le y - w_s} < \lceil n p \rceil \le N_{\le y} with N_{\le y} the number of delays at or below y, which reads the reported value as a type 1 quantile. Each count is binomial on the uncorrected grid distribution function, so the probability of the event is a difference of two binomial upper tails, computed on the log scale.

Usage

.meta_grid_crossing_ll(y, p, study_n, dist, args, slots)

Arguments

y

The reported quantile value.

p

The probability the quantile was reported at.

study_n

The number of delays the quantiles were computed from.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

Details

Unlike the continuity corrected forms, the information this carries saturates as the study grows: once the binomial spread of the crossing is narrower than a window the reported integer stops moving, and the likelihood tends to an indicator of the parameters that put the population quantile in the reported cell.

Matches meta_family_grid_crossing_ll() in Stan.

Value

A log probability mass.


The cohort grid distribution function at the two edges of one cell

Description

A cohort grid is normalised by the mass it holds, so its cumulative sum at cell k is (F(k \times swindow) - F(L)) / (F(n_{grid} \times swindow) - F(L)). A reported quantile therefore needs four distribution function evaluations rather than the whole grid, and three where the study counted every delay. This does not hold under an accrual design, which reweights each cell before renormalising and so must keep the full grid.

Usage

.meta_grid_edges(
  cell,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  growth_rate
)

Arguments

cell

The index of the grid cell, counting from zero.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

growth_rate

The exponential growth rate of primary events.

Value

The grid distribution function at the lower and upper cell edges, or two infinities if the grid mass underflows to zero.


The index of the first grid cell a left truncated study could have seen

Description

A study that only counted delays of at least lower never saw the grid cells recording a shorter delay, so they are dropped before the grid is renormalised. The index counts cells from zero, so it is zero when the study counted every delay.

Usage

.meta_grid_first(lower, swindow)

Arguments

lower

The study's minimum delay (its left truncation point).

swindow

The secondary censoring window width, which is also the grid spacing.

Value

An integer cell index.


Summaries of a discrete delay grid

Description

Summaries of a discrete delay grid

Usage

.meta_grid_moments(mass, first_delay, swindow)

Arguments

mass

A vector of grid probabilities from .meta_grid_pmf(), or a vector of NA if the grid mass underflowed to zero.

first_delay

The delay the first kept cell records.

swindow

The secondary censoring window width, which is also the grid spacing.

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The discrete delay distribution a naive study would observe

Description

Builds the probability mass function of the interval censored delays a study that took date differences directly would have summarised. The grid runs over delays of 0, swindow, 2 * swindow, and so on up to the largest multiple of swindow whose upper bound is within cutoff, and is renormalised so that it conditions on delays falling within the grid. This renormalisation is what applies the study's right truncation, and it discretises the truncation point to the nearest grid boundary.

Usage

.meta_grid_pmf(
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  growth_rate,
  accrual = 0L
)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

growth_rate

The exponential growth rate of primary events.

accrual

1 to apply the accrual weight, 0 otherwise.

Details

Cells recording a delay below lower are dropped before the grid is renormalised, which conditions it on the study's left truncation point. The normaliser is then the mass of the kept cells, which is F(D) - F(L) whenever lower falls on a grid boundary.

Under an accrual design the cell masses are additionally weighted by the follow up available to the cases each cell holds, before renormalising. A case is seen when its primary event fell early enough for its delay to complete before the calendar stop, and the primary event is known only to its window. A complete primary window starting at k w_p holds a delay of x from its start when k w_p + x \le A, so the growth weighted mass of the complete windows eligible for x is a step function of x that steps down at A - j w_p. Each cell is cut at those points and every piece is weighted by that mass. When cutoff is not a multiple of pwindow the last primary window is partial, of length l = A - w_p \lfloor A / w_p \rfloor. It only holds delays up to l, and the offset of its primary events runs over l rather than w_p, so its cases follow the primary censored distribution function with a window of l, weighted by the growth weighted length of the window, and are added to the cells below l. This is exact for any cutoff, pwindow and swindow, and reduces to the weight at the cell's lower edge when pwindow and swindow are equal and cutoff is a multiple of both.

A cohort grid is normalised by the distribution function at its top, which is already known. An accrual grid reweights each cell first, so its normaliser is not known in advance.

Value

A numeric vector of probabilities summing to one, one per kept cell, or a vector of NA the same length if the grid mass underflows to zero.


The continuity corrected distribution function of a discrete delay grid

Description

The step distribution function of the grid is replaced by the version that interpolates it linearly through the mid points of its cells. Without this correction a quantile of day resolution data, which must land on a jump of the step function, biases the implied probability upwards by several sampling standard errors.

Usage

.meta_grid_prob(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  growth_rate,
  accrual = 0L
)

Arguments

y

The delay to evaluate the distribution function at.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

growth_rate

The exponential growth rate of primary events.

accrual

1 to apply the accrual weight, 0 otherwise.

Details

A cohort grid only needs the two cell edges the value falls between, so it takes the three evaluation shortcut of .meta_grid_edges(). An accrual grid must be built in full.

Value

A probability, or Inf if the grid mass underflows to zero, which forces a -Inf log likelihood rather than a NaN one.


The continuity corrected cohort grid distribution function at several delays

Description

The vectorised form of .meta_grid_prob() for a cohort study. Every cell edge a set of reported quantiles needs is evaluated in one call, because a call to primarycensored::pprimarycensored() costs the same whether it is given one delay or a hundred.

Usage

.meta_grid_probs(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  growth_rate
)

Arguments

y

A numeric vector of delays.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

growth_rate

The exponential growth rate of primary events.

Value

A numeric vector of probabilities, or infinities if the grid mass underflows to zero.


Build a single meta model row from one group of summary estimates

Description

The group_start slot is filled in by .meta_estimate_rows() once every group has been built.

Usage

.meta_group_row(estimates, vcov = NULL, n_quad = .meta_n_quad())

Arguments

estimates

The rows of an epidist_estimates_data object making up one group.

vcov

The covariance matrix over the group's summaries, or NULL where the study reported standard errors or a sample size instead.

n_quad

The number of quadrature intervals the group's study is evaluated on, from .estimates_n_quad().

Value

A list with a one row tibble row, a tibble of its members, and the flat chol entries of its covariance matrix.


Pass the grouped summary members of a meta model to Stan

Description

A row that stands for several summaries reported by one study cannot carry them in its own slots, because a study may report any number of quantiles. They are passed instead as flat arrays that the row indexes into with its group_start and group_len slots. See .meta_estimate_rows().

Usage

.meta_group_stanvars(data)

Arguments

data

An epidist_meta_model object.

Value

A brms stanvars object holding the flat member arrays.


Whether any summary row of a meta model estimates its growth rate

Description

Whether any summary row of a meta model estimates its growth rate

Usage

.meta_growth_estimated(data)

Arguments

data

An epidist_meta_model object.

Value

TRUE where a summary row has a growth_known slot of 0.


The default pgrowth formula of a meta model

Description

See epidist_formula_model.epidist_meta_model().

Usage

.meta_growth_formula(data, formula)

Arguments

data

An epidist_meta_model object.

formula

A brmsformula object carrying its family.

Value

The formula, with pgrowth ~ 0 + study, or pgrowth ~ 1 for a single study, added where a summary row estimates its growth rate and no pgrowth formula was given.


Prior distributions for the growth rate of summary rows

Description

See epidist_model_prior.epidist_meta_model().

Usage

.meta_growth_prior(data, formula, default = NULL)

Arguments

data

An epidist_meta_model object, optionally holding a study and a growth_rate_sd column.

formula

A brmsformula object whose family$dpars say whether the model estimates pgrowth.

default

The result of brms::default_prior() on data and formula, or NULL to compute it here.

Value

A brmsprior object, or NULL where no summary row estimates its growth rate.


The density of the biased estimand at a reported quantile value

Description

Used to convert a quantile standard error reported on the delay scale to the cumulative probability scale the model works on, by the delta method. For a discrete estimand the density is the mass of the grid cell the value falls in divided by the grid spacing, which is exactly the slope of the continuity corrected distribution function there. For a continuous estimand it is the closed form density of the estimand over its truncation normaliser, or, under an accrual design, the slope of the interpolated distribution function. A primary censored delay with a non uniform primary event has no closed form density, so it falls back to a central difference.

Usage

.meta_implied_density(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  trunc_adjusted,
  cens_adjusted,
  growth_rate,
  trunc_design = 0L,
  n_quad = .meta_n_quad()
)

Arguments

y

The reported quantile value.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

trunc_adjusted

1 if the study adjusted for right truncation, 0 otherwise.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

trunc_design

0 for a cohort design, 1 for an accrual design.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A density on the delay scale, or Inf if the grid mass or the distribution function underflows to zero, which forces a -Inf log likelihood rather than a NaN one.


The summaries a study using a given procedure would report

Description

Forward models the summaries that a study would converge to given the biases in its estimation procedure. See as_epidist_estimates_data.data.frame() for what the adjustment codes mean.

Usage

.meta_implied_moments(
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  trunc_adjusted,
  cens_adjusted,
  growth_rate,
  trunc_design = 0L,
  n_quad = .meta_n_quad()
)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

trunc_adjusted

1 if the study adjusted for right truncation, 0 otherwise.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

trunc_design

0 for a cohort design, 1 for an accrual design.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Details

Under the uniform single interval approximation (cens_adjusted of 2) the study summarised the delay plus the uncorrected primary event offset. Where the study also adjusted for right truncation and the primary events were uniform within their window this is the analytic convolution, which adds pwindow / 2 to the mean and pwindow^2 / 12 to the variance. Otherwise the moments of the primary censored delay, truncated at cutoff, are used directly.

A study that adjusted for right truncation and counted only delays above lower has its analytic moments left truncated by .meta_left_moments(), so they do not depend on cutoff. A study whose primary events were not uniform within their window has no analytic moments, so it is truncated at cutoff by quadrature instead.

Under midpoint imputation (cens_adjusted of 3) the study assigned each delay to the centre of the interval it was observed in, so the estimand is the naive discrete grid shifted up by swindow / 2. The shift moves the mean and leaves every central moment unchanged.

Under midpoint imputation with a uniform interval (cens_adjusted of 4) the study placed the primary event at the midpoint of its window instead of at its lower edge, so the estimand is that of cens_adjusted of 2 shifted down by pwindow / 2. Both midpoint codes are evaluated by calling the code they shift. See .meta_cens_base() and .meta_cens_shift().

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The implied distribution function at equally spaced delays

Description

Returns the implied distribution function on a grid of delays, together with where that grid starts and how far apart its points are. Reading an implied quantile off the delay scale needs the inverse of the implied distribution function, which has no closed form on the discrete grid, so it is interpolated from these points instead. See .meta_node_quantile().

Usage

.meta_implied_nodes(dist, args, slots)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

Value

A list with the distribution function values, the delay origin of the first value, and the spacing between values.


The cumulative probability a study using a given procedure would report

Description

Evaluates the distribution function of the biased estimand at a reported quantile value. Working on the probability scale avoids inverting the distribution function, which has no closed form on the discrete grid.

Usage

.meta_implied_prob(
  y,
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  swindow,
  trunc_adjusted,
  cens_adjusted,
  growth_rate,
  trunc_design = 0L,
  n_quad = .meta_n_quad()
)

Arguments

y

The reported quantile value.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

pwindow, swindow

The primary and secondary censoring window widths.

trunc_adjusted

1 if the study adjusted for right truncation, 0 otherwise.

cens_adjusted

The censoring adjustment code, one of 0, 1, 2, 3, or 4.

growth_rate

The exponential growth rate of primary events.

trunc_design

0 for a cohort design, 1 for an accrual design.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Details

For a naive study (cens_adjusted of 0) the estimand is discrete, so the continuity corrected grid distribution function of .meta_grid_prob() is used. Midpoint imputation (cens_adjusted of 3) uses the same function evaluated half a secondary window lower, because the study shifted every delay up by that amount.

For the uniform single interval approximation (cens_adjusted of 2) the distribution function of the primary censored delay is used, so that it matches the moments used for reported means and standard deviations. Midpoint imputation with a uniform interval (cens_adjusted of 4) uses that function evaluated half a primary window higher, because the study anchored every delay at the centre of the primary window rather than at its lower edge.

Value

A probability, or Inf if the distribution function underflows to zero at cutoff, which forces a -Inf log likelihood rather than a NaN one.


The cumulative probabilities a study would report at several quantiles

Description

The vectorised form of .meta_implied_prob(), used for the set of quantiles one study reported. A cohort study on a discrete grid needs only the cell edges the reported values fall between, so all of them are evaluated in one call. Every other design falls back to evaluating each value on its own.

Usage

.meta_implied_probs(y, dist, args, slots)

Arguments

y

A vector of reported quantile values.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

Value

A numeric vector of probabilities.


The summaries a study would report, one per multivariate normal member

Description

Member types are 1 for a mean, 2 for a standard deviation and 3 for a quantile at the matching probability. Quantile members are read off the implied distribution function by .meta_node_quantile(), so they are on the delay scale, matching the reported values and the covariance matrix supplied with them.

Usage

.meta_implied_summary_vector(dist, args, slots, moments = NULL)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

moments

A summary vector from .meta_implied_moments() for this row and draw, or NULL to compute it here.

Value

A numeric vector of implied summaries.


Build the individual level rows of an epidist_meta_model object

Description

Build the individual level rows of an epidist_meta_model object

Usage

.meta_individual_rows(data)

Arguments

data

Individual level data prepared by .prepare_marginal_data().

Value

A tibble of individual level rows using the meta model slots.


Interpolate a distribution function held at equally spaced points

Description

Both the discrete grid and the accrual quadrature give the implied distribution function at equally spaced delays, and a reported quantile is read off by linear interpolation between them. Delays below the first point are given zero and delays at or beyond the last are given one.

Usage

.meta_interpolate(y, values, spacing, offset)

Arguments

y

A numeric vector of delays.

values

The distribution function at the points.

spacing

The distance between consecutive points.

offset

The offset, in points, of the first point from a delay of zero. This is half a cell for the continuity corrected grid, which interpolates through the mid points of its cells, and zero for the accrual quadrature.

Value

A numeric vector of probabilities.


The sampling covariance of the summaries one study reports

Description

The asymptotic covariance of a sample mean, a sample standard deviation and sample quantiles computed from the same study_n delays. The mean and standard deviation block is that of .meta_moment_pair_ll(). By the Bahadur representation a sample quantile at probability p is Q_p - (\hat{G}(Q_p) - p) / f(Q_p) up to a smaller order term, so with f_i = f(Q_{p_i}) the implied density at each implied quantile

\text{Cov}(q_i, q_j) = \frac{p_i (1 - p_j)}{n f_i f_j}, \quad p_i \le p_j,

\text{Cov}(\bar{x}, q_i) = -\frac{1}{n f_i} \int_L^{Q_{p_i}} (x - \mu) \text{d}G(x),

\text{Cov}(s, q_i) = -\frac{1}{2 \sigma n f_i} \int_L^{Q_{p_i}} \left((x - \mu)^2 - \sigma^2\right) \text{d}G(x),

the last carried from the sample variance to the standard deviation by the delta method. The integrals are the centred partial moments of .meta_quantile_partials(). Matches meta_family_joint_covariance() in Stan.

Usage

.meta_joint_covariance(types, probs, moments, density, partial, study_n)

Arguments

types

Member types, 1 for a mean, 2 for a standard deviation and 3 for a quantile.

probs

Member probabilities, zero for a mean or standard deviation.

moments

A summary vector from .meta_moment_vector().

density

The implied density at each implied quantile, one per quantile member in order.

partial

A two row matrix of centred partial moments from .meta_quantile_partials(), one column per quantile member in order.

study_n

The number of delays the summaries were computed from.

Value

A covariance matrix over the members.


The joint log likelihood of the summaries of one continuous study

Description

The multivariate normal of .meta_joint_study_terms(). A covariance that is not positive definite, which quadrature error can produce for a draw far from the reported summaries, is rejected with a log likelihood of -Inf, as are the failures listed there. Matches meta_family_joint_study_lpdf() in Stan.

Usage

.meta_joint_study_ll(y, dist, args, slots, moments = NULL)

Arguments

y

A numeric vector of reported summaries in member order.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

moments

A summary vector from .meta_implied_moments() for this row and draw, or NULL to compute it here.

Value

A log density.


The implied summaries of a joint study group and their sampling covariance

Description

A continuous estimand reporting a mean or a standard deviation alongside quantiles has every summary fitted jointly, with the covariance of .meta_joint_covariance() derived from the implied distribution rather than supplied. The quantiles are read off the implied nodes as for a covariance matrix group, see .meta_implied_summary_vector(), and the density and centred partial moments at each are taken from the same nodes.

Usage

.meta_joint_study_terms(dist, args, slots, moments = NULL)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

moments

A summary vector from .meta_implied_moments() for this row and draw, or NULL to compute it here.

Value

A list with the implied summary vector and the covariance matrix sigma, or NULL where the implied moments are not finite, the nodes underflow or a quantile sits where the estimand has no density, which the caller rejects.


Summaries of a distribution left truncated at lower

Description

A study that adjusted for right truncation and only counted delays above lower reported the moments of the delay conditioned on exceeding it. They are taken from the untruncated moments by removing the part below lower, E[\tau^k 1(\tau \le L)] = L^k F(L) - \int_0^L k t^{k - 1} F(t) dt, by Simpson's rule on [0, L], and dividing by 1 - F(L). The integral is over a bounded interval the quadrature resolves well, so the result does not depend on max_delay, and it matches the distribution function (F(y) - F(L)) / (1 - F(L)) used for the same study's quantile rows. It applies to any distribution whose untruncated moments and distribution function are available, which is the delay itself and the uniform single interval approximation of .meta_add_uniform(). Matches meta_family_left_moments in inst/stan/meta_model/functions.stan.

Usage

.meta_left_moments(full, cdf, lower)

Arguments

full

A summary vector from .meta_moment_vector() of the untruncated distribution.

cdf

The distribution function at n_quad + 1 equally spaced points running from zero to lower, for an even n_quad.

lower

The study's minimum delay (its left truncation point).

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The log follow up available to a delay under an accrual design

Description

A study that collected primary events over a window of length window and stopped at its calendar end could only observe a delay of d for the primary events that occurred at least d before the stop. With primary events arriving at a rate proportional to \exp(r t) the amount of such follow up is w(d) = \int_0^{window - d} \exp(r t) \text{d}t = (\exp(r (window - d)) - 1) / r, which tends to window - d as r tends to zero. This is the dynamical bias of Park et al. (2024); for a long window and a growing epidemic it approaches an exponential tilt of the delay distribution by \exp(-r d).

Usage

.meta_log_accrual_weight(d, window, growth_rate)

Arguments

d

A numeric vector of delays.

window

The length of the collection window.

growth_rate

The exponential growth rate of primary events.

Details

Working on the log scale keeps the weight finite for a fast growing epidemic observed over a long window, where the weight itself would overflow.

Value

A numeric vector of log follow up times.


The log mass of a binomial count with floored probabilities

Description

The binomial mass with the success and failure probabilities floored at 1e-300, so that a count the parameters make all but impossible is very unlikely rather than impossible and a chain can start from a random initial value. Matches the arithmetic of meta_family_grid_box_ll() in Stan.

Usage

.meta_log_binom(x, size, prob)

Arguments

x

A vector of counts.

size

A vector of numbers of trials.

prob

The success probability.

Value

A vector of log masses.


The log upper tail of a binomial count, stable far into the tail

Description

P(M >= m) for M ~ Binomial(size, prob). Nine standard deviations above the mean, or below a probability of 1e-12, the tail is summed term by term on the log scale until the terms fall forty nats below the first, or two hundred terms in with a geometric bound on the rest, which is exact to that tolerance and, unlike the distribution function, has finite partial derivatives there in Stan. Elsewhere it is the distribution function of the complement. Matches meta_family_log_binom_upper() in Stan.

Usage

.meta_log_binom_upper(m, size, prob)

Arguments

m

The smallest count in the tail, a vector.

size

The number of trials, a vector.

prob

The success probability, a vector.

Value

The log tail probabilities, recycled to the longest argument.


The log distribution function below which a node is severed

Description

Every grid and quadrature path evaluates the distribution function from the study's minimum delay upwards, so for a narrow delay it reaches deep into the lower tail, where the Stan primary censored distribution function of primarycensored returns a finite value with a non finite gradient. A node whose plain log distribution function is below this value holds a probability below exp(-100), which no moment or probability the model forms can resolve, so it is treated as holding no mass before that function is called. Matches the cut in meta_family_pcens_lcdf() and meta_family_dist_prob() in inst/stan/meta_model/functions.stan.

Usage

.meta_log_cdf_floor()

Value

A log probability.


The log of a difference of two exponentials

Description

Matches Stan's log_diff_exp(), returning -Inf where the difference is zero or negative rather than NaN.

Usage

.meta_log_diff_exp(upper, lower)

Arguments

upper, lower

Logarithms, with upper expected to be the larger.

Value

log(exp(upper) - exp(lower)).


A numerically stable log of a sum of exponentials

Description

A numerically stable log of a sum of exponentials

Usage

.meta_log_sum_exp(x)

Arguments

x

A numeric vector of log values.

Value

log(sum(exp(x))), or -Inf when every element is -Inf.


The largest correlation the joint moment likelihood will use

Description

The asymptotic correlation between a sample mean and a sample standard deviation is the skewness over the square root of the excess kurtosis, and \kappa \geq \gamma_1^2 + 1 holds for every distribution, so it never leaves [-1, 1]. Moments taken from a discrete grid or from quadrature can sit a little outside that bound, which would make the covariance matrix singular, so the correlation is held inside it.

Usage

.meta_max_correlation()

Details

Matches the value hard coded in inst/stan/meta_model/functions.stan so that the R and Stan implementations agree.

Value

A correlation.


Build the member table of one joint likelihood group

Description

The member type and probability are carried alongside the reported value because a group covered by a covariance matrix may mix means, standard deviations and quantiles, so the likelihood needs to know which implied summary each member is.

Usage

.meta_member_table(estimates, count, lower = 0L)

Arguments

estimates

The rows of an epidist_estimates_data object making up one group, already ordered.

count

The cumulative counts the multinomial quantile likelihood uses, the largest counts below each reported day for quantiles of integer day delays, or zeros for a group that uses neither.

lower

The smallest counts at or below each reported day for quantiles of integer day delays, or zeros otherwise.

Details

A set of quantiles of integer day delays carries the box each reported day puts on the study's cumulative counts: count is the largest number of delays the study can have seen below the day and lower the smallest at or below it. See .meta_grid_box_ll().

Value

A tibble of member value, count, lower, type and p columns.


The grouped summary members of an epidist_meta_model object

Description

The grouped summary members of an epidist_meta_model object

Usage

.meta_members(data)

Arguments

data

An epidist_meta_model object.

Value

A tibble of member value, count, lower, type and p columns.


The smallest quantile standard error the model will use

Description

A quantile standard error supplied on the delay scale is used as reported, held at or above this value as a guard against a standard error of zero, which would give a degenerate likelihood.

Usage

.meta_min_prob_se()

Value

A delay scale standard error.


The correlation between a reported mean and a reported standard deviation

Description

The correlation between a reported mean and a reported standard deviation

Usage

.meta_moment_correlation(moments)

Arguments

moments

A summary vector from .meta_moment_vector().

Value

A correlation strictly inside [-1, 1].


The summary vector returned when a normaliser underflows to zero

Description

An infinite mean and standard deviation make the normal log likelihood evaluate to -Inf for any finite reported value, so a draw that hits this case is rejected rather than turning the log likelihood into NaN.

Usage

.meta_moment_failure()

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The joint log likelihood of a mean and a standard deviation from one study

Description

A sample mean and a sample standard deviation computed from the same delays are correlated, so fitting them as two independent normal terms overstates how much a study reporting both tells us. They are instead given the asymptotic bivariate normal of the pair, with \text{Cov}(\bar{x}, s^2) = \mu_3 / n carried onto the standard deviation scale by the delta method, giving \text{Cov}(\bar{x}, s) = \mu_3 / (2 n \sigma) and a correlation of \gamma_1 / \sqrt{\kappa - 1}. See .meta_moment_correlation().

Usage

.meta_moment_pair_ll(y_mean, y_sd, moments, study_n)

Arguments

y_mean

The reported mean.

y_sd

The reported standard deviation.

moments

A summary vector from .meta_moment_vector().

study_n

The number of delays the summaries were computed from.

Value

A log density.


Summarise a distribution from its mean and central moments

Description

The kurtosis is needed as well as the mean and standard deviation because the sampling error of a reported standard deviation depends on it. See .meta_summary_terms(). The skewness is needed because the sampling covariance of a reported mean and a reported standard deviation from the same study depends on it. See .meta_moment_pair_ll().

Usage

.meta_moment_vector(mean, variance, third, fourth)

Arguments

mean

The mean of the distribution.

variance

The variance of the distribution.

third

The third central moment of the distribution.

fourth

The fourth central moment of the distribution.

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


Central moments of the delay distributions with analytic summaries

Description

Each returns the mean, the variance and the third and fourth central moments. They mirror the Stan functions of the same name in inst/stan/meta_model/functions.stan. The weibull and generalised gamma share .meta_moments_scaled(), since their raw moments are E[T^r] = scale^r g_r.

Usage

.meta_moments_lognormal(args)

.meta_moments_gamma(args)

.meta_moments_scaled(scale, g)

.meta_moments_weibull(args)

.meta_moments_gengamma(args)

Arguments

args

A named list of distribution parameters.

scale

The scale of the distribution.

g

The ratios g_1, \dots, g_4 of the raw moments.

Value

A numeric vector of length four.


The log density of a study's summaries under a supplied covariance

Description

A study that cannot share its delays can report a vector of summaries with a covariance matrix over them, which keeps the correlation between the quantities it reports. The Cholesky factor of that matrix is built once when the model data are prepared and passed to Stan, so the sampler never decomposes it.

Usage

.meta_multi_normal_ll(y, implied, chol)

Arguments

y

A numeric vector of reported summaries.

implied

A numeric vector of implied summaries from .meta_implied_summary_vector().

chol

The lower triangular Cholesky factor of the reported covariance matrix.

Value

A log density.


The smallest number of quadrature intervals used for a summary row

Description

Set with options(epidist.meta_n_quad = ), as an even number of at least two. Each summary row carries its own number of intervals in its n_quad slot, chosen by .estimates_n_quad() from the spread the study reported so that the quadrature resolves the delay, and this is the floor of that choice. Set it before building the model data, since the slot is filled in then. It also lifts the cap of .meta_n_quad_max() when set above it.

Usage

.meta_n_quad()

Value

An integer number of intervals.


The default number of quadrature intervals for truncated continuous moments

Description

The default number of quadrature intervals for truncated continuous moments

Usage

.meta_n_quad_default()

Value

An integer number of intervals.


The largest number of quadrature intervals chosen for a summary row

Description

Every quadrature node costs a distribution function evaluation on each gradient, so the number of intervals .estimates_n_quad() chooses for a study is capped here unless options(epidist.meta_n_quad = ) is set higher. as_epidist_estimates_data() warns about a study the cap leaves unresolved.

Usage

.meta_n_quad_max()

Value

An integer number of intervals.


The number of Newton steps taken from the chord inverse

Description

Matches meta_family_node_quantile() in Stan. Each step squares the error of the chord, which is of the order of the node spacing squared, so two steps leave a residual well below the sampling standard error of any reported quantile.

Usage

.meta_newton_steps()

Value

An integer.


The index of the node interval holding a delay

Description

Interval i runs from node i to node i + 1. It is found by stepping through the nodes rather than by rounding, because in Stan the delay is a parameter and cannot be converted to an integer. Matches meta_family_node_interval() in Stan.

Usage

.meta_node_interval(nodes, q)

Arguments

nodes

The output of .meta_implied_nodes().

q

A delay between the first and last node.

Value

An integer between 1 and the number of intervals.


The delay at which an implied distribution function reaches p

Description

Inverts the distribution function of .meta_implied_nodes() by linear interpolation between the two points that bracket p. On the discrete grid that interpolant is the model's own definition of the continuity corrected quantile, so the chord is exact there. For a continuous estimand the chord is only as accurate as the node spacing, which for a truncation adjusted study is about a day, so it is refined by .meta_refine_quantile() when the design is supplied. The result stays a differentiable function of the delay distribution parameters, which a root search would not be.

Usage

.meta_node_quantile(nodes, p, dist = NULL, args = NULL, slots = NULL)

Arguments

nodes

The output of .meta_implied_nodes().

p

A probability.

dist

A primarycensored distribution function name, or NULL to return the chord inverse alone.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

Value

A delay.


Map summary types to their observation type codes

Description

Map summary types to their observation type codes

Usage

.meta_obs_type(type)

Arguments

type

A character vector of summary types.

Value

An integer vector of observation type codes.


Order the summaries within a joint likelihood group

Description

Members are stored as the mean, then the standard deviation, then the quantiles in increasing probability, so that the bivariate normal knows which member is which and a joint study group is laid out as its covariance is built. The quantiles must be non decreasing in the reported value for the cells of the multinomial to be a partition of the delay axis. Coincident values are merged into one cell by the likelihood.

Usage

.meta_order_group(estimates, vcov = NULL)

Arguments

estimates

The rows of an epidist_estimates_data object making up one group.

vcov

The covariance matrix over the group's summaries, or NULL.

Details

A group covered by a covariance matrix keeps the order its rows were given in, because that is the order the matrix is indexed by.

Value

The input, reordered.


The primary censored distribution function, guarded against underflow

Description

Primary distributions without an analytical solution are integrated numerically, which can return a non finite or negative cumulative probability deep in the lower tail. Those cases carry negligible probability and are treated as zero, matching the guard in inst/stan/meta_model/functions.stan. A delay whose plain distribution function is below the cut of .meta_log_cdf_floor() is severed to zero before the primary censored function is called, as it is in Stan, since the primary censored distribution function is never above the plain one.

Usage

.meta_pcens_cdf(q, dist, args, pwindow, growth_rate)

Arguments

q

A numeric vector of delays.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

pwindow

The primary censoring window width.

growth_rate

The exponential growth rate of primary events.

Value

A numeric vector of cumulative probabilities.


Summaries of a right truncated primary censored delay distribution

Description

The estimand is the delay plus the primary event offset within its window, conditioned on falling below the cutoff. Under an accrual design the quadrature is reweighted by the follow up available to each delay, offset by half a primary window because the estimand already includes the primary event offset. See .meta_accrual_reweight().

Usage

.meta_pcens_trunc_moments(
  dist,
  args,
  lower = 0,
  cutoff,
  pwindow,
  growth_rate,
  accrual = 0L,
  n_quad = .meta_n_quad()
)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

growth_rate

The exponential growth rate of primary events.

accrual

1 to apply the accrual weight, 0 otherwise.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The primary event distribution implied by a growth rate

Description

A growth rate of zero corresponds to a uniform primary event within its censoring window. Any other value uses the exponential growth primary distribution from primarycensored.

Usage

.meta_primary(growth_rate)

Arguments

growth_rate

The exponential growth rate of primary events.

Value

A list with elements dprimary and dprimary_args.


The cumulative counts implied by a set of reported quantiles

Description

The multinomial likelihood of .meta_quantile_set_ll() needs the number of delays a study saw at or below each reported quantile. Rounding the cumulative probabilities rather than the increments keeps the counts non decreasing and bounded by the sample size, so the cell counts are non negative and sum to the sample size however the probabilities round.

Usage

.meta_quantile_counts(p, study_n)

Arguments

p

A vector of quantile probabilities in increasing order.

study_n

The number of delays the quantiles were computed from.

Value

An integer vector of cumulative counts.


The entries of the joint sampling covariance of one study's summaries

Description

.meta_quantile_covariance() gives the Bahadur covariance of two quantiles, .meta_cross_covariance() that of a mean or a standard deviation and a quantile, and .meta_moment_covariance() that of two moment summaries, see .meta_joint_covariance(). They mirror the Stan functions meta_family_quantile_covariance(), meta_family_cross_covariance() and meta_family_moment_covariance() in inst/stan/meta_model/functions.stan.

Usage

.meta_quantile_covariance(prob_i, prob_j, density_i, density_j, study_n)

.meta_cross_covariance(moment_type, prob, density, partial, spread, study_n)

.meta_moment_covariance(type_i, type_j, se_mean, se_sd, rho)

Arguments

prob_i, prob_j, prob

Member probabilities.

density_i, density_j, density

The implied density at the implied quantiles.

study_n

The number of delays the summaries were computed from.

moment_type, type_i, type_j

Member types, 1 for a mean and 2 for a standard deviation.

partial

The two centred partial moments at the quantile, a column of .meta_quantile_partials().

spread

The implied standard deviation.

se_mean, se_sd

The sampling standard errors of the mean and the standard deviation.

rho

The sampling correlation of the mean and the standard deviation from .meta_moment_correlation().

Value

A covariance.


The density of a continuous estimand at its implied quantile

Description

Where the quantile is left on its chord, see .meta_quantile_on_chord(), the estimand is the linear interpolant of its nodes and its density is the slope of the interval holding the quantile. Otherwise it is the closed form density of .meta_implied_density(). Matches meta_family_quantile_density() in Stan.

Usage

.meta_quantile_density(q, index, nodes, dist, args, slots)

Arguments

q

The implied quantile from .meta_node_quantile().

index

The node interval holding q, from .meta_node_interval().

nodes

The output of .meta_implied_nodes().

dist

A primarycensored distribution function name, or NULL to return the chord inverse alone.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

Value

A density on the delay scale.


Whether the implied quantile of a design is left on its chord

Description

The chord inverse of .meta_node_quantile() is refined only where the implied distribution function and density exist in closed form. A discrete grid, an accrual estimand and a uniform single interval estimand with a growing primary event are defined by the interpolation between their nodes, so their chord is the implied quantile and the slope of the interval holding it is the implied density. See .meta_refine_quantile(). Matches the early returns of meta_family_node_quantile() in Stan.

Usage

.meta_quantile_on_chord(slots)

Arguments

slots

The output of .meta_row_slots().

Value

A logical scalar.


The centred partial moments of an estimand below its implied quantile

Description

The sampling covariance of a reported mean or standard deviation with a reported quantile depends on \int_L^{q} (x - \mu)^k \text{d}G(x) for k = 1, 2, with G the implied distribution function, \mu the implied mean and L the smallest delay the study counted. Integrating by parts gives (q - \mu)^k p - \int_L^{q} k (x - \mu)^{k - 1} G(x) \text{d}x, and the remaining integral is taken by the trapezoid rule over the linear interpolant of the nodes, which reaches p at q. Its error is of the order of the node spacing squared, which .estimates_n_quad() holds to a quarter of the reported spread. Matches meta_family_quantile_partials() in Stan.

Usage

.meta_quantile_partials(nodes, q, p, index, centre)

Arguments

nodes

The output of .meta_implied_nodes().

q

The implied quantile from .meta_node_quantile().

p

The probability of the quantile.

index

The node interval holding q, from .meta_node_interval().

centre

The implied mean of the estimand.

Value

A numeric vector of the first and second centred partial moments.


The joint log likelihood of a set of quantiles from one study

Description

Quantiles reported at probabilities p_1 < \dots < p_k with values y_1 \le \dots \le y_k split the delay axis into the cells (0, y_1], \dots, (y_{k-1}, y_k], (y_k, \infty), and the number of delays falling in each cell is multinomial with probabilities given by the increments of the implied distribution function. This is the joint version of the empirical distribution function likelihood used for a single quantile, and it reduces to the exact binomial when only one quantile of a continuous estimand is reported. Fitting each quantile separately ignores the positive correlation between the empirical distribution function at different points, which over weights a study reporting a median with an interquartile range.

Usage

.meta_quantile_set_ll(
  y,
  cum_count,
  study_n,
  dist,
  args,
  slots,
  p = slots$group_p,
  lower = slots$group_lower
)

Arguments

y

A vector of reported quantile values in non decreasing order.

cum_count

A vector of cumulative counts from .meta_quantile_counts(), or for quantiles of integer day delays the largest count of delays below each reported day, from .meta_crossing_counts() less one.

study_n

The number of delays the quantiles were computed from.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

p

The probabilities the quantiles were reported at, in the order of y. Only used for a single quantile of integer day delays.

lower

For quantiles of integer day delays, the smallest count of delays at or below each reported day, from .meta_crossing_counts(). Unused otherwise.

Details

Two quantiles reported at the same value are two constraints on the empirical distribution function at one cell, so they are merged into that cell with their combined count.

Quantiles of integer day delays (cens_adjusted 0 or 3) are discrete statistics, and the multinomial on the continuity corrected distribution function keeps sharpening with the study size while a rounded quantile stops moving. A single such quantile is fitted by .meta_grid_crossing_ll() as the cell in which the empirical distribution function crossed its probability, and several by .meta_grid_box_ll() as the joint probability of every such crossing, with cum_count and lower read as the box each crossing puts on the counts below and at the reported day. Both start the grid at delay_min moved back by .meta_cens_lower(), as the mean and standard deviation of the same study do. For a midpoint imputed grid (cens_adjusted 3) the reported delay_min sits on the midpointed scale, so an off grid value would otherwise drop the lowest counted cell.

A cell whose implied probability underflows to zero while the study saw delays in it is floored at .meta_cell_floor().

Value

A log probability mass.


The first four raw moments of a set of summaries

Description

Inverts .meta_central_from_raw().

Usage

.meta_raw_from_central(moments)

Arguments

moments

A summary vector from .meta_moment_vector().

Value

A numeric vector of the first four raw moments.


Refine the chord inverse of a continuous implied distribution function

Description

Where the family quantile function is available, that is for a lognormal or weibull delay reported by a study that adjusted for censoring and did not use an accrual design, the implied quantile is Q(F(L) + p (F(D) - F(L))) exactly. Otherwise Newton steps are taken from the chord using the implied distribution function and density of .meta_implied_prob() and .meta_implied_density(), which exist in closed form for every remaining continuous design with a uniform primary event. An accrual estimand, or a uniform single interval estimand with a growing primary event, is defined by linear interpolation between its nodes, so its chord is left alone, as is a discrete grid.

Usage

.meta_refine_quantile(chord, p, dist, args, slots, floor, ceiling)

Arguments

chord

The chord inverse from .meta_node_quantile().

p

A probability.

dist

A primarycensored distribution function name, or NULL to return the chord inverse alone.

args

A named list of distribution parameters.

slots

The output of .meta_row_slots().

floor, ceiling

The delays at the first and last node, which the refined value is held between.

Details

The Stan mirror meta_family_node_quantile() cannot evaluate the primary censored distribution function at a parameter dependent delay, so the cases refined here are exactly those it can refine with closed forms.

Value

A delay.


The implied summaries of one meta model row for every posterior draw

Description

Rows sharing a study design, the same parameter draws and the same quadrature resolution imply the same summaries, so they are computed once and reused. The cache is bounded and lives in the package namespace, so it is never written into a fitted model object. See .meta_draws. A row with an estimated growth rate holds one rate per draw, so the rates are part of what a cached entry is compared against, and each draw is summarised at its own rate.

Usage

.meta_row_draw_moments(slots, dist, dist_args)

Arguments

slots

The output of .meta_row_slots().

dist

A primarycensored distribution function name.

dist_args

A list of named parameter lists, one per posterior draw.

Details

Only reported means and standard deviations need implied summaries. Quantile rows work on the cumulative probability scale, so they get a list of NULL and nothing is computed for them.

Value

A list of summary vectors, one per posterior draw.


The log likelihood of one meta model summary row for one draw

Description

Ungrouped rows use the normal approximations of .meta_summary_terms(). A group row, which stands for several summaries reported by one study, uses the joint likelihood of its members: .meta_moment_pair_ll() for a mean and a standard deviation, .meta_quantile_set_ll() for a set of quantiles, which hands quantiles of integer day delays to .meta_grid_crossing_ll() or .meta_grid_box_ll(), and .meta_joint_study_ll() for a continuous estimand reporting both kinds.

Usage

.meta_row_log_lik(slots, dist, args, moments = NULL)

Arguments

slots

The output of .meta_row_slots().

dist

A primarycensored distribution function name.

args

A named list of distribution parameters for a single draw.

moments

A summary vector from .meta_implied_moments() for this row and draw, or NULL to compute it here.

Details

A draw whose implied moments are not all finite, which an extreme delay distribution parameter can produce by overflowing the analytic kurtosis, is rejected with a log likelihood of -Inf rather than NaN, for every row that uses the moments. Matches the guard in meta_family_lpmf in inst/stan/meta_model/functions.stan.

Value

A log density.


The log of a sum of exponentials over each row of a matrix

Description

The log of a sum of exponentials over each row of a matrix

Usage

.meta_row_log_sum_exp(m)

Arguments

m

A numeric matrix of log values.

Value

A numeric vector, one value per row, -Inf where every element of the row is -Inf.


The summaries implied by one meta model row for one draw

Description

The summaries implied by one meta model row for one draw

Usage

.meta_row_moments(slots, dist, args)

Arguments

slots

The output of .meta_row_slots().

dist

A primarycensored distribution function name.

args

A named list of distribution parameters for a single draw.

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


Extract the meta model slots for a single row

Description

Group rows point into the flat member arrays passed to Stan as data, so the reported values and cumulative counts of the group are read back out here for the R mirrors of the joint likelihoods.

Usage

.meta_row_slots(i, prep)

Arguments

i

The row index.

prep

A brms prep object.

Details

A row whose growth_known slot is 0 estimates its growth rate as the pgrowth distributional parameter, so its growth_rate element holds one value per posterior draw rather than the number in the slot. Everything that works one draw at a time takes the slots of that draw from .meta_draw_slots(). A fit made before the slot existed has no growth_known and every row of it is known.

Value

A named list of the observation type, study metadata and reported values for row i.


The sampling standard error of a reported standard deviation

Description

Uses the asymptotic standard error of the sample standard deviation, \sigma \sqrt{(\kappa - 1) / (4 n)}, where \kappa is the kurtosis of the estimand the study was summarising. The normal theory expression \sigma / \sqrt{2 (n - 1)} is not used because it is far too narrow for the skewed distributions delays usually follow.

Usage

.meta_sd_se(moments, study_n)

Arguments

moments

A summary vector from .meta_moment_vector().

study_n

The number of delays the standard deviation was computed from.

Value

The standard error of the reported standard deviation.


Attach the grouped summary members to an epidist_meta_model object

Description

The members of a group row cannot be stored in the row itself because a study may report any number of quantiles, so they are held alongside the data and passed to Stan as flat arrays that the group row indexes into. See .meta_estimate_rows().

Usage

.meta_set_members(data, members, chol = numeric(0))

Arguments

data

An epidist_meta_model object.

members

A tibble of member value, count, lower, type and p columns.

chol

A flat numeric vector of Cholesky factor entries, in column major order, for the groups covered by a covariance matrix.

Value

The input with the members attached.


The number of quadrature intervals a row's slots ask for

Description

Rows built by as_epidist_meta_model() carry it in their n_quad slot. A slots list assembled by hand without one uses the floor.

Usage

.meta_slots_n_quad(slots)

Arguments

slots

The output of .meta_row_slots().

Value

An integer number of intervals.


Whether the primary event of a meta model row is tilted

Description

Mirrors the primary event id of meta_family_lpmf() in Stan, which takes the exponential growth path for every row that estimates its rate, whatever value the parameter holds, and for a known rate other than zero.

Usage

.meta_slots_tilted(slots)

Arguments

slots

The output of .meta_draw_slots().

Value

TRUE where the primary event is not uniform.


The kernel of a forward pass step as a matrix

Description

The binomial mass of a step from s to t counts splits into a factor in s, a factor in t and 1 / (t - s)!, so the step is a matrix in t - s times a vector in s. The matrix holds \exp((t - s) \lambda - \log (t - s)!) scaled by .meta_step_kernel_top(), which keeps its entries in range around the expected step, and is zero where t < s. It depends on the parameters only through the scaling, so Stan builds it as data and the step costs one matrix product on the autodiff stack rather than an entry per pair of counts. Matches meta_family_step_kernel() in Stan.

Usage

.meta_step_kernel(a, b, a2, b2, lambda_scaled)

Arguments

a, b

The first and last source count.

a2, b2

The first and last target count.

lambda_scaled

The log expected step from .meta_fixed_point().

Value

A matrix with a row per target and a column per source count.


Whether the kernel of a forward pass step is in range at its likely size

Description

The kernel falls away from the expected step like a Poisson mass, so it underflows at a step hundreds of nats from the expected one. The boxes force such a step only where the parameters are that far from fitting the study, and the step then takes the slower path that sums on the log scale. Matches meta_family_step_kernel_alive() in Stan.

Usage

.meta_step_kernel_alive(d_star, lambda_scaled)

Arguments

d_star

The step of the most likely path.

lambda_scaled

The log expected step from .meta_fixed_point().

Value

TRUE or FALSE.


The log kernel of a forward pass step at its expected size

Description

The kernel of a step is \exp(d \lambda - \log d!) at a step of d counts, with \lambda the log expected step, and is divided by its value at the expected step so that no entry exceeds one. Matches meta_family_step_kernel_top() in Stan.

Usage

.meta_step_kernel_top(lambda_scaled)

Arguments

lambda_scaled

The log expected step from .meta_fixed_point().

Value

A number.


The probability of a step of the chain of cumulative counts

Description

Given the count at one edge, the delays beyond it fall at or below the next edge with this probability. A distribution function that has reached one leaves nothing to place, so the step probability is zero.

Usage

.meta_step_prob(from, to)

Arguments

from, to

The grid distribution function at the two edges.

Value

A probability.


Check that a family is supported for meta model summary rows

Description

Check that a family is supported for meta model summary rows

Usage

.meta_summary_dist(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

The primarycensored distribution function name, or NULL if the family is not supported.


The implied summary and its standard error for one summary row and one draw

Description

A standard error reported for a quantile row is on the scale of the reported delay, as studies report it, so such a row is fitted on that scale against the implied quantile of .meta_node_quantile(). A quantile row without a standard error is fitted on the cumulative probability scale, where the binomial standard error of an empirical distribution function applies.

Usage

.meta_summary_terms(slots, dist, args, moments = NULL)

Arguments

slots

The output of .meta_row_slots().

dist

A primarycensored distribution function name.

args

A named list of distribution parameters for a single draw.

moments

A summary vector from .meta_implied_moments() for this row and draw, or NULL to compute it here.

Details

A group row stands for several summaries reported by one study, and this returns the marginal of its first member, which is the reported mean of a mean and standard deviation pair and the cumulative probability at the smallest reported quantile of a quantile set. For a group covered by a covariance matrix it is the first element of the reported vector, with the first diagonal entry of the Cholesky factor as its standard error, so a posterior predictive check of such a row describes that element alone and not the rest of the group. That marginal is what the posterior predictive draws for the row. The joint log likelihood of the whole group is .meta_row_log_lik().

Value

A named numeric vector with elements observed, implied and se.


Summaries implied by a distribution function evaluated on a grid

Description

Uses Simpson's rule on the survival integrals \int_L^D k t^{k - 1} (F(D) - F(t)) dt, which with the boundary term L^k (F(D) - F(L)) give the first four raw moments of the distribution truncated to (L, D]. The boundary term vanishes when L is zero, recovering the untruncated expression. Matches the implementation in inst/stan/meta_model/functions.stan.

Usage

.meta_survival_moments(cdf, lower = 0, cutoff)

Arguments

cdf

The distribution function at n_quad + 1 equally spaced points running from lower to cutoff, for an even n_quad.

lower

The study's minimum delay (its left truncation point).

cutoff

The right truncation point.

Value

A named numeric vector with elements mean, sd and kurtosis, or .meta_moment_failure() if the distribution function holds no mass between lower and cutoff.


Map truncation designs to their slot codes

Description

Map truncation designs to their slot codes

Usage

.meta_trunc_design(design)

Arguments

design

A character vector of truncation designs.

Value

An integer vector, 0 for a cohort design and 1 for an accrual design.


Summaries of a right truncated delay distribution

Description

Under an accrual design the quadrature is reweighted by the follow up available to each delay before the moments are taken, which is exact for a study that adjusted for censoring because the weight then applies to the delay itself.

Usage

.meta_trunc_moments(
  dist,
  args,
  lower = 0,
  cutoff,
  growth_rate = 0,
  accrual = 0L,
  n_quad = .meta_n_quad()
)

Arguments

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

lower

The study's minimum delay (its left truncation point).

cutoff

The grid cutoff, either the study observation time or max_delay.

growth_rate

The exponential growth rate of primary events.

accrual

1 to apply the accrual weight, 0 otherwise.

n_quad

The number of quadrature intervals, an even number. Rows built by as_epidist_meta_model() carry the number chosen for their study by .estimates_n_quad().

Value

A named numeric vector with elements mean, sd, kurtosis and skewness.


The density of a delay censored by a uniform primary window

Description

Averaging the distribution function over a uniform primary window makes the density of the primary censored delay the difference of the delay distribution function across the window, divided by its width.

Usage

.meta_uniform_pcens_density(y, dist, args, pwindow)

Arguments

y

The delay.

dist

A primarycensored distribution function name.

args

A named list of distribution parameters.

Value

A density on the delay scale.


The censoring window slot of a summary row

Description

A fully adjusted study (cens_adjusted code 1) may leave its windows NA in as_epidist_estimates_data(), because none of its estimands read them. The slot still has to hold a number for Stan, so a missing window is filled with 1, which no code 1 path uses.

Usage

.meta_window_slot(window)

Arguments

window

A censoring window width, possibly NA.

Value

A number.


Evaluate an expression, muffling the brms infinite data warning

Description

Muffles only the warning .infinite_data_warning() matches, through the muffleWarning restart, so every other warning expr raises is left to propagate. The restart is only invoked when it exists, so a condition signalled without one is passed on rather than erroring.

Usage

.muffle_infinite_data_warning(expr, muffle = TRUE)

Arguments

expr

An expression to evaluate.

muffle

A logical. expr is evaluated unguarded when FALSE.

Value

The value of expr.


Resolve an optional column name of a data frame of draws

Description

Resolve an optional column name of a data frame of draws

Usage

.multivariate_column(supplied, draws, default)

Arguments

supplied

The column name the user gave, or NULL.

draws

A data frame of draws.

default

The column name to fall back on where the data frame has one.

Value

A column name, or NULL.


The smallest relative eigenvalue a reported covariance may have

Description

Applied to the correlation matrix, so that it does not depend on the scales of the reported quantities. A covariance over summaries that are functions of fewer parameters is singular up to the curvature of the map and Monte Carlo error, which leaves an eigenvalue around a millionth of the largest rather than zero. A likelihood built on such a matrix charges any error in the implied summaries, of numerical or family origin, against that eigenvalue, so it is refused.

Usage

.multivariate_eigen_floor()

Value

A number.


Build an epidist_multivariate object from a matrix of draws

Description

Build an epidist_multivariate object from a matrix of draws

Usage

.multivariate_from_matrix(wide, params, index)

Arguments

wide

A numeric matrix with one row per draw and one column per element.

params

The parameter names, in order.

index

The trajectory points, in order.

Value

An object of class epidist_multivariate.


The element names of a multivariate representation

Description

The element names of a multivariate representation

Usage

.multivariate_names(params, index)

Arguments

params

The parameter names, in order.

index

The trajectory points, in order.

Value

A character vector of element names, ordered index major and parameter minor.


The parameter columns of a data frame of draws

Description

The parameter columns of a data frame of draws

Usage

.multivariate_params(params, draws, structural)

Arguments

params

The columns the user gave, or NULL.

draws

A data frame of draws.

structural

The index and draw columns.

Value

A character vector of column names.


Widen a data frame of draws into one column per element

Description

Widen a data frame of draws into one column per element

Usage

.multivariate_wide(draws, params, index, draw, index_values)

Arguments

draws

A data frame of draws.

params

The parameter columns.

index

The index column, or NULL.

draw

The draw column, or NULL.

index_values

The trajectory points, in order.

Value

A numeric matrix with one row per draw and one column per element, ordered index major and parameter minor.


Class constructor for epidist_delay_draws objects

Description

Records the delay distribution family, and the variables that define the strata, on a data.frame of draws of the distributional parameters, and adds the epidist_delay_draws class in front of its existing classes. The class gives the draws a plot() method. Most dplyr verbs rebuild their input and so drop the class and what it records.

Usage

.new_delay_draws(data, family, vars = NULL)

Arguments

data

A data.frame of draws of the distributional parameters, as returned by delay_parameter_draws().

family

A list with the delay distribution name and its distributional parameters dpars, as returned by .delay_family().

vars

A character vector of the columns of data that define the strata, or NULL when there are none.

Value

data with the epidist_delay_draws class and the epidist_family and epidist_vars attributes.


Set the class of an epidist data object

Description

Adds class to data along with the shared epidist_data class, which is placed after all of the epidist classes so that dispatch on the specific classes takes precedence. Used by the ⁠new_epidist_*()⁠ constructors.

Usage

.new_epidist_data(data, class)

Arguments

data

A data.frame to set the class of.

class

A character string giving the epidist class to add.

Value

data with class and epidist_data added to its class.


Build an epidist_meta_model object from its individual and summary parts

Description

Build an epidist_meta_model object from its individual and summary parts

Usage

.new_meta_model_from_parts(data, estimates, primary = "uniform")

Arguments

data

Individual level data prepared by .prepare_marginal_data(), or NULL.

estimates

An epidist_estimates_data object, or NULL.

primary

The primary event distribution of the individual level rows, "uniform" or "expgrowth".

Value

An object of class epidist_meta_model.


Columns that epidist may set to an infinite observation time

Description

The relative observation time is infinite when the delay is not right truncated, which is the default of the epidist_newdata() methods. The marginal model also sets it for observation times far beyond the longest delay, keeping the original in orig_relative_obs_time.

Usage

.obs_time_cols()

Value

A character vector of column names.


The primarycensored distribution name for a family

Description

The generalised gamma distribution function lives in flexsurv, so primarycensored records no name for it and the name is given here. Falls back to the lower cased family name if primarycensored does not recognise it, so the caller can still report a name in a message. Uses .delay_family() rather than family$family directly, so this resolves correctly whether family is a plain brms family, a custom family such as gengamma(), or a model family such as meta_lognormal wrapped by brms::custom_family(), which records its own name as "custom".

Usage

.pcd_family_dist_name(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

A primarycensored distribution function name, for example "plnorm".


Choose between the new and the old value of a prior column

Description

Keeps the result a character vector when there are no priors to choose between, so that the result can still be combined with other priors.

Usage

.pick_prior_col(updated, new, old)

Arguments

updated

A logical vector flagging where a new prior was supplied.

new

The values from the new priors.

old

The values from the old priors.

Value

A character vector the same length as updated.


Plot the delay distribution the draws imply

Description

Plot the delay distribution the draws imply

Usage

.plot_delay_draws(
  strata,
  family,
  ndraws = NULL,
  probs = c(0.05, 0.95),
  max_delay = NULL
)

Arguments

strata

A list as returned by .draw_strata().

family

A list with the delay distribution name and its distributional parameters dpars, as returned by .delay_family().

Value

A ggplot object.


Plot the observed delays of one or more datasets

Description

Plot the observed delays of one or more datasets

Usage

.plot_observed_delays(
  datasets,
  by = NULL,
  binwidth = 1,
  delay_min = NULL,
  reference = NULL,
  family = "lognormal"
)

Arguments

datasets

A named list of epidist_linelist_data objects.

by

A string naming a column of x to stratify the delays by.

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

delay_min

The minimum delay to mark with a dashed vertical line, as a number on the scale of the event times. If NULL, the default, the delay_min column of x is used when it has one and no line is drawn otherwise.

reference

A named numeric vector of the distributional parameters of a delay distribution to draw over the columns, as c(mu = 1.8, sigma = 0.5) for a lognormal delay. If NULL, the default, no distribution is drawn.

family

A brms family, or the name of one, giving the delay distribution reference holds the parameters of. Defaults to "lognormal".

Value

A ggplot object.


Plot the posterior density of each parameter

Description

Plot the posterior density of each parameter

Usage

.plot_parameter_draws(strata, family, pars = NULL, true_values = NULL)

Arguments

strata

A list as returned by .draw_strata().

family

A list with the delay distribution name and its distributional parameters dpars, as returned by .delay_family().

pars

A character vector of the columns to plot when type = "parameters". If NULL, the default, the distributional parameters of the family are plotted, along with the mean, sd and quantile columns present.

true_values

A named numeric vector of true parameter values to mark with dashed vertical lines when type = "parameters". The names must be among the parameters plotted.

Value

A ggplot object.


Bin the delays a fitted model predicts for each case

Description

Predicts the delay of every case in the model data from each posterior draw, bins the predictions of each draw as .bin_delays() bins the observed delays, and summarises the proportion in each bin across the draws. Draws with no prediction in a bin count as a proportion of zero.

Usage

.predicted_delays(x, delays, binwidth = 1, ndraws = 100, probs = c(0.05, 0.95))

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

delays

A tibble of the observed delays with their .stratum, as returned by .draw_strata().

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

ndraws

The number of posterior draws to predict from, sampled at random. Defaults to 100, which is enough for the median and the quantiles of a binned distribution and bounds the size of the prediction. Use NULL to predict from every draw.

probs

A numeric vector of two probabilities giving the quantiles the ribbon spans. Defaults to c(0.05, 0.95).

Value

A tibble with one row per stratum and bin, holding the lower edge of the bin as delay, the posterior median density and the lower and upper quantiles of it.


Prepare linelist data for a marginal likelihood

Description

Calculates the delay bounds, censoring windows and relative observation times required by the marginal likelihood, adds weights and the left truncation point, and sets observation times far beyond the maximum delay to Inf. Shared by as_epidist_marginal_model() and as_epidist_meta_model().

Usage

.prepare_marginal_data(
  data,
  obs_time_threshold = 2,
  weight = NULL,
  delay_min = NULL
)

Arguments

data

An epidist_linelist_data object

obs_time_threshold

Ratio used to determine threshold for setting relative observation times to Inf. Observation times greater than obs_time_threshold times the maximum delay will be set to Inf to improve model efficiency by reducing the number of unique observation times. Default is 2.

weight

A column name containing counts of identical linelist items. When specified, the user is declaring that rows with the same values represent the same observation occurring multiple times. This allows for efficient data representation by storing unique patterns with their counts rather than repeating identical rows. The marginal model will further aggregate these counts based on the formula specification. Default is NULL, which assigns a count of 1 to each row. Internally this is used to define the 'n' column of the returned object.

delay_min

Minimum delay (left truncation point). Can be:

  • NULL (default): uses a delay_min column from the data if present, otherwise defaults to 0 (no left truncation).

  • A numeric scalar: applied to all observations.

  • A column name string: looks up the named column in the data. This is passed as the L parameter to primarycensored::dpcens().

Value

The input data with the marginal likelihood columns added.


Primary event arguments for post-processing

Description

The post-processing functions read distributional parameters by name, so without this a fit made with a non-uniform primary event would be post-processed as though it were uniform.

Usage

.primary_args(spec, prep, i, draw = NULL)

Arguments

spec

A registry entry, as returned by .primary_spec().

prep

A brms prep object.

i

The observation index.

draw

The posterior draw index, or NULL for all draws.

Value

A named list of arguments for spec$ddist and spec$rdist.


The name primarycensored gives the primary distribution arguments

Description

primarycensored 1.5.2 renamed dprimary_args to primary_args, because the arguments reach both the primary density and its distribution function, and kept the old name as a soft deprecation. A soft deprecation stays quiet for calls from another package but warns while that package's tests run, so the old name is only passed where the new one does not exist yet.

Usage

.primary_args_name()

Value

A length one character vector naming the argument.


Names of the supported primary event distributions

Description

Names of the supported primary event distributions

Usage

.primary_choices()

Value

A character vector, with the default first.


The primary event distribution of an epidist object

Description

Absent for objects made before this was configurable, which were uniform.

Usage

.primary_dist(data)

Arguments

data

An epidist data object.

Value

The primary event distribution as a string.


Supported primary event distributions

Description

Supported primary event distributions

Usage

.primary_registry()

Value

A named list, one entry per distribution. Each entry gives the primarycensored id used to dispatch in Stan, the dpars it adds to the family, their links and bounds, the R density ddist and sampler rdist used in post-processing, and the args of those two functions that the dpars supply.


Look up a primary event distribution

Description

Look up a primary event distribution

Usage

.primary_spec(primary)

Arguments

primary

The distribution name.

Value

The registry entry for primary.


The primary event distribution of a family

Description

Families built outside epidist_family(), and those made before this was configurable, carry no primary event distribution and were uniform.

Usage

.primary_spec_from_family(family)

Arguments

family

A brms family object.

Value

The registry entry for the family's primary event distribution.


The primary event distribution a fit was made with

Description

The post-processing functions are built from a family, which the caller may supply directly rather than taking it from the fit. The fit itself is authoritative, so prefer what it carries and fall back on the family.

Usage

.primary_spec_from_prep(prep, spec)

Arguments

prep

A brms prep object.

spec

The registry entry of the family the caller supplied.

Value

A registry entry.


The primary event distribution arguments for Stan

Description

The primary event distribution arguments for Stan

Usage

.primary_stancode_args(spec, empty = "primary_params")

Arguments

spec

A registry entry, as returned by .primary_spec().

empty

The Stan expression to pass when the distribution takes no parameters.

Value

The distribution id and its parameters, as Stan code.


The columns used to match brms prior distributions

Description

The columns used to match brms prior distributions

Usage

.prior_match_cols()

Value

A character vector of column names.


Name a quantile column as posterior does

Description

Name a quantile column as posterior does

Usage

.quantile_name(prob)

Arguments

prob

A probability.

Value

A column name.


Refit a model to new data, reusing the compiled model

Description

Refit a model to new data, reusing the compiled model

Usage

.refit(fit, newdata, ...)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

newdata

The data to refit to.

...

Additional arguments passed to brms::update.brmsfit() and so to brms::brm(), such as chains, iter, refresh and silent.

Value

A fit with the classes of fit.


Rename the columns of a data.frame

Description

Rename the columns of a data.frame

Usage

.rename_columns(data, new_names, old_names)

Arguments

data

A data.frame to rename the columns of.

new_names

A character vector of new column names.

old_names

A character vector of old column names.

Value

The data.frame with its columns renamed.


Replace brms prior distributions

Description

This function takes an existing set of prior distributions and updates them with new prior specifications. It matches priors based on their parameter class, coefficient, group, response, distributional parameter, and non-linear parameter.

Usage

.replace_prior(old_prior, prior, enforce_presence = TRUE)

Arguments

old_prior

One or more prior distributions in the class brmsprior to be updated.

prior

One or more prior distributions in the class brmsprior containing the new specifications. Can include manually specified priors using the syntax parameter ~ distribution.

enforce_presence

If TRUE then only keep rows that have both old and new priors. If FALSE then keep all rows but use new priors where available, otherwise keep old priors. Defaults to TRUE.

Details

Prior distributions can be specified in two ways:

  1. Using the standard brms prior specification format. These priors are replaced based on matching parameter metadata (class, coefficient, group, etc.).

  2. Using manually specified priors with the syntax parameter ~ distribution. These replace existing manual priors for the same parameter name and are otherwise left alone. Manual priors are excluded from the metadata based matching.

Value

A brmsprior object containing the updated prior distributions.


Check that flexsurv is installed

Description

Check that flexsurv is installed

Usage

.require_flexsurv()

Value

NULL, invisibly, called for the error it may raise.


Resolve the delay distribution family of a data.frame of draws

Description

Resolve the delay distribution family of a data.frame of draws

Usage

.resolve_delay_family(data, family = NULL)

Arguments

data

A data.frame of draws of the distributional parameters, as returned by delay_parameter_draws().

family

A model fit with epidist(), a brms family, an epidist family such as gengamma(), or the name of one, giving the delay distribution. If NULL, the default, the family is taken from data, which delay_parameter_draws() records on it. Some dplyr verbs drop that record, so pass the fit or the family if data has been through one of them.

Value

A list with the delay distribution name and its distributional parameters dpars.


Restore environment variables captured by .capture_compile_env()

Description

Restore environment variables captured by .capture_compile_env()

Usage

.restore_compile_env(vars)

Arguments

vars

A named character vector as returned by .capture_compile_env(), with NA for variables that were unset.

Value

Nothing, called for side effects only


Put the epidist_delay_draws class of a template back on an object

Description

dplyr builds a new object rather than keeping the class of its input, so the class, and the family and stratum variables it records, are lost whenever the draws are modified. This puts them back, in front of the classes data already has, so that a grouped result carries epidist_delay_draws followed by grouped_df. Used by the methods documented in epidist_delay_draws.

Usage

.restore_delay_draws(data, template)

Arguments

data

A data.frame to put the class back on.

template

The object to take the class and its records from.

Value

data with the epidist_delay_draws class, or data unchanged when it is not a data.frame or template does not have the class.


Put the epidist classes of a template back on an object

Description

dplyr builds a new grouped tibble rather than keeping the class of its input, so the epidist classes are lost whenever a grouped object is modified. This puts them back, in front of the classes data already has, so that a grouped result carries the epidist classes followed by grouped_df. The result still needs checking, which .revalidate_epidist() does after calling this.

Usage

.restore_epidist_class(data, template)

Arguments

data

A data.frame to add the classes to.

template

The object whose epidist classes to add.

Value

data with the epidist classes of template, or data unchanged if it is not a data.frame or template has none.


Re-check a modified epidist object and drop any classes it fails

Description

Puts the epidist classes of original back on data with .restore_epidist_class(), then checks data against each of them using .check_epidist_class() and drops those it no longer meets the requirements of. Modifications that leave the object unchanged are not checked. Used by the methods documented in epidist_data.

Usage

.revalidate_epidist(data, original = NULL)

Arguments

data

A modified epidist object. An object with no columns is never valid, and is unclassed without a warning because it is usually the prototype vctrs takes rather than something the user asked for.

original

The object before it was modified. Checking is skipped when the modification left the object unchanged.

Value

data with any epidist class whose requirements it no longer meets removed.


Add summaries by simulating from the delay distribution

Description

Add summaries by simulating from the delay distribution

Usage

.sample_summaries(data, family, probs = NULL, nsim = 1000)

Arguments

data

A data.frame of draws of the distributional parameters, as returned by delay_parameter_draws().

family

A model fit with epidist(), a brms family, an epidist family such as gengamma(), or the name of one, giving the delay distribution. If NULL, the default, the family is taken from data, which delay_parameter_draws() records on it. Some dplyr verbs drop that record, so pass the fit or the family if data has been through one of them.

probs

A numeric vector of probabilities to add quantiles of the delay distribution for. If NULL, the default, no quantiles are added.

nsim

The number of delays to simulate per row of data. Defaults to 1000. Only used when simulating.

Value

The input with summary columns added.


Simulate delays from each draw of the distributional parameters

Description

Simulation goes through the posterior prediction function .get_brms_fn() gives for the family. Rows are simulated in chunks to bound the memory used.

Usage

.simulate_delays(family, dpars, nsim = 1000)

Arguments

family

A delay distribution family as returned by .resolve_delay_family(), a list with the family name and its distributional parameters dpars.

dpars

A named list of distributional parameter vectors.

nsim

The number of delays to simulate per row of data. Defaults to 1000. Only used when simulating.

Value

A matrix with one row per element of the vectors in dpars and nsim columns.


Read in an epidist Stan code chunk

Description

This function is used to obtain Stan code chunks from the ⁠stan/⁠ folder of the epidist package. It is used within the epidist_stancode() function.

Usage

.stan_chunk(path)

Arguments

path

The path within the ⁠stan/⁠ folder of the installed epidist package to the Stan code chunk of interest.

Value

A character string containing the Stan code chunk of interest.


Name the rows of newdata by the columns that differ between them

Description

Name the rows of newdata by the columns that differ between them

Usage

.stratum_names(newdata)

Arguments

newdata

A data.frame of data to predict for, with one row per delay distribution wanted. If NULL, the default, epidist_newdata() builds one row per unique combination of the predictors, with no censoring and no truncation. See the details.

Value

A character vector with one element per row of newdata.


The bootstrap covariance of a study's mean and standard deviation

Description

The bootstrap covariance of a study's mean and standard deviation

Usage

.study_bootstrap(delays, reps = 1000L)

Arguments

delays

The measured delays the study summarised.

reps

The number of bootstrap replicates.

Value

An epidist_multivariate object holding the mean and standard deviation of delays, their bootstrap covariance and the replicates.


The cases of a simulated line list with their exact event times

Description

The cases of a simulated line list with their exact event times

Usage

.study_cases(data)

Arguments

data

An epidist_linelist_data object built from simulated event times, with the exact ptime and stime columns kept by simulate_dates() when keep_times = TRUE. Every case must use the same primary window and the same secondary window.

Value

A tibble with the exact times checked against their windows.


The delay a study measured from each case

Description

The delay a study measured from each case

Usage

.study_measured_delay(cases, cens_adjusted, pwindow, swindow)

Arguments

cases

The tibble of .study_cases().

cens_adjusted

The censoring adjustment code.

pwindow, swindow

The primary and secondary window widths.

Value

A numeric vector of measured delays.


Whether a study that did not adjust for right truncation saw each case

Description

A cohort study bounds the underlying delay by its observation time, so a study on the discrete grid keeps a case only if the whole window its delay fell in is below the cutoff, and a midpoint primary study keeps a case if its uniform single interval delay is. An accrual study keeps the cases whose secondary event fell before its calendar stop.

Usage

.study_observed(
  cases,
  measured,
  cens_adjusted,
  trunc_design,
  relative_obs_time,
  swindow
)

Arguments

cases

The tibble of .study_cases().

measured

The measured delays of .study_measured_delay().

cens_adjusted

The censoring adjustment code.

trunc_design

The truncation design.

relative_obs_time

The study observation time.

Value

A logical vector.


The summary rows a study reports

Description

The summary rows a study reports

Usage

.study_rows(delays, report, probs)

Arguments

delays

The measured delays the study summarised.

report

What the study published. "moments" gives a mean and a standard deviation with the sample size, "quantiles" the quantiles at probs with the sample size, "multivariate" the mean and standard deviation with their bootstrap covariance, through new_epidist_multivariate(), and "mean_se" a mean with its standard error and no sample size.

probs

The probabilities of the quantiles a "quantiles" study reports.

Value

A tibble with type, value, p, n and se columns.


The single censoring window of a simulated study

Description

The single censoring window of a simulated study

Usage

.study_window(width, event)

Arguments

width

The window widths of every case.

event

Which event the window belongs to, used in the error.

Value

The window width.


Summarise data by grouping variables and count occurrences

Description

Summarise data by grouping variables and count occurrences

Usage

.summarise_n_by_formula(data, by = character(), formula = NULL)

Arguments

data

A data.frame to summarise which must contain a n column which is a count of occurrences.

by

Character vector of column names to group by.

formula

Optional brms formula object to extract additional grouping terms from.

Value

A data.frame summarised by the grouping variables with counts.


Response families that epidist does not support

Description

Ordinal, categorical, mixture and Cox families need extra handling in brms that the helpers in this file deliberately do not reproduce. Mixture families are tracked in epidist issue 617.

Usage

.unsupported_families()

Value

A character vector of family names.


Validate model data

Description

Replaces the checks that epidist relies on from brms:::validate_data(). epidist calls the brms internal only for its errors and discards the returned model frame, so this helper checks the same conditions and returns data invisibly. It errors when data cannot be coerced to a data.frame, when it has no rows, when a variable used in the formula is absent, when a column name contains a double underscore or ends in an underscore, or when no complete case remains. It warns when a used column contains infinite values.

Usage

.validate_data(data, bterms)

Arguments

data

A data.frame containing the model data.

bterms

An object returned by brms::brmsterms().

Value

data, invisibly.


Validate a response family

Description

Replaces brms:::validate_family(). Guarantees that a family given as a family function, a brms family object, a stats family object or a character string is returned as a brmsfamily object. Unlike the brms internal it does not handle the threshold argument of ordinal families, which epidist never sets, and it also accepts the name of a family epidist defines itself, such as "gengamma".

Usage

.validate_family(family, link = NULL)

Arguments

family

A family function, a brmsfamily object, a stats family object, or a character string naming a brms or epidist family.

link

Optional character string giving the link function. Only used when family is a character string without a second element.

Value

A brmsfamily object.


Validate a model formula

Description

Replaces brms:::validate_formula() for the families epidist supports. Guarantees that the result is a brmsformula object carrying the validated family, with any . on the right hand side expanded against data and with mecor set to its default of TRUE. The brms internal additionally handles ordinal, categorical, mixture and Cox families, and the deprecated autocor, sparse and cov_ranef arguments. None of those are supported here.

Usage

.validate_formula(formula, family = NULL, data = NULL)

Arguments

formula

A formula or brmsformula object.

family

A description of the response distribution and link function.

data

A data.frame used to expand . in the formula.

Value

A brmsformula object.


Label a epidist Stan model with a version indicator

Description

This function is used within epidist_stancode() to label the generated Stan code with the version of epidist used. To view the full Stan code for any particular epidist model, we recommend use of brms::make_stancode().

Usage

.version_stanvar()

Value

A brms Stan chunk containing the epidist package version used to build the Stan code.


Warn about user priors which are not parameters of the model

Description

Manually specified priors are passed to Stan unchanged and so are not checked here.

Usage

.warn_unmatched_prior(prior, known)

Arguments

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

known

One or more prior distributions in the class brmsprior covering the parameters of the model.

Value

NULL, invisibly, called for the warning it may raise.


Take a quantile of the proportions of every draw

Description

A draw with no prediction in a bin has no row for it, and so a proportion of zero. Pads the proportions back up to one per draw before taking the quantile.

Usage

.zero_padded_quantile(p, n_draws, prob)

Arguments

p

The proportions of the draws that predicted into the bin.

n_draws

The number of draws.

prob

The probability of the quantile to take.

Value

A number.


Add natural scale summaries of the delay distribution

Description

Adds the mean and standard deviation of the delay distribution implied by each draw of the distributional parameters, and quantiles of that distribution if probs is given. Analytic solutions are used for the families that have one. The exponential family is summarised by simulating delays from it.

Usage

add_summaries(
  data,
  family = NULL,
  probs = NULL,
  method = c("auto", "analytic", "sample"),
  nsim = 1000
)

Arguments

data

A data.frame of draws of the distributional parameters, as returned by delay_parameter_draws().

family

A model fit with epidist(), a brms family, an epidist family such as gengamma(), or the name of one, giving the delay distribution. If NULL, the default, the family is taken from data, which delay_parameter_draws() records on it. Some dplyr verbs drop that record, so pass the fit or the family if data has been through one of them.

probs

A numeric vector of probabilities to add quantiles of the delay distribution for. If NULL, the default, no quantiles are added.

method

Either "auto", the default, which uses the analytic solution when there is one and simulates otherwise, "analytic", which errors when there is no analytic solution, or "sample", which always simulates.

nsim

The number of delays to simulate per row of data. Defaults to 1000. Only used when simulating.

Details

The summaries describe the delay distribution, not the posterior. A row of data holds one draw of the distributional parameters, and the columns added are the mean, standard deviation and quantiles of the delay distribution those parameters define. Summarise the resulting columns across draws to get posterior summaries of them.

Quantile columns are named as in posterior::quantile2(), so probs = 0.05 gives a q5 column.

Simulation adds Monte Carlo error to the summaries. The standard error of the mean is the delay standard deviation divided by the square root of nsim. Simulation is also memory hungry, because it draws nsim delays for every row of data. Reduce the number of rows with epidist_strata(), or the number of draws with the ndraws argument of delay_parameter_draws(), if it is slow.

Value

The input with mean and sd columns added, and one column per element of probs. It has the epidist_delay_draws class, which records the family used and gives it a plot() method.

See Also

Other postprocess: as_dist_spec.epidist_fit(), delay_parameter_draws(), delay_summary_draws(), epidist_delay_draws, epidist_strata()

Examples

draws <- data.frame(mu = c(1.8, 2.0), sigma = c(0.5, 0.4))
add_summaries(draws, family = "lognormal", probs = c(0.05, 0.95))

Export a fitted delay distribution as a distspec distribution

Description

Summarises the posterior of a fitted delay distribution into an uncertain ⁠<dist_spec>⁠ from the distspec package, for use in packages that take their delay distributions in that form. The natural parameters of the delay distribution are computed for each posterior draw and summarised into a prior on each of them.

Usage

## S3 method for class 'epidist_fit'
as_dist_spec(x, newdata = NULL, max = Inf, cdf_max = 1, ...)

Arguments

x

A model fit with epidist().

newdata

A data.frame of data to predict for, with one row per delay distribution wanted. If NULL, the default, epidist_newdata() builds one row per unique combination of the predictors, with no censoring and no truncation. See the details.

max

The maximum of the delay distribution, passed to distspec::bound_dist(). Defaults to Inf, which is no maximum.

cdf_max

The cumulative probability to keep the delay distribution up to, passed to distspec::bound_dist(). Defaults to 1, which keeps the whole distribution.

...

Additional arguments passed to brms::prepare_predictions(), such as ndraws or re_formula.

Details

The lognormal, gamma and Weibull families are supported, as those are the delay distributions distspec has. Their brms parameters are mapped to the natural parameters of the matching distspec constructor for every draw before summarising:

Open an issue at https://github.com/epiforecasts/distspec/issues to ask distspec for another distribution.

Each natural parameter gets a distspec::Normal() prior with the mean and standard deviation of its marginal posterior. The posterior correlation between the parameters is not represented, so sampling from the result gives a wider range of delay distributions than the posterior does.

The default newdata is built with epidist_newdata() by expanding the variables in the model formula into a grid, so it has one row per unique combination of the predictors, and gives the delay distribution with no censoring and no truncation. A model with only an intercept gets a single row. A continuous predictor gets a row per distinct value, so pass newdata for such a model.

Value

A ⁠<dist_spec>⁠ when newdata has one row. A named list of them, one per row of newdata, when it has several. The names give the values of the columns of newdata that differ between rows, such as "sex=0", and are the row numbers when no column differs.

See Also

delay_parameter_draws() for the draws this summarises and epidist_newdata() to build newdata.

Other postprocess: add_summaries(), delay_parameter_draws(), delay_summary_draws(), epidist_delay_draws, epidist_strata()

Examples


if (requireNamespace("distspec", quietly = TRUE)) {
  fit <- sierra_leone_ebola_data |>
    as_epidist_linelist_data(
      pdate_lwr = "date_of_symptom_onset",
      sdate_lwr = "date_of_sample_tested"
    ) |>
    as_epidist_aggregate_data() |>
    as_epidist_marginal_model() |>
    epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))

  dist <- distspec::as_dist_spec(fit)
  dist

  # The delay distribution at the posterior mean of its parameters
  distspec::fix_parameters(dist, strategy = "mean")

  # Bound the delay distribution at 60 days for a package that takes bounds
  distspec::as_dist_spec(fit, max = 60)
}


Create an epidist_aggregate_data object

Description

Creates an epidist_aggregate_data object from various input formats. This is useful when working with pre-aggregated data where each row represents multiple identical observations. See the specific methods for details on supported input formats and usage examples.

Usage

as_epidist_aggregate_data(data, ...)

Arguments

data

The data to convert

...

Additional arguments passed to methods

Value

An object of class epidist_aggregate_data.

See Also

Other aggregate_data: as_epidist_aggregate_data.data.frame(), as_epidist_aggregate_data.default(), as_epidist_aggregate_data.epidist_linelist_data(), assert_epidist.epidist_aggregate_data(), is_epidist_aggregate_data(), new_epidist_aggregate_data()


Create an epidist_aggregate_data object from a data.frame

Description

This method takes a data.frame containing event dates (primary/secondary event dates and observation date) along with counts and creates an epidist_aggregate_data object. This format is useful when working with pre-aggregated data where each row represents multiple identical observations with the count stored in a specified column. Internally it makes use of as_epidist_linelist_data.data.frame() to convert the data to a linelist format before adding the count column. See the other methods for other data input options.

Usage

## S3 method for class 'data.frame'
as_epidist_aggregate_data(
  data,
  n = NULL,
  pdate_lwr = NULL,
  sdate_lwr = NULL,
  pdate_upr = NULL,
  sdate_upr = NULL,
  obs_date = NULL,
  ...
)

Arguments

data

A data.frame containing line list data

n

A character string giving the name of the column containing the counts for each row. If NULL then the column n must be present in the data.

pdate_lwr

A string giving the column of data containing the primary event lower bound as a datetime. Defaults to NULL which assumes that the variable pdate_lwr is present.

sdate_lwr

A string giving the column of data containing the secondary event lower bound as a datetime. Defaults to NULL which assumes that the variable sdate_lwr is present.

pdate_upr

A string giving the column of data containing the primary event upper bound as a datetime. If this column exists in the data it will be used, otherwise if not supplied then the value of pdate_lwr + 1 day is used.

sdate_upr

A string giving the column of data containing the secondary event upper bound as a datetime. If this column exists in the data it will be used, otherwise if not supplied then the value of sdate_lwr + 1 day is used.

obs_date

A string giving the column of data containing the observation time as a datetime. Optional, if not supplied then the maximum of sdate_upr is used.

...

Additional arguments passed to methods

Value

An object of class epidist_aggregate_data.

See Also

Other aggregate_data: as_epidist_aggregate_data(), as_epidist_aggregate_data.default(), as_epidist_aggregate_data.epidist_linelist_data(), assert_epidist.epidist_aggregate_data(), is_epidist_aggregate_data(), new_epidist_aggregate_data()

Examples

sierra_leone_ebola_data |>
  dplyr::count(date_of_symptom_onset, date_of_sample_tested) |>
  as_epidist_aggregate_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested",
    n = "n"
  )

Create an epidist_aggregate_data object from vectors of event times

Description

This method takes vectors of event times (primary/secondary event times and observation time) along with counts and creates an epidist_aggregate_data object. This format is useful when working with pre-aggregated data where each row represents multiple identical observations with the count stored in the n column. Internally it makes use of as_epidist_linelist_data.default() to convert the data to a linelist format before adding the count column. See the other methods for other data input options.

Usage

## Default S3 method:
as_epidist_aggregate_data(
  data,
  n = NULL,
  ptime_upr = NULL,
  stime_lwr = NULL,
  stime_upr = NULL,
  obs_time = NULL,
  ...
)

Arguments

data

Numeric vector giving lower bounds for primary times.

n

An integerish vector containing the counts for each row. Must be the same length as the input data vector.

ptime_upr

Numeric vector giving upper bounds for primary times.

stime_lwr, stime_upr

Numeric vectors giving lower and upper bounds for secondary times.

obs_time

Numeric vector giving observation times.

...

Additional columns to add to the epidist_linelist_data object.

Value

An object of class epidist_aggregate_data.

See Also

Other aggregate_data: as_epidist_aggregate_data(), as_epidist_aggregate_data.data.frame(), as_epidist_aggregate_data.epidist_linelist_data(), assert_epidist.epidist_aggregate_data(), is_epidist_aggregate_data(), new_epidist_aggregate_data()

Examples

as_epidist_aggregate_data(
  data = c(1, 2, 3),
  ptime_upr = c(2, 3, 4),
  stime_lwr = c(3, 4, 5),
  stime_upr = c(4, 5, 6),
  obs_time = c(5, 6, 7),
  n = c(1, 2, 3)
)

Convert linelist data to aggregate format

Description

This method takes an epidist_linelist_data object (see as_epidist_linelist_data()) and aggregates it by counting unique combinations of the required time variables (primary/secondary event times and observation time) and any additional variables specified in by. The result is a more compact representation of the same data where each row represents multiple identical observations with the count stored in the n column.

Usage

## S3 method for class 'epidist_linelist_data'
as_epidist_aggregate_data(data, by = NULL, ...)

Arguments

data

The data to convert

by

Character vector of additional variables to stratify by, beyond the required time variables.

...

Additional arguments passed to methods

Value

An object of class epidist_aggregate_data.

See Also

Other aggregate_data: as_epidist_aggregate_data(), as_epidist_aggregate_data.data.frame(), as_epidist_aggregate_data.default(), assert_epidist.epidist_aggregate_data(), is_epidist_aggregate_data(), new_epidist_aggregate_data()

Examples

# Default stratification by required time variables only
sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data()

# Additional stratification by other variables
sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data(by = "age")

Create an epidist_estimates_data object

Description

Creates an epidist_estimates_data object from published summary estimates of a delay distribution. Each row is a single reported summary component (a mean, a standard deviation, or a quantile) together with the metadata needed to work out what the study that reported it was actually estimating. These objects are the summary data input to as_epidist_meta_model(). See the specific methods for details on supported input formats and usage examples.

Usage

as_epidist_estimates_data(data, ...)

Arguments

data

The data to convert

...

Additional arguments passed to methods

Details

The meta model these objects feed is experimental. Its interface may still change in future releases.

Value

An object of class epidist_estimates_data.

See Also

Other estimates_data: as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()


Create an epidist_estimates_data object from a data frame

Description

This method takes a data.frame of published summary estimates and creates an epidist_estimates_data object. Column names may either match the names used below or be supplied via the corresponding argument.

Usage

## S3 method for class 'data.frame'
as_epidist_estimates_data(
  data,
  study = NULL,
  type = NULL,
  value = NULL,
  se = NULL,
  n = NULL,
  p = NULL,
  pwindow = NULL,
  swindow = NULL,
  relative_obs_time = NULL,
  trunc_adjusted = NULL,
  trunc_design = NULL,
  cens_adjusted = NULL,
  delay_min = NULL,
  growth_rate = NULL,
  growth_rate_sd = NULL,
  max_delay = NULL,
  advise = TRUE,
  ...
)

Arguments

data

A data.frame of published summary estimates.

study

A string giving the column of data containing the study identifier. Defaults to NULL which assumes the variable study is present.

type

A string giving the column of data containing the summary type. Each entry must be one of "mean", "sd", or "quantile". Defaults to NULL which assumes the variable type is present.

value

A string giving the column of data containing the reported value of the summary. Defaults to NULL which assumes the variable value is present.

se

A string giving the column of data containing the reported standard error of the summary. Optional. When supplied it overrides the standard error implied by the sample size, and takes the row out of the joint likelihood as_epidist_meta_model() otherwise uses for summaries a study computed from the same delays. It is always on the scale of the reported value, so for a "quantile" row it is a standard error for the reported delay.

n

A string giving the column of data containing the number of delays the summary was computed from. Required unless se is supplied.

p

A string giving the column of data containing the probability of a reported quantile. Required for rows with type of "quantile" and ignored otherwise.

pwindow, swindow

Strings giving the columns of data containing the primary and secondary event censoring window widths. Default to 1 (daily reporting) when not supplied. A fully adjusted study (cens_adjusted code 1) does not use them, because its estimand is the continuous delay distribution itself, so its rows may leave them NA. Every other code needs them.

relative_obs_time

A string giving the column of data containing the observation time relative to the primary event, that is the right truncation point on the delay scale for a cohort design, or the length of the collection window for an accrual design. Defaults to Inf, meaning no truncation.

trunc_adjusted

A string giving the column of data containing a logical flag for whether the study corrected for right truncation. Defaults to TRUE for a study with no finite relative_obs_time, which includes every study where no relative_obs_time column is supplied, and FALSE otherwise. A study assumed to have adjusted is warned about, because real time estimates are right truncated unless the study corrected for it and reviews rarely record which studies did. Supply the column to say so yourself.

trunc_design

A string giving the column of data containing how the study stopped collecting data, either "cohort" (it followed every primary event for the same relative_obs_time) or "accrual" (it collected over a window of that length and stopped at its calendar end). Defaults to "cohort", and is only used for studies that did not adjust for right truncation. The accrual weight on the grid of a study that did not adjust for censoring is exact for any relative_obs_time, pwindow and swindow. The weight used for the uniform single interval approximation is exact only for a narrow pwindow, and puts the implied mean about 3% high with a weekly primary window, a collection window of 28 days, a delay of mean 4.6 days and a growth rate of 0.2. See vignette("model").

cens_adjusted

A string giving the column of data containing the censoring adjustment code (0, 1, 2, 3, or 4, as described above). Defaults to 0.

delay_min

A string giving the column of data containing the smallest delay the study counted, its left truncation point, on the scale the study reported. Defaults to 0, meaning the study counted every delay, which for cens_adjusted code 4 includes any delay reported below zero. Must be below the grid cutoff, and no reported mean or quantile may fall below it.

growth_rate

A string giving the column of data containing the exponential growth rate of primary events during the study period. Defaults to 0. It plays two roles. Within each primary window it tilts the primary event towards the end of the window, which for a daily window is negligible. Under trunc_design = "accrual" it also weights the follow up available to each delay, which is the dynamical bias of a growing epidemic and can move the implied mean by a day or more. A non-zero rate is expensive, because the primary censored delay distribution then has no analytical solution and every evaluation becomes a numerical integration. Leave it at 0 unless the study accrued cases over a period of growth. A number is taken as known. NA means the rate is unknown, and the study then uses the pgrowth distributional parameter of the meta model, the same parameter that primary = "expgrowth" estimates from individual level data in as_epidist_marginal_model(). Give growth_rate_sd as well to treat a reported rate as an informative prior on that parameter rather than as a fixed number. See as_epidist_meta_model() and vignette("primary-events").

growth_rate_sd

A string giving the column of data containing the standard deviation of growth_rate, where the study reported the rate with uncertainty. Defaults to NA, meaning the rate is known exactly. A positive value makes the study estimate its rate as the pgrowth distributional parameter, with a normal prior centred on growth_rate with this standard deviation. That prior is set up by as_epidist_meta_model(), see there for the formula it uses. A value of 0 is the same as NA, and a value with an NA growth_rate is an error, because the prior has no centre.

max_delay

A string giving the column of data containing the delay beyond which the implied summaries are truncated when building the discrete grid. Only used when the study adjusted for right truncation. Defaults to the delay beyond which one percent of the second moment of a lognormal matched to the study's summaries lies, through its mean and standard deviation, or its median and largest quantile above the median where it reported only quantiles. The lognormal is used whatever family is fitted later, because the family is not known when the data are built and, for the same mean and standard deviation, its tail is heavier than the gamma's or the Weibull's, so the cutoff is far enough for those families and only longer than they need. That is the yardstick of the short cutoff check in the Checks section, so the default never trips it where it binds. It is rounded up to a whole number of secondary windows, with a minimum of ten and a maximum of twenty times the largest reported value, because for a heavy tail one percent of the second moment lies thousands of delays out, and is five times the largest reported value where nothing can be matched. Raise it for a delay with a longer tail than a lognormal, whose implied standard deviation is biased downwards if the distribution has not decayed by the cutoff, and lower it to fit faster. A message names the studies whose cutoff is too short, see the Checks section.

advise

Whether to run the advisory checks of the Checks section and message about the studies they flag. Defaults to TRUE. The list method sets it to FALSE for each element and runs the checks once on the combined object.

...

Not used in this method.

Value

An object of class epidist_estimates_data.

What we need from each study

Published delay estimates are almost never estimates of the true continuous delay distribution. To use them we forward model what the study's estimation procedure would converge to, which means we need to know how the study handled the biases we support, along with the data process it saw. vignette("model") derives each estimand, and vignette("meta") works through assembling this metadata for simulated and real studies. For each study we need:

Systematic reviews rarely record this metadata, so you must supply your own assumption and say so alongside any results. Where it is missing entirely, a covariate for the phase of the outbreak each estimate was made in is another option, since the brms formula makes it a meta-regression that estimates the residual bias rather than correcting it mechanically.

What shape a study reported its estimate in

This method takes a long table with one row per reported summary. Two other shapes are common enough to have their own entry points, each returning an object this one would.

A study that published draws of its parameters, rather than point summaries of them, can report the correlation between the quantities it reports. Pass the draws to as_epidist_multivariate() and the result to as_epidist_estimates_data(), which is the only route by which a covariance reaches as_epidist_meta_model(). Such rows need no n and no se.

Contributions from several studies combine by passing them in a list, which as_epidist_estimates_data() binds into one object.

Checks

Beyond validating its input, this method runs advisory checks on the summaries and messages about the studies they flag. They run once, when the object is built, and not again when it is passed to as_epidist_meta_model(). Each message names the studies concerned, and the row of the input where a single summary is meant, and a pointer here follows the messages of a call. Studies combined in a list are checked once, together, and simulate_study() leaves the checks to that combined object. Set advise = FALSE to skip them.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

as_epidist_estimates_data(
  data.frame(
    study = c("A", "A", "B"),
    type = c("mean", "sd", "quantile"),
    value = c(7.5, 3.6, 11.2),
    p = c(NA, NA, 0.9),
    n = c(120, 120, 80),
    relative_obs_time = c(20, 20, Inf),
    trunc_adjusted = c(FALSE, FALSE, TRUE),
    cens_adjusted = c(0, 0, 1)
  )
)

Return an epidist_estimates_data object unchanged

Description

An object carrying the class has already been checked, and the epidist_data methods re-check it whenever it is modified, so nothing is done here.

Usage

## S3 method for class 'epidist_estimates_data'
as_epidist_estimates_data(data, ...)

Arguments

data

The data to convert

...

Not used in this method.

Value

The input, unchanged.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

estimates <- epidist_estimates_summaries(
  "A",
  mean = 7.5, n = 120, trunc_adjusted = TRUE
)
identical(as_epidist_estimates_data(estimates), estimates)

Create an epidist_estimates_data object from a multivariate representation

Description

This is the only route by which a covariance between a study's reported summaries reaches as_epidist_meta_model(). The covariance comes from draws of the study's parameters, so it is one the study could have computed, and the summaries it covers are fitted with a multivariate normal likelihood rather than as independent observations.

Usage

## S3 method for class 'epidist_multivariate'
as_epidist_estimates_data(
  data,
  study,
  family = NULL,
  moments = c("mean", "sd"),
  probs = numeric(0),
  mvn_id = NULL,
  advise = TRUE,
  ...
)

Arguments

data

The data to convert

study

A string naming the study the draws come from.

family

The distribution the study fitted, one of "lognormal", "gamma" or "weibull", where the draws hold its natural parameters. Defaults to NULL, meaning the draws already hold reported summaries.

moments

Which moments to report, any of "mean" and "sd". Only used where family is given.

probs

A numeric vector of probabilities to report quantiles at. Only used where family is given.

mvn_id

A string identifying the covariance matrix. Defaults to study, and only needs setting where one study contributes more than one multivariate object.

advise

Whether to run the advisory checks of the Checks section and message about the studies they flag. Defaults to TRUE. The list method sets it to FALSE for each element and runs the checks once on the combined object.

...

Study metadata, as documented in as_epidist_estimates_data.data.frame().

Details

Where family is given, the draws hold the natural parameters of a distribution the study fitted. Each draw is pushed through to the summaries the fitted distribution implies, over the range of delays the study could have seen, and the covariance is taken over those. This is the exact version of the delta method epidist_estimates_parameters() applies, and it needs no linearisation.

Where family is NULL, the parameters must already be quantities a study reports. Name them mean, sd, or q followed by a probability, such as q0.25.

Draws over more than one index point are not yet supported for fitting, because the linear predictor would have to vary within one likelihood observation.

Value

An object of class epidist_estimates_data with one row per reported summary and the covariance matrix attached.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

set.seed(1)
draws <- cbind(mean = rnorm(500, 7.5, 0.3), sd = rnorm(500, 3.6, 0.2))
as_epidist_estimates_data(
  as_epidist_multivariate(draws),
  study = "site A",
  trunc_adjusted = TRUE,
  cens_adjusted = 1
)

Combine epidist_estimates_data objects from several studies

Description

Each element is coerced on its own and the results are bound into one object. Combining is associative, so contributions can be assembled in any order and in any grouping. The advisory checks of the Checks section of as_epidist_estimates_data.data.frame() run once, on the combined object, so each message names every study it applies to.

Usage

## S3 method for class 'list'
as_epidist_estimates_data(data, advise = TRUE, ...)

Arguments

data

The data to convert

advise

Whether to run the advisory checks of the Checks section and message about the studies they flag. Defaults to TRUE. The list method sets it to FALSE for each element and runs the checks once on the combined object.

...

Passed to the method used for each element.

Value

An object of class epidist_estimates_data holding the rows of every element.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

as_epidist_estimates_data(list(
  epidist_estimates_summaries(
    "A",
    mean = 7.5, sd = 3.6, n = 120, trunc_adjusted = TRUE
  ),
  epidist_estimates_summaries(
    "B",
    mean = 6.9, n = 80, relative_obs_time = 20, trunc_adjusted = FALSE
  )
))

Convert an object to an epidist_latent_model object

Description

Creates an epidist_latent_model object from various input formats. This enables fitting latent variable models for epidemiological delays using epidist(), as described in Park et al. (2024) and Charniga et al. (2024) The latent model approach accounts for double interval censoring and right truncation in delay data.

Usage

as_epidist_latent_model(data, ...)

Arguments

data

An object to be converted to the class epidist_latent_model

...

Additional arguments passed to methods.

Value

An object of class epidist_latent_model.

References

See Also

Other latent_model: as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()


The latent model method for epidist_aggregate_data objects

Description

This method converts aggregate data to a latent model format by first converting it to linelist format using as_epidist_linelist_data.epidist_aggregate_data() and then passing it to as_epidist_latent_model.epidist_linelist_data(). This ensures that the counts in the aggregate data are properly expanded into individual observations before fitting the latent model.

Usage

## S3 method for class 'epidist_aggregate_data'
as_epidist_latent_model(data, primary = .primary_choices(), ...)

Arguments

data

An epidist_aggregate_data object

primary

The distribution of the primary event within its censoring window. "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter.

...

Not used in this method.

Value

An object of class epidist_latent_model.

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()

Examples

sierra_leone_ebola_data |>
  dplyr::count(date_of_symptom_onset, date_of_sample_tested) |>
  as_epidist_aggregate_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested",
    n = "n"
  ) |>
  as_epidist_latent_model()

The latent model method for epidist_linelist_data objects

Description

This method takes an epidist_linelist_data object and converts it to a format suitable for fitting latent variable models. It calculates key variables needed for the latent variable method described in Park et al. (2024) and Charniga et al. (2024). This approach adjusts for double interval censoring and right truncation in the data.

Usage

## S3 method for class 'epidist_linelist_data'
as_epidist_latent_model(data, primary = .primary_choices(), ...)

Arguments

data

An epidist_linelist_data object containing individual-level observations with primary and secondary event times. See as_epidist_linelist_data() for details on creating this object.

primary

The distribution of the primary event within its censoring window. "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter.

...

Not used in this method.

Value

An object of class epidist_latent_model.

References

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_latent_model()

Create an epidist_linelist_data object

Description

Creates an epidist_linelist_data object from various input formats. This is useful when working with individual-level data where each row represents a single observation with primary and secondary event times. See the specific methods for details on supported input formats and usage examples.

Usage

as_epidist_linelist_data(data, ...)

Arguments

data

The data to convert

...

Additional arguments passed to methods

Value

An object of class epidist_linelist_data.

See Also

Other linelist_data: as_epidist_linelist_data.data.frame(), as_epidist_linelist_data.default(), as_epidist_linelist_data.epidist_aggregate_data(), assert_epidist.epidist_linelist_data(), is_epidist_linelist_data(), new_epidist_linelist_data()


Create an epidist_linelist_data object from a data frame with event dates

Description

This method takes a data.frame containing event dates (primary/secondary event dates and observation date) and creates an epidist_linelist_data object. This format is useful when working with individual-level data where each row represents a single observation. Internally it converts dates to numeric times relative to the earliest primary event date and uses as_epidist_linelist_data.default() to create the final object. See the other methods for other data input options.

Usage

## S3 method for class 'data.frame'
as_epidist_linelist_data(
  data,
  pdate_lwr = NULL,
  sdate_lwr = NULL,
  pdate_upr = NULL,
  sdate_upr = NULL,
  obs_date = NULL,
  ...
)

Arguments

data

A data.frame containing line list data

pdate_lwr

A string giving the column of data containing the primary event lower bound as a datetime. Defaults to NULL which assumes that the variable pdate_lwr is present.

sdate_lwr

A string giving the column of data containing the secondary event lower bound as a datetime. Defaults to NULL which assumes that the variable sdate_lwr is present.

pdate_upr

A string giving the column of data containing the primary event upper bound as a datetime. If this column exists in the data it will be used, otherwise if not supplied then the value of pdate_lwr + 1 day is used.

sdate_upr

A string giving the column of data containing the secondary event upper bound as a datetime. If this column exists in the data it will be used, otherwise if not supplied then the value of sdate_lwr + 1 day is used.

obs_date

A string giving the column of data containing the observation time as a datetime. Optional, if not supplied then the maximum of sdate_upr is used.

...

Additional arguments passed to methods

Value

An object of class epidist_linelist_data.

See Also

Other linelist_data: as_epidist_linelist_data(), as_epidist_linelist_data.default(), as_epidist_linelist_data.epidist_aggregate_data(), assert_epidist.epidist_linelist_data(), is_epidist_linelist_data(), new_epidist_linelist_data()

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  )

Create an epidist_linelist_data object from vectors of event times

Description

This method takes vectors of event times (primary/secondary event times and observation time) and creates an epidist_linelist_data object. This format is useful when working with individual-level data where each row represents a single observation. See the other methods for other data input options.

Usage

## Default S3 method:
as_epidist_linelist_data(
  data,
  ptime_upr = NULL,
  stime_lwr = NULL,
  stime_upr = NULL,
  obs_time = NULL,
  ...
)

Arguments

data

Numeric vector giving lower bounds for primary times.

ptime_upr

Numeric vector giving upper bounds for primary times.

stime_lwr, stime_upr

Numeric vectors giving lower and upper bounds for secondary times.

obs_time

Numeric vector giving observation times.

...

Additional columns to add to the epidist_linelist_data object.

Value

An object of class epidist_linelist_data.

See Also

Other linelist_data: as_epidist_linelist_data(), as_epidist_linelist_data.data.frame(), as_epidist_linelist_data.epidist_aggregate_data(), assert_epidist.epidist_linelist_data(), is_epidist_linelist_data(), new_epidist_linelist_data()

Examples

as_epidist_linelist_data(
  data = c(1, 2, 3),
  ptime_upr = c(2, 3, 4),
  stime_lwr = c(3, 4, 5),
  stime_upr = c(4, 5, 6),
  obs_time = c(5, 6, 7)
)

Convert aggregate data to linelist format

Description

This method expands an epidist_aggregate_data object into individual observations by uncounting the n column, then converts it to linelist format using as_epidist_linelist_data.data.frame().

Usage

## S3 method for class 'epidist_aggregate_data'
as_epidist_linelist_data(data, ...)

Arguments

data

The data to convert

...

Additional arguments passed to methods

Value

An object of class epidist_linelist_data.

See Also

Other linelist_data: as_epidist_linelist_data(), as_epidist_linelist_data.data.frame(), as_epidist_linelist_data.default(), assert_epidist.epidist_linelist_data(), is_epidist_linelist_data(), new_epidist_linelist_data()

Examples

sierra_leone_ebola_data |>
  dplyr::count(date_of_symptom_onset, date_of_sample_tested) |>
  as_epidist_aggregate_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested",
    n = "n"
  ) |>
  as_epidist_linelist_data()

Convert an object to an epidist_marginal_model object

Description

Creates an epidist_marginal_model object from various input formats. This enables fitting marginal models for epidemiological delays using epidist(). The marginal model approach uses the likelihood from the primarycensored package to efficiently handle censoring in both primary and secondary events as well as truncation due to observation times. See the specific methods as_epidist_marginal_model.epidist_linelist_data() and as_epidist_marginal_model.epidist_aggregate_data() for details on supported input formats and usage examples.

Usage

as_epidist_marginal_model(data, ...)

Arguments

data

An object to be converted to the class epidist_marginal_model

...

Additional arguments passed to the methods. These set the primary event distribution and other fitting options; see the methods for the arguments they take.

Value

An object of class epidist_marginal_model.

See Also

Other marginal_model: as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()


The marginal model method for epidist_aggregate_data objects

Description

This method converts aggregate data to a marginal model format by passing it to as_epidist_marginal_model.epidist_linelist_data() with the n column used as weights. This ensures that the likelihood is weighted by the counts in the aggregate data.

Usage

## S3 method for class 'epidist_aggregate_data'
as_epidist_marginal_model(
  data,
  obs_time_threshold = 2,
  delay_min = NULL,
  primary = .primary_choices(),
  ...
)

Arguments

data

An epidist_aggregate_data object

obs_time_threshold

Ratio used to determine threshold for setting relative observation times to Inf. Observation times greater than obs_time_threshold times the maximum delay will be set to Inf to improve model efficiency by reducing the number of unique observation times. Default is 2.

delay_min

Minimum delay (left truncation point). Can be:

  • NULL (default): uses a delay_min column from the data if present, otherwise defaults to 0 (no left truncation).

  • A numeric scalar: applied to all observations.

  • A column name string: looks up the named column in the data. This is passed as the L parameter to primarycensored::dpcens().

primary

The distribution of the primary event within its censoring window. "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter.

...

Not used in this method.

Value

An object of class epidist_marginal_model.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()

Examples

sierra_leone_ebola_data |>
  dplyr::count(date_of_symptom_onset, date_of_sample_tested) |>
  as_epidist_aggregate_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested",
    n = "n"
  ) |>
  as_epidist_marginal_model()

The marginal model method for epidist_linelist_data objects

Description

This method converts linelist data to a marginal model format by calculating delays between primary and secondary events, along with observation times and censoring windows. The likelihood used is imported from the primarycensored package which handles censoring in both primary and secondary events as well as truncation due to observation times. In principle, this method should be more accurate and more computationally efficient than the latent model (as_epidist_latent_model()) approach in most settings except when the number of unique strata approaches the number of observations.

Usage

## S3 method for class 'epidist_linelist_data'
as_epidist_marginal_model(
  data,
  obs_time_threshold = 2,
  weight = NULL,
  primary = .primary_choices(),
  delay_min = NULL,
  ...
)

Arguments

data

An epidist_linelist_data object

obs_time_threshold

Ratio used to determine threshold for setting relative observation times to Inf. Observation times greater than obs_time_threshold times the maximum delay will be set to Inf to improve model efficiency by reducing the number of unique observation times. Default is 2.

weight

A column name containing counts of identical linelist items. When specified, the user is declaring that rows with the same values represent the same observation occurring multiple times. This allows for efficient data representation by storing unique patterns with their counts rather than repeating identical rows. The marginal model will further aggregate these counts based on the formula specification. Default is NULL, which assigns a count of 1 to each row. Internally this is used to define the 'n' column of the returned object.

primary

The distribution of the primary event within its censoring window. "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter.

delay_min

Minimum delay (left truncation point). Can be:

  • NULL (default): uses a delay_min column from the data if present, otherwise defaults to 0 (no left truncation).

  • A numeric scalar: applied to all observations.

  • A column name string: looks up the named column in the data. This is passed as the L parameter to primarycensored::dpcens().

...

Not used in this method.

Details

The marginal model performs internal aggregation to optimize computational efficiency while preserving all statistical information. If your data already contains repeated observations with identical characteristics, you can use the weight parameter to provide counts of these duplicates. This allows for more efficient data representation without any loss of information.

When a formula is specified in epidist(), the data will be transformed using epidist_transform_data_model.epidist_marginal_model() to prepare it for model fitting. This transformation summarises the data by counting unique combinations of delays, observation times, censoring windows and any variables in the model formula.

Value

An object of class epidist_marginal_model.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_marginal_model()

Convert an object to an epidist_meta_model object

Description

Creates an epidist_meta_model object from individual level data, published summary estimates, or a mix of the two. This enables fitting a single delay distribution to all of the evidence available using epidist().

Usage

as_epidist_meta_model(data = NULL, estimates = NULL, ...)

Arguments

data

An epidist_linelist_data or epidist_aggregate_data object of individual level observations, an epidist_estimates_data object of published summary estimates, or NULL.

estimates

An epidist_estimates_data object of published summary estimates, or NULL.

...

Additional arguments passed to methods.

Details

The meta model is experimental. Its interface may still change in future releases.

Individual level rows use the same likelihood as the marginal model (see as_epidist_marginal_model()), imported from the primarycensored package. Summary rows are instead forward modelled. Given the delay distribution, the model works out what the study's own estimation procedure would have converged to, and fits the reported value to that. Published estimates that did not adjust for right truncation, or that treated interval censored data as continuous, can therefore still contribute unbiased information. That holds only where the metadata describing what each study did is correct. It is usually the analyst's judgement rather than something the study reported, so state it explicitly and vary it in a sensitivity analysis. vignette("model") gives the forward model, the sampling likelihoods and the accuracy of the approximations, and vignette("meta") works through a simulated and a real example.

At least one of data and estimates must be supplied. Study level heterogeneity is specified through the brms formula in epidist(), for example mu ~ 1 + (1 | study), rather than through this function. Individual level rows are labelled "individual" in the study column so that they form their own level of any such term.

Value

An object of class epidist_meta_model.

What this means in practice

Summaries that one study computed from the same delays are correlated, so they are fitted jointly. Two are grouped when they agree on every column of as_epidist_estimates_data() other than the summary itself, and a summary supplied with its own se is fitted alone. A study that reported integer date differences (cens_adjusted 0 or 3) is the exception: its mean and standard deviation form one group and its quantiles another. One observation is therefore a group rather than a single reported value, so log_lik() and loo::loo() report per group, and loo only compares fits to the same studies and the same mix of individual and summary rows. Summary rows are evaluated in R for each posterior draw, so both are slow for a fit with many draws and summary rows. Pass ndraws to use fewer draws, as epidist_gen_meta_log_lik() explains. See vignette("faq"). epidist_meta_leave_one_out() asks the study level question instead, refitting with each study held out.

The sampling standard errors are plug in quantities that depend on the parameters, so allow for genuine differences between studies with a term such as mu ~ 1 + (1 | study) rather than relying on them alone. Supply a reported se in as_epidist_estimates_data() for quantiles read off a fitted distribution rather than the empirical data. Where a study reported integer date differences, keep its mean and standard deviation and drop its quantiles. as_epidist_estimates_data() warns for the studies the approximations serve least well, and documents the two settings, max_delay and options(epidist.meta_n_quad = ), that trade accuracy against speed.

Advanced: an estimated growth rate

A summary row tilts its primary event, and weights the follow up of an accrual design, by the growth_rate of its study. Where that rate is NA in as_epidist_estimates_data(), or was given there with a growth_rate_sd, the study estimates it as the pgrowth distributional parameter instead. That is the parameter primary = "expgrowth" estimates from individual level rows, so the two can share it. The model adds pgrowth ~ 0 + study unless a pgrowth formula is given, and epidist_model_prior() sets the priors from the reported rates. Summaries carry little information about the rate on their own, so share the coefficient with rows that do inform it, for example pgrowth ~ 1 with a line list from the same outbreak. vignette("model") gives the details.

See Also

as_epidist_estimates_data() for preparing the summary estimates, and for the checks and the settings the approximations here depend on.

Other meta_model: as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()


The meta model method for summary estimates only

Description

Used when no individual level data is available and only the estimates argument is supplied. It takes no primary argument, because summary rows tilt the primary event by the growth_rate metadata of their study, estimating it only where that is NA or has a growth_rate_sd. Passing one is an error.

Usage

## S3 method for class ''NULL''
as_epidist_meta_model(data = NULL, estimates = NULL, ...)

Arguments

data

NULL.

estimates

An epidist_estimates_data object of published summary estimates, or NULL.

...

Additional arguments passed to methods.

Value

An object of class epidist_meta_model.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()

Examples

estimates <- as_epidist_estimates_data(
  data.frame(
    study = c("A", "A"),
    type = c("mean", "sd"),
    value = c(7.5, 3.6),
    n = c(120, 120),
    relative_obs_time = c(20, 20),
    trunc_adjusted = c(FALSE, FALSE),
    cens_adjusted = c(0, 0)
  )
)
as_epidist_meta_model(estimates = estimates)

The meta model method for epidist_aggregate_data objects

Description

This method converts aggregate data to a meta model format by passing it to as_epidist_meta_model.epidist_linelist_data() with the n column used as weights.

Usage

## S3 method for class 'epidist_aggregate_data'
as_epidist_meta_model(
  data,
  estimates = NULL,
  obs_time_threshold = 2,
  delay_min = NULL,
  primary = .primary_choices(),
  ...
)

Arguments

data

An epidist_aggregate_data object.

estimates

An epidist_estimates_data object of published summary estimates, or NULL.

obs_time_threshold

Ratio used to determine threshold for setting relative observation times to Inf. Observation times greater than obs_time_threshold times the maximum delay will be set to Inf to improve model efficiency by reducing the number of unique observation times. Default is 2.

delay_min

Minimum delay (left truncation point). Can be:

  • NULL (default): uses a delay_min column from the data if present, otherwise defaults to 0 (no left truncation).

  • A numeric scalar: applied to all observations.

  • A column name string: looks up the named column in the data. This is passed as the L parameter to primarycensored::dpcens().

primary

The distribution of the primary event within its censoring window for the individual level rows, as in as_epidist_marginal_model.epidist_linelist_data(). "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter. Summary rows are unaffected. They tilt the primary event by the growth_rate metadata of their study, or estimate it as the same pgrowth parameter where that is NA or has a growth_rate_sd, see as_epidist_meta_model().

...

Additional arguments passed to methods.

Value

An object of class epidist_meta_model.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()

Examples

sierra_leone_ebola_data |>
  dplyr::count(date_of_symptom_onset, date_of_sample_tested) |>
  as_epidist_aggregate_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested",
    n = "n"
  ) |>
  as_epidist_meta_model()

The meta model method for epidist_estimates_data objects

Description

Allows summary estimates to be passed as the first argument, so that as_epidist_meta_model(estimates) and as_epidist_meta_model(estimates = estimates) are equivalent.

Usage

## S3 method for class 'epidist_estimates_data'
as_epidist_meta_model(data, estimates = NULL, ...)

Arguments

data

An epidist_estimates_data object.

estimates

An epidist_estimates_data object of published summary estimates, or NULL.

...

Additional arguments passed to methods.

Details

A model built from summaries alone takes no primary argument, because summary rows tilt the primary event by the growth_rate metadata of their study, estimating it only where that is NA or has a growth_rate_sd. Passing one is an error.

Value

An object of class epidist_meta_model.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()

Examples

estimates <- as_epidist_estimates_data(
  data.frame(
    study = c("A", "A"),
    type = c("mean", "sd"),
    value = c(7.5, 3.6),
    n = c(120, 120),
    relative_obs_time = c(20, 20),
    trunc_adjusted = c(FALSE, FALSE),
    cens_adjusted = c(0, 0)
  )
)
as_epidist_meta_model(estimates)

The meta model method for epidist_linelist_data objects

Description

Prepares individual level data exactly as as_epidist_marginal_model.epidist_linelist_data() does and then stacks it with any supplied summary estimates.

Usage

## S3 method for class 'epidist_linelist_data'
as_epidist_meta_model(
  data,
  estimates = NULL,
  obs_time_threshold = 2,
  weight = NULL,
  delay_min = NULL,
  primary = .primary_choices(),
  ...
)

Arguments

data

An epidist_linelist_data object.

estimates

An epidist_estimates_data object of published summary estimates, or NULL.

obs_time_threshold

Ratio used to determine threshold for setting relative observation times to Inf. Observation times greater than obs_time_threshold times the maximum delay will be set to Inf to improve model efficiency by reducing the number of unique observation times. Default is 2.

weight

A column name containing counts of identical linelist items. When specified, the user is declaring that rows with the same values represent the same observation occurring multiple times. This allows for efficient data representation by storing unique patterns with their counts rather than repeating identical rows. The marginal model will further aggregate these counts based on the formula specification. Default is NULL, which assigns a count of 1 to each row. Internally this is used to define the 'n' column of the returned object.

delay_min

Minimum delay (left truncation point). Can be:

  • NULL (default): uses a delay_min column from the data if present, otherwise defaults to 0 (no left truncation).

  • A numeric scalar: applied to all observations.

  • A column name string: looks up the named column in the data. This is passed as the L parameter to primarycensored::dpcens().

primary

The distribution of the primary event within its censoring window for the individual level rows, as in as_epidist_marginal_model.epidist_linelist_data(). "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter. Summary rows are unaffected. They tilt the primary event by the growth_rate metadata of their study, or estimate it as the same pgrowth parameter where that is NA or has a growth_rate_sd, see as_epidist_meta_model().

...

Additional arguments passed to methods.

Value

An object of class epidist_meta_model.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_meta_model()

Create an epidist_multivariate object

Description

Summarises draws of a set of parameters by their mean vector and covariance matrix. The result is a multivariate normal approximation to whatever the draws describe, and it is the only route by which a covariance between reported quantities reaches as_epidist_meta_model().

Usage

as_epidist_multivariate(draws, ...)

Arguments

draws

Draws of the parameters. See the methods for supported formats.

...

Additional arguments passed to methods.

Details

The draws may be of any parameters. Posterior draws of a delay mean and standard deviation, of a meanlog and sdlog, or of a shape and a scale all give the same object. Nothing here checks that a parameter is something a study could report, because that only matters when the object is converted with as_epidist_estimates_data().

Draws may also cover a trajectory, with the parameters varying over an index. The elements are then ordered index major and parameter minor, so a mean and an sd over two index points give mean[1], sd[1], mean[2], sd[2]. The order is fixed because the covariance is indexed by it.

There is no method for a vector of individual delays. Resampling delays manufactures a covariance the study never estimated, which is not what this represents.

Value

An object of class epidist_multivariate.

See Also

Other multivariate: as_epidist_multivariate.data.frame(), as_epidist_multivariate.matrix(), assert_epidist.epidist_multivariate(), is_epidist_multivariate(), new_epidist_multivariate(), print.epidist_multivariate(), vcov.epidist_multivariate()


Create an epidist_multivariate object from a data frame of draws

Description

delay_parameter_draws() returns exactly this shape, with a .draw column, a .row column and one column per parameter, so its output can be passed straight in. Add add_summaries() to report the natural scale mean and standard deviation rather than the distributional parameters.

Usage

## S3 method for class 'data.frame'
as_epidist_multivariate(draws, params = NULL, index = NULL, draw = NULL, ...)

Arguments

draws

Draws of the parameters. See the methods for supported formats.

params

A character vector of the columns holding the parameter draws. Defaults to every numeric column other than draw and index. Supply it wherever the draws carry more columns than the parameters being reported, because parameters that are functions of each other have a singular covariance.

index

A string giving the column that identifies the trajectory point. Defaults to ".row" where such a column exists, as delay_parameter_draws() returns, and otherwise to NULL, meaning the draws describe a single point.

draw

A string giving the column that identifies the draw. Defaults to ".draw" where such a column exists, and otherwise to NULL, meaning row order.

...

Not used in this method.

Value

An object of class epidist_multivariate.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.matrix(), assert_epidist.epidist_multivariate(), is_epidist_multivariate(), new_epidist_multivariate(), print.epidist_multivariate(), vcov.epidist_multivariate()

Examples

set.seed(1)
draws <- data.frame(
  mean = rnorm(500, 7.5, 0.3), sd = rnorm(500, 3.6, 0.2)
)
as_epidist_multivariate(draws)

Create an epidist_multivariate object from a matrix of draws

Description

Rows are draws and columns are parameters, describing a single point.

Usage

## S3 method for class 'matrix'
as_epidist_multivariate(draws, params = NULL, ...)

Arguments

draws

Draws of the parameters. See the methods for supported formats.

params

A character vector naming the columns of draws. Defaults to the column names of draws.

...

Not used in this method.

Value

An object of class epidist_multivariate.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.data.frame(), assert_epidist.epidist_multivariate(), is_epidist_multivariate(), new_epidist_multivariate(), print.epidist_multivariate(), vcov.epidist_multivariate()

Examples

set.seed(1)
draws <- cbind(mean = rnorm(500, 7.5, 0.3), sd = rnorm(500, 3.6, 0.2))
as_epidist_multivariate(draws)

Convert an object to an epidist_naive_model object

Description

Creates an epidist_naive_model object from various input formats. This enables fitting naive models for epidemiological delays using epidist(). The naive model approach ignores censoring and truncation in the data, using only the lower bounds of the intervals as point estimates. This is the simplest approach but may lead to biased estimates if there is substantial censoring or truncation in the data.

Usage

as_epidist_naive_model(data, ...)

Arguments

data

An object to be converted to the class epidist_naive_model

...

Additional arguments passed to methods.

Value

An object of class epidist_naive_model.

See Also

Other naive_model: as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()


The naive model method for epidist_aggregate_data objects

Description

This method converts aggregate data to a naive model format by passing it to as_epidist_naive_model.epidist_linelist_data() with the n column used as weights. This ensures that the likelihood is weighted by the counts in the aggregate data.

Usage

## S3 method for class 'epidist_aggregate_data'
as_epidist_naive_model(data, ...)

Arguments

data

An epidist_aggregate_data object.

...

Additional arguments passed to methods.

Value

An object of class epidist_naive_model.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()

Examples

sierra_leone_ebola_data |>
  dplyr::count(date_of_symptom_onset, date_of_sample_tested) |>
  as_epidist_aggregate_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested",
    n = "n"
  ) |>
  as_epidist_naive_model()

The naive model method for epidist_linelist_data objects

Description

This method converts linelist data to a naive model format by calculating delays between primary and secondary events to enable model fitting in epidist(). If the input data contains an n column (e.g. from aggregated data), the likelihood will be weighted by these counts.

Usage

## S3 method for class 'epidist_linelist_data'
as_epidist_naive_model(data, weight = NULL, ...)

Arguments

data

An epidist_linelist_data object.

weight

A column name to use for weighting. If NULL, weights default to 1. Internally this is used to define the 'n' column of the returned object.

...

Additional arguments passed to methods.

Details

When a formula is specified in epidist(), the data will be transformed using epidist_transform_data_model.epidist_naive_model() to prepare it for model fitting. This transformation summarises the data by counting unique combinations of delays and any variables in the model formula.

The naive model is the simplest approach but ignores censoring and truncation in the data by using only lower bounds as point estimates. For data with substantial censoring or truncation, consider using as_epidist_latent_model() or as_epidist_marginal_model() which properly account for these features.

Value

An object of class epidist_naive_model.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_naive_model()

Validation for epidist objects

Description

Validation for epidist objects

Usage

assert_epidist(data, ...)

Arguments

data

Object to validate

...

Additional arguments

Value

NULL invisibly


Assert validity of epidist_aggregate_data objects

Description

Assert validity of epidist_aggregate_data objects

Usage

## S3 method for class 'epidist_aggregate_data'
assert_epidist(data, ...)

Arguments

data

An object to check

...

Additional arguments

Value

NULL, invisibly. Called for the side effect of validating data.

See Also

Other aggregate_data: as_epidist_aggregate_data(), as_epidist_aggregate_data.data.frame(), as_epidist_aggregate_data.default(), as_epidist_aggregate_data.epidist_linelist_data(), is_epidist_aggregate_data(), new_epidist_aggregate_data()

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  assert_epidist()

Assert validity of epidist_estimates_data objects

Description

Assert validity of epidist_estimates_data objects

Usage

## S3 method for class 'epidist_estimates_data'
assert_epidist(data, ...)

Arguments

data

An object to check for validity.

...

Additional arguments

Value

NULL, invisibly. Called for the side effect of validating data.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()


Assert validity of epidist_linelist_data objects

Description

Assert validity of epidist_linelist_data objects

Usage

## S3 method for class 'epidist_linelist_data'
assert_epidist(data, ...)

Arguments

data

An object to check for validity.

...

Additional arguments

Value

NULL, invisibly. Called for the side effect of validating data.

See Also

Other linelist_data: as_epidist_linelist_data(), as_epidist_linelist_data.data.frame(), as_epidist_linelist_data.default(), as_epidist_linelist_data.epidist_aggregate_data(), is_epidist_linelist_data(), new_epidist_linelist_data()


Assert validity of epidist_meta_model objects

Description

Assert validity of epidist_meta_model objects

Usage

## S3 method for class 'epidist_meta_model'
assert_epidist(data, ...)

Arguments

data

An object to check for validity.

...

Additional arguments

Value

NULL, invisibly. Called for the side effect of validating data.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()


Assert validity of epidist_multivariate objects

Description

Assert validity of epidist_multivariate objects

Usage

## S3 method for class 'epidist_multivariate'
assert_epidist(data, ...)

Arguments

data

An object to check for validity.

...

Additional arguments.

Value

NULL, invisibly. Called for the side effect of validating data.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.data.frame(), as_epidist_multivariate.matrix(), is_epidist_multivariate(), new_epidist_multivariate(), print.epidist_multivariate(), vcov.epidist_multivariate()


Posterior draws of the delay distribution parameters

Description

Returns posterior draws of the parameters of the delay distribution in the long format used by tidybayes. The delay parameters are the distributional parameters of the brms family, evaluated on the response scale for each row of newdata. For a lognormal model they are mu and sigma. They are the parameters of the delay distribution itself, so they do not describe the censoring or truncation of the observation process, and they are not the natural scale mean and standard deviation of the delay. Use add_summaries() to add those.

add_delay_parameter_draws() is the same function with newdata first, for use at the start of a pipeline as with tidybayes::add_epred_draws().

Usage

delay_parameter_draws(object, newdata = NULL, ...)

add_delay_parameter_draws(newdata, object, ...)

Arguments

object

A model fit with epidist().

newdata

A data.frame of data to predict for. If NULL, the default, the data the model was fitted to is used. The brms models epidist fits need the model variables as well as the predictors, so build newdata with epidist_strata() rather than from the predictors alone.

...

Additional arguments passed to brms::prepare_predictions(), such as ndraws or re_formula.

Details

The returned columns follow the tidybayes conventions. The columns of newdata come first, followed by .row, .chain, .iteration and .draw, followed by one column per distributional parameter. The result is grouped by the columns of newdata and by .row. .chain and .iteration are NA when the draws have been subset, because the chain a subset draw came from is not recoverable.

Every row of newdata gets its own draws, so passing the data the model was fitted to produces many identical draws when the model has few unique combinations of predictors. epidist_strata() returns one row per unique combination and is usually the better input.

Value

A tibble of posterior draws of the delay distribution parameters, grouped by the columns of newdata and by .row. It has the epidist_delay_draws class, which records the delay distribution family and gives it a plot() method.

See Also

add_summaries() to add natural scale summaries of the delay, epidist_strata() to build newdata, and plot.epidist_delay_draws() to plot the draws.

Other postprocess: add_summaries(), as_dist_spec.epidist_fit(), delay_summary_draws(), epidist_delay_draws, epidist_strata()

Examples


fit <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model() |>
  epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))

fit |>
  epidist_strata() |>
  add_delay_parameter_draws(fit) |>
  add_summaries(probs = c(0.05, 0.95))


Posterior draws of the delay distribution, summarised

Description

The usual last step of a fit. Builds one row per unique combination of the predictors with epidist_strata(), draws the delay distribution parameters for each with delay_parameter_draws(), and adds the natural scale mean and standard deviation, and any quantiles asked for, with add_summaries().

Each of those three steps is available on its own where a step needs different arguments, or where newdata is built some other way.

Usage

delay_summary_draws(
  object,
  newdata = NULL,
  vars = NULL,
  probs = NULL,
  method = c("auto", "analytic", "sample"),
  nsim = 1000,
  ...
)

Arguments

object

A model fit with epidist().

newdata

A data.frame of data to predict for. If NULL, the default, epidist_strata() builds one row per unique combination of the predictors the model uses.

vars

A character vector of variables to stratify by, passed to epidist_strata(). Only used when newdata is NULL.

probs

A numeric vector of probabilities to add quantiles of the delay distribution for. If NULL, the default, no quantiles are added.

method

Passed to add_summaries(). Either "auto", the default, which uses the analytic solution when there is one and simulates otherwise, "analytic", or "sample".

nsim

The number of delays to simulate per row. Passed to add_summaries() and only used when simulating.

...

Additional arguments passed to brms::prepare_predictions(), such as ndraws or re_formula.

Value

A tibble of posterior draws of the delay distribution parameters with mean and sd columns added, and one column per element of probs. Grouped as delay_parameter_draws() returns it.

See Also

delay_parameter_draws() for the parameters alone, add_summaries() to summarise draws you already have, and epidist_strata() to build newdata.

Other postprocess: add_summaries(), as_dist_spec.epidist_fit(), delay_parameter_draws(), epidist_delay_draws, epidist_strata()

Examples


fit <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model() |>
  epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))

delay_summary_draws(fit, probs = c(0.05, 0.95))


Fit epidemiological delay distributions using a brms interface

Description

Fit epidemiological delay distributions using a brms interface

Usage

epidist(
  data,
  formula = mu ~ 1,
  family = lognormal(),
  prior = NULL,
  merge_priors = TRUE,
  fn = brms::brm,
  ...
)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

merge_priors

If TRUE then merge user priors with default priors, if FALSE only use user priors. Defaults to TRUE. This may be useful if the built in approaches for merging priors are not flexible enough for a particular use case.

fn

The internal function to be called. By default this is brms::brm() which performs inference for the specified model. Other options are brms::make_stancode() which returns the Stan code for the specified model, or brms::make_standata() which returns the data passed to Stan. These two later options may be useful for model debugging and extensions.

...

Additional arguments passed to fn method.

Value

A fitted model of class epidist_fit.

Examples


fit <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model() |>
  epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))

summary(fit)


Keep epidist objects in their class

Description

Every epidist data object also carries the epidist_data class. The methods documented here re-check an object after it has been modified and drop any epidist class whose requirements the modified object no longer meets, warning about what was dropped and why. An object that still carries an epidist class is therefore a valid object of that class, so functions which accept one do not need to re-check it.

Usage

## S3 method for class 'epidist_data'
x[...]

## S3 replacement method for class 'epidist_data'
x[...] <- value

## S3 replacement method for class 'epidist_data'
x[[...]] <- value

## S3 replacement method for class 'epidist_data'
x$... <- value

## S3 replacement method for class 'epidist_data'
names(x) <- value

## S3 method for class 'epidist_data'
rbind(..., deparse.level = 1)

## S3 method for class 'epidist_data'
dplyr_reconstruct(data, template)

## S3 method for class 'epidist_data'
dplyr_row_slice(data, i, ...)

## S3 method for class 'epidist_data'
dplyr_col_modify(data, cols)

## S3 method for class 'epidist_data'
group_by(.data, ..., .add = FALSE, .drop = dplyr::group_by_drop_default(.data))

## S3 method for class 'epidist_data'
ungroup(x, ...)

Arguments

x, .data

An object with the epidist_data class.

...

Passed to the underlying method.

value

A replacement value.

deparse.level

Passed to base::rbind().

data, template

Passed to dplyr::dplyr_reconstruct().

i, cols

Passed to dplyr::dplyr_row_slice() and dplyr::dplyr_col_modify().

.add, .drop

Passed to dplyr::group_by().

Details

Methods are provided for base subsetting and replacement, and for dplyr::dplyr_reconstruct(), which dplyr verbs such as dplyr::mutate(), dplyr::filter() and dplyr::select() use to restore the class of their input. dplyr::group_by() and dplyr::ungroup() build a new tibble rather than restoring the class of their input, as do the grouped_df methods for dplyr::dplyr_row_slice() and dplyr::dplyr_col_modify(), so each has a method of its own that puts the classes back. A grouped object keeps the grouped_df class after the epidist classes, and the dplyr verbs keep both. dplyr::summarise() builds a new object from the groups rather than modifying its input, so its result does not carry the epidist classes.

A result with no columns is unclassed without a warning. Such a result is almost always the prototype vctrs takes internally, in dplyr::bind_cols() for example, rather than something the user asked for, and it cannot be told apart from a deliberate empty selection.

Value

The modified object with any epidist class whose requirements it no longer meets removed.

See Also

Other epidist_data: is_epidist_data()

Examples

linelist_data <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  )

# Subsetting rows keeps the class
class(linelist_data[1:10, ])

# Dropping a required column drops the class
class(dplyr::select(linelist_data, -"obs_time"))

# Grouping keeps the class alongside the grouped_df class
class(dplyr::group_by(linelist_data, obs_time))

Keep the epidist_delay_draws class through dplyr verbs

Description

The epidist_delay_draws class records the delay distribution family and the variables that define the strata, which add_summaries() and plot.epidist_delay_draws() read. Most dplyr verbs build a new object rather than keeping the class of their input, so the methods documented here put the class and what it records back.

Usage

## S3 method for class 'epidist_delay_draws'
x[...]

## S3 replacement method for class 'epidist_delay_draws'
names(x) <- value

## S3 method for class 'epidist_delay_draws'
dplyr_reconstruct(data, template)

## S3 method for class 'epidist_delay_draws'
dplyr_row_slice(data, i, ...)

## S3 method for class 'epidist_delay_draws'
dplyr_col_modify(data, cols)

## S3 method for class 'epidist_delay_draws'
group_by(.data, ..., .add = FALSE, .drop = dplyr::group_by_drop_default(.data))

## S3 method for class 'epidist_delay_draws'
ungroup(x, ...)

Arguments

x, .data

An epidist_delay_draws object.

...

Passed to the underlying method.

value

A replacement value.

data, template

Passed to dplyr::dplyr_reconstruct().

i, cols

Passed to dplyr::dplyr_row_slice() and dplyr::dplyr_col_modify().

.add, .drop

Passed to dplyr::group_by().

Details

Methods are provided for base subsetting and renaming, and for dplyr::dplyr_reconstruct(), which verbs such as dplyr::mutate() and dplyr::bind_rows() use to restore the class of their input. dplyr::group_by() and dplyr::ungroup() build a new tibble rather than restoring the class of their input, as do the grouped_df methods for dplyr::dplyr_row_slice() and dplyr::dplyr_col_modify(), so each has a method of its own that puts the class back. A grouped object keeps the epidist_delay_draws class ahead of grouped_df, and the dplyr verbs keep both. dplyr::summarise() builds a new object from the groups rather than modifying its input, so its result does not carry the class.

dplyr::bind_rows() restores the class from its first argument, so combining draws keeps the family and the stratum variables of the first set of draws. Combining draws from two fits of different families therefore describes the result by the family of the first. Pass the family to add_summaries() or plot() with the family argument when the draws combined are not all from the same family.

Value

The modified object with the epidist_delay_draws class, and the family and stratum variables it records, put back.

See Also

Other postprocess: add_summaries(), as_dist_spec.epidist_fit(), delay_parameter_draws(), delay_summary_draws(), epidist_strata()

Examples

draws <- data.frame(mu = c(1.8, 2.0), sigma = c(0.5, 0.4)) |>
  add_summaries(family = "lognormal")

# Adding a column keeps the class
class(dplyr::mutate(draws, model = "a"))

# Combining two sets of draws keeps the class
class(dplyr::bind_rows(draws, draws))

Diagnostics for epidist_fit models

Description

This function computes diagnostics to assess the quality of a fitted model. When the fitting algorithm used is "sampling" (HMC) then the output of epidist_diagnostics is a data.frame containing:

Usage

epidist_diagnostics(fit)

Arguments

fit

A fitted model of class epidist_fit

Details

When the fitting algorithm is not "sampling" (see brms::brm() for other possible algorithms) then diagnostics are yet to be implemented.

Value

A data.frame of summary diagnostics for the fit.

Examples


fit <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model() |>
  epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))
epidist_diagnostics(fit)


Report studies from an epireview parameter table

Description

Maps a table of published delay estimates from the epireview package, one row per reported estimate, to the long format as_epidist_estimates_data() takes, and returns the epidist_estimates_data object it builds. epireview collates the parameter estimates gathered by the Pathogen Epidemiology Review Group. It is not on CRAN, and is installed from the mrc-ide r-universe. Filter the params table of epireview::load_epidata() to one delay before passing it here, because the rows of one object all describe the same delay.

Usage

epidist_estimates_epireview(
  data,
  study = "article_label",
  metadata = NULL,
  keep = NULL,
  advise = TRUE,
  ...
)

Arguments

data

A data.frame of epireview delay estimates, such as the params element of epireview::load_epidata() filtered to one delay. It needs the parameter_value, parameter_value_type and population_sample_size columns and the column named by study. The other ⁠parameter_*⁠ and ⁠distribution_*⁠ columns are used where present.

study

A string naming the column of data that identifies the study. Defaults to "article_label".

metadata

A data.frame of study metadata, or NULL. It needs a study column holding values of the study column of data, and takes any of n, pwindow, swindow, relative_obs_time, trunc_adjusted, trunc_design, cens_adjusted, delay_min and growth_rate, as documented in as_epidist_estimates_data.data.frame(). Each value replaces the value of that column for the study's records, and an NA leaves it as it is.

keep

A character vector of columns of data to carry onto the rows of the result, for use as covariates. Defaults to NULL.

advise

Whether to run the advisory checks of as_epidist_estimates_data.data.frame(). Defaults to TRUE.

...

Study metadata applied to every record, each a single value, as documented in as_epidist_estimates_data.data.frame(). Any of pwindow, swindow, relative_obs_time, trunc_adjusted, trunc_design, cens_adjusted, delay_min and growth_rate.

Value

An epidist_estimates_data object.

What each record becomes

A record is mapped by its parameter_value_type.

A range is the smallest and largest delay a study saw rather than a summary of the distribution, and is not used. A spread that does not match the value type, such as a standard deviation reported alongside a median, is not used either, because the two kinds of summary from a study that reported integer date differences are fitted as though they were independent.

Records that cannot be mapped are dropped with a message naming them. These are records reporting an inverse rate, units other than days, a value with a scaling exponent, no mean or median and no usable distribution parameters, and records left with no sample size and no standard error. Fill a missing sample size through metadata.

Several records may share a study, for example estimates stratified by outbreak or by group, and they are then fitted as separate summaries of the same study.

Study metadata

epireview does not record how a study handled censoring or right truncation, its censoring windows or its observation time. Give the metadata that applies to every record through ..., and the metadata that differs by study through metadata, a data frame with one row per study whose values replace those of ... for that study's records. Anything given for neither is assumed as as_epidist_estimates_data() assumes it, with the same messages, and a study that metadata leaves blank for a column it holds is assumed in the same way and named. The Checks section of as_epidist_estimates_data.data.frame() says which assumptions matter most.

The result is an epidist_estimates_data object, so metadata learnt later can be edited in with dplyr::mutate() or ⁠[<-⁠. The object is checked again after each change and drops its class if the change breaks a requirement, so make related changes, such as setting trunc_adjusted to FALSE and giving the relative_obs_time it then needs, in one call. See epidist_data.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

# A table with the columns epireview uses
records <- data.frame(
  article_label = c("A 2015", "B 2016", "B 2016"),
  parameter_value = c(10.6, 14, 8.9),
  parameter_value_type = c("Mean", "Median", "Mean"),
  parameter_unit = "Days",
  parameter_uncertainty_single_value = c(3.2, NA, NA),
  parameter_uncertainty_singe_type = c("Standard Deviation", NA, NA),
  parameter_uncertainty_lower_value = c(NA, 11, NA),
  parameter_uncertainty_upper_value = c(NA, 15, NA),
  parameter_uncertainty_type = c(NA, "IQR", NA),
  population_sample_size = c(76, 20, 92)
)
epidist_estimates_epireview(
  records,
  metadata = data.frame(
    study = "A 2015", relative_obs_time = 60, trunc_adjusted = FALSE
  ),
  trunc_adjusted = TRUE,
  cens_adjusted = 0
)

Report a study that published the parameters of a distribution it fitted

Description

Studies often publish the parameters of a distribution they fitted rather than summaries of the delays themselves. This converts those parameters into the summaries the fitted distribution implies, which is what as_epidist_meta_model() fits to.

Usage

epidist_estimates_parameters(
  study,
  family,
  parameters,
  moments = c("mean", "sd"),
  probs = numeric(0),
  se = NULL,
  n = NULL,
  ...
)

Arguments

study

A string naming the study.

family

The distribution the study fitted, one of "lognormal", "gamma" or "weibull".

parameters

A named numeric vector of the reported parameters. The names must be meanlog and sdlog for a lognormal, shape with either scale or rate for a gamma, and shape and scale for a weibull.

moments

Which moments to report, any of "mean" and "sd".

probs

A numeric vector of probabilities to report quantiles at.

se

A numeric vector of the reported standard errors of parameters, in the same order. Optional.

n

The number of delays the study fitted. Optional, and used for the sampling uncertainty of the summaries where no se is given.

...

Study metadata, as documented in as_epidist_estimates_data.data.frame().

Value

An epidist_estimates_data object.

What the reported parameters are taken to mean

The reported parameters describe the distribution the study's own estimation procedure converged to. Where the procedure was correct, that is the delay distribution itself. Where it was not, it is the biased distribution the procedure targeted, which is exactly what the meta model forward models from the study metadata. Converting to summaries therefore covers both cases with one route, and the study metadata documented in as_epidist_estimates_data.data.frame() is supplied in the same way as for any other summary.

Because the returned rows are summaries, the family the study fitted need not match the family being fitted to it. A study reporting a gamma can be used in a lognormal meta model. Parameters are never compared across families, which would be meaningless. For a two parameter family the map from parameters to a mean and a standard deviation is one to one, so a study that fitted correctly loses nothing by being converted.

What this does assume is that summaries of the study's reported distribution are the summaries of what its procedure targeted. That holds exactly when the study reported a distribution of the same shape as its estimand, and approximately otherwise, for example where a study fitted a continuous distribution to integer date differences.

The range the summaries are taken over

A study that did not correct for right truncation fitted a distribution to delays that stop at its observation time, but the families studies fit have a tail running past that point. Taking the reported distribution's summaries over its whole support would then charge it with spread its data never had, which is worst for a standard deviation and can reach tens of percent for a short observation time.

Summaries are therefore taken over the range of delays the study could have seen, conditioning the reported distribution on falling between delay_min and relative_obs_time. This is the same range the meta model computes its implied summaries over, so the two sides are the same functional of the two distributions. Both fields are read from the metadata passed through ..., and a study that adjusted for right truncation is left unconditioned above. A reported quantile at probability p is the value the conditioned distribution puts p below, so it too stays inside the observed range.

Where the study fitted a family that cannot represent its own estimand, quantiles inside the body of the distribution are more reliable than a standard deviation, which depends on a tail the study never saw.

Uncertainty

Supply the standard errors the study reported on its parameters through se. They are carried onto the summary scale by the delta method, using a numerical Jacobian of the map from parameters to summaries, and the summaries are reported with the covariance matrix that implies between them, so they are fitted jointly as a multivariate normal in the same way as the output of as_epidist_multivariate(). For a fit with as many summaries as parameters this carries the study's information about its parameters exactly, which fitting each summary with its own standard error would not.

Summaries of a two parameter fit are deterministic functions of two numbers, so at most two of them can carry the reported uncertainty, and asking for more with se is an error. A study that published a full parameter covariance rather than standard errors can draw from it, push each draw through to the summaries, and use as_epidist_multivariate(), which needs no linearisation.

Without se the summaries fall back to the sample size likelihoods, which derive their sampling uncertainty from n, and any number of them may be reported.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_summaries(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

epidist_estimates_parameters(
  "study A",
  family = "gamma",
  parameters = c(shape = 4.1, rate = 0.55),
  se = c(0.4, 0.06),
  relative_obs_time = 20,
  trunc_adjusted = FALSE,
  cens_adjusted = 0
)

Report a study that published summaries of its delays

Description

Builds the rows as_epidist_meta_model() takes from the summaries a study published in wide form, one argument per kind of summary.

Usage

epidist_estimates_summaries(
  study,
  mean = NULL,
  sd = NULL,
  quantiles = NULL,
  probs = NULL,
  se = NULL,
  n = NULL,
  ...
)

Arguments

study

A string naming the study.

mean

The reported mean delay. Optional.

sd

The reported standard deviation of the delays. Optional.

quantiles

A numeric vector of reported quantiles. Optional.

probs

The probabilities of quantiles, in the same order. Required where quantiles is given.

se

A numeric vector of the reported standard errors of the summaries, ordered mean, standard deviation, then quantiles, skipping any that was not reported. Optional.

n

The number of delays the study summarised. Optional.

...

Study metadata, as documented in as_epidist_estimates_data.data.frame().

Details

Give the uncertainty of each summary through se, or the number of delays the study summarised through n, which the model uses to derive a sampling uncertainty instead. One of the two is needed for every row.

Value

An epidist_estimates_data object.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), is_epidist_estimates_data(), new_epidist_estimates_data()

Examples

epidist_estimates_summaries(
  "study A",
  mean = 7.5, sd = 3.6, n = 120,
  relative_obs_time = 20, trunc_adjusted = FALSE, cens_adjusted = 0
)

Define epidist family

Description

This function is used within epidist() to create a model specific custom brms family object. This custom family is passed to brms. It is unlikely that as a user you will need this function, but we export it nonetheless to be transparent about what happens inside of a call to epidist().

Usage

epidist_family(data, family = lognormal(), ...)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

...

Additional arguments passed to fn method.

Details

The family may be any brms family of a positive response, such as brms::lognormal(), Gamma(link = "log") or brms::weibull(), or a family epidist defines itself, such as gengamma().

Value

A brms custom family object.

See Also

Other family: epidist_family_model(), epidist_family_model.default(), epidist_family_param(), epidist_family_param.default(), epidist_family_param.gengamma(), gengamma()

Examples

data <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model()
family <- epidist_family(data, family = lognormal())
family

The model-specific parts of an epidist_family() call

Description

The model-specific parts of an epidist_family() call

Usage

epidist_family_model(data, family, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

Output of a call to brms::brmsfamily() with additional information as provided by .add_dpar_info()

...

Additional arguments passed to fn method.

Value

A brms custom family object.

See Also

Other family: epidist_family(), epidist_family_model.default(), epidist_family_param(), epidist_family_param.default(), epidist_family_param.gengamma(), gengamma()


Default method for defining a model specific family

Description

Default method for defining a model specific family

Usage

## Default S3 method:
epidist_family_model(data, family, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

Output of a call to brms::brmsfamily() with additional information as provided by .add_dpar_info()

...

Additional arguments passed to fn method.

Value

A brms custom family object.

See Also

Other family: epidist_family(), epidist_family_model(), epidist_family_param(), epidist_family_param.default(), epidist_family_param.gengamma(), gengamma()


Create the model-specific component of an epidist custom family

Description

Create the model-specific component of an epidist custom family

Usage

## S3 method for class 'epidist_latent_model'
epidist_family_model(data, family, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

Output of a call to brms::brmsfamily() with additional information as provided by .add_dpar_info()

...

Additional arguments passed to method.

Value

A brms custom family object.

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()


Create the model-specific component of an epidist custom family

Description

Create the model-specific component of an epidist custom family

Usage

## S3 method for class 'epidist_marginal_model'
epidist_family_model(data, family, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

Output of a call to brms::brmsfamily() with additional information as provided by .add_dpar_info()

...

Additional arguments passed to method.

Value

A brms custom family object.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()


Create the model-specific component of an epidist custom family

Description

Create the model-specific component of an epidist custom family

Usage

## S3 method for class 'epidist_meta_model'
epidist_family_model(data, family, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

Output of a call to brms::brmsfamily() with additional information as provided by .add_dpar_info()

...

Additional arguments passed to method.

Value

A brms custom family object.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()


Reparameterise an epidist family to align brms and Stan

Description

Called by epidist_family(). A custom model supplies its family through epidist_family_model() rather than by calling this.

Usage

epidist_family_param(family, ...)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

...

Additional arguments passed to fn method.

Value

The family with a param element giving the Stan parameter ordering.

See Also

Other family: epidist_family(), epidist_family_model(), epidist_family_model.default(), epidist_family_param.default(), epidist_family_param.gengamma(), gengamma()


Default method for families which do not require a reparameterisation

Description

This function extracts the Stan parameterisation for a given brms family by creating a dummy model and parsing its Stan code. It looks for the log probability density function (lpdf) call in the Stan code and extracts the parameter order used by Stan. This is needed because brms and Stan may use different parameter orderings for the same distribution.

Usage

## Default S3 method:
epidist_family_param(family, ...)

Arguments

family

A brms family object containing at minimum a family element specifying the distribution family name.

...

Additional arguments passed to methods (not used)

Details

The function works by:

  1. Creating a minimal dummy model using the specified family

  2. Extracting the Stan code for this model

  3. Finding the lpdf function call for the family

  4. Parsing out the parameter ordering used in Stan

  5. Adding this as the param element to the family object

Value

The input family object with an additional param element containing the Stan parameter ordering as a string

See Also

Other family: epidist_family(), epidist_family_model(), epidist_family_model.default(), epidist_family_param(), epidist_family_param.gengamma(), gengamma()


Method for the gengamma() family

Description

The latent and naive models call the Stan density in the order brms declares the parameters. The marginal and meta models pass pcd_param, the Stacy form primarycensored takes.

Usage

## S3 method for class 'gengamma'
epidist_family_param(family, ...)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

...

Additional arguments passed to fn method.

Value

The family with param and pcd_param elements.

See Also

Other family: epidist_family(), epidist_family_model(), epidist_family_model.default(), epidist_family_param(), epidist_family_param.default(), gengamma()


Family specific prior distributions

Description

This function contains brms prior distributions which are specific to particular likelihood families e.g. brms::lognormal().

Usage

epidist_family_prior(family, ...)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

...

Additional arguments passed to fn method.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other prior: epidist_family_prior.default(), epidist_family_prior.gengamma(), epidist_family_prior.lognormal(), epidist_model_prior(), epidist_model_prior.default(), epidist_model_prior.epidist_meta_model(), epidist_prior()


Default family specific prior distributions

Description

By default, we do not return any family specific prior distributions.

Usage

## Default S3 method:
epidist_family_prior(family, formula, ...)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.gengamma(), epidist_family_prior.lognormal(), epidist_model_prior(), epidist_model_prior.default(), epidist_model_prior.epidist_meta_model(), epidist_prior()


Family specific prior distributions for the generalised gamma family

Description

mu and sigma get the intercept priors of the lognormal family. The intercept of Q, on the log scale, gets normal(0, 0.5), centred on the Weibull case.

Usage

## S3 method for class 'gengamma'
epidist_family_prior(family, formula, ...)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsprior object.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.default(), epidist_family_prior.lognormal(), epidist_model_prior(), epidist_model_prior.default(), epidist_model_prior.epidist_meta_model(), epidist_prior()


Family specific prior distributions for the lognormal family

Description

We suggest priors to overwrite the brms defaults for the lognormal family.

Usage

## S3 method for class 'lognormal'
epidist_family_prior(family, formula, ...)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.default(), epidist_family_prior.gengamma(), epidist_model_prior(), epidist_model_prior.default(), epidist_model_prior.epidist_meta_model(), epidist_prior()


Define a model specific formula

Description

This function is used within epidist() to create the formula object passed to brms. It is unlikely that as a user you will need this function, but we export it nonetheless to be transparent about what exactly is happening inside of a call to epidist().

Usage

epidist_formula(data, family, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model created using epidist_family().

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsformula object.

See Also

Other formula: epidist_formula_model(), epidist_formula_model.default()

Examples

data <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model()
family <- epidist_family(data, family = lognormal())
formula <- epidist_formula(data, family = family, formula = mu ~ 1)
formula

The model-specific parts of an epidist_formula() call

Description

The model-specific parts of an epidist_formula() call

Usage

epidist_formula_model(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsformula object.

See Also

Other formula: epidist_formula(), epidist_formula_model.default()


Default method for defining a model specific formula

Description

Default method for defining a model specific formula

Usage

## Default S3 method:
epidist_formula_model(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsformula object.

See Also

Other formula: epidist_formula(), epidist_formula_model()


Define the model-specific component of an epidist custom formula for the latent model

Description

Define the model-specific component of an epidist custom formula for the latent model

Usage

## S3 method for class 'epidist_latent_model'
epidist_formula_model(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to method.

Value

A brmsformula object.

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()


Define the model-specific component of an epidist custom formula for the marginal model

Description

Define the model-specific component of an epidist custom formula for the marginal model

Usage

## S3 method for class 'epidist_marginal_model'
epidist_formula_model(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to method.

Value

A brmsformula object.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()


Define the model-specific component of an epidist custom formula for the meta model

Description

Adds the response and the slots of the meta model to the formula. Where a summary row estimates its growth rate as the pgrowth distributional parameter, see as_epidist_meta_model(), and the formula has no term for pgrowth, pgrowth ~ 0 + study is added so that each study has its own rate and the priors epidist_model_prior() builds from the reported rates have a coefficient to act on. Data holding a single study get pgrowth ~ 1 instead, because brms cannot code a factor with one level. A pgrowth formula given by the user is kept as it is.

Usage

## S3 method for class 'epidist_meta_model'
epidist_formula_model(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to method.

Value

A brmsformula object.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()


Define the model-specific component of an epidist custom formula for the naive model

Description

Define the model-specific component of an epidist custom formula for the naive model

Usage

## S3 method for class 'epidist_naive_model'
epidist_formula_model(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to method.

Value

A brmsformula object.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()


Create a function to calculate the marginalised log likelihood for double censored and truncated delay distributions

Description

This function creates a log likelihood function that calculates the marginal likelihood for a single observation by integrating over the latent primary and secondary event windows. Where analytical solutions exist in primarycensored::dpcens() these are used, otherwise the integration is performed numerically. primarycensored::dpcens() handles the double censoring and truncation of the delay distribution.

Usage

epidist_gen_log_lik(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Details

The marginal likelihood accounts for uncertainty in both the primary and secondary event windows by integrating over their possible values, weighted by their respective uniform distributions.

Value

A function that calculates the marginal log likelihood for a single observation. The prep object must have the following variables:

See Also

brms::log_lik() for details on the brms log likelihood interface.

Other gen: epidist_gen_meta_log_lik(), epidist_gen_meta_predict(), epidist_gen_posterior_epred(), epidist_gen_posterior_predict()


Create a function to calculate the meta model log likelihood

Description

Individual level rows use the marginal model log likelihood created by epidist_gen_log_lik(). Summary rows use the sampling distributions described in as_epidist_meta_model(), evaluated at the implied summaries for each posterior draw. A row that stands for several summaries reported by one study returns the joint log likelihood of all of them, so an observation here is a group of summaries rather than a single reported value.

Usage

epidist_gen_meta_log_lik(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Details

Summary rows are evaluated in R, one posterior draw at a time, and each evaluation can run a quadrature of up to 2000 intervals by default. The cost of brms::log_lik() and loo::loo() therefore grows with the number of draws times the number of summary rows. Pass ndraws to either to use fewer draws, at the price of noisier estimates.

Value

A function that calculates the log likelihood for a single observation. The prep object must have the meta model vint and vreal slots.

See Also

brms::log_lik() for details on the brms log likelihood interface.

Other gen: epidist_gen_log_lik(), epidist_gen_meta_predict(), epidist_gen_posterior_epred(), epidist_gen_posterior_predict()


Create a function to draw from the meta model posterior predictive distribution

Description

Individual level rows are predicted as in the marginal model using epidist_gen_posterior_predict(). For summary rows the predicted quantity is the reported summary itself, that is a simulated reported mean, standard deviation, or, for quantile rows, cumulative probability at the reported value. A row that stands for several summaries reported by one study predicts the first of them, drawn from its marginal. Predictions for summary rows are therefore not on the delay scale and should not be compared directly with individual level predictions. They come from the normal approximations described in as_epidist_meta_model(), so a predicted cumulative probability for a quantile row can fall outside [0, 1] when the study sample size is small.

Usage

epidist_gen_meta_predict(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

A function that takes a prep argument from brms and returns a matrix of posterior predictions.

See Also

brms::posterior_predict() for details on how this is used within brms.

Other gen: epidist_gen_log_lik(), epidist_gen_meta_log_lik(), epidist_gen_posterior_epred(), epidist_gen_posterior_predict()


Create a function to draw from the expected value of the posterior predictive distribution for a model

Description

This function creates a function that calculates the expected value of the posterior predictive distribution for a latent model. The returned function takes a prep argument (from brms) and returns posterior expected values. This is used internally by brms::posterior_epred() to calculate expected values for latent models.

Usage

epidist_gen_posterior_epred(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

A function that takes a prep argument from brms and returns a matrix of posterior expected values, with one row per posterior draw and one column per observation.

See Also

brms::posterior_epred() for details on how this is used within brms.

Other gen: epidist_gen_log_lik(), epidist_gen_meta_log_lik(), epidist_gen_meta_predict(), epidist_gen_posterior_predict()


Create a function to draw from the posterior predictive distribution for a double censored and truncated delay distribution

Description

This function creates a function that draws from the posterior predictive distribution for a latent model using primarycensored::rpcens() to handle censoring and truncation. The returned function takes a prep argument from brms and returns posterior predictions. This is used internally by brms::posterior_predict() to generate predictions for latent models.

Usage

epidist_gen_posterior_predict(family)

Arguments

family

A description of the response distribution and link function to be used in the model. Every family function has a link argument allowing users to specify the link function to be applied on the response variable. If not specified, default links are used. For details of all supported families see brms::brmsfamily(). Commonly used, such as brms::lognormal(), are also reexported as part of epidist.

Value

A function that takes a prep argument from brms and returns a matrix of posterior predictions, with one row per posterior draw and one column per observation. The prep object must have the following variables:

See Also

brms::posterior_predict() for details on how this is used within brms, primarycensored::rpcens() for details on the censoring approach

Other gen: epidist_gen_log_lik(), epidist_gen_meta_log_lik(), epidist_gen_meta_predict(), epidist_gen_posterior_epred()


Refit a meta model leaving each study out in turn

Description

Refits a meta model once per study with that study removed, and compares the delay mean and standard deviation of each refit with the full fit.

Usage

epidist_meta_leave_one_out(
  fit,
  data = NULL,
  newdata = NULL,
  re_formula = NA,
  width = 0.95,
  keep_fits = FALSE,
  studies = NULL,
  cores = NULL,
  ...
)

Arguments

fit

A meta model fitted with epidist() to an epidist_meta_model object.

data

The epidist_meta_model object fit was fitted to. Only needed when fit$data has no study column, which happens when the formula does not use study. If NULL, the default, the model data stored in fit is used.

newdata

A data.frame of data to predict the delay for, passed to delay_summary_draws(). If NULL, the default, a single row giving the population level delay with no censoring and no truncation is built with epidist_newdata().

re_formula

Passed to brms::prepare_predictions() through delay_summary_draws(). The default NA switches off any study level term, so the summaries are of the population level delay.

width

The width of the central posterior intervals. Defaults to 0.95.

keep_fits

If TRUE, the refits are returned in the fits attribute of the result as a list named by the held out study. Defaults to FALSE.

studies

A character vector of the studies to hold out, one refit each. If NULL, the default, every study is held out in turn. Holding out a few studies, such as the largest, keeps the cost down when a model has many.

cores

The number of cores each refit uses. If NULL, the default, the mc.cores option where it is set, and otherwise one core per chain, so the chains of each refit run in parallel.

...

Additional arguments passed to brms::update.brmsfit() and so to brms::brm(), such as chains, iter, refresh and silent.

Details

Individual level rows are held out together as the "individual" study. If the formula does not use study, pass the epidist_meta_model object as data, because brms drops unused variables from fit$data. Each refit reuses the compiled model through brms::update.brmsfit(). The refits are exact because Pareto smoothed importance sampling (Vehtari et al. 2017) is often unreliable when a whole study is left out.

The comparison is reported as estimates with intervals and no threshold, as in marginaleffects (Arel-Bundock et al. 2024). difference is the refit posterior minus the full fit's posterior median. The two fits share most of their data, so their draws are not differenced.

Value

A tibble with one row per held out study, row of newdata and summary ("mean" or "sd"). It gives the posterior median (estimate) and interval (lower, upper) of the refit and of the full fit (⁠full_*⁠), and the difference from the full fit with its interval. Predictors of the model in newdata other than study are included. The width attribute records the interval width.

References

See Also

delay_summary_draws() for the summaries the comparison uses and epidist_newdata() to build newdata.

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()

Examples


estimates <- as_epidist_estimates_data(
  data.frame(
    study = c("A", "A", "B", "B", "C", "C"),
    type = c("mean", "sd", "mean", "sd", "mean", "sd"),
    value = c(7.5, 3.6, 6.4, 3.1, 8.2, 4.0),
    n = c(120, 120, 80, 80, 150, 150),
    relative_obs_time = c(20, 20, 25, 25, Inf, Inf),
    trunc_adjusted = c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE),
    cens_adjusted = c(0, 0, 0, 0, 1, 1)
  )
)
meta <- as_epidist_meta_model(estimates = estimates)
fit <- epidist(
  meta,
  chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0)
)

# The formula does not use study, so pass the model data
epidist_meta_leave_one_out(fit, data = meta, refresh = 0)


Model specific prior distributions

Description

This function contains brms prior distributions which are specific to particular epidist models e.g. the latent_lognormal model.

Usage

epidist_model_prior(data, ...)

Arguments

data

An object with class corresponding to an implemented model.

...

Additional arguments passed to fn method.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.default(), epidist_family_prior.gengamma(), epidist_family_prior.lognormal(), epidist_model_prior.default(), epidist_model_prior.epidist_meta_model(), epidist_prior()


Default model specific prior distributions

Description

By default, we do not return any model specific prior distributions.

Usage

## Default S3 method:
epidist_model_prior(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.default(), epidist_family_prior.gengamma(), epidist_family_prior.lognormal(), epidist_model_prior(), epidist_model_prior.epidist_meta_model(), epidist_prior()


Model specific prior distributions for latent models

Description

Defines prior distributions for the latent model parameters pwindow_raw and swindow_raw which control the width of the observation windows.

Usage

## S3 method for class 'epidist_latent_model'
epidist_model_prior(data, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

...

Additional arguments passed to fn method.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()


Model specific prior distributions for the meta model

Description

The response column of a meta model is a placeholder on every summary row, and brms centres its default prior for the intercept of mu on the response. For a model fitted to summaries alone that default is centred on a delay of zero. This method puts a normal(1, 1) prior on the intercept instead, the scale of the lognormal family prior in epidist_family_prior(), so that a Gamma or Weibull meta fit gets a prior on the same scale as a lognormal one. On the log scale it is a median delay of about 3 days with a 95% range of roughly 0.4 to 20 days.

Usage

## S3 method for class 'epidist_meta_model'
epidist_model_prior(data, formula, default = NULL, ...)

Arguments

data

An object with class corresponding to an implemented model.

formula

An object of class stats::formula or brms::brmsformula (or one that can be coerced to those classes). A symbolic description of the model to be fitted. A formula must be provided for the distributional parameter mu, and may optionally be provided for other distributional parameters.

default

The default prior distributions from brms::default_prior(), which epidist_prior() passes so that they are not built twice. Built here where missing.

...

Additional arguments passed to fn method.

Details

The centre is fixed rather than taken from the reported values, because a prior chosen from the data is not a prior. It would put the posterior of a small review where the data already sit and understate how much the studies disagree. The prior is added where mu is on the log scale, which is the lognormal family, whose mu is the log of the median under an identity link, and any family with a log link. Nothing is added for other links, and a model with individual level rows only adds no prior, so the family or brms default applies as it does for the marginal model.

The between study spread of any group level term, such as (1 | study), gets a half normal prior with a standard deviation of 0.25 on the scale of the linear predictor, so that a small review cannot fit that spread from almost nothing under the wide brms default. It is dropped where the formula has no group level term. The prior on the intercept of the other distributional parameters is left to the family or to brms.

Where a summary row estimates its growth rate as the pgrowth distributional parameter, see as_epidist_meta_model(), the coefficients and intercept of pgrowth get a normal(0, 0.25) prior, which is weakly informative for a delay measured in days, because the brms default is flat and the summaries carry little information about the rate. A study that reported its rate with a growth_rate_sd gets a normal prior with that centre and spread on its own coefficient, which exists under the default pgrowth ~ 0 + study formula, or on the intercept of pgrowth where it is the only study. Under another pgrowth formula the reported rates have no coefficient to act on and are dropped with a warning, so set their priors yourself.

Value

A brmsprior object, or NULL when the model adds no priors.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.default(), epidist_family_prior.gengamma(), epidist_family_prior.lognormal(), epidist_model_prior(), epidist_model_prior.default(), epidist_prior()

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()


Build newdata for prediction from an epidist data object

Description

Prediction with brms and tidybayes needs a newdata argument holding every variable the model uses. As well as the variables in your formula that means the response and the observation process variables that epidist adds. Their names depend on the model, so building newdata by hand means knowing how each model is specified. This function builds it for you. It expands the variables you supply into a grid, in the same way as tidyr::expand(), and adds the rest with values you set through named arguments.

Usage

epidist_newdata(data, ...)

Arguments

data

An epidist data object, such as one returned by as_epidist_marginal_model(), as_epidist_latent_model(), as_epidist_naive_model() or as_epidist_meta_model().

...

Variables to expand into a grid, passed to tidyr::expand(). Supply the variables used in the model formula, such as sex. Each combination of their unique values becomes a row. Supply no variables to get a single row, which is what an intercept only model needs. A variable expanded here keeps its expanded values, so naming it as an argument of the method as well is an error.

Details

The defaults give the delay distribution with no censoring and no truncation. Set pwindow and swindow to ask for censoring, and relative_obs_time to ask for truncation. See the method for each model for the arguments it takes.

The result is a plain tibble::tibble(). Pass it to brms::posterior_epred(), brms::posterior_predict(), add_delay_parameter_draws() or delay_parameter_draws(), or to the tidybayes functions add_epred_draws() and add_predicted_draws().

Value

A tibble::tibble() of newdata ready to predict from.

See Also

Other newdata: epidist_newdata.default(), epidist_newdata.epidist_latent_model(), epidist_newdata.epidist_marginal_model(), epidist_newdata.epidist_meta_model(), epidist_newdata.epidist_naive_model()

Examples

prep_obs <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_marginal_model()

# An intercept only model
epidist_newdata(prep_obs)

# A row for each sex
epidist_newdata(prep_obs, sex)

Default method for building newdata

Description

Default method for building newdata

Usage

## Default S3 method:
epidist_newdata(data, ...)

Arguments

data

An epidist data object, such as one returned by as_epidist_marginal_model(), as_epidist_latent_model(), as_epidist_naive_model() or as_epidist_meta_model().

...

Variables to expand into a grid, passed to tidyr::expand(). Supply the variables used in the model formula, such as sex. Each combination of their unique values becomes a row. Supply no variables to get a single row, which is what an intercept only model needs. A variable expanded here keeps its expanded values, so naming it as an argument of the method as well is an error.

Value

This method errors. It is called when data is not an epidist model data object.

See Also

Other newdata: epidist_newdata(), epidist_newdata.epidist_latent_model(), epidist_newdata.epidist_marginal_model(), epidist_newdata.epidist_meta_model(), epidist_newdata.epidist_naive_model()


Build newdata for the latent model

Description

The latent model uses the response, the observation time relative to the primary event, and the primary and secondary censoring windows. This method adds all of them. The response is set to NA because it is the quantity being predicted. The rest are set here.

Usage

## S3 method for class 'epidist_latent_model'
epidist_newdata(data, ..., pwindow = 0, swindow = 0, relative_obs_time = Inf)

Arguments

data

An epidist data object, such as one returned by as_epidist_marginal_model(), as_epidist_latent_model(), as_epidist_naive_model() or as_epidist_meta_model().

...

Variables to expand into a grid, passed to tidyr::expand(). Supply the variables used in the model formula, such as sex. Each combination of their unique values becomes a row. Supply no variables to get a single row, which is what an intercept only model needs. A variable expanded here keeps its expanded values, so naming it as an argument of the method as well is an error.

pwindow

Width of the primary event censoring window. Defaults to 0, which is no censoring.

swindow

Width of the secondary event censoring window. Defaults to 0, which is no censoring.

relative_obs_time

Observation time relative to the primary event. Defaults to Inf, which is no right truncation. brms warns about infinite values in the data when this is Inf. That warning is safe here, because prediction is done in R and never passes the value to Stan.

Details

The defaults give the delay distribution with no censoring and no truncation, which is a continuous probability density function. For a discrete probability mass function with daily censoring set pwindow and swindow to 1. For the delay distribution as it would be seen at a given time set relative_obs_time to that time relative to the primary event.

Value

A tibble::tibble() of newdata ready to predict from.

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), is_epidist_latent_model(), new_epidist_latent_model()

Other newdata: epidist_newdata(), epidist_newdata.default(), epidist_newdata.epidist_marginal_model(), epidist_newdata.epidist_meta_model(), epidist_newdata.epidist_naive_model()

Examples

prep_obs <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_latent_model()

# A row for each sex, with no censoring and no truncation
epidist_newdata(prep_obs, sex)

# The same, with daily censoring
epidist_newdata(prep_obs, sex, pwindow = 1, swindow = 1)

Build newdata for the marginal model

Description

The marginal model uses the response, the observation time relative to the primary event, the primary and secondary censoring windows, the upper bound of the delay and the minimum delay. This method adds all of them. The response and its upper bound are set to 0. brms needs the response in newdata and needs it to be a whole number for this model, but prediction ignores its value. The rest are set here.

Usage

## S3 method for class 'epidist_marginal_model'
epidist_newdata(
  data,
  ...,
  pwindow = 0,
  swindow = 0,
  relative_obs_time = Inf,
  delay_min = 0
)

Arguments

data

An epidist data object, such as one returned by as_epidist_marginal_model(), as_epidist_latent_model(), as_epidist_naive_model() or as_epidist_meta_model().

...

Variables to expand into a grid, passed to tidyr::expand(). Supply the variables used in the model formula, such as sex. Each combination of their unique values becomes a row. Supply no variables to get a single row, which is what an intercept only model needs. A variable expanded here keeps its expanded values, so naming it as an argument of the method as well is an error.

pwindow

Width of the primary event censoring window. Defaults to 0, which is no censoring.

swindow

Width of the secondary event censoring window. Defaults to 0, which is no censoring.

relative_obs_time

Observation time relative to the primary event. Defaults to Inf, which is no right truncation. brms warns about infinite values in the data when this is Inf. That warning is safe here, because prediction is done in R and never passes the value to Stan.

delay_min

Minimum delay, the left truncation point. Defaults to 0, which is no left truncation.

Details

The defaults give the delay distribution with no censoring and no truncation, which is a continuous probability density function. For a discrete probability mass function with daily censoring set pwindow and swindow to 1. For the delay distribution as it would be seen at a given time set relative_obs_time to that time relative to the primary event.

Value

A tibble::tibble() of newdata ready to predict from.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()

Other newdata: epidist_newdata(), epidist_newdata.default(), epidist_newdata.epidist_latent_model(), epidist_newdata.epidist_meta_model(), epidist_newdata.epidist_naive_model()

Examples

prep_obs <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_marginal_model()

# A row for each sex, with no censoring and no truncation
epidist_newdata(prep_obs, sex)

# The same, with daily censoring
epidist_newdata(prep_obs, sex, pwindow = 1, swindow = 1)

Build newdata for the meta model

Description

The meta model holds individual level rows and summary rows in one data frame, telling them apart by the obs_type slot. Prediction is for the delay distribution itself, so this method builds an individual level row. It takes the same arguments as epidist_newdata.epidist_marginal_model(), and fills the slots a summary row would use with the values an individual row carries. The result is what delay_parameter_draws() and add_summaries() need, so there is no need to copy a summary row out of the model data and overwrite its covariates.

Usage

## S3 method for class 'epidist_meta_model'
epidist_newdata(
  data,
  ...,
  pwindow = 0,
  swindow = 0,
  relative_obs_time = Inf,
  delay_min = 0
)

Arguments

data

An epidist data object, such as one returned by as_epidist_marginal_model(), as_epidist_latent_model(), as_epidist_naive_model() or as_epidist_meta_model().

...

Variables to expand into a grid, passed to tidyr::expand(). Supply the variables used in the model formula, such as sex. Each combination of their unique values becomes a row. Supply no variables to get a single row, which is what an intercept only model needs. A variable expanded here keeps its expanded values, so naming it as an argument of the method as well is an error.

pwindow

Width of the primary event censoring window. Defaults to 0, which is no censoring.

swindow

Width of the secondary event censoring window. Defaults to 0, which is no censoring.

relative_obs_time

Observation time relative to the primary event. Defaults to Inf, which is no right truncation. brms warns about infinite values in the data when this is Inf. That warning is safe here, because prediction is done in R and never passes the value to Stan.

delay_min

Minimum delay, the left truncation point. Defaults to 0, which is no left truncation.

Details

A model with a study level term, such as mu ~ 1 + (1 | study), needs either a study column in newdata or re_formula = NA when predicting. Expand study here to predict for each study, or leave it out and pass re_formula = NA for the population level delay. The primary event distribution of the individual level rows is a parameter of the model rather than a column, so it needs nothing here.

Value

A tibble::tibble() of newdata ready to predict from.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()

Other newdata: epidist_newdata(), epidist_newdata.default(), epidist_newdata.epidist_latent_model(), epidist_newdata.epidist_marginal_model(), epidist_newdata.epidist_naive_model()

Examples

estimates <- as_epidist_estimates_data(
  data.frame(
    study = c("A", "A", "B"),
    type = c("mean", "sd", "mean"),
    value = c(7.5, 3.6, 6.4),
    n = c(120, 120, 80),
    relative_obs_time = c(20, 20, Inf),
    trunc_adjusted = c(FALSE, FALSE, TRUE),
    cens_adjusted = c(0, 0, 1)
  )
)
meta <- as_epidist_meta_model(estimates = estimates)

# The population level delay, with no censoring and no truncation
epidist_newdata(meta)

# A row for each study, with daily censoring
epidist_newdata(meta, study, pwindow = 1, swindow = 1)

Build newdata for the naive model

Description

The naive model accounts for neither censoring nor truncation, so the only variable it uses beyond those in the model formula is the response. This method adds it, set to NA because it is the quantity being predicted.

Usage

## S3 method for class 'epidist_naive_model'
epidist_newdata(data, ...)

Arguments

data

An epidist data object, such as one returned by as_epidist_marginal_model(), as_epidist_latent_model(), as_epidist_naive_model() or as_epidist_meta_model().

...

Variables to expand into a grid, passed to tidyr::expand(). Supply the variables used in the model formula, such as sex. Each combination of their unique values becomes a row. Supply no variables to get a single row, which is what an intercept only model needs. A variable expanded here keeps its expanded values, so naming it as an argument of the method as well is an error.

Value

A tibble::tibble() of newdata ready to predict from.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()

Other newdata: epidist_newdata(), epidist_newdata.default(), epidist_newdata.epidist_latent_model(), epidist_newdata.epidist_marginal_model(), epidist_newdata.epidist_meta_model()

Examples

prep_obs <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_naive_model()

# A row for each sex
epidist_newdata(prep_obs, sex)

Define custom prior distributions for epidist models

Description

This function combines model specific prior distributions from epidist_model_prior(), family specific prior distributions from epidist_family_prior(), and user provided prior distributions into a single set of custom priors. Each element overwrites previous elements, such that user provided prior distributions have the highest priority. If a user prior distribution is provided which is not a parameter of the model, a warning will be shown.

Usage

epidist_prior(
  data,
  family,
  formula,
  prior,
  merge = TRUE,
  enforce_presence = FALSE
)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model created using epidist_family().

formula

A symbolic description of the model to be fitted created using epidist_formula().

prior

One or more brmsprior objects created by brms::set_prior() or related functions. These priors are passed to epidist_prior() in the prior argument. Some models have default priors that are automatically added (see epidist_model_prior()). These can be merged with user-provided priors using the merge_priors argument.

merge

If TRUE then merge new priors with existing ones, if FALSE only use new priors. Defaults to TRUE. This may be useful if the built in approaches for merging priors are not flexible enough for a particular use case.

enforce_presence

If TRUE then only allow user priors that match existing default priors. If FALSE then allow user priors that are not present in the default set. Defaults to FALSE.

Details

Note that the matching of priors is imperfect as it does not use brms' internal prior matching functionality. For example, it cannot distinguish between a prior for all coefficients (class = "b") and a prior for a specific coefficient (class = "b" and coef specified).

Some models add parameters which brms does not know about, such as the event windows of the latent model. Priors for these are written using the parameter ~ distribution syntax of brms::set_prior() and are passed to Stan unchanged. A prior written this way replaces any existing prior for the same parameter and is not checked against the parameters of the model. Note that the latent model requires a uniform(0, 1) prior on its event windows.

Value

A brmsprior object containing the combined custom prior distributions.

See Also

Other prior: epidist_family_prior(), epidist_family_prior.default(), epidist_family_prior.gengamma(), epidist_family_prior.lognormal(), epidist_model_prior(), epidist_model_prior.default(), epidist_model_prior.epidist_meta_model()

Examples

data <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model()
family <- epidist_family(data, family = lognormal())
formula <- epidist_formula(data, family = family, formula = mu ~ 1)
epidist_prior(data, family = family, formula = formula, prior = NULL)

Define model specific Stan code

Description

This function is used within epidist() to create any custom Stan code which is injected into brms via the stanvars argument. It is unlikely that as a user you will need this function, but we export it nonetheless to be transparent about what exactly is happening inside of a call to epidist().

Usage

epidist_stancode(data, ...)

Arguments

data

An object with class corresponding to an implemented model.

...

Additional arguments passed to fn method.

Value

A list of stanvars objects, or NULL when none are needed.

See Also

Other stan: epidist_stancode.default()

Examples

data <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model()
family <- epidist_family(data, family = lognormal())
formula <- epidist_formula(data, family = family, formula = mu ~ 1)
epidist_stancode(data, family = family, formula = formula)

Default method for defining model specific Stan code

Description

Default method for defining model specific Stan code

Usage

## Default S3 method:
epidist_stancode(data, ...)

Arguments

data

An object with class corresponding to an implemented model.

...

Additional arguments passed to fn method.

Value

A list of stanvars objects, or NULL when none are needed.

See Also

Other stan: epidist_stancode()


Define the Stan code of the naive model

Description

The naive model uses the brms family as it is, so it only needs Stan code for a family brms does not have, such as gengamma(), whose density brms calls by name.

Usage

## S3 method for class 'epidist_naive_model'
epidist_stancode(
  data,
  family = epidist_family(data),
  formula = epidist_formula(data),
  ...
)

Arguments

data

An object with class corresponding to an implemented model.

family

The epidist family object specifying the distribution

formula

The model formula

...

Additional arguments passed to fn method.

Value

A list of stanvars objects, or NULL when none are needed.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()


Unique combinations of the predictors in a model

Description

Returns one row of the model data for each unique combination of the variables used to predict the delay distribution parameters. Passing this to delay_parameter_draws() gives one set of draws per combination rather than one per observation, which is the same result with far fewer draws.

Usage

epidist_strata(object, vars = NULL)

Arguments

object

A model fit with epidist().

vars

A character vector of variables to take unique combinations of. If NULL, the default, the variables in the distributional parameter formulas are used.

Details

The variables are taken from the right hand side of each distributional parameter formula. The remaining columns are kept from the first row of the model data in which each combination occurs. This keeps the model variables that brms requires in newdata, such as the relative observation time and the censoring windows for the latent and marginal models. Those variables do not enter the distributional parameters, so the values kept do not change the draws.

A model with only an intercept has no predictors and so returns a single row. A continuous predictor has as many combinations as it has distinct values, so consider passing vars and a grid of your own instead.

Value

A tibble with one row per unique combination of vars, with the combination columns first.

See Also

Other postprocess: add_summaries(), as_dist_spec.epidist_fit(), delay_parameter_draws(), delay_summary_draws(), epidist_delay_draws

Examples


fit <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model() |>
  epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))

epidist_strata(fit)


Transform data for an epidist model

Description

This function is used within epidist() to transform data before passing to brms. It dispatches to epidist_transform_data_model(), which is the generic a custom model implements. This wrapper is internal; extensions should write a method for epidist_transform_data_model() instead.

Usage

epidist_transform_data(data, family, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model created using epidist_family().

formula

A formula object created using epidist_formula().

...

Additional arguments passed to fn method.

Value

The data transformed ready for fitting.

See Also

Other transform_data: epidist_transform_data_model(), epidist_transform_data_model.default()


The model-specific parts of an epidist_transform_data() call

Description

The model-specific parts of an epidist_transform_data() call

Usage

epidist_transform_data_model(data, family, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model created using epidist_family().

formula

A formula object created using epidist_formula().

...

Additional arguments passed to fn method.

Value

The data transformed ready for fitting.

See Also

Other transform_data: epidist_transform_data(), epidist_transform_data_model.default()


Default method for transforming data for a model

Description

Default method for transforming data for a model

Usage

## Default S3 method:
epidist_transform_data_model(data, family, formula, ...)

Arguments

data

An object with class corresponding to an implemented model.

family

A description of the response distribution and link function to be used in the model created using epidist_family().

formula

A formula object created using epidist_formula().

...

Additional arguments passed to fn method.

Value

The data transformed ready for fitting.

See Also

Other transform_data: epidist_transform_data(), epidist_transform_data_model()


Transform data for the marginal model

Description

This method transforms data into the format required by the marginal model by:

  1. Identifying required columns for the marginal model

  2. Summarising the data by counting unique combinations of these columns and any variables in the model formula using .summarise_n_by_formula()

  3. Converting the summarised data to a marginal model object using new_epidist_marginal_model() and checking it with assert_epidist()

  4. Informing the user about any data aggregation that occurred using .inform_data_summarised()

Usage

## S3 method for class 'epidist_marginal_model'
epidist_transform_data_model(data, family, formula, ...)

Arguments

data

The data to transform

family

The epidist family object specifying the distribution

formula

The model formula

...

Additional arguments passed to methods

Value

The data transformed ready for fitting.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), is_epidist_marginal_model(), new_epidist_marginal_model()


Transform data for the meta model

Description

Individual level rows are summarised by counting unique combinations of the meta model columns and any variables in the model formula, exactly as epidist_transform_data_model.epidist_marginal_model() does. Summary rows are passed through unchanged because each one is a distinct reported quantity.

Usage

## S3 method for class 'epidist_meta_model'
epidist_transform_data_model(data, family, formula, ...)

Arguments

data

The data to transform

family

The epidist family object specifying the distribution

formula

The model formula

...

Additional arguments passed to methods

Value

An epidist_meta_model object with the individual level rows summarised and the summary rows unchanged.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), is_epidist_meta_model(), new_epidist_meta_model()


Transform data for the naive model

Description

This method transforms data into the format required by the naive model by:

  1. Identifying required columns for the naive model

  2. Summarising the data by counting unique combinations of these columns and any variables in the model formula using .summarise_n_by_formula()

  3. Converting the summarised data to a naive model object using new_epidist_naive_model() and checking it with assert_epidist()

  4. Informing the user about any data aggregation that occurred using .inform_data_summarised()

Usage

## S3 method for class 'epidist_naive_model'
epidist_transform_data_model(data, family, formula, ...)

Arguments

data

The data to transform

family

The epidist family object specifying the distribution

formula

The model formula

...

Additional arguments passed to methods

Value

The data transformed ready for fitting.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), is_epidist_naive_model(), new_epidist_naive_model()


Generalised gamma delay distribution family

Description

A brms custom family for the generalised gamma distribution in the Prentice (1974) parameterisation of flexsurv::dgengamma(). mu and sigma are the location and scale of the log delay and Q is a positive shape. The Weibull (Q = 1) and gamma (Q = sigma) families are special cases and the lognormal is the limit as Q goes to zero. It needs the flexsurv package and works with every epidist model.

Usage

gengamma(link = "identity", link_sigma = "log", link_Q = "log")

Arguments

link, link_sigma, link_Q

The link functions of mu, sigma and Q.

Value

A brms custom family object.

References

Prentice, R. L. (1974). A log gamma model and its maximum likelihood estimation. Biometrika, 61(3), 539-544. doi:10.1093/biomet/61.3.539

See Also

Other family: epidist_family(), epidist_family_model(), epidist_family_model.default(), epidist_family_param(), epidist_family_param.default(), epidist_family_param.gengamma()

Examples


gengamma()


Check if data has the epidist_aggregate_data class

Description

Check if data has the epidist_aggregate_data class

Usage

is_epidist_aggregate_data(data)

Arguments

data

The data to convert

Value

A logical, TRUE if data inherits from epidist_aggregate_data and FALSE otherwise.

See Also

Other aggregate_data: as_epidist_aggregate_data(), as_epidist_aggregate_data.data.frame(), as_epidist_aggregate_data.default(), as_epidist_aggregate_data.epidist_linelist_data(), assert_epidist.epidist_aggregate_data(), new_epidist_aggregate_data()


Check if data has the epidist_data class

Description

All epidist data objects carry this class in addition to their specific class. See epidist_data for the methods it provides.

Usage

is_epidist_data(data)

Arguments

data

An object.

Value

A logical, TRUE if data inherits from epidist_data and FALSE otherwise.

See Also

Other epidist_data: epidist_data

Examples

sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  is_epidist_data()

Check if data has the epidist_estimates_data class

Description

Check if data has the epidist_estimates_data class

Usage

is_epidist_estimates_data(data)

Arguments

data

The data to convert

Value

A logical, TRUE if data inherits from epidist_estimates_data and FALSE otherwise.

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), new_epidist_estimates_data()

Examples

is_epidist_estimates_data(data.frame())
is_epidist_estimates_data(new_epidist_estimates_data(data.frame()))

Check if data has the epidist_latent_model class

Description

Check if data has the epidist_latent_model class

Usage

is_epidist_latent_model(data)

Arguments

data

An object

Value

A logical, TRUE if data inherits from epidist_latent_model and FALSE otherwise.

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), new_epidist_latent_model()


Check if data has the epidist_linelist_data class

Description

Check if data has the epidist_linelist_data class

Usage

is_epidist_linelist_data(data)

Arguments

data

The data to convert

Value

A logical, TRUE if data inherits from epidist_linelist_data and FALSE otherwise.

See Also

Other linelist_data: as_epidist_linelist_data(), as_epidist_linelist_data.data.frame(), as_epidist_linelist_data.default(), as_epidist_linelist_data.epidist_aggregate_data(), assert_epidist.epidist_linelist_data(), new_epidist_linelist_data()


Check if data has the epidist_marginal_model class

Description

Check if data has the epidist_marginal_model class

Usage

is_epidist_marginal_model(data)

Arguments

data

A data.frame containing line list data

Value

A logical, TRUE if data inherits from epidist_marginal_model and FALSE otherwise.

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), new_epidist_marginal_model()


Check if data has the epidist_meta_model class

Description

Check if data has the epidist_meta_model class

Usage

is_epidist_meta_model(data)

Arguments

data

A data.frame to check.

Value

A logical, TRUE if data inherits from epidist_meta_model and FALSE otherwise.

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), new_epidist_meta_model()

Examples

is_epidist_meta_model(data.frame())
is_epidist_meta_model(new_epidist_meta_model(data.frame()))

Check if an object has the epidist_multivariate class

Description

Check if an object has the epidist_multivariate class

Usage

is_epidist_multivariate(data)

Arguments

data

An object.

Value

A logical.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.data.frame(), as_epidist_multivariate.matrix(), assert_epidist.epidist_multivariate(), new_epidist_multivariate(), print.epidist_multivariate(), vcov.epidist_multivariate()

Examples

is_epidist_multivariate(1)

Check if data has the epidist_naive_model class

Description

Check if data has the epidist_naive_model class

Usage

is_epidist_naive_model(data)

Arguments

data

An object.

Value

A logical, TRUE if data inherits from epidist_naive_model and FALSE otherwise.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), new_epidist_naive_model()


Class constructor for epidist_aggregate_data objects

Description

Class constructor for epidist_aggregate_data objects

Usage

new_epidist_aggregate_data(data)

Arguments

data

A data.frame to convert

Value

An object of class epidist_aggregate_data

See Also

Other aggregate_data: as_epidist_aggregate_data(), as_epidist_aggregate_data.data.frame(), as_epidist_aggregate_data.default(), as_epidist_aggregate_data.epidist_linelist_data(), assert_epidist.epidist_aggregate_data(), is_epidist_aggregate_data()

Examples

df <- new_epidist_aggregate_data(data.frame())
class(df)

Class constructor for epidist_estimates_data objects

Description

Class constructor for epidist_estimates_data objects

Usage

new_epidist_estimates_data(data)

Arguments

data

A data.frame to convert

Value

An object of class epidist_estimates_data

See Also

Other estimates_data: as_epidist_estimates_data(), as_epidist_estimates_data.data.frame(), as_epidist_estimates_data.epidist_estimates_data(), as_epidist_estimates_data.epidist_multivariate(), as_epidist_estimates_data.list(), assert_epidist.epidist_estimates_data(), epidist_estimates_epireview(), epidist_estimates_parameters(), epidist_estimates_summaries(), is_epidist_estimates_data()

Examples

df <- new_epidist_estimates_data(data.frame())
class(df)

Class constructor for epidist_latent_model objects

Description

Class constructor for epidist_latent_model objects

Usage

new_epidist_latent_model(data, primary = .primary_choices(), ...)

Arguments

data

An object to be set with the class epidist_latent_model

primary

The distribution of the primary event within its censoring window. "uniform", the default, assumes it is equally likely at any point. "expgrowth" tilts it, with the growth rate estimated as the pgrowth distributional parameter.

...

Additional arguments passed to methods.

Value

An object of class epidist_latent_model

See Also

Other latent_model: as_epidist_latent_model(), as_epidist_latent_model.epidist_aggregate_data(), as_epidist_latent_model.epidist_linelist_data(), epidist_family_model.epidist_latent_model(), epidist_formula_model.epidist_latent_model(), epidist_model_prior.epidist_latent_model(), epidist_newdata.epidist_latent_model(), is_epidist_latent_model()


Class constructor for epidist_linelist_data objects

Description

Class constructor for epidist_linelist_data objects

Usage

new_epidist_linelist_data(data)

Arguments

data

A data.frame to convert

Value

An object of class epidist_linelist_data

See Also

Other linelist_data: as_epidist_linelist_data(), as_epidist_linelist_data.data.frame(), as_epidist_linelist_data.default(), as_epidist_linelist_data.epidist_aggregate_data(), assert_epidist.epidist_linelist_data(), is_epidist_linelist_data()


Class constructor for epidist_marginal_model objects

Description

Class constructor for epidist_marginal_model objects

Usage

new_epidist_marginal_model(data, primary = .primary_choices())

Arguments

data

A data.frame to convert

primary

The primary event distribution, "uniform" or "expgrowth".

Value

An object of class epidist_marginal_model

See Also

Other marginal_model: as_epidist_marginal_model(), as_epidist_marginal_model.epidist_aggregate_data(), as_epidist_marginal_model.epidist_linelist_data(), epidist_family_model.epidist_marginal_model(), epidist_formula_model.epidist_marginal_model(), epidist_newdata.epidist_marginal_model(), epidist_transform_data_model.epidist_marginal_model(), is_epidist_marginal_model()


Class constructor for epidist_meta_model objects

Description

Class constructor for epidist_meta_model objects

Usage

new_epidist_meta_model(data, primary = .primary_choices())

Arguments

data

A data.frame to convert

primary

The primary event distribution of the individual level rows, "uniform" or "expgrowth". Summary rows use their growth_rate metadata instead, or the pgrowth parameter where their growth_known slot is 0.

Value

An object of class epidist_meta_model

See Also

Other meta_model: as_epidist_meta_model(), as_epidist_meta_model.NULL(), as_epidist_meta_model.epidist_aggregate_data(), as_epidist_meta_model.epidist_estimates_data(), as_epidist_meta_model.epidist_linelist_data(), assert_epidist.epidist_meta_model(), epidist_family_model.epidist_meta_model(), epidist_formula_model.epidist_meta_model(), epidist_meta_leave_one_out(), epidist_model_prior.epidist_meta_model(), epidist_newdata.epidist_meta_model(), epidist_transform_data_model.epidist_meta_model(), is_epidist_meta_model()


Class constructor for epidist_multivariate objects

Description

Use this where a study published a mean vector and a covariance matrix directly, rather than draws they can be computed from. Converting the object with a family, which needs the draws themselves, is then unavailable.

Usage

new_epidist_multivariate(
  value,
  vcov,
  params,
  index = 1,
  n_draws = NA_integer_,
  draws = NULL
)

Arguments

value

A named numeric vector of the mean of each element.

vcov

The covariance matrix of value.

params

A character vector of the parameter names, in order.

index

The trajectory points, in order. Defaults to a single point.

n_draws

The number of draws value and vcov were computed from, or NA where they were published directly.

draws

A matrix of draws with one row per draw and one column per element of value, or NULL.

Value

An object of class epidist_multivariate.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.data.frame(), as_epidist_multivariate.matrix(), assert_epidist.epidist_multivariate(), is_epidist_multivariate(), print.epidist_multivariate(), vcov.epidist_multivariate()

Examples

new_epidist_multivariate(
  value = c(mean = 7.5, sd = 3.6),
  vcov = matrix(c(0.09, 0.02, 0.02, 0.04), nrow = 2),
  params = c("mean", "sd")
)

Class constructor for epidist_naive_model objects

Description

Class constructor for epidist_naive_model objects

Usage

new_epidist_naive_model(data)

Arguments

data

An object to be set with the class epidist_naive_model.

Value

An object of class epidist_naive_model.

See Also

Other naive_model: as_epidist_naive_model(), as_epidist_naive_model.epidist_aggregate_data(), as_epidist_naive_model.epidist_linelist_data(), epidist_formula_model.epidist_naive_model(), epidist_newdata.epidist_naive_model(), epidist_stancode.epidist_naive_model(), epidist_transform_data_model.epidist_naive_model(), is_epidist_naive_model()


Plot posterior draws of the delay distribution

Description

Plots the draws returned by delay_parameter_draws(), delay_summary_draws() and add_summaries(). The default, type = "parameters", draws the posterior density of each distributional parameter, and of any summary column add_summaries() added, in its own panel. type = "delay" draws the delay distribution the draws imply over a grid of delays, as the posterior median density with a ribbon between two quantiles, or as one line per draw when ndraws is given.

Usage

## S3 method for class 'epidist_delay_draws'
plot(x, ...)

## S3 method for class 'epidist_delay_draws'
autoplot(
  object,
  type = c("parameters", "delay"),
  by = NULL,
  pars = NULL,
  true_values = NULL,
  ndraws = NULL,
  probs = c(0.05, 0.95),
  max_delay = NULL,
  family = NULL,
  ...
)

Arguments

x, object

An epidist_delay_draws object, as returned by delay_parameter_draws(), delay_summary_draws() or add_summaries().

...

Passed from plot() to autoplot(). Unused otherwise.

type

Either "parameters", the default, to plot the posterior density of each parameter, or "delay" to plot the delay distribution the draws imply.

by

A character vector of columns of object that define the strata to colour by. If NULL, the default, the variables recorded on object are used. See the details.

pars

A character vector of the columns to plot when type = "parameters". If NULL, the default, the distributional parameters of the family are plotted, along with the mean, sd and quantile columns present.

true_values

A named numeric vector of true parameter values to mark with dashed vertical lines when type = "parameters". The names must be among the parameters plotted.

ndraws

The number of draws per stratum to plot the delay distribution of when type = "delay", one line each, sampled at random. If NULL, the default, the posterior median density is drawn with a ribbon between the probs quantiles instead.

probs

A numeric vector of two probabilities giving the quantiles the ribbon spans when type = "delay". Defaults to c(0.05, 0.95).

max_delay

The largest delay to evaluate the delay distribution at when type = "delay". If NULL, the default, the posterior median of the 99% quantile of the delay distribution is used.

family

A model fit with epidist(), a brms family, or the name of one, giving the delay distribution. If NULL, the default, the family recorded on object is used.

Details

The strata of the draws are coloured. By default they are the unique combinations of the variables in the distributional parameter formulas, which delay_parameter_draws() records, and each .row when the draws have several rows of newdata but no such variables. Pass by to stratify by other columns of the draws. The columns in by are kept in the plot data, so the plot can be faceted by them.

The delay distribution is evaluated with the density of the family for the lognormal, gamma and Weibull families. For any other family, delays are simulated from each draw as in add_summaries() and their density is estimated with stats::density(). Either way the density is evaluated at every draw, so thin the draws with the ndraws argument of delay_parameter_draws(), or build newdata with epidist_strata(), when there are many.

plot() and autoplot() are the same function. Both need ggplot2.

The plot is drawn with ggplot2::theme_minimal() and the colour blind friendly palette the package documentation uses. Add a theme or a scale of your own to the returned plot to override either.

Value

A ggplot object.

See Also

delay_parameter_draws() and delay_summary_draws() for the draws, and plot_events() to plot the data.

Other plot: plot_delays(), plot_delays.default(), plot_delays.epidist_fit(), plot_delays.epidist_linelist_data(), plot_delays.list(), plot_events()

Examples


draws <- data.frame(
  mu = rnorm(200, 1.8, 0.05),
  sigma = exp(rnorm(200, log(0.5), 0.05))
) |>
  add_summaries(family = "lognormal", probs = 0.5)
plot(draws, true_values = c(mu = 1.8, sigma = 0.5))
plot(draws, type = "delay")
plot(draws, type = "delay", ndraws = 50)


Plot the observed delay distribution

Description

Bins the delay between the lower bounds of the primary and secondary event windows of each case, the delay as it was observed, and draws the proportion of cases in each bin as a column. Pass a named list of datasets to compare their observed delays, a reference distribution to draw the delay distribution they are a sample of, or a model fitted with epidist() to draw the delays it predicts over the delays it was fitted to.

Usage

plot_delays(x, ...)

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

...

Passed to the method.

Details

The observed delay is stime_lwr - ptime_lwr, the delay between the days the events were reported on when the data is censored daily. It is the response the naive model fits, so the plot shows the data that model sees rather than the delay distribution itself. Censoring and truncation both bias it, which is what the reference distribution makes visible.

Counts are weighted by the n column when the data has one, so aggregate data gives the same plot as the linelist it was aggregated from.

Proportions are within each stratum, so datasets of different sizes can be compared. The density is the proportion divided by binwidth, which puts the columns on the scale of the reference distribution.

The columns named by by are kept in the plot data, so the plot can be faceted by them.

Value

A ggplot object.

See Also

plot_events() to plot the event windows the delays come from, and plot.epidist_delay_draws() to plot a fitted delay distribution.

Other plot: plot.epidist_delay_draws(), plot_delays.default(), plot_delays.epidist_fit(), plot_delays.epidist_linelist_data(), plot_delays.list(), plot_events()

Examples


linelist <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  )
plot_delays(linelist)
plot_delays(linelist, reference = c(mu = 1.8, sigma = 1))
plot_delays(list(All = linelist, Early = head(linelist, 500)))


Default method for plotting observed delays

Description

Default method for plotting observed delays

Usage

## Default S3 method:
plot_delays(x, ...)

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

...

Passed to the method.

Value

This method errors. It is called when x is neither delay data nor a fitted model.

See Also

Other plot: plot.epidist_delay_draws(), plot_delays(), plot_delays.epidist_fit(), plot_delays.epidist_linelist_data(), plot_delays.list(), plot_events()


Plot the delays a fitted model predicts over the delays it was fitted to

Description

Draws the observed delays of the data the model was fitted to as columns, as plot_delays.epidist_linelist_data() does, and the delays the model predicts for the same cases over them, as the posterior median proportion in each bin with a ribbon between two quantiles.

Usage

## S3 method for class 'epidist_fit'
plot_delays(
  x,
  by = NULL,
  binwidth = 1,
  ndraws = 100,
  probs = c(0.05, 0.95),
  ...
)

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

by

A character vector of columns of the model data that define the strata to colour by. If NULL, the default, the variables in the distributional parameter formulas are used, as epidist_strata() does.

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

ndraws

The number of posterior draws to predict from, sampled at random. Defaults to 100, which is enough for the median and the quantiles of a binned distribution and bounds the size of the prediction. Use NULL to predict from every draw.

probs

A numeric vector of two probabilities giving the quantiles the ribbon spans. Defaults to c(0.05, 0.95).

...

Passed to the method.

Details

The predictions come from brms::posterior_predict(), so they are of the delay as it was observed, under the censoring and truncation of each case. That makes the plot a posterior predictive check of the observed delays rather than a picture of the delay distribution itself, which plot.epidist_delay_draws() draws.

Both the columns and the predictions are proportions within each stratum, so a bin holds the share of cases with that delay. Bins where neither the data nor the predictive interval puts any mass are dropped, which trims the tail of the predictive distribution.

Value

A ggplot object.

See Also

Other plot: plot.epidist_delay_draws(), plot_delays(), plot_delays.default(), plot_delays.epidist_linelist_data(), plot_delays.list(), plot_events()

Examples



fit <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  ) |>
  as_epidist_aggregate_data() |>
  as_epidist_marginal_model() |>
  epidist(chains = 2, cores = 2, refresh = ifelse(interactive(), 250, 0))

plot_delays(fit)



Plot the observed delays of a dataset

Description

Plot the observed delays of a dataset

Usage

## S3 method for class 'epidist_linelist_data'
plot_delays(
  x,
  by = NULL,
  binwidth = 1,
  delay_min = NULL,
  reference = NULL,
  family = "lognormal",
  ...
)

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

by

A string naming a column of x to stratify the delays by.

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

delay_min

The minimum delay to mark with a dashed vertical line, as a number on the scale of the event times. If NULL, the default, the delay_min column of x is used when it has one and no line is drawn otherwise.

reference

A named numeric vector of the distributional parameters of a delay distribution to draw over the columns, as c(mu = 1.8, sigma = 0.5) for a lognormal delay. If NULL, the default, no distribution is drawn.

family

A brms family, or the name of one, giving the delay distribution reference holds the parameters of. Defaults to "lognormal".

...

Passed to the method.

Value

A ggplot object.

See Also

Other plot: plot.epidist_delay_draws(), plot_delays(), plot_delays.default(), plot_delays.epidist_fit(), plot_delays.list(), plot_events()


Compare the observed delays of several datasets

Description

The names of x label the strata.

Usage

## S3 method for class 'list'
plot_delays(
  x,
  by = NULL,
  binwidth = 1,
  delay_min = NULL,
  reference = NULL,
  family = "lognormal",
  ...
)

Arguments

x

An epidist_linelist_data or epidist_aggregate_data object, a named list of them to compare, or a model fitted with epidist().

by

A string naming a column of x to stratify the delays by.

binwidth

The width of the delay bins, on the scale of the event times. Defaults to 1, the daily censoring the data usually has.

delay_min

The minimum delay to mark with a dashed vertical line, as a number on the scale of the event times. If NULL, the default, the delay_min column of x is used when it has one and no line is drawn otherwise.

reference

A named numeric vector of the distributional parameters of a delay distribution to draw over the columns, as c(mu = 1.8, sigma = 0.5) for a lognormal delay. If NULL, the default, no distribution is drawn.

family

A brms family, or the name of one, giving the delay distribution reference holds the parameters of. Defaults to "lognormal".

...

Passed to the method.

Value

A ggplot object.

See Also

Other plot: plot.epidist_delay_draws(), plot_delays(), plot_delays.default(), plot_delays.epidist_fit(), plot_delays.epidist_linelist_data(), plot_events()


Plot the primary and secondary event windows of each case

Description

Draws one row per case, ordered by primary event time, with the primary and secondary event windows as horizontal segments joined by a line for the delay between them. A dashed vertical line marks the observation time when one is given. This is the plot the vignettes use to show how censoring and truncation obscure the delays.

Usage

plot_events(data, obs_time = NULL, by = NULL, n = 200)

Arguments

data

An epidist_linelist_data object.

obs_time

The observation time to mark with a dashed vertical line, as a date or a number on the scale of the event times. If NULL, the default, no line is drawn.

by

A string naming a column of data to colour the cases by. If NULL, the default, the primary and secondary event windows are coloured differently instead.

n

The maximum number of cases to draw. Defaults to 200. Use Inf to draw every case.

Details

Dates are used when data has the date columns that as_epidist_linelist_data.data.frame() keeps, pdate_lwr and so on, and the numeric time columns otherwise. obs_time must be on the same scale.

Cases are ordered by the lower bound of their primary event window and numbered in that order, so the vertical axis shows the growth of the outbreak. When there are more than n cases, n evenly spaced cases in that order are drawn. This keeps the shape of the outbreak without over-plotting.

The plot is drawn with ggplot2::theme_minimal() and the colour blind friendly palette the package documentation uses. Add a theme or a scale of your own to the returned plot to override either. The column named by by is kept in the plot data, so the plot can be faceted by it.

Value

A ggplot object.

See Also

Other plot: plot.epidist_delay_draws(), plot_delays(), plot_delays.default(), plot_delays.epidist_fit(), plot_delays.epidist_linelist_data(), plot_delays.list()

Examples


linelist <- sierra_leone_ebola_data |>
  as_epidist_linelist_data(
    pdate_lwr = "date_of_symptom_onset",
    sdate_lwr = "date_of_sample_tested"
  )
plot_events(linelist, n = 100)
plot_events(linelist, obs_time = as.Date("2014-10-01"), by = "district")


Print an epidist_multivariate object

Description

Print an epidist_multivariate object

Usage

## S3 method for class 'epidist_multivariate'
print(x, ...)

Arguments

x

An epidist_multivariate object.

...

Not used.

Value

The input, invisibly.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.data.frame(), as_epidist_multivariate.matrix(), assert_epidist.epidist_multivariate(), is_epidist_multivariate(), new_epidist_multivariate(), vcov.epidist_multivariate()

Examples

print(new_epidist_multivariate(
  value = c(mean = 7.5, sd = 3.6),
  vcov = matrix(c(0.09, 0.02, 0.02, 0.04), nrow = 2),
  params = c("mean", "sd")
))

Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

brms

bf(), lognormal(), weibull()

stats

Gamma()


Ebola linelist data from Fang et al. (2016)

Description

Linelist data for the Ebola virus collected in Sierra Leone. If you use this data in your work, please cite the corresponding paper.

Usage

sierra_leone_ebola_data

Format

A tibble with 8,358 rows and 7 columns:

id

Unique identification number for the case

age

Age as numeric

sex

Sex as character, either "Female", "Male" or NA

date_of_symptom_onset

The date symptoms began

date_of_sample_tested

The date the sample was tested

district

The district (ADM2)

chiefdom

The chiefdom (ADM3)

Source

doi:10.1073/pnas.1518587113


Convert simulated event times to dates

Description

Takes the continuous event times produced by simulate_gillespie() and simulate_secondary() and returns the dates an analyst would actually receive. Event times are floored to their reporting window, so each event is known only by the window it fell in, and are then offset from outbreak_start_date.

Usage

simulate_dates(
  data,
  outbreak_start_date = as.Date("2024-01-01"),
  primary_window = 1,
  secondary_window = primary_window,
  obs_time = NULL,
  keep_times = FALSE
)

Arguments

data

A data.frame with numeric ptime and stime columns, as returned by simulate_secondary().

outbreak_start_date

The date the outbreak started, corresponding to time zero.

primary_window

Width of the primary event reporting window in days. Either a single value used for every observation, or one value per row of data. The default of 1 gives daily reporting. Use 7 for weekly.

secondary_window

Width of the secondary event reporting window in days, in the same form as primary_window. Defaults to primary_window, so the two events share a reporting interval unless you say otherwise.

obs_time

Optional numeric observation time, in the same units as ptime and stime. When supplied an obs_date column is added. When NULL, the default, no observation date is added and as_epidist_linelist_data() falls back to the day after the last secondary event.

keep_times

Whether to keep the underlying numeric times. Useful when comparing estimates against the values used to simulate.

Details

The returned columns are named to match as_epidist_linelist_data(), so the output can be passed straight to it.

Value

A data.frame with pdate_lwr, pdate_upr, sdate_lwr and sdate_upr columns, and obs_date when obs_time is supplied.

See Also

Other simulate: simulate_exponential_cases(), simulate_gillespie(), simulate_secondary(), simulate_study(), simulate_uniform_cases()

Examples

simulate_gillespie(seed = 1) |>
  simulate_secondary(meanlog = 1.8, sdlog = 0.5) |>
  simulate_dates(outbreak_start_date = as.Date("2024-02-01")) |>
  head()

Simulate exponential cases

Description

This function simulates cases from an exponential distribution. The user may specify the rate parameter r, the sample size, and the upper bound of the survival time. If the rate parameter is 0, then this function defaults to the uniform distribution.

Usage

simulate_exponential_cases(r = 0.2, sample_size = 10000, seed = NULL, t = 30)

Arguments

r

The exponential growth rate parameter. Defaults to 0.2.

sample_size

The number of cases to simulate. Defaults to 10000.

seed

The random seed to be used in the simulation process. Defaults to NULL, which leaves the random number generator as it is.

t

Upper bound of the survival time. Defaults to 30.

Value

A data.frame with two columns: case (case number) and ptime (primary event time).

See Also

Other simulate: simulate_dates(), simulate_gillespie(), simulate_secondary(), simulate_study(), simulate_uniform_cases()

Examples

simulate_exponential_cases(r = 0.2, sample_size = 5, seed = 101)

Simulate cases from a stochastic SIR model

Description

This function simulates cases from an stochastic SIR model. The user may specify the initial epidemic growth rate r, the rate of recovery gamma \gamma, the initial number of infected cases I_0, and the total population size N.

Usage

simulate_gillespie(r = 0.2, gamma = 1/7, I0 = 50, N = 10000, seed = NULL)

Arguments

r

The initial epidemic growth rate. Defaults to 0.2.

gamma

The rate of recovery. Defaults to 1/7.

I0

The initial number of infected people. Defaults to 50.

N

The total population size. Defaults to 10000.

seed

The random seed to be used in the simulation process. Defaults to NULL, which leaves the random number generator as it is.

Value

A data.frame with two columns: case (case number) and ptime (primary event time).

See Also

Other simulate: simulate_dates(), simulate_exponential_cases(), simulate_secondary(), simulate_study(), simulate_uniform_cases()

Examples

cases <- simulate_gillespie(
  r = 0.2, gamma = 1 / 7, I0 = 5, N = 50, seed = 101
)
head(cases)

Simulate secondary events based on a delay distribution

Description

This function simulates secondary events based on a given delay distribution. The input dataset should have the primary event times in a column named ptime.

Usage

simulate_secondary(data, dist = rlnorm, ...)

Arguments

data

A data frame with the primary event times.

dist

The delay distribution to be used. Defaults to rlnorm().

...

Arguments to be passed to the delay distribution function.

Value

A data.frame that augments data with two new columns: delay (secondary event latency) and stime (the time of the secondary event).

See Also

Other simulate: simulate_dates(), simulate_exponential_cases(), simulate_gillespie(), simulate_study(), simulate_uniform_cases()

Examples

simulate_uniform_cases(sample_size = 5) |>
  simulate_secondary(meanlog = 1.8, sdlog = 0.5)

Simulate the summaries a published study would have reported

Description

Applies the observation and estimation procedure of one study to a simulated line list and returns the summaries that study would have published, with the metadata as_epidist_estimates_data() needs to forward model them. The line list must carry the exact event times that simulate_dates() keeps when keep_times = TRUE, because the censoring adjustments a study may have used differ in how much of each event time they saw.

Usage

simulate_study(
  data,
  study,
  report = c("moments", "quantiles", "multivariate", "mean_se"),
  probs = c(0.25, 0.5, 0.75),
  cens_adjusted = 0,
  trunc_adjusted = FALSE,
  trunc_design = c("cohort", "accrual"),
  relative_obs_time = Inf,
  delay_min = 0,
  growth_rate = 0,
  n = NULL,
  max_delay = NULL,
  ...
)

Arguments

data

An epidist_linelist_data object built from simulated event times, with the exact ptime and stime columns kept by simulate_dates() when keep_times = TRUE. Every case must use the same primary window and the same secondary window.

study

A string labelling the study.

report

What the study published. "moments" gives a mean and a standard deviation with the sample size, "quantiles" the quantiles at probs with the sample size, "multivariate" the mean and standard deviation with their bootstrap covariance, through new_epidist_multivariate(), and "mean_se" a mean with its standard error and no sample size.

probs

The probabilities of the quantiles a "quantiles" study reports.

cens_adjusted

The censoring adjustment code the study used, one of 0 to 4 as described above and in as_epidist_estimates_data().

trunc_adjusted

Whether the study corrected for right truncation. If FALSE, the study's truncation is applied to the line list.

trunc_design

How the study stopped collecting, "cohort" or "accrual". Only used when trunc_adjusted is FALSE.

relative_obs_time

The study's observation time. For a "cohort" design this bounds each delay, and for an "accrual" design it is the length of the collection window from the start of the line list. Defaults to Inf, which is only allowed for a study that adjusted for right truncation.

delay_min

The smallest measured delay the study counted. Cases below it are dropped.

growth_rate

The growth rate the study is described by. Passed through as metadata and not used to select cases, so it should be the rate the line list was simulated with, or NA for a study that estimates it, see as_epidist_estimates_data(). A growth_rate_sd passes through ....

n

The number of cases the study sampled from those it could have seen. Defaults to NULL, meaning all of them.

max_delay

The grid cutoff passed through to as_epidist_estimates_data(), or NULL for its default.

...

Further columns, such as covariates, added to every row of the result.

Details

The study measures each delay as its censoring adjustment code says, drops the cases its truncation would have hidden from it, drops delays below delay_min, takes a sample of n cases and summarises them. Each step follows the estimand the meta model uses for that code, see vignette("model").

The measured delay is, by cens_adjusted code:

A study that did not adjust for right truncation sees a case only if its delay had completed by its observation time. Under a "cohort" design the delay the observation time bounds is the underlying one, so a study on the discrete grid (codes 0 and 3) keeps a case only if the whole window its delay fell in is below relative_obs_time, and a code 4 study keeps a case if its code 2 delay is. Under an "accrual" design the study stopped at a calendar date relative_obs_time after the start of the line list, and keeps every case whose secondary event fell before it.

Sampling n cases and the bootstrap behind report = "multivariate" use the random number generator, so set a seed for a reproducible study.

The advisory checks of as_epidist_estimates_data() do not run on the result. They run once on the combined object when several studies are passed to as_epidist_estimates_data() in a list.

Value

An epidist_estimates_data object with one row per reported summary.

See Also

Other simulate: simulate_dates(), simulate_exponential_cases(), simulate_gillespie(), simulate_secondary(), simulate_uniform_cases()

Examples

linelist <- simulate_gillespie(seed = 1) |>
  simulate_secondary(meanlog = 1.8, sdlog = 0.5) |>
  simulate_dates(keep_times = TRUE) |>
  as_epidist_linelist_data()
simulate_study(
  linelist, "naive snapshot",
  cens_adjusted = 0, trunc_adjusted = FALSE, relative_obs_time = 15
)

Simulate cases from a uniform distribution

Description

This function simulates cases from a uniform distribution, where the primary event times are uniformly distributed between 0 and t.

Usage

simulate_uniform_cases(sample_size = 1000, t = 60)

Arguments

sample_size

The number of cases to simulate.

t

Upper bound of the uniform distribution to generate primary event times.

Value

A data.frame with two columns: case (case number) and ptime (primary event time).

See Also

Other simulate: simulate_dates(), simulate_exponential_cases(), simulate_gillespie(), simulate_secondary(), simulate_study()

Examples

simulate_uniform_cases(sample_size = 5, t = 10)

The covariance matrix of an epidist_multivariate object

Description

The covariance matrix of an epidist_multivariate object

Usage

## S3 method for class 'epidist_multivariate'
vcov(object, ...)

Arguments

object

An epidist_multivariate object.

...

Not used.

Value

The covariance matrix.

See Also

Other multivariate: as_epidist_multivariate(), as_epidist_multivariate.data.frame(), as_epidist_multivariate.matrix(), assert_epidist.epidist_multivariate(), is_epidist_multivariate(), new_epidist_multivariate(), print.epidist_multivariate()

Examples

vcov(new_epidist_multivariate(
  value = c(mean = 7.5, sd = 3.6),
  vcov = matrix(c(0.09, 0.02, 0.02, 0.04), nrow = 2),
  params = c("mean", "sd")
))