| Title: | Primary Event Censored Distributions |
| Version: | 1.6.0 |
| Description: | Provides functions for working with primary event censored distributions and 'Stan' implementations for use in Bayesian modeling. Primary event censored distributions are useful for modeling delayed reporting scenarios in epidemiology and other fields (Charniga et al. (2024) <doi:10.48550/arXiv.2405.08841>). It also provides support for arbitrary delay distributions, a range of common primary distributions, and allows for truncation and secondary event censoring to be accounted for (Park et al. (2024) <doi:10.1101/2024.01.12.24301247>). A subset of common distributions also have analytical solutions implemented, allowing for faster computation. In addition, it provides multiple methods for fitting primary event censored distributions to data via optional dependencies. |
| License: | MIT + file LICENSE |
| URL: | https://primarycensored.epinowcast.org, https://github.com/epinowcast/primarycensored |
| BugReports: | https://github.com/epinowcast/primarycensored/issues |
| Depends: | R (≥ 4.0.0) |
| Imports: | lifecycle |
| Suggests: | bookdown, cmdstanr, dplyr, fitdistrplus, flexsurv, knitr, ggplot2, rmarkdown, spelling, testthat (≥ 3.1.9), usethis, withr |
| Additional_repositories: | https://stan-dev.r-universe.dev |
| Config/Needs/hexsticker: | hexSticker, sysfonts, ggplot2 |
| Config/Needs/website: | r-lib/pkgdown, epinowcast/enwtheme |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Language: | en-GB |
| LazyData: | true |
| VignetteBuilder: | knitr |
| RoxygenNote: | 7.3.3 |
| NeedsCompilation: | no |
| Packaged: | 2026-09-25 10:51:16 UTC; lshsa2 |
| Author: | Sam Abbott |
| Maintainer: | Sam Abbott <contact@samabbott.co.uk> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-25 12:00:02 UTC |
primarycensored: Primary Event Censored Distributions
Description
Provides functions for working with primary event censored distributions and 'Stan' implementations for use in Bayesian modeling. Primary event censored distributions are useful for modeling delayed reporting scenarios in epidemiology and other fields (Charniga et al. (2024) doi:10.48550/arXiv.2405.08841). It also provides support for arbitrary delay distributions, a range of common primary distributions, and allows for truncation and secondary event censoring to be accounted for (Park et al. (2024) doi:10.1101/2024.01.12.24301247). A subset of common distributions also have analytical solutions implemented, allowing for faster computation. In addition, it provides multiple methods for fitting primary event censored distributions to data via optional dependencies.
Author(s)
Maintainer: Sam Abbott contact@samabbott.co.uk (ORCID) [copyright holder]
Authors:
Sam Brand usi1@cdc.gov (ORCID)
James Mba Azam james.azam@lshtm.ac.uk (ORCID)
Carl Pearson carl.ab.pearson@gmail.com (ORCID)
Sebastian Funk sebastian.funk@lshtm.ac.uk (ORCID)
Kelly Charniga kelly.charniga@gmail.com (ORCID)
Other contributors:
Adam Howes adamthowes@gmail.com (ORCID) [contributor]
See Also
Useful links:
Report bugs at https://github.com/epinowcast/primarycensored/issues
Resolve, validate and build the pcens object for one call
Description
Shared by dprimarycensored(), pprimarycensored() and
qprimarycensored(). Distribution names are looked up once here and
reused for the primary CDF and the class.
Usage
.build_pcens(pdist, dprimary, primary_args, pprimary, args, pwindow, D, check)
Arguments
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of primary event distribution arguments. |
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
args |
Named list of delay distribution parameters. |
pwindow |
Primary event window. Use |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
check |
Logical; if |
Value
A pcens object. See new_pcens().
Build the (dpcens_dist, ppcens_dist) closure pair for fitdistdoublecens
Description
Single path: scalar named parameters are gathered from the closure's
environment, optionally folded into the vector argument named by
vector_param via the distribution's param_transform, and
dispatched through .dpcens/.ppcens. Formals on the closures
are derived from the supplied start list (parametric) or from a
vector_param-aware naming convention (non-parametric).
Only the supplied parameters become closure arguments, so a distribution
with redundant parameterisations (e.g. gamma with rate and
scale) is fitted in whichever one start uses.
Usage
.build_pcens_closures(
pdist,
ddist,
params,
dprimary,
primary_args,
pprimary = NULL,
vector_param,
param_transform = NULL,
fit_penalty,
prior,
N,
start,
fix_names = NULL,
pdist_extras = list(),
check_once = function() FALSE
)
Arguments
fix_names |
Character vector of parameter names held fixed through
the |
check_once |
A function returning |
Resolve a registry name or alias to its function name
Description
Resolve a registry name or alias to its function name
Usage
.canonical_name(name, registry, column)
Arguments
name |
Character string, a distribution name as given by
|
registry |
A registry data frame, pcd_distributions or pcd_primary_distributions. |
column |
The registry column holding the function names, |
Value
The function name in column for the registry row whose name
or aliases is name, or name itself if it is already a function
name or is not in the registry.
Check that every element of a list is named
Description
Check that every element of a list is named
Usage
.check_named_list(x, what)
Arguments
x |
A list. |
what |
Character string describing |
Value
NULL invisibly. Called for its error.
Check that the primary density and CDF refer to the same distribution
Description
Check that the primary density and CDF refer to the same distribution
Usage
.check_primary_names(d_name, pprimary)
Arguments
d_name |
Name of the primary density function, as given by
|
pprimary |
The primary CDF function. |
Value
NULL invisibly. Called for its error.
Validate truncation bounds L and D
Description
Internal function to validate that L (lower truncation) and D (upper
truncation) parameters are valid. L must be less than D. L may be negative
or -Inf for delay distributions with support below zero.
Usage
.check_truncation_bounds(L, D)
Arguments
L |
Lower truncation bound (may be negative or |
D |
Upper truncation bound |
Value
Invisible NULL if valid, otherwise stops with an error message.
Validate truncation bounds in a data frame
Description
Internal function to validate that L (lower truncation) is less than D (upper truncation) for all rows in a data frame.
Usage
.check_truncation_bounds_df(data, L_col, D_col)
Arguments
data |
Data frame containing the L and D columns |
L_col |
Name of the column containing L values |
D_col |
Name of the column containing D values |
Value
Invisible NULL if valid, otherwise stops with an error message.
Delay CDF of a pcens object
Description
Evaluates the delay distribution CDF of a pcens object with its stored
parameters. This is the primary event censored CDF when pwindow = 0.
Usage
.delay_cdf(object, q)
Arguments
object |
A |
q |
Vector of quantiles. |
Value
Vector of delay CDF values.
Get the distribution name of a function
Description
Returns the "name" attribute of func if set. A stats function that
is identical to one named in pcd_distributions or
pcd_primary_distributions gets that name. Otherwise the name is found
with .extract_function_name(), which deparses the function body and is
slower.
Usage
.dist_name(func)
Arguments
func |
Function, for example the |
Value
Character string with the name of the function, or "unknown".
Define a fitdistrplus compatible wrapper around dprimarycensored
Description
Define a fitdistrplus compatible wrapper around dprimarycensored
Usage
.dpcens(
x,
params,
pdist,
dprimary,
primary_args,
pprimary = NULL,
check = TRUE,
pcens_cache = NULL,
...
)
Arguments
x |
Vector of quantiles |
params |
A data frame with columns 'swindow', 'pwindow', 'L', and 'D' corresponding to the secondary window sizes, primary window sizes, upper truncation times, and lower truncation times for each element in x. |
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
check |
Logical; if |
pcens_cache |
Optional environment shared across calls with the same
|
... |
Additional arguments to be passed to the distribution function |
Extract base function name
Description
This helper function extracts the base name of a function, removing
namespace prefixes.
Base R distribution functions are identified from the C routine they call.
Functions exported by another package (for example
flexsurv::pgengamma.orig()) are identified by their exported name.
Usage
.extract_function_name(func)
Arguments
func |
Function, for example the |
Value
Character string representing the base name of the function, or
"unknown" if it cannot be determined.
Extract function names or content from Stan code
Description
Extract function names or content from Stan code
Usage
.extract_stan_functions(content, names_only = FALSE, functions = NULL)
Arguments
content |
Character vector containing Stan code |
names_only |
Logical, if TRUE extract function names, otherwise extract function content. |
functions |
Optional, character vector of function names to extract content for. |
Value
Character vector of function names or content
Get the pcens object for a likelihood evaluation
Description
Builds a pcens object with .build_pcens(), or, when cache already
holds one, updates its delay parameters with update().
Usage
.fit_pcens_state(cache, pdist, dprimary, primary_args, pprimary, args)
Arguments
cache |
Environment to keep the object in, or |
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
args |
Named list of delay distribution parameters. |
Value
An environment with the pcens object in obj. This is cache
when it is not NULL.
Extract and Combine Distribution Names
Description
This helper function attempts to determine distribution names and uses those to establish a class hierarchy for potential analytical solutions.
Usage
.format_class(
pdist,
dprimary,
pdist_name = .dist_name(pdist),
dprim_name = .dist_name(dprimary)
)
Arguments
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
pdist_name |
Name of |
dprim_name |
Name of |
Details
Registry names and aliases are resolved to the function names used by the
pcens_cdf() methods, for example "lognormal" to "plnorm" and
"uniform" to "dunif". Other names are used as they are.
Value
A character vector of class names: specific (delay + primary), delay-only, and base class.
Shared MAP penalty for the logit-hazard families
Description
Both RW and RE variants share priors on alpha, log_sigma,
and eps_*; only how the hazards are built from those scalars
differs (see .make_hazard_transform()).
Usage
.hazard_fit_penalty(par_named, N, prior_settings = NULL)
Test for a zero-width censoring window
Description
Test for a zero-width censoring window
Usage
.is_exact_window(window)
Arguments
window |
A censoring window width. |
Value
TRUE if window is a single value equal to zero.
Test whether a numeric vector lies on the simplex
Description
Returns TRUE when the vector contains no missing values, no
negative entries, and sums to 1 within 10^{-8}. Used by the
discretestep family to apply a soft penalty inside fitting
closures rather than erroring.
Usage
.is_valid_simplex(p, tol = 1e-08)
Look up the density matching a delay CDF
Description
Finds the d function paired with a p function by name, for example
dgamma() for pgamma(). The name is taken from the "name" attribute
of pdist or inferred with .dist_name(). The density is searched
for from the environment of pdist, then in stats and
primarycensored.
Usage
.lookup_ddist(pdist)
Arguments
pdist |
Delay distribution CDF. |
Value
The density function. An error is raised if none is found.
Look up the primary event CDF from the registry
Description
Given a primary event density function dprimary, looks up the
corresponding CDF function from pcd_primary_distributions using
the "name" attribute. Returns NULL silently when no match
is found so that callers can fall back to numerical integration.
Usage
.lookup_pprimary(dprimary, dprim_name = .dist_name(dprimary))
Arguments
dprimary |
Function. The primary event density function. |
dprim_name |
Name of |
Value
A function (the primary CDF) or NULL.
Build a hazard-vector transform for a given model
Description
Returns a function that maps a named list of scalar parameters
(alpha, log_sigma, eps_1, ..., eps_{K-1})
to a length-K hazard vector with the final entry pinned to 1.
model = "rw" uses a Gaussian random walk on the logit hazard;
model = "re" treats the innovations as IID logit random effects
around the intercept.
Usage
.make_hazard_transform(model = c("rw", "re"))
Build a pcens object from resolved inputs
Description
Internal constructor used by new_pcens() and the functions that build a
pcens object for each call. It does no validation or lookups other than
the names used for the class.
Usage
.new_pcens(
pdist,
dprimary,
primary_args,
pprimary,
args,
pdist_name = .dist_name(pdist),
dprim_name = .dist_name(dprimary)
)
Arguments
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of primary event distribution arguments. |
pprimary |
The primary event CDF, or |
args |
Named list of delay distribution parameters. |
pdist_name |
Name of |
dprim_name |
Name of |
Value
A pcens object. See new_pcens().
Normalise a primary event censored CDF
Description
Internal function to normalise a primary event censored CDF when truncation is applied. The CDF is normalised using (F(q) - F(L)) / (F(D) - F(L)) and values outside [L, D] are clamped to 0 or 1.
Usage
.normalise_cdf(result, q, L, D, pcens_obj, pwindow)
Arguments
result |
Numeric vector of CDF values to normalise. |
q |
Numeric vector of quantiles at which CDF was evaluated. |
L |
Numeric lower truncation point (may be negative or |
D |
Numeric upper truncation point |
pcens_obj |
A primarycensored object as created by |
pwindow |
Secondary event window |
Value
Normalised CDF values as a numeric vector
Group observations that share censoring and truncation settings
Description
Group observations that share censoring and truncation settings
Usage
.param_groups(params, cols)
Arguments
params |
A data frame of per-observation settings. |
cols |
Names of the columns to group by. |
Value
A list with one element per unique combination of cols. Each
element is a list of the values of cols and a logical mask selecting
the rows of params with those values.
Primary event censored CDF at a truncation point
Description
Returns the primary event censored CDF, before truncation, at a single truncation point, reusing an already computed value where possible.
Usage
.pcens_cdf_at(object, bound, pwindow, points, cdfs, inf_value)
Arguments
object |
A |
bound |
Numeric truncation point ( |
pwindow |
Primary event window. |
points |
Numeric vector of points at which |
cdfs |
Numeric vector of CDF values at |
inf_value |
CDF value to return when |
Value
A single numeric CDF value.
Analytical primary event censored CDF for the generalised gamma
Description
Shared implementation for the Stacy parameterisation used by both
generalised gamma pcens_cdf() methods.
Usage
.pcens_cdf_gengamma_unif(q, pwindow, shape, scale, k)
Arguments
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
shape, scale, k |
Generalised gamma parameters in the Stacy
parameterisation of |
Value
Vector of computed primary event censored CDFs
Primary event censored density
Description
Computes the density of the primary event censored delay, the derivative
of pcens_cdf() in x. This is the contribution of an observation with a
zero-width secondary window.
Usage
.pcens_density(object, x, pwindow)
Arguments
object |
A |
x |
Vector of points at which to evaluate the density. |
pwindow |
Primary event window. |
Details
With pwindow = 0 this is the delay density. With a uniform primary
event distribution it is (F(x) - F(x - pwindow)) / pwindow, which
only needs the delay CDF. Otherwise the delay density is integrated
against the primary event density over [0, pwindow].
Value
Vector of densities, not normalised for truncation.
Define a fitdistrplus compatible wrapper around pprimarycensored
Description
Define a fitdistrplus compatible wrapper around pprimarycensored
Usage
.ppcens(
q,
params,
pdist,
dprimary,
primary_args,
pprimary = NULL,
check = TRUE,
pcens_cache = NULL,
...
)
Arguments
q |
Vector of quantiles |
params |
A data frame with columns 'swindow', 'pwindow', 'L', and 'D' corresponding to the secondary window sizes, primary window sizes, upper truncation times, and lower truncation times for each element in x. |
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
check |
Logical; if |
pcens_cache |
Optional environment shared across calls with the same
|
... |
Additional arguments to be passed to pdist |
Recycle observation settings to a given length
Description
Recycle observation settings to a given length
Usage
.recycle_params(params, n)
Arguments
params |
A data frame of per-observation settings. |
n |
Number of rows to return. |
Value
params with its rows recycled or cut to n rows.
Name a stats function found in the distribution registries
Description
Takes the C routine called at the end of the body of a stats function
(for example C_pgamma for stats::pgamma()) as the candidate name. The
name is returned if it is in pcd_distributions or
pcd_primary_distributions and func is identical to the stats
function of that name.
Usage
.registry_name(func)
Arguments
func |
Function, for example the |
Value
The registry name of func, or NULL if it is not found.
Resolve the prior settings for the hazard fit_penalty
Description
Defaults: alpha ~ N(0, 5), log_sigma ~ N(log(0.5), 1).
User overrides are merged in: each component of prior_settings
may itself be a list with mean and sd entries.
Usage
.resolve_hazard_prior(prior_settings = NULL)
Resolve a delay distribution function from a name or function
Description
Accepts either a function (returned as-is, with its existing
"name" attribute preserved) or a character string that is looked
up against pcd_distributions. When a string is supplied,
the corresponding base R p<name> function is returned with the
"name" attribute attached so analytical solutions can dispatch.
Usage
.resolve_pdist(pdist, type = c("p", "d"))
Arguments
pdist |
Either a function or a character string. |
type |
Character string. |
Value
A function with a "name" attribute.
Resolve the primary CDF, validating against dprimary if both supplied
Description
Returns the primary CDF to use. If the user supplies pprimary
explicitly (either a function or a string name), it is returned (after
resolving the string via pcd_dist_name). When both
dprimary and pprimary carry a "name" attribute,
the names must agree on everything except the leading d/p;
otherwise we error to catch typos like dunif + pexpgrowth.
If pprimary is not supplied, falls back to a registry lookup
against dprimary via .lookup_pprimary, which may
return NULL.
Usage
.resolve_pprimary(dprimary, pprimary = NULL, d_name = .dist_name(dprimary))
Arguments
dprimary |
The primary density function. |
pprimary |
Optional user-supplied primary CDF (function or string). |
d_name |
Name of |
Value
A primary CDF function, or NULL if no match was found.
Resolve primary_args / dprimary_args with a deprecation
Description
The resolver distinguishes "user supplied nothing" from "user supplied
an empty list" so the deprecated dprimary_args path can be
detected. The returned list is never NULL.
Usage
.resolve_primary_args(
primary_args,
dprimary_args,
fn,
env = parent.frame(),
user_env = parent.frame(2)
)
Arguments
primary_args |
The new argument value (or |
dprimary_args |
The old argument value (or |
fn |
Character string identifying the calling function (used in the deprecation message). |
env |
Environment of the exported function that owns the deprecated argument. Defaults to the caller of this helper. |
user_env |
Environment the exported function was called from. Defaults to the caller of the caller of this helper. |
Details
The deprecation is soft (lifecycle::deprecate_soft()): a warning
is shown when the exported function is called from the global
environment or from the package under test, and calls from other
packages stay silent.
Value
A list (possibly empty) of primary distribution arguments.
Check whether two names refer to the same registry primary distribution
Description
Check whether two names refer to the same registry primary distribution
Usage
.same_primary(d_name, p_name)
Arguments
d_name, p_name |
Names of a primary density and CDF. Each may be a name, alias, density or CDF name from pcd_primary_distributions. |
Value
TRUE if both names match the same row of
pcd_primary_distributions, otherwise FALSE.
Sort eps_* parameter names by trailing numeric suffix
Description
Lexicographic sorting of c("eps_1", ..., "eps_10") returns
eps_10 before eps_2, which would scramble the random-walk
innovations when K > 10. This helper extracts the trailing integer
and orders by it.
Usage
.sort_eps_names(eps_names)
Validate boundaries and pmf for step distribution functions
Description
Validate boundaries and pmf for step distribution functions
Usage
.validate_discretestep_args(boundaries, pmf)
Helper method for custom distributions
Description
pprimarycensored() and related functions can identify which distributions
are provided via the pdist and dprimary arguments when those are base R
functions (e.g. punif, dexp) via the name attribute.
Usage
add_name_attribute(func, name)
Arguments
func |
Function, for example the |
name |
Character string, starting with "p" or "d" indicating the underlying distribution. |
Details
If you need to use a non-base R implementation, but know the distribution
name, you can use this helper function to set it in a way that will be
detected by pprimarycensored() and related functions.
This is useful as it enables the automatic use of analytical solutions for
distributions where they exist. You can check which analytical solutions are
available using methods(pcens_cdf) and check distribution names using
pcd_dist_name().
Value
Function, with a "name" attribute added
See Also
Utility functions for working with distributions
pcd_dist_name(),
pcd_distributions,
pcd_primary_distributions
Examples
dist <- add_name_attribute(pnorm, "hello")
attr(dist, "name")
Check if a function is a valid bounded probability density function (PDF)
Description
This function tests whether a given function behaves like a valid PDF by checking if it integrates to approximately 1 over the specified range and if it takes the arguments min and max.
Usage
check_dprimary(dprimary, pwindow, dprimary_args = list(), tolerance = 0.001)
Arguments
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
pwindow |
Primary event window. Use |
dprimary_args |
[Deprecated] Use |
tolerance |
The tolerance for the integral to be considered close to 1 |
Value
NULL. The function will stop execution with an error message if
dprimary is not a valid PDF. With pwindow = 0 the primary event
time is exact and only the arguments of dprimary are checked.
See Also
Distribution checking functions
check_pdist(),
check_truncation()
Examples
check_dprimary(dunif, pwindow = 1)
Check if a function is a valid cumulative distribution function (CDF)
Description
This function tests whether a given function behaves like a valid CDF by checking if it's monotonically increasing and bounded between 0 and 1.
Usage
check_pdist(pdist, D = Inf, ...)
Arguments
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
... |
Additional arguments to be passed to pdist |
Value
NULL. The function will stop execution with an error message if pdist is not a valid CDF.
See Also
Distribution checking functions
check_dprimary(),
check_truncation()
Examples
check_pdist(pnorm, D = 10)
Check if truncation time is appropriate relative to the maximum delay
Description
This function checks if the truncation time D is appropriate relative to the
maximum delay. If D is much larger than necessary, it suggests
considering setting it to Inf for better efficiency with minimal accuracy
cost.
Usage
check_truncation(delays, D, multiplier = 2)
Arguments
delays |
A numeric vector of delay times |
D |
The truncation time |
multiplier |
The multiplier for the maximum delay to compare with D. Default is 2. |
Value
Invisible NULL. Prints a message if the condition is met.
See Also
Distribution checking functions
check_dprimary(),
check_pdist()
Examples
check_truncation(delays = c(1, 2, 3, 4), D = 10, multiplier = 2)
Hazard-parameterised piecewise-constant PMF
Description
Returns the probability mass for each value in x. Converts
hazards to a PMF via hazards_to_pmf() then delegates to
ddiscretestep().
Usage
ddiscretehazard(x, boundaries = NULL, hazards)
Arguments
x |
Numeric vector of values at which to evaluate the PMF. |
boundaries |
Numeric vector of length |
hazards |
Numeric vector of length |
Details
Outside fitting it is a deterministic wrapper around ddiscretestep().
It earns its keep as a fitting parameterisation in fitdistdoublecens()
because the random walk on the logit hazard smooths the recovered PMF.
Value
Numeric vector of PMF values, the same length as x.
See Also
ddiscretestep(), hazards_to_pmf(), pmf_to_hazards(),
fitdistdoublecens()
Other pdiscretehazard:
discretehazard_start(),
pdiscretehazard(),
rdiscretehazard()
Examples
hazards <- c(0.3, 0.5, 1)
ddiscretehazard(c(1, 2, 3), boundaries = 0:3, hazards = hazards)
Step (piecewise-constant) PMF
Description
Returns the probability mass for each value in x. Mass
pmf[i] is located at boundaries[i+1] (the right edge of
bin i); all other values return 0.
Usage
ddiscretestep(x, boundaries = NULL, pmf)
Arguments
x |
Numeric vector of values at which to evaluate the PMF. |
boundaries |
Numeric vector of length |
pmf |
Numeric vector of length |
Details
Like pdiscretestep, this function applies a soft simplex
penalty: if pmf contains negative entries or fails to sum to 1
(within 10^{-8}), the function returns near-zero density
(.Machine$double.eps) rather than erroring. This makes it safe to
call from inside fitdistrplus::fitdist() closures driven by
fitdistdoublecens.
Value
Numeric vector of PMF values, the same length as x.
See Also
Other pdiscretestep:
hazards_to_pmf(),
pdiscretestep(),
pmf_to_hazards(),
rdiscretestep()
Examples
ddiscretestep(c(0, 1, 2, 3), boundaries = 0:3, pmf = c(0.2, 0.5, 0.3))
Start values for the logit-hazard parameterisation
Description
Builds a named list of starting values for fitdistdoublecens() with
distr = "discretehazard". The free parameters are the logit
intercept alpha, the log random-walk (or random-effect) scale
log_sigma, and the K - 1 innovations eps_1, ...,
eps_{K-1}. The final bin hazard is pinned to 1 inside the
parameterisation so the implied PMF sums to 1.
Usage
discretehazard_start(K, alpha = -2, log_sigma = log(1), eps = 0)
Arguments
K |
Integer, number of bins in the hazard parameterisation. |
alpha |
Numeric, start value for the logit intercept. |
log_sigma |
Numeric, start value for the log scale. |
eps |
Numeric, scalar or length- |
Value
Named list suitable for the start argument of
fitdistdoublecens().
See Also
Other pdiscretehazard:
ddiscretehazard(),
pdiscretehazard(),
rdiscretehazard()
Examples
discretehazard_start(K = 5)
Compute the primary event censored PMF for delays
Description
This function computes the primary event censored probability mass function (PMF) for a given set of quantiles. It adjusts the PMF of the primary event distribution by accounting for the delay distribution and potential truncation at a maximum delay (D) and minimum delay (L). The function allows for custom primary event distributions and delay distributions.
Usage
dprimarycensored(
x,
pdist,
pwindow = 1,
swindow = 1,
L = -Inf,
D = Inf,
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
log = FALSE,
...,
check = TRUE
)
dpcens(
x,
pdist,
pwindow = 1,
swindow = 1,
L = -Inf,
D = Inf,
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
log = FALSE,
...,
check = TRUE
)
Arguments
x |
Vector of quantiles |
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
pwindow |
Primary event window. Use |
swindow |
Secondary event window (default: 1). Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
dprimary_args |
[Deprecated] Use |
log |
Logical; if TRUE, probabilities p are given as log(p) |
... |
Additional arguments to be passed to the distribution function |
check |
Logical; if |
Details
The primary event censored PMF is computed by taking the difference of the
primary event censored cumulative distribution function (CDF) at two points,
d + \text{swindow} and d. The primary event censored PMF,
f_{\text{cens}}(d), is given by:
f_{\text{cens}}(d) = F_{\text{cens}}(d + \text{swindow}) - F_{\text{cens}}(d)
where F_{\text{cens}} is the primary event censored CDF.
The function creates a pcens object with new_pcens() and computes
the PMF with pcens_pmf(). This evaluates the CDF once for all unique
points (including both d and d + \text{swindow}) and
reuses these values to calculate the PMF for each input value.
When the secondary censoring interval extends past the upper truncation
point (d + \text{swindow} > D) but the lower endpoint satisfies
d < D, the upper endpoint is internally clipped to D before
evaluating the CDF. The likelihood for such an observation is
P(X \in [d, \min(d + \text{swindow}, D)] \mid L \le X \le D), which
equals the usual interval probability when d + \text{swindow} \le D.
This avoids erroring when an observation's secondary window straddles the
truncation point (relevant for non-parametric delays such as
pdiscretestep()).
Observations with d \ge D are rejected with an error: under the
truncation X \le D, no event with latent value d \ge D is
observable, and accepting such inputs would otherwise yield a 0/0
likelihood.
The PMF is normalised to ensure it sums to 1 over the range [L, D\). This normalization uses:
f_{\text{cens,norm}}(d) = \frac{f_{\text{cens}}(d)}{
F_{\text{cens}}(D) - F_{\text{cens}}(L)}
where f_{\text{cens,norm}}(d) is the normalized PMF. For the
explanation and mathematical details of the CDF, refer to the documentation
of pprimarycensored().
Zero-width windows
With pwindow = 0 the primary event time is known exactly and the
primary event censored CDF is the delay CDF, so the PMF is
F(d + \text{swindow}) - F(d).
With swindow = 0 the secondary event time is known exactly. The
probability of the interval is then zero, so the density of the primary
event censored delay at d is returned instead. This is the
derivative of F_{\text{cens}} at d, the limit of the PMF
divided by swindow as swindow goes to zero. With pwindow = 0 as well
it is the delay density. With a uniform primary event distribution it is
(F(d) - F(d - \text{pwindow})) / \text{pwindow}. Otherwise the
delay density is integrated against the primary event density. The delay
density is found from the name of pdist (for example dgamma() for
pgamma()) and an error is raised if it cannot be found. Densities are
normalised for truncation in the same way as probabilities. swindow may
be a vector, so densities and probabilities can be mixed in one call.
Value
Vector of primary event censored PMFs, normalized over [L, D] if truncation is applied
See Also
Primary event censored distribution functions
pprimarycensored(),
qprimarycensored(),
rprimarycensored()
Examples
# Example: Weibull distribution with uniform primary events
dprimarycensored(c(0.1, 0.5, 1), pweibull, shape = 1.5, scale = 2.0)
# Example: Weibull distribution with exponential growth primary events
dprimarycensored(
c(0.1, 0.5, 1), pweibull,
dprimary = dexpgrowth,
primary_args = list(r = 0.2), shape = 1.5, scale = 2.0
)
# Example: Left-truncated distribution (e.g., for generation intervals)
dprimarycensored(1:9, pweibull, L = 1, D = 10, shape = 1.5, scale = 2.0)
# Example: exact primary events, and exact secondary events (a density)
dprimarycensored(1:3, pweibull, pwindow = 0, shape = 1.5, scale = 2.0)
dprimarycensored(
1:3, pweibull,
pwindow = 1, swindow = 0, shape = 1.5, scale = 2.0
)
Exponential growth distribution functions
Description
Density, distribution function, and random generation for the exponential growth distribution.
Usage
dexpgrowth(x, min = 0, max = 1, r, log = FALSE)
pexpgrowth(q, min = 0, max = 1, r, lower.tail = TRUE, log.p = FALSE)
rexpgrowth(n, min = 0, max = 1, r)
Arguments
x, q |
Vector of quantiles. |
min |
Minimum value of the distribution range. Default is 0. |
max |
Maximum value of the distribution range. Default is 1. |
r |
Rate parameter for the exponential growth. |
log, log.p |
Logical; if TRUE, probabilities p are given as log(p). |
lower.tail |
Logical; if TRUE (default), probabilities are P[X <= x], otherwise, P[X > x]. |
n |
Number of observations. If |
Details
The exponential growth distribution is defined on the interval [min, max] with rate parameter (r). Its probability density function (PDF) is:
f(x) = \frac{r \cdot \exp(r \cdot x)}{\exp(r \cdot max) -
\exp(r \cdot min)}
The cumulative distribution function (CDF) is:
F(x) = \frac{\exp(r \cdot x) - \exp(r \cdot min)}{
\exp(r \cdot max) - \exp(r \cdot min)}
For random number generation, we use the inverse transform sampling method:
Generate
u \sim \text{Uniform}(0,1)Set
F(x) = uand solve forx:x = \frac{1}{r} \cdot \log(u \cdot \exp(r \cdot max) + (1 - u) \cdot \exp(r \cdot min))
This method works because of the probability integral transform theorem,
which states that if X is a continuous random variable with CDF
F(x), then Y = F(X) follows a \text{Uniform}(0,1)
distribution. Conversely, if U is a \text{Uniform}(0,1) random
variable, then F^{-1}(U) has the same distribution as X, where
F^{-1} is the inverse of the CDF.
In our case, we generate u from \text{Uniform}(0,1), then solve
F(x) = u for x to get a sample from our exponential growth
distribution. The formula for x is derived by algebraically solving
the equation:
u = \frac{\exp(r \cdot x) - \exp(r \cdot min)}{\exp(r \cdot max) -
\exp(r \cdot min)}
When r is very close to 0 (|r| < 1e-10), the distribution
approximates a uniform distribution on [min, max], and we use a simpler
method to generate samples directly from this uniform distribution.
Value
dexpgrowth gives the density, pexpgrowth gives the distribution
function, and rexpgrowth generates random deviates.
The length of the result is determined by n for rexpgrowth, and is the
maximum of the lengths of the numerical arguments for the other functions.
Examples
x <- seq(0, 1, by = 0.1)
probs <- dexpgrowth(x, r = 0.2)
cumprobs <- pexpgrowth(x, r = 0.2)
samples <- rexpgrowth(100, r = 0.2)
Fit a distribution to doubly censored data
Description
This function wraps the custom approach for fitting distributions to doubly censored data using fitdistrplus and primarycensored. It handles primary censoring (when the primary event time is not known exactly), secondary censoring (when the secondary event time is interval-censored), and truncation (when events are only observed within a delay range [L, D]).
Usage
fitdistdoublecens(
censdata,
distr,
left = "left",
right = "right",
pwindow = "pwindow",
L = "L",
D = "D",
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
truncation_check_multiplier = 2,
prior = NULL,
hazard_model = c("rw", "re"),
check = TRUE,
...
)
Arguments
censdata |
A data frame with columns 'left' and 'right' representing
the lower and upper bounds of the censored observations. Unlike
|
distr |
A character string naming the distribution to be fitted.
Special values |
left |
Column name for lower bound of observed values (default: "left"). |
right |
Column name for upper bound of observed values (default: "right"). |
pwindow |
Column name for primary window (default: "pwindow"). Use a primary window of 0 for an exactly observed primary event. |
L |
Column name for minimum delay (lower truncation point). For any
finite L the distribution is left-truncated at L; use |
D |
Column name for maximum delay (upper truncation point). If finite,
the distribution is truncated at D. If set to Inf, no upper truncation is
applied. (default: "D"). Observations whose secondary censoring interval
straddles |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
dprimary_args |
[Deprecated] Use |
truncation_check_multiplier |
Numeric multiplier to use for checking if the truncation time D is appropriate relative to the maximum delay. Set to NULL to skip the check. Default is 2. |
prior |
Optional list of prior settings used by the dist function's
|
hazard_model |
One of |
check |
Logical; if |
... |
Additional arguments to be passed to |
Details
How distribution functions are resolved
The distr argument names a distribution. The function looks up the
density and CDF functions by prepending d and p to the name (e.g.
distr = "gamma" resolves to dgamma() and pgamma()). Custom
distributions can be used as long as the corresponding d<distr>() and
p<distr>() functions are defined.
Parametric distributions are fitted in the parameterisation named by
start, and the returned estimates and covariance matrix use the same
names. For example, gamma can be fitted with either
start = list(shape = , rate = ) or start = list(shape = , scale = ).
Parameters can be held fixed by passing fix.arg to
fitdistrplus::fitdist() through ..., either as a named list or as a
function of the delays returning one.
Non-parametric distributions
Two non-parametric distributions are supported. They share a common
fitting machinery: the dist function carries a vector_param attribute
("pmf" for pdiscretestep()/ddiscretestep(), "hazards" for
pdiscretehazard()/ddiscretehazard()) that drives this function to
build a closure mapping flat scalar parameters into the underlying
vector argument.
-
distr = "discretestep": free parametersp1, ..., p_{K-1}(in[0, 1]); the last bin probability is1 - sum(p1, ..., p_{K-1}). Seepdiscretestep()for parameterisation details and the soft simplex penalty applied when probabilities are infeasible. -
distr = "discretehazard": free parametersalpha,log_sigma,eps_1, ..., eps_{K-1}. The hazard form parameterises the same family of step distributions as"discretestep", but its free parameters drive either a Gaussian random walk on the logit hazard (hazard_model = "rw", the default,logit(h_i) = alpha + sigma * cumsum(eps)) or an IID logit random-effect transform (hazard_model = "re",logit(h_i) = alpha + sigma * eps_iwitheps_i ~ N(0, 1)). The smoothing of the random walk regularises the recovered PMF against over-fitting in sparse data and replaces the simplex constraint with an unconstrained optimisation; the random-effect variant models hazards as independent draws aroundalpharather than a smoothed trajectory. Seepdiscretehazard()for full parameterisation details and the MAP-equivalent prior penalty applied during fitting; passpriorto override the default prior settings.
For non-parametric distributions K is implied by length(start):
K = length(start) + 1 for "discretestep" and
K = length(start) - 1 for "discretehazard". start is therefore
required.
Exact observations
Rows with pwindow = 0 have an exactly known primary event time. Rows
with left == right have an exactly known secondary event time and
contribute a density rather than a probability to the likelihood (see
dprimarycensored()). Rows of different types can be mixed in one fit,
as for the exact, single interval censored and doubly interval censored
observations of coarseDataTools::dic.fit(). Data with the primary
event in [EL, ER] and the secondary event in [SL, SR] map
to left = SL - EL, right = SR - EL and pwindow = ER - EL.
Value
An object of class "fitdist" as returned by fitdistrplus::fitdist.
See Also
pdiscretestep() pdiscretehazard()
Modelling wrappers for external fitting packages
pcd_as_stan_data(),
pcd_cmdstan_model()
Examples
# Example with normal distribution
set.seed(123)
n <- 1000
true_mean <- 5
true_sd <- 2
pwindow <- 2
swindow <- 2
D <- 10
samples <- rprimarycensored(
n, rnorm,
mean = true_mean, sd = true_sd,
pwindow = pwindow, swindow = swindow, D = D
)
delay_data <- data.frame(
left = samples,
right = samples + swindow,
pwindow = rep(pwindow, n),
D = rep(D, n)
)
fit_norm <- fitdistdoublecens(
delay_data,
distr = "norm",
start = list(mean = 0, sd = 1)
)
summary(fit_norm)
# Example with discretestep (non-parametric PMF) distribution
set.seed(42)
true_pmf <- c(0.1, 0.3, 0.4, 0.15, 0.05)
step_samples <- rprimarycensored(
500, rdiscretestep,
boundaries = 0:5, pmf = true_pmf,
pwindow = 1, swindow = 1, D = 6
)
step_data <- data.frame(
left = step_samples,
right = step_samples + 1,
pwindow = rep(1, 500),
D = rep(6, 500)
)
fit_step <- fitdistdoublecens(
step_data,
distr = "discretestep",
boundaries = 0:5,
start = as.list(setNames(rep(0.2, 4), paste0("p", 1:4)))
)
# Example with discretehazard (logit-hazard random walk) distribution
fit_haz <- fitdistdoublecens(
step_data,
distr = "discretehazard",
boundaries = 0:5,
start = c(
list(alpha = -2, log_sigma = log(0.5)),
as.list(setNames(rep(0, 4), paste0("eps_", 1:4)))
)
)
Convert discrete-time hazards to a PMF
Description
Given a vector of discrete-time hazards h_1, \ldots, h_K, computes
the corresponding PMF:
pmf_i = h_i \prod_{j < i} (1 - h_j)
Usage
hazards_to_pmf(hazards)
Arguments
hazards |
Numeric vector of hazards in |
Details
The last hazard must equal 1 (to ensure the PMF sums to 1). If a vector
of length K-1 is supplied (all hazards except the final exit
hazard), 1 is appended automatically.
Value
Numeric vector of PMF values.
See Also
Other pdiscretestep:
ddiscretestep(),
pdiscretestep(),
pmf_to_hazards(),
rdiscretestep()
Examples
hazards_to_pmf(c(0.2, 0.3, 1))
S3 class for primary event censored distribution computation
Description
S3 class for primary event censored distribution computation
Usage
new_pcens(
pdist,
dprimary,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
...
)
Arguments
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
|
pprimary |
CDF of the primary event distribution. May be a function
or a character string naming a primary distribution in
|
dprimary_args |
[Deprecated] Use |
... |
Additional arguments to be passed to pdist |
Value
An object with class hierarchy
c("pcens_{pdist_name}_{dprimary_name}", "pcens_{pdist_name}",
"pcens"). It is a list with the fields:
pdistThe delay distribution CDF.
dprimaryThe primary event distribution density.
primary_argsA list of arguments passed to
dprimaryandpprimary.dprimary_argsA copy of
primary_args, kept for backward compatibility.pprimaryThe primary event CDF, or
NULLif none is available.argsA named list of the delay distribution parameters passed through
....
It can be used with pcens_cdf() to compute the primary event
censored CDF and with pcens_pmf() to compute the PMF. Use
update() to change its parameters.
See Also
Low level primary event censored distribution objects and methods
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Examples
new_pcens(
pdist = pgamma, dprimary = dunif,
primary_args = list(min = 0, max = 1),
shape = 1, scale = 1
)
Prepare data for primarycensored Stan model
Description
This function takes in delay data and prepares it for use with the primarycensored Stan model.
Usage
pcd_as_stan_data(
data,
delay = "delay",
delay_upper = "delay_upper",
n = "n",
pwindow = "pwindow",
start_relative_obs_time = "start_relative_obs_time",
relative_obs_time = "relative_obs_time",
dist_id,
primary_id,
param_bounds,
primary_param_bounds,
priors,
primary_priors,
compute_log_lik = FALSE,
use_reduce_sum = FALSE,
truncation_check_multiplier = 2,
dist_options = NULL
)
Arguments
data |
A data frame containing the delay data. |
delay |
Column name for observed delays (default: "delay") |
delay_upper |
Column name for upper bound of delays (default: "delay_upper") |
n |
Column name for count of observations (default: "n") |
pwindow |
Column name for primary window (default: "pwindow") |
start_relative_obs_time |
Column name for start of relative observation
time, used as the lower truncation point L. Values may be any finite real
number (including negatives) or |
relative_obs_time |
Column name for relative observation time, used as
the upper truncation point D. Values may be any finite real number
(including negatives, paired with a smaller |
dist_id |
Integer identifying the delay distribution:
You can use |
primary_id |
Integer identifying the primary distribution:
You can use |
param_bounds |
A list with elements |
primary_param_bounds |
A list with elements |
priors |
A list with elements |
primary_priors |
A list with elements |
compute_log_lik |
Logical; compute log likelihood? (default: FALSE) |
use_reduce_sum |
Logical; use reduce_sum for performance? (default: FALSE) |
truncation_check_multiplier |
Numeric multiplier to use for checking if the truncation time D is appropriate relative to the maximum delay for each unique D value. Set to NULL to skip the check. Default is 2. |
dist_options |
Optional list carrying the shape of a
non-parametric delay. When
Priors and
|
Value
A list containing the data formatted for use with
pcd_cmdstan_model()
See Also
Modelling wrappers for external fitting packages
fitdistdoublecens(),
pcd_cmdstan_model()
Examples
data <- data.frame(
delay = c(1, 2, 3),
delay_upper = c(2, 3, 4),
n = c(10, 20, 15),
pwindow = c(1, 1, 2),
relative_obs_time = c(10, 10, 10)
)
stan_data <- pcd_as_stan_data(
data,
dist_id = 1,
primary_id = 1,
param_bounds = list(lower = c(0, 0), upper = c(10, 10)),
primary_param_bounds = list(lower = numeric(0), upper = numeric(0)),
priors = list(location = c(1, 1), scale = c(1, 1)),
primary_priors = list(location = numeric(0), scale = numeric(0))
)
Create a CmdStanModel with primarycensored Stan functions
Description
This function creates a CmdStanModel object using the Stan model and functions from primarycensored and optionally includes additional user-specified Stan files.
Usage
pcd_cmdstan_model(include_paths = primarycensored::pcd_stan_path(), ...)
Arguments
include_paths |
Character vector of paths to include for Stan
compilation. Defaults to the result of |
... |
Additional arguments passed to cmdstanr::cmdstan_model(). |
Details
The underlying Stan model (pcens_model.stan) supports various features:
Multiple probability distributions for modeling delays
Primary and secondary censoring
Truncation
Optional use of reduce_sum for improved performance (via within chain parallelism).
Flexible prior specifications
Optional computation of log-likelihood for model comparison
Value
A CmdStanModel object.
See Also
Modelling wrappers for external fitting packages
fitdistdoublecens(),
pcd_as_stan_data()
Examples
if (!is.null(cmdstanr::cmdstan_version(error_on_NA = FALSE))) {
model <- pcd_cmdstan_model(compile = FALSE)
model
}
Get distribution function cdf or pdf name
Description
Get distribution function cdf or pdf name
Usage
pcd_dist_name(name, type = c("delay", "primary"))
Arguments
name |
String. Distribution name or alias |
type |
String. "delay" or "primary" corresponding to the type of
distribution to use as the look up. If delay then |
Value
String distribution function name or NA if no base R implementation
See Also
Utility functions for working with distributions
add_name_attribute(),
pcd_distributions,
pcd_primary_distributions
Examples
pcd_dist_name("lnorm")
pcd_dist_name("lognormal")
pcd_dist_name("gamma")
pcd_dist_name("weibull")
pcd_dist_name("exp")
pcd_dist_name("unif", type = "primary")
pcd_dist_name("expgrowth", type = "primary")
Supported delay distributions
Description
A dataset containing information about the supported delay distributions in primarycensored. Includes both distributions with base R implementations and those only available in Stan. Distributions beyond these are not supported in the stan code but any user functions can be used in the R code.
Usage
pcd_distributions
Format
A data.frame with 28 rows and 4 columns:
- name
Distribution name
- pdist
R distribution function name (e.g. plnorm), NA if there is no base R implementation
- aliases
Alternative names/identifiers
- stan_id
Stan distribution ID used in the stan code
See Also
Utility functions for working with distributions
add_name_attribute(),
pcd_dist_name(),
pcd_primary_distributions
Load Stan functions as a string
Description
Load Stan functions as a string
Usage
pcd_load_stan_functions(
functions = NULL,
stan_path = primarycensored::pcd_stan_path(),
wrap_in_block = FALSE,
write_to_file = FALSE,
output_file = "pcd_functions.stan",
dependencies = FALSE
)
Arguments
functions |
Character vector of function names to load. Defaults to all functions. |
stan_path |
Character string, the path to the Stan code. Defaults to the path to the Stan code in the primarycensored package. |
wrap_in_block |
Logical, whether to wrap the functions in a
|
write_to_file |
Logical, whether to write the output to a file. Default is FALSE. |
output_file |
Character string, the path to write the output file if write_to_file is TRUE. Defaults to "pcd_functions.stan". |
dependencies |
Logical, whether to include all functions that the requested functions depend on. When TRUE, recursively finds and includes all dependencies in the correct order (dependencies before the functions that use them). Default is FALSE. |
Value
A character string containing the requested Stan functions
See Also
Tools for working with package Stan functions
pcd_stan_dist_id(),
pcd_stan_files(),
pcd_stan_function_deps(),
pcd_stan_functions(),
pcd_stan_path()
Supported primary event distributions
Description
A dataset containing information about the supported primary event distributions in primarycensored. Distributions beyond these are not supported in the stan code but any user functions can be used in the R code.
Usage
pcd_primary_distributions
Format
A data.frame with 2 rows and 4 columns:
- name
Distribution name
- dprimary
R density function name
- aliases
Alternative names/identifiers
- stan_id
Stan distribution ID used in the stan code
See Also
Utility functions for working with distributions
add_name_attribute(),
pcd_dist_name(),
pcd_distributions
Get distribution stan ID by name
Description
Get distribution stan ID by name
Usage
pcd_stan_dist_id(name, type = c("delay", "primary"))
Arguments
name |
String. Distribution name or alias |
type |
String. "delay" or "primary" corresponding to the type of
distribution to use as the look up. If delay then |
Value
Numeric distribution ID
See Also
Tools for working with package Stan functions
pcd_load_stan_functions(),
pcd_stan_files(),
pcd_stan_function_deps(),
pcd_stan_functions(),
pcd_stan_path()
Examples
pcd_stan_dist_id("lnorm")
pcd_stan_dist_id("lognormal")
pcd_stan_dist_id("gamma")
pcd_stan_dist_id("weibull")
pcd_stan_dist_id("exp")
pcd_stan_dist_id("unif", type = "primary")
Get Stan files containing specified functions
Description
This function retrieves Stan files from a specified directory, optionally filtering for files that contain specific functions.
Usage
pcd_stan_files(functions = NULL, stan_path = primarycensored::pcd_stan_path())
Arguments
functions |
Character vector of function names to search for. If NULL, all Stan files are returned. |
stan_path |
Character string specifying the path to the directory containing Stan files. Defaults to the Stan path of the primarycensored package. |
Value
A character vector of file paths to Stan files.
See Also
Tools for working with package Stan functions
pcd_load_stan_functions(),
pcd_stan_dist_id(),
pcd_stan_function_deps(),
pcd_stan_functions(),
pcd_stan_path()
Get dependencies for a Stan function
Description
Returns all Stan functions that the specified function depends on, in topological order (dependencies before the functions that use them).
Usage
pcd_stan_function_deps(
function_name,
stan_path = primarycensored::pcd_stan_path()
)
Arguments
function_name |
Character string, the name of the Stan function. |
stan_path |
Character string specifying the path to the directory containing Stan files. Defaults to the Stan path of the primarycensored package. |
Value
A character vector of function names that the specified function depends on, ordered so that dependencies come before functions that use them. The requested function itself is included as the last element.
See Also
Tools for working with package Stan functions
pcd_load_stan_functions(),
pcd_stan_dist_id(),
pcd_stan_files(),
pcd_stan_functions(),
pcd_stan_path()
Examples
# See what primarycensored_lpmf depends on
pcd_stan_function_deps("primarycensored_lpmf")
# A function with no dependencies
pcd_stan_function_deps("expgrowth_pdf")
Get Stan function names from Stan files
Description
This function reads all Stan files in the specified directory and extracts the names of all functions defined in those files.
Usage
pcd_stan_functions(stan_path = primarycensored::pcd_stan_path())
Arguments
stan_path |
Character string specifying the path to the directory containing Stan files. Defaults to the Stan path of the primarycensored package. |
Value
A character vector containing unique names of all functions found in the Stan files.
See Also
Tools for working with package Stan functions
pcd_load_stan_functions(),
pcd_stan_dist_id(),
pcd_stan_files(),
pcd_stan_function_deps(),
pcd_stan_path()
Get the path to the Stan code
Description
Get the path to the Stan code
Usage
pcd_stan_path()
Value
A character string with the path to the Stan code
See Also
Tools for working with package Stan functions
pcd_load_stan_functions(),
pcd_stan_dist_id(),
pcd_stan_files(),
pcd_stan_function_deps(),
pcd_stan_functions()
Compute primary event censored CDF
Description
This function dispatches to either analytical solutions (if available) or
numerical integration via the default method. To see which combinations have
analytical solutions implemented, use methods(pcens_cdf). For example,
pcens_cdf.gamma_unif indicates an analytical solution exists for gamma
delay with uniform primary event distributions.
Usage
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Details
When pwindow = 0 the primary event time is known exactly and the
primary event censored CDF is the delay CDF. This case is handled before
dispatch, so every method returns pdist(q) without integrating over the
primary event window.
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Default method for computing primary event censored CDF
Description
This method serves as a fallback for combinations of delay and primary event distributions that don't have specific implementations. It uses a numeric integration method.
Usage
## Default S3 method:
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Details
This method implements the numerical integration approach for computing
the primary event censored CDF. It uses the same mathematical formulation
as described in the details section of pprimarycensored(), but
applies numerical integration instead of analytical solutions.
Value
Vector of computed primary event censored CDFs
See Also
pprimarycensored() for the mathematical details of the
primary event censored CDF computation.
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Examples
# Create a primarycensored object with gamma delay and uniform primary
pcens_obj <- new_pcens(
pdist = pgamma,
dprimary = dunif,
primary_args = list(min = 0, max = 1),
shape = 3,
scale = 2
)
# Compute CDF for a single value
pcens_cdf(pcens_obj, q = 9, pwindow = 1)
# Compute CDF for multiple values
pcens_cdf(pcens_obj, q = c(4, 6, 8), pwindow = 1)
Method for hazard CDF delay with general primary event distribution
Description
Computes the analytic primary event censored CDF for a hazard-parameterised
piecewise-constant delay distribution. Converts hazards to a PMF via
hazards_to_pmf() then dispatches back through pcens_cdf() using a
freshly constructed step-distribution object. The same primary event
distribution and arguments are preserved.
Usage
## S3 method for class 'pcens_pdiscretehazard'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Method for step CDF delay with general primary event distribution
Description
Computes the analytic primary event censored CDF for a piecewise-constant
(step) delay distribution and an arbitrary primary event distribution
whose CDF F_{primary} is available via object$pprimary.
Usage
## S3 method for class 'pcens_pdiscretestep'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Details
The observation CDF is
F_{obs}(q) = \int_0^{pwindow} F_{step}(q-p)\,dF_{primary}(p)
Because F_{step} is piecewise constant, the integral reduces to
F_{obs}(q) = \sum_k c_k \,[F_{primary}(p^{end}_k) -
F_{primary}(p^{start}_k)]
where c_k is the constant value of F_{step} on the
k-th sub-interval of the primary event window induced by the
step-function knots.
The partition is exact for any bin widths, so bins may be wider or
narrower than pwindow, and for boundaries that start below zero.
Falls back to pcens_cdf.default when use_numeric = TRUE
or when no primary CDF is available on the object.
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Method for Gamma delay with uniform primary
Description
Method for Gamma delay with uniform primary
Usage
## S3 method for class 'pcens_pgamma_dunif'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Method for generalised gamma delay with uniform primary
Description
Analytical solution for the generalised gamma distribution in the Stacy
parameterisation used by flexsurv::pgengamma.orig(), with parameters
shape, scale and k.
The delay CDF is F_T(t) = P(k, (t / \theta)^a) with P the
regularised lower incomplete gamma function, a the shape and
\theta the scale.
The mean is E[T] = \theta \Gamma(k + 1/a) / \Gamma(k) and the partial
expectation distribution is \tilde F_T(t) = P(k + 1/a, (t / \theta)^a),
so the solution generalises the gamma (shape = 1) and Weibull (k = 1)
cases.
See vignette("analytic-solutions") for the derivation.
Usage
## S3 method for class 'pcens_pgengamma.orig_dunif'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Examples
pcens_obj <- new_pcens(
pdist = flexsurv::pgengamma.orig,
dprimary = dunif,
dprimary_args = list(min = 0, max = 1),
shape = 1.5,
scale = 2,
k = 0.8
)
pcens_cdf(pcens_obj, q = c(1, 4, 8), pwindow = 1)
Method for generalised gamma (Prentice parameterisation) delay with uniform primary
Description
Analytical solution for the generalised gamma distribution in the Prentice
parameterisation used by flexsurv::pgengamma(), with parameters mu,
sigma and Q.
For Q > 0 this is mapped to the Stacy parameterisation of
pcens_cdf.pcens_pgengamma.orig_dunif() via shape = Q / sigma,
scale = exp(mu) * Q^(2 * sigma / Q) and k = 1 / Q^2.
For Q <= 0 (the lognormal and reflected cases) the numerical
pcens_cdf.default() method is used.
Usage
## S3 method for class 'pcens_pgengamma_dunif'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Method for Log-Normal delay with uniform primary
Description
Method for Log-Normal delay with uniform primary
Usage
## S3 method for class 'pcens_plnorm_dunif'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Method for Weibull delay with uniform primary
Description
Method for Weibull delay with uniform primary
Usage
## S3 method for class 'pcens_pweibull_dunif'
pcens_cdf(object, q, pwindow, use_numeric = FALSE)
Arguments
object |
A |
q |
Vector of quantiles |
pwindow |
Primary event window. Use |
use_numeric |
Logical, if TRUE forces use of numeric integration even for distributions with analytical solutions. This is primarily useful for testing purposes or for settings where the analytical solution breaks down. |
Value
Vector of computed primary event censored CDFs
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Compute primary event censored PMF
Description
Computes the primary event censored PMF for a pcens object as created
by new_pcens(). Secondary event windows and truncation are handled as in
dprimarycensored().
Usage
pcens_pmf(object, x, pwindow, swindow = 1, L = -Inf, D = Inf, log = FALSE, ...)
Arguments
object |
A |
x |
Vector of quantiles |
pwindow |
Primary event window. Use |
swindow |
Secondary event window (default: 1). Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
log |
Logical; if TRUE, probabilities p are given as log(p) |
... |
Additional arguments passed to methods. |
Value
Vector of primary event censored PMFs, normalized over [L, D] if truncation is applied
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Default method for computing primary event censored PMF
Description
Computes the PMF by differencing pcens_cdf() at x and
min(x + swindow, D), normalised over [L, D]. Where swindow = 0 the
primary event censored density at x is returned instead. See
dprimarycensored() for the details.
Usage
## Default S3 method:
pcens_pmf(object, x, pwindow, swindow = 1, L = -Inf, D = Inf, log = FALSE, ...)
Arguments
object |
A |
x |
Vector of quantiles |
pwindow |
Primary event window. Use |
swindow |
Secondary event window (default: 1). Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
log |
Logical; if TRUE, probabilities p are given as log(p) |
... |
Additional arguments passed to methods. |
Value
Vector of primary event censored PMFs, normalized over [L, D] if truncation is applied
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_quantile(),
pcens_quantile.default(),
update.pcens()
Examples
obj <- new_pcens(
pdist = pgamma, dprimary = dunif,
primary_args = list(min = 0, max = 1),
shape = 3, scale = 2
)
pcens_pmf(obj, x = 0:9, pwindow = 1, D = 10)
Compute primary event censored quantiles
Description
This function inverts the primary event censored CDF to compute quantiles.
It uses numerical optimisation via optim to find the value q such that
pcens_cdf() is close to the specified probability. Currently, only the
default numerical inversion method is implemented. Future analytical
solutions may be added.
Usage
pcens_quantile(object, p, pwindow, L = -Inf, D = Inf, use_numeric = FALSE, ...)
Arguments
object |
A |
p |
A vector of probabilities at which to compute the quantiles. |
pwindow |
Primary event window. Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
use_numeric |
Logical; if TRUE forces the use of numeric inversion even if an analytical solution is available (not yet implemented). |
... |
Additional arguments to be passed to pdist |
Value
Vector of primary event censored quantiles.
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile.default(),
update.pcens()
Default method for computing primary event censored quantiles
Description
This method inverts the primary event censored CDF by root-finding via
stats::uniroot() with extendInt = "upX". The censored CDF is monotone
in q, so stats::uniroot() extends its starting bracket outward as
needed and handles infinite L or D without special casing.
Usage
## Default S3 method:
pcens_quantile(
object,
p,
pwindow,
L = -Inf,
D = Inf,
use_numeric = FALSE,
init = 5,
tol = 1e-08,
max_iter = 10000,
...
)
Arguments
object |
A |
p |
A vector of probabilities at which to compute the quantiles. |
pwindow |
Primary event window. Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
use_numeric |
Logical; if TRUE forces the use of numeric inversion even if an analytical solution is available (not yet implemented). |
init |
Half-width of the initial search interval used when one or
both truncation bounds are infinite. The starting interval is taken as
|
tol |
Numeric tolerance passed to |
max_iter |
Maximum number of |
... |
Additional arguments passed to underlying functions. |
Value
A numeric vector containing the computed primary event censored quantiles.
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
update.pcens()
Examples
# Create a primarycensored object with gamma delay and uniform primary
pcens_obj <- new_pcens(
pdist = pgamma,
dprimary = dunif,
primary_args = list(min = 0, max = 1),
shape = 3,
scale = 2
)
# Compute quantile for a single probability
pcens_quantile(pcens_obj, p = 0.8, pwindow = 1)
# Compute quantiles for multiple probabilities
pcens_quantile(pcens_obj, p = c(0.25, 0.5, 0.75), pwindow = 1)
# Compute quantiles for multiple probabilities with truncation
pcens_quantile(pcens_obj, p = c(0.25, 0.5, 0.75), pwindow = 1, D = 10)
# Compute quantiles with left truncation
pcens_quantile(pcens_obj, p = c(0.25, 0.5, 0.75), pwindow = 1, L = 1, D = 10)
Hazard-parameterised piecewise-constant CDF
Description
Returns the CDF of a discrete distribution specified by its bin-wise
discrete-time hazards. Converts hazards to a PMF via
hazards_to_pmf() then delegates to pdiscretestep().
Usage
pdiscretehazard(q, boundaries = NULL, hazards)
Arguments
q |
Numeric vector of quantiles. |
boundaries |
Numeric vector of length |
hazards |
Numeric vector of length |
Details
Outside fitting it is a deterministic wrapper around pdiscretestep().
It earns its keep as a fitting parameterisation in fitdistdoublecens()
because the random walk on the logit hazard smooths the recovered PMF.
Value
Numeric vector of CDF values, the same length as q.
See Also
pdiscretestep(), hazards_to_pmf(), pmf_to_hazards(),
fitdistdoublecens()
Other pdiscretehazard:
ddiscretehazard(),
discretehazard_start(),
rdiscretehazard()
Examples
hazards <- c(0.3, 0.5, 1)
pdiscretehazard(c(0.5, 1, 2, 3), boundaries = 0:3, hazards = hazards)
Step (piecewise-constant) CDF
Description
Returns the CDF of a discrete distribution whose mass is concentrated at
the right boundary of each bin. The CDF is right-continuous and piecewise
constant with jumps at boundaries[2], ..., boundaries[K+1].
Usage
pdiscretestep(q, boundaries = NULL, pmf)
Arguments
q |
Numeric vector of quantiles. |
boundaries |
Numeric vector of length |
pmf |
Numeric vector of length |
Details
Below boundaries[1] the function returns 0. At
boundaries[i+1] (the right edge of bin i), F jumps by
pmf[i], so F(boundaries[i+1]) = \sum_{j=1}^{i} pmf_j.
For q in [boundaries[i], boundaries[i+1]), F equals
\sum_{j=1}^{i-1} pmf_j. At or above boundaries[K+1]
the function returns 1.
Use with fitdistdoublecens()
This function carries the attribute vector_param = "pmf" so that
fitdistdoublecens can drive it from a flat list of scalar
parameters p1, ..., p_{K-1}. The free parameters are the first
K-1 bin probabilities; the last is set to
1 - sum(p1, ..., p_{K-1}). When the implied probabilities violate
the simplex (any negative entry, or sum departing from 1 by more than
10^{-8}), the function returns 0 (or near-zero density in
ddiscretestep) rather than erroring; this drives the
optimiser back to the feasible region.
Value
Numeric vector of CDF values, the same length as q.
See Also
Other pdiscretestep:
ddiscretestep(),
hazards_to_pmf(),
pmf_to_hazards(),
rdiscretestep()
Examples
# Two-bin PMF: mass 0.3 at x=1, mass 0.7 at x=2
pdiscretestep(c(0.5, 1, 1.5, 2), boundaries = 0:2, pmf = c(0.3, 0.7))
Convert a PMF to discrete-time hazards
Description
Inverts hazards_to_pmf(): given a PMF, computes the discrete-time
conditional hazard at each time point.
h_i = pmf_i / (1 - \sum_{j < i} pmf_j)
Usage
pmf_to_hazards(pmf)
Arguments
pmf |
Numeric vector of probabilities. Must be non-negative and sum to approximately 1. |
Details
The returned vector has the same length as pmf, with the last
entry equal to 1.
Value
Numeric vector of hazards in [0, 1].
See Also
Other pdiscretestep:
ddiscretestep(),
hazards_to_pmf(),
pdiscretestep(),
rdiscretestep()
Examples
pmf_to_hazards(c(0.2, 0.3, 0.5))
Compute the primary event censored CDF for delays
Description
This function computes the primary event censored cumulative distribution function (CDF) for a given set of quantiles. It adjusts the CDF of the primary event distribution by accounting for the delay distribution and potential truncation at a maximum delay (D) and minimum delay (L). The function allows for custom primary event distributions and delay distributions.
Usage
pprimarycensored(
q,
pdist,
pwindow = 1,
L = -Inf,
D = Inf,
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
...,
check = TRUE
)
ppcens(
q,
pdist,
pwindow = 1,
L = -Inf,
D = Inf,
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
...,
check = TRUE
)
Arguments
q |
Vector of quantiles |
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
pwindow |
Primary event window. Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
dprimary_args |
[Deprecated] Use |
... |
Additional arguments to be passed to pdist |
check |
Logical; if |
Details
The primary event censored CDF is computed by integrating the product of the delay distribution function (CDF) and the primary event distribution function (PDF) over the primary event window. The integration is adjusted for truncation if specified.
The primary event censored CDF, F_{\text{cens}}(q), is given by:
F_{\text{cens}}(q) = \int_{0}^{pwindow} F(q - p) \cdot f_{\text{primary}}(p)
\, dp
where F is the CDF of the delay distribution,
f_{\text{primary}} is the PDF of the primary event times, and
pwindow is the primary event window.
If truncation is applied (finite D or finite L), the CDF is
normalized:
F_{\text{cens,norm}}(q) = \frac{F_{\text{cens}}(q) - F_{\text{cens}}(L)}{
F_{\text{cens}}(D) - F_{\text{cens}}(L)}
where F_{\text{cens,norm}}(q) is the normalized CDF. For values
q \leq L, the function returns 0; for values q \geq D, it
returns 1.
This function creates a primarycensored object using
new_pcens() and then computes the primary event
censored CDF using pcens_cdf(). This abstraction allows
for automatic use of analytical solutions when available, while
seamlessly falling back to numerical integration when necessary.
See methods(pcens_cdf) for which combinations have analytical
solutions implemented.
Value
Vector of primary event censored CDFs, normalized over [L, D] if truncation is applied
See Also
Primary event censored distribution functions
dprimarycensored(),
qprimarycensored(),
rprimarycensored()
Examples
# Example: Lognormal distribution with uniform primary events
pprimarycensored(c(0.1, 0.5, 1), plnorm, meanlog = 0, sdlog = 1)
# Example: Lognormal distribution with exponential growth primary events
pprimarycensored(
c(0.1, 0.5, 1), plnorm,
dprimary = dexpgrowth,
primary_args = list(r = 0.2), meanlog = 0, sdlog = 1
)
# Example: Left-truncated distribution (e.g., for generation intervals)
pprimarycensored(
c(1, 2, 3), plnorm,
L = 1, D = 10,
meanlog = 0, sdlog = 1
)
Compute quantiles corresponding to target probabilities for primary event censored delays
Description
This function computes the quantiles (delay values) that correspond to specified probabilities in the primary event censored distribution. For a given probability p, it computes the delay value q such that the cumulative probability up to q equals p in the primary event censored distribution. The distribution accounts for both the delay distribution and the primary event timing distribution.
Usage
qprimarycensored(
p,
pdist,
pwindow = 1,
L = -Inf,
D = Inf,
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
...,
check = TRUE
)
qpcens(
p,
pdist,
pwindow = 1,
L = -Inf,
D = Inf,
dprimary = dunif,
primary_args = NULL,
pprimary = NULL,
dprimary_args = NULL,
...,
check = TRUE
)
Arguments
p |
Vector of probabilities between 0 and 1 for which to compute corresponding quantiles |
pdist |
Distribution function (CDF). The package can identify base R
distributions for potential analytical solutions. For non-base R functions,
users can apply |
pwindow |
Primary event window. Use |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
dprimary |
Function to generate the probability density function
(PDF) of primary event times. This function should take a value |
primary_args |
List of additional arguments to be passed to
dprimary (and the matching primary CDF). For example, when using
|
pprimary |
Optional CDF for the primary event distribution. May be
a function or a character string naming a primary distribution in
|
dprimary_args |
[Deprecated] Use |
... |
Additional arguments to be passed to pdist |
check |
Logical; if |
Details
For each probability, the function finds the delay value where that proportion of events have occurred by that time in the primary event censored distribution. This is done by inverting the cumulative distribution function.
The function creates a primarycensored object using new_pcens() and then
computes the quantiles using pcens_quantile(). This approach allows for
analytical solutions when available, falling back to numerical methods when
necessary.
For example, if p = 0.5, the function returns the median delay (truncated over [L, D] if specified) where 50% of censored events occur by this time and 50% occur after.
See methods(pcens_quantile) for which combinations have analytical
solutions implemented.
Value
Vector of delay values (quantiles) corresponding to the input probabilities
See Also
new_pcens() and pcens_quantile()
Primary event censored distribution functions
dprimarycensored(),
pprimarycensored(),
rprimarycensored()
Examples
# Compute delays where 25%, 50%, and 75% of events occur by (quartiles)
# Using lognormal delays with uniform primary events
qprimarycensored(c(0.25, 0.5, 0.75), plnorm, meanlog = 0, sdlog = 1)
# Same quartiles but with exponential growth in primary events
qprimarycensored(
c(0.25, 0.5, 0.75), plnorm,
dprimary = dexpgrowth,
primary_args = list(r = 0.2), meanlog = 0, sdlog = 1
)
# Same quartiles but with truncation at 10
qprimarycensored(
c(0.25, 0.5, 0.75), plnorm,
dprimary = dexpgrowth,
primary_args = list(r = 0.2), meanlog = 0, sdlog = 1, D = 10
)
# Left-truncated distribution (e.g., for generation intervals)
qprimarycensored(
c(0.25, 0.5, 0.75), plnorm,
L = 1, D = 10, meanlog = 0, sdlog = 1
)
Sample from a hazard-parameterised step distribution
Description
Draws n independent samples from the discrete distribution defined
by hazards. Converts hazards to a PMF via
hazards_to_pmf() then delegates to rdiscretestep().
Usage
rdiscretehazard(n, boundaries = NULL, hazards)
Arguments
n |
Integer. Number of samples to draw. |
boundaries |
Numeric vector of length |
hazards |
Numeric vector of length |
Details
Outside fitting it is a deterministic wrapper around rdiscretestep().
It earns its keep as a fitting parameterisation in fitdistdoublecens()
because the random walk on the logit hazard smooths the recovered PMF.
Value
Numeric vector of length n.
See Also
rdiscretestep(), hazards_to_pmf(), pmf_to_hazards(),
fitdistdoublecens()
Other pdiscretehazard:
ddiscretehazard(),
discretehazard_start(),
pdiscretehazard()
Examples
set.seed(42)
rdiscretehazard(10, boundaries = 0:3, hazards = c(0.3, 0.5, 1))
Sample from a step distribution
Description
Draws n independent samples from the discrete distribution with
probability mass pmf[i] at boundaries[i+1].
Usage
rdiscretestep(n, boundaries = NULL, pmf)
Arguments
n |
Integer. Number of samples to draw. |
boundaries |
Numeric vector of length |
pmf |
Numeric vector of length |
Value
Numeric vector of length n.
See Also
Other pdiscretestep:
ddiscretestep(),
hazards_to_pmf(),
pdiscretestep(),
pmf_to_hazards()
Examples
set.seed(42)
rdiscretestep(10, boundaries = 0:3, pmf = c(0.2, 0.5, 0.3))
Generate random samples from a primary event censored distribution
Description
This function generates random samples from a primary event censored distribution. It adjusts the distribution by accounting for the primary event distribution and potential truncation at a maximum delay (D) and minimum delay (L). The function allows for custom primary event distributions and delay distributions.
Usage
rprimarycensored(
n,
rdist,
pwindow = 1,
swindow = 1,
L = -Inf,
D = Inf,
rprimary = stats::runif,
rprimary_args = list(),
oversampling_factor = 1.2,
...
)
rpcens(
n,
rdist,
pwindow = 1,
swindow = 1,
L = -Inf,
D = Inf,
rprimary = stats::runif,
rprimary_args = list(),
oversampling_factor = 1.2,
...
)
Arguments
n |
Number of random samples to generate. |
rdist |
Function to generate random samples from the delay distribution
for example |
pwindow |
Primary event window. Use |
swindow |
Integer specifying the window size for rounding the delay
(default is 1). If |
L |
Minimum delay (lower truncation point). Defaults to |
D |
Maximum delay (upper truncation point). If finite, the distribution is truncated at D. If set to Inf, no upper truncation is applied. Defaults to Inf. |
rprimary |
Function to generate random samples from the primary
distribution (default is |
rprimary_args |
List of additional arguments to be passed to rprimary. |
oversampling_factor |
Factor by which to oversample the number of samples to account for truncation (default is 1.2). |
... |
Additional arguments to be passed to the distribution function. |
Details
The mathematical formulation for generating random samples from a primary event censored distribution is as follows:
Generate primary event times (p) from the specified primary event distribution (f_p) with parameters phi, defined between 0 and the primary event window (pwindow):
p \sim f_p(\phi), \quad p \in [0, pwindow]Generate delays (d) from the specified delay distribution (f_d) with parameters theta:
d \sim f_d(\theta)Calculate the total delays (t) by adding the primary event times and the delays:
t = p + dApply upper truncation to remove delays >= D:
t_{upper} = \{t \mid t < D\}Round the delays to the nearest secondary event window (swindow):
t_{rounded} = \lfloor \frac{t_{upper}}{swindow} \rfloor \times swindowApply lower truncation on the rounded values to ensure observed delays are >= L:
t_{valid} = \{t_{rounded} \mid t_{rounded} \geq L\}
The function oversamples to account for potential truncation and generates additional samples if needed to reach the desired number of valid samples.
Value
Vector of random samples from the primary event censored distribution censored by the secondary event window.
See Also
Primary event censored distribution functions
dprimarycensored(),
pprimarycensored(),
qprimarycensored()
Examples
# Example: Lognormal distribution with uniform primary events
rprimarycensored(10, rlnorm, meanlog = 0, sdlog = 1)
# Example: Lognormal distribution with exponential growth primary events
rprimarycensored(
10, rlnorm,
rprimary = rexpgrowth, rprimary_args = list(r = 0.2),
meanlog = 0, sdlog = 1
)
# Example: Left-truncated distribution (e.g., for generation intervals)
rprimarycensored(10, rlnorm, L = 1, D = 10, meanlog = 0, sdlog = 1)
Update the parameters of a pcens object
Description
Replaces the delay distribution parameters, and optionally the primary
event distribution arguments, of an existing pcens object.
The delay and primary distribution functions, the primary event CDF and
the class are kept as they are.
The updated object therefore dispatches to the same pcens_cdf() method
without looking up names or rebuilding the class.
This is cheaper than calling new_pcens() again when one distribution is
evaluated for many parameter sets, for example posterior draws.
Usage
## S3 method for class 'pcens'
update(object, ..., primary_args = NULL)
Arguments
object |
A |
... |
Named delay distribution parameters. Each one replaces the
entry of the same name in |
primary_args |
Optional named list of primary event distribution
arguments. These are merged into |
Details
Parameters are merged rather than replaced as a whole, so
update(object, scale = 3) changes scale and keeps all other
parameters. Parameters cannot be removed; use new_pcens() for that.
A name in ... that is not already in object$args must be an argument
of object$pdist other than its first, unless pdist takes ....
Otherwise an error is raised. Names in primary_args are not checked
against dprimary.
Value
A pcens object with the same class as object and updated
args, primary_args and dprimary_args fields. See new_pcens() for
the fields of a pcens object.
See Also
Low level primary event censored distribution objects and methods
new_pcens(),
pcens_cdf(),
pcens_cdf.default(),
pcens_cdf.pcens_pdiscretehazard(),
pcens_cdf.pcens_pdiscretestep(),
pcens_cdf.pcens_pgamma_dunif(),
pcens_cdf.pcens_pgengamma.orig_dunif(),
pcens_cdf.pcens_pgengamma_dunif(),
pcens_cdf.pcens_plnorm_dunif(),
pcens_cdf.pcens_pweibull_dunif(),
pcens_pmf(),
pcens_pmf.default(),
pcens_quantile(),
pcens_quantile.default()
Examples
obj <- new_pcens(
pdist = pgamma, dprimary = dunif,
primary_args = list(min = 0, max = 1),
shape = 1, scale = 1
)
obj <- update(obj, shape = 2, scale = 3)
pcens_cdf(obj, q = c(1, 5, 10), pwindow = 1)
# Update the primary event distribution arguments
obj <- new_pcens(
pdist = pgamma, dprimary = dexpgrowth,
primary_args = list(r = 0.2),
shape = 2, scale = 3
)
obj <- update(obj, primary_args = list(r = 0.5))
pcens_pmf(obj, x = 0:5, pwindow = 1)