Skip to content

Imperfect Tests

At low prevalence or low event rates, false positives from an imperfect test can be as common as true positives. Prevalence estimates are then biased upward, and efficacy estimates are diluted toward zero because false events fall on both arms (or, in a test-negative design, move people between the case and control groups). These helpers correct a prevalence estimate, combine repeated tests into one rule, and give the efficacy a study should expect from its endpoint calls, so that event targets and power curves use the right inputs.

Sensitivity and specificity are treated as known. Uncertainty in them, for example from a small validation study, is not propagated, and repeated tests are assumed conditionally independent given the true status.

trade_study.CorrectedPrevalence(k, n, apparent, estimate, low, high, sensitivity, specificity, confidence, method, truncated) dataclass

Prevalence corrected for test sensitivity and specificity.

Attributes:

Name Type Description
k int

Test-positive results.

n int

Tests.

apparent float

Observed positive share k / n.

estimate float

Rogan-Gladen estimate, clipped to [0, 1].

low float

Lower bound, clipped to [0, 1].

high float

Upper bound, clipped to [0, 1].

sensitivity float

Assumed sensitivity.

specificity float

Assumed specificity.

confidence float

Nominal two-sided level.

method str

Binomial interval method for the apparent prevalence.

truncated bool

Whether the unclipped estimate fell outside [0, 1].

trade_study.corrected_prevalence(k, n, *, sensitivity, specificity, confidence=0.95, method='clopper-pearson')

Correct an apparent prevalence for known test sensitivity and specificity.

The Rogan-Gladen estimate is (a + Sp - 1) / (Se + Sp - 1) for apparent prevalence a. The bounds map the binomial interval for the apparent prevalence through the same increasing function and clip to [0, 1]. With known accuracy the corrected interval covers the true prevalence exactly when the binomial interval covers the apparent one; clipping removes only impossible values. Uncertainty in sensitivity and specificity is not included, so the interval is too narrow when they are estimated from a small validation study.

Parameters:

Name Type Description Default
k int

Test-positive results.

required
n int

Tests (positive).

required
sensitivity float

Probability that a true positive tests positive.

required
specificity float

Probability that a true negative tests negative.

required
confidence float

Two-sided level in (0, 1).

0.95
method str

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

'clopper-pearson'

Returns:

Type Description
CorrectedPrevalence

Corrected estimate and bounds.

Raises:

Type Description
ValueError

If counts, accuracy or level are invalid.

Examples:

>>> result = corrected_prevalence(
...     30, 1000, sensitivity=0.9, specificity=0.99
... )
>>> round(result.estimate, 4)
0.0225
>>> corrected_prevalence(
...     5, 1000, sensitivity=0.9, specificity=0.99
... ).estimate
0.0
Source code in src/trade_study/misclassification.py
def corrected_prevalence(
    k: int,
    n: int,
    *,
    sensitivity: float,
    specificity: float,
    confidence: float = 0.95,
    method: str = "clopper-pearson",
) -> CorrectedPrevalence:
    """Correct an apparent prevalence for known test sensitivity and specificity.

    The Rogan-Gladen estimate is ``(a + Sp - 1) / (Se + Sp - 1)`` for
    apparent prevalence ``a``. The bounds map the binomial interval for the
    apparent prevalence through the same increasing function and clip to
    [0, 1]. With known accuracy the corrected interval covers the true
    prevalence exactly when the binomial interval covers the apparent one;
    clipping removes only impossible values. Uncertainty in sensitivity and
    specificity is not included, so the interval is too narrow when they are
    estimated from a small validation study.

    Args:
        k: Test-positive results.
        n: Tests (positive).
        sensitivity: Probability that a true positive tests positive.
        specificity: Probability that a true negative tests negative.
        confidence: Two-sided level in (0, 1).
        method: ``"clopper-pearson"`` (SciPy) or ``"wilson"``.

    Returns:
        Corrected estimate and bounds.

    Raises:
        ValueError: If counts, accuracy or level are invalid.

    Examples:
        >>> result = corrected_prevalence(
        ...     30, 1000, sensitivity=0.9, specificity=0.99
        ... )
        >>> round(result.estimate, 4)
        0.0225
        >>> corrected_prevalence(
        ...     5, 1000, sensitivity=0.9, specificity=0.99
        ... ).estimate
        0.0
    """
    se = _unit(sensitivity, "sensitivity")
    sp = _unit(specificity, "specificity")
    scale = se + sp - 1.0
    if scale <= 0:
        msg = "sensitivity + specificity must exceed 1 for an informative test"
        raise ValueError(msg)
    interval = proportion_interval(k, n, confidence=confidence, method=method)

    def correct(value: float) -> float:
        return (value + sp - 1.0) / scale

    raw = correct(interval.estimate)
    estimate = min(1.0, max(0.0, raw))
    return CorrectedPrevalence(
        interval.k,
        interval.n,
        interval.estimate,
        estimate,
        min(1.0, max(0.0, correct(interval.low))),
        min(1.0, max(0.0, correct(interval.high))),
        se,
        sp,
        interval.confidence,
        interval.method,
        truncated=raw != estimate,
    )

trade_study.repeated_test_accuracy(sensitivity, specificity, *, tests=2, rule='all')

Sensitivity and specificity of a rule that combines repeated tests.

Under rule="all" a result is positive only when every test is positive (confirmation): sensitivity Se**m and specificity 1 - (1 - Sp)**m. Under rule="any" one positive suffices: sensitivity 1 - (1 - Se)**m and specificity Sp**m. Tests are assumed conditionally independent given the true status. Correlated errors, such as repeated testing of a cross-reactive sample, make confirmation less effective than this.

Parameters:

Name Type Description Default
sensitivity float

Sensitivity of one test.

required
specificity float

Specificity of one test.

required
tests int

Number of tests combined (at least 1).

2
rule str

"all" or "any".

'all'

Returns:

Type Description
tuple[float, float]

Combined (sensitivity, specificity).

Raises:

Type Description
ValueError

If an argument is invalid.

Examples:

>>> se, sp = repeated_test_accuracy(0.9, 0.99, tests=2)
>>> round(se, 2), round(sp, 4)
(0.81, 0.9999)
Source code in src/trade_study/misclassification.py
def repeated_test_accuracy(
    sensitivity: float, specificity: float, *, tests: int = 2, rule: str = "all"
) -> tuple[float, float]:
    """Sensitivity and specificity of a rule that combines repeated tests.

    Under ``rule="all"`` a result is positive only when every test is
    positive (confirmation): sensitivity ``Se**m`` and specificity
    ``1 - (1 - Sp)**m``. Under ``rule="any"`` one positive suffices:
    sensitivity ``1 - (1 - Se)**m`` and specificity ``Sp**m``. Tests are
    assumed conditionally independent given the true status. Correlated
    errors, such as repeated testing of a cross-reactive sample, make
    confirmation less effective than this.

    Args:
        sensitivity: Sensitivity of one test.
        specificity: Specificity of one test.
        tests: Number of tests combined (at least 1).
        rule: ``"all"`` or ``"any"``.

    Returns:
        Combined ``(sensitivity, specificity)``.

    Raises:
        ValueError: If an argument is invalid.

    Examples:
        >>> se, sp = repeated_test_accuracy(0.9, 0.99, tests=2)
        >>> round(se, 2), round(sp, 4)
        (0.81, 0.9999)
    """
    se = _unit(sensitivity, "sensitivity")
    sp = _unit(specificity, "specificity")
    if isinstance(tests, bool) or not isinstance(tests, int) or tests < 1:
        msg = "tests must be a positive integer"
        raise ValueError(msg)
    if rule not in _RULES:
        msg = f"rule must be one of {_RULES}"
        raise ValueError(msg)
    if rule == "all":
        return se**tests, 1.0 - (1.0 - sp) ** tests
    return 1.0 - (1.0 - se) ** tests, sp**tests

trade_study.ObservedEfficacy(efficacy, observed, control_positive, treatment_positive, false_share) dataclass

Expected efficacy and endpoint calls under test misclassification.

Attributes:

Name Type Description
efficacy float

True efficacy on the risk scale.

observed float

Expected efficacy computed from positive calls.

control_positive float

Probability that a control participant is called positive over follow-up.

treatment_positive float

The same for a treated participant.

false_share float

Expected share of positive calls, over both arms, that are false.

trade_study.observed_efficacy(efficacy, control_event_probability, *, sensitivity, specificity, rho=1.0)

Efficacy a cohort trial should expect when endpoint calls are imperfect.

Each participant is called positive with probability Se * r + (1 - Sp) * (1 - r), where r is the true endpoint risk over follow-up (r_c for control, (1 - E) r_c for treatment). Efficacy here is 1 - risk ratio; for rare endpoints it is close to 1 - rate ratio. Misclassification is assumed nondifferential between arms, which blinding supports.

Parameters:

Name Type Description Default
efficacy float

True efficacy, at most 1.

required
control_event_probability float

Control-arm risk over follow-up, in (0, 1].

required
sensitivity float

Probability that a true event is called positive.

required
specificity float

Probability that a participant without the event is called negative.

required
rho float

Treatment-to-control allocation ratio (weights false_share).

1.0

Returns:

Type Description
ObservedEfficacy

Expected observed efficacy, call probabilities and false share.

Raises:

Type Description
ValueError

If an argument is invalid.

Examples:

>>> result = observed_efficacy(0.7, 0.01, sensitivity=0.9, specificity=0.99)
>>> round(result.observed, 3)
0.33
Source code in src/trade_study/misclassification.py
def observed_efficacy(
    efficacy: float,
    control_event_probability: float,
    *,
    sensitivity: float,
    specificity: float,
    rho: float = 1.0,
) -> ObservedEfficacy:
    """Efficacy a cohort trial should expect when endpoint calls are imperfect.

    Each participant is called positive with probability
    ``Se * r + (1 - Sp) * (1 - r)``, where ``r`` is the true endpoint risk
    over follow-up (``r_c`` for control, ``(1 - E) r_c`` for treatment).
    Efficacy here is ``1 - risk ratio``; for rare endpoints it is close to
    ``1 - rate ratio``. Misclassification is assumed nondifferential between
    arms, which blinding supports.

    Args:
        efficacy: True efficacy, at most 1.
        control_event_probability: Control-arm risk over follow-up, in (0, 1].
        sensitivity: Probability that a true event is called positive.
        specificity: Probability that a participant without the event is
            called negative.
        rho: Treatment-to-control allocation ratio (weights ``false_share``).

    Returns:
        Expected observed efficacy, call probabilities and false share.

    Raises:
        ValueError: If an argument is invalid.

    Examples:
        >>> result = observed_efficacy(0.7, 0.01, sensitivity=0.9, specificity=0.99)
        >>> round(result.observed, 3)
        0.33
    """
    se, sp = _accuracy(sensitivity, specificity)
    risk = _unit(control_event_probability, "control_event_probability")
    if (
        not math.isfinite(efficacy)
        or efficacy > 1
        or not math.isfinite(rho)
        or rho <= 0
    ):
        msg = "efficacy must be at most 1 and rho must be positive"
        raise ValueError(msg)
    treated_risk = (1.0 - efficacy) * risk
    if treated_risk > 1:
        msg = "Treatment-arm risk (1 - efficacy) * risk exceeds 1"
        raise ValueError(msg)
    control = se * risk + (1.0 - sp) * (1.0 - risk)
    treated = se * treated_risk + (1.0 - sp) * (1.0 - treated_risk)
    false = (1.0 - sp) * (rho * (1.0 - treated_risk) + (1.0 - risk))
    return ObservedEfficacy(
        float(efficacy),
        1.0 - treated / control,
        control,
        treated,
        false / (rho * treated + control),
    )

trade_study.tnd_observed_efficacy(efficacy, positivity, *, sensitivity, specificity, control_coverage)

Efficacy a test-negative design should expect when the test is imperfect.

Among people presenting with the syndrome, a share positivity truly has the target infection. Truly negative presenters are vaccinated with probability c; truly positive presenters with c OR / (1 - c + c OR), where OR = 1 - efficacy. False positives move truly negative presenters into the case group and false negatives move true cases into the control group, which pulls the observed odds ratio toward 1. At low positivity, specificity dominates the bias.

Parameters:

Name Type Description Default
efficacy float

True efficacy, below 1.

required
positivity float

Share of presenters with the target infection, in (0, 1).

required
sensitivity float

Test sensitivity.

required
specificity float

Test specificity.

required
control_coverage float

Vaccinated share among truly negative presenters, in (0, 1).

required

Returns:

Type Description
float

Expected 1 - OR computed from test results.

Raises:

Type Description
ValueError

If an argument is invalid.

Examples:

>>> round(
...     tnd_observed_efficacy(
...         0.8,
...         0.01,
...         sensitivity=0.95,
...         specificity=0.999,
...         control_coverage=0.5,
...     ),
...     3,
... )
0.753
Source code in src/trade_study/misclassification.py
def tnd_observed_efficacy(
    efficacy: float,
    positivity: float,
    *,
    sensitivity: float,
    specificity: float,
    control_coverage: float,
) -> float:
    """Efficacy a test-negative design should expect when the test is imperfect.

    Among people presenting with the syndrome, a share ``positivity`` truly
    has the target infection. Truly negative presenters are vaccinated with
    probability ``c``; truly positive presenters with ``c OR / (1 - c + c OR)``,
    where ``OR = 1 - efficacy``. False positives move truly negative
    presenters into the case group and false negatives move true cases into
    the control group, which pulls the observed odds ratio toward 1. At low
    positivity, specificity dominates the bias.

    Args:
        efficacy: True efficacy, below 1.
        positivity: Share of presenters with the target infection, in (0, 1).
        sensitivity: Test sensitivity.
        specificity: Test specificity.
        control_coverage: Vaccinated share among truly negative presenters,
            in (0, 1).

    Returns:
        Expected ``1 - OR`` computed from test results.

    Raises:
        ValueError: If an argument is invalid.

    Examples:
        >>> round(
        ...     tnd_observed_efficacy(
        ...         0.8,
        ...         0.01,
        ...         sensitivity=0.95,
        ...         specificity=0.999,
        ...         control_coverage=0.5,
        ...     ),
        ...     3,
        ... )
        0.753
    """
    se, sp = _accuracy(sensitivity, specificity)
    if not math.isfinite(efficacy) or efficacy >= 1:
        msg = "efficacy must be finite and below 1"
        raise ValueError(msg)
    for value, name in (
        (positivity, "positivity"),
        (control_coverage, "control_coverage"),
    ):
        if not math.isfinite(value) or not 0 < value < 1:
            msg = f"{name} must lie in (0, 1)"
            raise ValueError(msg)
    c = control_coverage
    ratio = 1.0 - efficacy
    case_vaccinated = c * ratio / (1.0 - c + c * ratio)
    true, other = positivity, 1.0 - positivity
    cases_vaccinated = true * se * case_vaccinated + other * (1.0 - sp) * c
    cases_unvaccinated = true * se * (1.0 - case_vaccinated) + other * (1.0 - sp) * (
        1.0 - c
    )
    controls_vaccinated = true * (1.0 - se) * case_vaccinated + other * sp * c
    controls_unvaccinated = true * (1.0 - se) * (1.0 - case_vaccinated) + other * sp * (
        1.0 - c
    )
    odds = (cases_vaccinated / cases_unvaccinated) / (
        controls_vaccinated / controls_unvaccinated
    )
    return 1.0 - odds