Skip to content

Rare-Event Planning

Rare outcomes are estimated from few events, so precision depends on how many events or positives are observed, not on how many people are enrolled or tested. These functions plan follow-up and testing effort: exact Poisson rate intervals over person-time, the number of tests or person-time needed to observe a number of positives with a stated assurance, and the expected relative precision of a proportion at a planned sample size. See the planning guide for a worked example, and person_time_for_events to convert a trial's event target into person-time.

Intervals assume independent events at a common rate or probability. Clustering and heterogeneity between sites or participants widen the true uncertainty; assess them by simulation with run_grid.

All functions require SciPy (trade-study[stats]).

trade_study.RateInterval(events, person_time, estimate, low, high, confidence) dataclass

Exact two-sided interval for a Poisson rate per unit of person-time.

Attributes:

Name Type Description
events int

Observed events.

person_time float

Total person-time at risk.

estimate float

events / person_time.

low float

Lower bound (0 when no events were observed).

high float

Upper bound.

confidence float

Nominal two-sided level.

trade_study.rate_interval(events, person_time, *, confidence=0.95)

Estimate an event rate with the exact Garwood interval.

The bounds are chi-square quantiles: chi2(a/2, 2k) / 2T and chi2(1 - a/2, 2k + 2) / 2T, computed through the inverse regularized incomplete gamma function. Events must follow a Poisson process with a common rate over the person-time; clustering or heterogeneity between participants widens the true uncertainty beyond this interval.

Parameters:

Name Type Description Default
events int

Observed event count.

required
person_time float

Positive total person-time.

required
confidence float

Two-sided level in (0, 1).

0.95

Returns:

Type Description
RateInterval

Estimate and exact bounds.

Raises:

Type Description
ValueError

If the count, person-time or level is invalid.

Examples:

>>> interval = rate_interval(0, 1000.0)
>>> interval.low, round(interval.high * 1000, 3)
(0.0, 3.689)
Source code in src/trade_study/rates.py
def rate_interval(
    events: int, person_time: float, *, confidence: float = 0.95
) -> RateInterval:
    """Estimate an event rate with the exact Garwood interval.

    The bounds are chi-square quantiles: ``chi2(a/2, 2k) / 2T`` and
    ``chi2(1 - a/2, 2k + 2) / 2T``, computed through the inverse regularized
    incomplete gamma function. Events must follow a Poisson process with a
    common rate over the person-time; clustering or heterogeneity between
    participants widens the true uncertainty beyond this interval.

    Args:
        events: Observed event count.
        person_time: Positive total person-time.
        confidence: Two-sided level in (0, 1).

    Returns:
        Estimate and exact bounds.

    Raises:
        ValueError: If the count, person-time or level is invalid.

    Examples:
        >>> interval = rate_interval(0, 1000.0)
        >>> interval.low, round(interval.high * 1000, 3)
        (0.0, 3.689)
    """
    k = _count(events, "events")
    if (
        isinstance(person_time, bool)
        or not isinstance(person_time, Real)
        or not math.isfinite(person_time)
        or person_time <= 0
    ):
        msg = "person_time must be positive and finite"
        raise ValueError(msg)
    tail = _level(confidence)
    special = _scipy_special()
    time = float(person_time)
    low = 0.0 if k == 0 else float(special.gammaincinv(k, tail)) / time
    high = float(special.gammainccinv(k + 1, tail)) / time
    return RateInterval(k, time, k / time, low, high, float(confidence))

trade_study.trials_for_positives(probability, positives, *, assurance=0.9)

Smallest number tested with at least positives positives at assurance.

The chance P(Binomial(n, p) >= k) rises with n, so the boundary is found by doubling and bisection. Use this to plan surveillance that must observe enough positives to describe them (for example to sequence or to estimate a positivity), not to guarantee interval precision.

Parameters:

Name Type Description Default
probability float

Probability that one tested person is positive, in (0, 1].

required
positives int

Required number of positives (0 needs no testing).

required
assurance float

Required probability in (0, 1).

0.9

Returns:

Type Description
int

Number of people to test.

Raises:

Type Description
ValueError

If an argument is invalid or more than 2**53 are needed.

Examples:

>>> trials_for_positives(0.5, 1, assurance=0.75)
2
Source code in src/trade_study/rates.py
def trials_for_positives(
    probability: float, positives: int, *, assurance: float = 0.9
) -> int:
    """Smallest number tested with at least ``positives`` positives at ``assurance``.

    The chance ``P(Binomial(n, p) >= k)`` rises with ``n``, so the boundary
    is found by doubling and bisection. Use this to plan surveillance that
    must observe enough positives to describe them (for example to sequence
    or to estimate a positivity), not to guarantee interval precision.

    Args:
        probability: Probability that one tested person is positive, in (0, 1].
        positives: Required number of positives (0 needs no testing).
        assurance: Required probability in (0, 1).

    Returns:
        Number of people to test.

    Raises:
        ValueError: If an argument is invalid or more than 2**53 are needed.

    Examples:
        >>> trials_for_positives(0.5, 1, assurance=0.75)
        2
    """
    p = _probability(probability, "probability")
    k = _count(positives, "positives")
    target = _probability(assurance, "assurance", open_upper=True)
    if k == 0:
        return 0
    binom = _scipy_stats().binom

    def enough(n: int) -> bool:
        return bool(binom.sf(k - 1, n, p) >= target)

    hi = max(k, math.ceil(k / p))
    while not enough(hi):
        hi *= 2
        if hi > _MAX_TRIALS:
            msg = "More than 2**53 trials would be needed"
            raise ValueError(msg)
    lo = k - 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if enough(mid):
            hi = mid
        else:
            lo = mid
    return hi

trade_study.person_time_for_positives(rate, positives, *, assurance=0.9)

Person-time with at least positives Poisson events at assurance.

P(Poisson(rate * T) >= k) equals the regularized lower incomplete gamma function P(k, rate * T), so the person-time is exact: T = gammaincinv(k, assurance) / rate.

Parameters:

Name Type Description Default
rate float

Positive event rate per unit of person-time.

required
positives int

Required number of events.

required
assurance float

Required probability in (0, 1).

0.9

Returns:

Type Description
float

Person-time (0 when no events are required).

Raises:

Type Description
ValueError

If an argument is invalid.

Examples:

>>> round(person_time_for_positives(0.01, 1, assurance=0.95), 1)
299.6
Source code in src/trade_study/rates.py
def person_time_for_positives(
    rate: float, positives: int, *, assurance: float = 0.9
) -> float:
    """Person-time with at least ``positives`` Poisson events at ``assurance``.

    ``P(Poisson(rate * T) >= k)`` equals the regularized lower incomplete
    gamma function ``P(k, rate * T)``, so the person-time is exact:
    ``T = gammaincinv(k, assurance) / rate``.

    Args:
        rate: Positive event rate per unit of person-time.
        positives: Required number of events.
        assurance: Required probability in (0, 1).

    Returns:
        Person-time (0 when no events are required).

    Raises:
        ValueError: If an argument is invalid.

    Examples:
        >>> round(person_time_for_positives(0.01, 1, assurance=0.95), 1)
        299.6
    """
    if (
        isinstance(rate, bool)
        or not isinstance(rate, Real)
        or not math.isfinite(rate)
        or rate <= 0
    ):
        msg = "rate must be positive and finite"
        raise ValueError(msg)
    k = _count(positives, "positives")
    target = _probability(assurance, "assurance", open_upper=True)
    if k == 0:
        return 0.0
    return float(_scipy_special().gammaincinv(k, target)) / float(rate)

trade_study.expected_relative_half_width(n, probability, *, method='clopper-pearson', confidence=0.95)

Expected interval half-width relative to the true probability at n.

The half-width (high - low) / 2 is averaged over the binomial distribution of the number of positives, including outcomes with none, rather than evaluated at the expected count. Outcomes outside the central 1 - 1e-12 binomial mass are omitted and the remaining weights renormalized.

Parameters:

Name Type Description Default
n int

Planned number tested (positive).

required
probability float

True probability in (0, 1).

required
method str

"clopper-pearson" (SciPy) or "wilson".

'clopper-pearson'
confidence float

Two-sided level in (0, 1).

0.95

Returns:

Type Description
float

Expected half-width divided by probability.

Raises:

Type Description
ValueError

If an argument is invalid.

Examples:

>>> wide = expected_relative_half_width(1000, 0.01)
>>> narrow = expected_relative_half_width(10000, 0.01)
>>> narrow < wide
True
Source code in src/trade_study/rates.py
def expected_relative_half_width(
    n: int,
    probability: float,
    *,
    method: str = "clopper-pearson",
    confidence: float = 0.95,
) -> float:
    """Expected interval half-width relative to the true probability at ``n``.

    The half-width ``(high - low) / 2`` is averaged over the binomial
    distribution of the number of positives, including outcomes with none,
    rather than evaluated at the expected count. Outcomes outside the central
    ``1 - 1e-12`` binomial mass are omitted and the remaining weights
    renormalized.

    Args:
        n: Planned number tested (positive).
        probability: True probability in (0, 1).
        method: ``"clopper-pearson"`` (SciPy) or ``"wilson"``.
        confidence: Two-sided level in (0, 1).

    Returns:
        Expected half-width divided by ``probability``.

    Raises:
        ValueError: If an argument is invalid.

    Examples:
        >>> wide = expected_relative_half_width(1000, 0.01)
        >>> narrow = expected_relative_half_width(10000, 0.01)
        >>> narrow < wide
        True
    """
    trials = _count(n, "n")
    if not 0 < trials <= _MAX_TRIALS:
        msg = "n must be a positive integer at most 2**53"
        raise ValueError(msg)
    p = _probability(probability, "probability", open_upper=True)
    if method not in _METHODS:
        msg = f"method must be one of {_METHODS}"
        raise ValueError(msg)
    tail = _level(confidence)
    binom = _scipy_stats().binom
    lo = int(binom.ppf(0.5e-12, trials, p))
    hi = int(binom.isf(0.5e-12, trials, p))
    support = np.arange(max(0, lo - 1), min(trials, hi + 1) + 1, dtype=np.int64)
    weights = binom.pmf(support, trials, p)
    widths = _half_widths(support, trials, tail, method)
    return float(np.dot(weights, widths) / weights.sum() / p)

trade_study.trials_for_relative_precision(probability, relative_half_width, *, method='clopper-pearson', confidence=0.95)

Number tested whose expected relative half-width meets a target.

The expectation of :func:expected_relative_half_width falls with n almost monotonically; the boundary is found by doubling and bisection, and the returned n satisfies the target. Because the expectation is not exactly monotone, an adjacent smaller n can also satisfy it.

Parameters:

Name Type Description Default
probability float

True probability in (0, 1).

required
relative_half_width float

Target half-width divided by the probability.

required
method str

"clopper-pearson" (SciPy) or "wilson".

'clopper-pearson'
confidence float

Two-sided level in (0, 1).

0.95

Returns:

Type Description
int

Planned number tested.

Raises:

Type Description
ValueError

If an argument is invalid or more than 2**53 are needed.

Examples:

>>> n = trials_for_relative_precision(0.01, 0.5)
>>> expected_relative_half_width(n, 0.01) <= 0.5
True
Source code in src/trade_study/rates.py
def trials_for_relative_precision(
    probability: float,
    relative_half_width: float,
    *,
    method: str = "clopper-pearson",
    confidence: float = 0.95,
) -> int:
    """Number tested whose expected relative half-width meets a target.

    The expectation of :func:`expected_relative_half_width` falls with ``n``
    almost monotonically; the boundary is found by doubling and bisection,
    and the returned ``n`` satisfies the target. Because the expectation is
    not exactly monotone, an adjacent smaller ``n`` can also satisfy it.

    Args:
        probability: True probability in (0, 1).
        relative_half_width: Target half-width divided by the probability.
        method: ``"clopper-pearson"`` (SciPy) or ``"wilson"``.
        confidence: Two-sided level in (0, 1).

    Returns:
        Planned number tested.

    Raises:
        ValueError: If an argument is invalid or more than 2**53 are needed.

    Examples:
        >>> n = trials_for_relative_precision(0.01, 0.5)
        >>> expected_relative_half_width(n, 0.01) <= 0.5
        True
    """
    p = _probability(probability, "probability", open_upper=True)
    if (
        isinstance(relative_half_width, bool)
        or not isinstance(relative_half_width, Real)
        or not math.isfinite(relative_half_width)
        or relative_half_width <= 0
    ):
        msg = "relative_half_width must be positive and finite"
        raise ValueError(msg)

    def meets(n: int) -> bool:
        width = expected_relative_half_width(n, p, method=method, confidence=confidence)
        return width <= relative_half_width

    hi = 1
    while not meets(hi):
        hi *= 2
        if hi > _MAX_TRIALS:
            msg = "More than 2**53 trials would be needed"
            raise ValueError(msg)
    lo = hi // 2
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if meets(mid):
            hi = mid
        else:
            lo = mid
    return hi