Skip to content

API: Testing

Each test object holds the data and settings for one comparison. Call it to run the test. This page summarizes the available tests and their exact inputs and results.

Pick a test

See Choose a test to match a task to a test. Exact inputs and results are listed on the pages for MannWhitneyU, Dsos, DeLong, and Venkatraman.

Run a test

  1. Make a holder with your data.
  2. Configure the test.
  3. Call the holder to run it.
  4. Read pvalue.

The holder keeps your data and settings together. Configuration returns a new holder and leaves the original unchanged.

Design note

The holder pattern takes inspiration from R infer for separating test steps and Julia HypothesisTests.jl for holder objects and frozen results.

For two-group tests, source is the reference group and target is the group under review. For paired model tests, candidate is the model being considered and reference is the baseline.

import numpy as np
import samesame as ss

source = np.array([0.10, 0.22, 0.28, 0.35])
target = np.array([0.30, 0.42, 0.55, 0.61])

test = ss.MannWhitneyU(source, target)
test = test.set_permutation(seed=np.random.default_rng(12345))
shift = test()

DeLong uses an asymptotic normal test by default and needs no permutation settings. To use its permutation version, call .set_permutation(...) before running the test.

Set batch for large runs

Permutation settings default to seed=None, n_permutations=9999, and batch=None. Set a seed to repeat sampled results.

Use batch when the sample is large (n > 5000) or you run many permutations (n_permutations >= 9999). Try batch=100 as a starting point. It processes permutations in chunks to limit peak memory. Keep the same seed, permutation count, and batch size when reproducing a sampled result.

test = test.set_permutation(seed=np.random.default_rng(12345), n_permutations=9999, batch=100)

Batching limits peak memory by processing permutations in chunks. With batch=100, the test processes 100 permutations at a time. Keep the seed, permutation count, and batch size fixed when reproducing a sampled result.

Results

Each call returns a frozen TestResult. Its fields cannot be reassigned. Some values inside extra can be mutable; permutation null arrays are read-only. The result holds the p-value (pvalue), the observed measure (statistic), the test name, the direction tested, and additional details in extra.

A p-value measures how unusual the observed result would be if the test's null hypothesis were true. The selected alternative defines which results count as more extreme. A p-value is not the probability that the null is true or a measure of harm. The meaning of statistic depends on the test:

Test statistic test_name alternative
MannWhitneyU AUROC with source = 0 and target = 1 Mann-Whitney U (permutation) two-sided
Dsos Tail-weighted AUC; it is not AUROC D-SOS (permutation) greater
DeLong AUROC(candidate) - AUROC(reference) DeLong (asymptotic) or DeLong (permutation) caller selects
Venkatraman Non-negative summed gap between paired ROC curves Venkatraman (permutation) two-sided

AUROC is the area under the receiver operating characteristic curve. It summarizes how well a score ranks cases with and without the outcome.

Permutation tests compare the observed result with a permutation distribution. The two-sample tests permute group labels while keeping scores and weights fixed; paired tests swap candidate and reference predictions within each case. The observed configuration contributes to the tail count, so permutation p-values are not zero. A two-sided test checks for a difference in either direction.

n_permutations is the requested number of resamples. If SciPy can enumerate all possible arrangements with fewer resamples, it evaluates them all. In that case, extra["null"] has fewer entries than the requested count, while extra["n_permutations"] still reports the requested count.

References

  • DeLong, DeLong, and Clarke-Pearson, “Comparing the Areas under Two or More Correlated Receiver Operating Characteristic Curves: A Nonparametric Approach,” Biometrics, 1988.
  • Sun and Xu, “Fast Implementation of DeLong’s Algorithm for Comparing the Areas Under Correlated Receiver Operating Characteristic Curves,” IEEE Signal Processing Letters, 2014.
  • Mann and Whitney, “On a Test of Whether One of Two Random Variables Is Stochastically Larger than the Other,” Annals of Mathematical Statistics, 1947. The package does not implement asymptotic MannWhitneyU. Use scipy.stats.mannwhitneyu(..., method="asymptotic") instead.
  • Venkatraman and Begg, “A Distribution-Free Procedure for Comparing Receiver Operating Characteristic Curves from a Paired Experiment,” Biometrika, 1996. This package uses average midranks without jitter.

Objects

samesame.TestResult dataclass

Fixed result returned by each test call.

Attributes:

Name Type Description
pvalue float

P-value in [0, 1]. Under the test's null hypothesis, it is the probability of a statistic at least as extreme as the observed statistic, using the specified alternative. It is not the probability that the null is true or that harm occurred. Two-sample tests and paired permutation tests use permutation distributions; asymptotic DeLong uses a normal approximation.

statistic float

Observed measure. MannWhitneyU reports AUROC. Dsos reports tail-weighted AUC. DeLong reports the difference AUROC(candidate) - AUROC(reference). Venkatraman reports the summed gap between the curves.

test_name Literal['Mann-Whitney U (permutation)', 'D-SOS (permutation)', 'DeLong (asymptotic)', 'DeLong (permutation)', 'Venkatraman (permutation)']

Test that produced the result.

alternative Literal['two-sided', 'greater', 'less']

Tail or direction used to assess the statistic.

extra Mapping[str, Any]

Per-test payload, excluded from equality. Permutation tests carry "null" (a read-only array of evaluated statistics) and "n_permutations" (the requested resample count). If SciPy enumerates all possible arrangements, "null" can be shorter than the requested count. Paired permutation tests add "auroc" with per-scorer AUROC values. Asymptotic DeLong carries "auroc", "se", and "z". The repr summarizes arrays by shape.

Source code in src/samesame/_common.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@dataclass(frozen=True, slots=True)
class TestResult:
    """Fixed result returned by each test call.

    Attributes
    ----------
    pvalue :
        P-value in ``[0, 1]``. Under the test's null hypothesis, it is the
        probability of a statistic at least as extreme as the observed
        statistic, using the specified alternative. It is not the
        probability that the null is true or that harm occurred. Two-sample
        tests and paired permutation tests use permutation distributions;
        asymptotic ``DeLong`` uses a normal approximation.
    statistic :
        Observed measure. ``MannWhitneyU`` reports AUROC. ``Dsos``
        reports tail-weighted AUC. ``DeLong`` reports the difference
        ``AUROC(candidate) - AUROC(reference)``. ``Venkatraman`` reports
        the summed gap between the curves.
    test_name :
        Test that produced the result.
    alternative :
        Tail or direction used to assess the statistic.
    extra :
        Per-test payload, excluded from equality. Permutation tests carry
        ``"null"`` (a read-only array of evaluated statistics) and
        ``"n_permutations"`` (the requested resample count). If SciPy
        enumerates all possible arrangements, ``"null"`` can be shorter
        than the requested count. Paired permutation tests add
        ``"auroc"`` with per-scorer AUROC values. Asymptotic ``DeLong``
        carries ``"auroc"``, ``"se"``, and ``"z"``. The repr summarizes
        arrays by shape.
    """

    pvalue: float
    statistic: float
    test_name: Literal[
        "Mann-Whitney U (permutation)",
        "D-SOS (permutation)",
        "DeLong (asymptotic)",
        "DeLong (permutation)",
        "Venkatraman (permutation)",
    ]
    alternative: Literal["two-sided", "greater", "less"]
    extra: Mapping[str, Any] = field(default_factory=dict, compare=False, hash=False)

    def __repr__(self) -> str:
        parts = []
        for key, value in self.extra.items():
            if isinstance(value, np.ndarray):
                parts.append(f"{key}=array(shape={value.shape}, dtype={value.dtype})")
            else:
                parts.append(f"{key}={value!r}")
        inner = ", ".join(parts)
        return (
            f"TestResult(pvalue={self.pvalue!r}, statistic={self.statistic!r}, "
            f"test_name={self.test_name!r}, "
            f"alternative={self.alternative!r}, extra={{{inner}}})"
        )