Skip to content

Bench Statistics

benchmatrix.bench_statistics

Run-level statistical inference for benchmark comparisons.

BootstrapInterval dataclass

One deterministic bootstrap effect estimate and confidence interval.

Source code in src/benchmatrix/bench_statistics.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass(frozen=True, slots=True)
class BootstrapInterval:
    """One deterministic bootstrap effect estimate and confidence interval."""

    estimate: float | None
    low: float | None
    high: float | None
    method: str
    warnings: tuple[str, ...] = ()
    issues: tuple[str, ...] = ()

    @property
    def adequate(self) -> bool:
        """Return whether the interval was calculated successfully."""
        return not self.issues and self.estimate is not None and self.low is not None and self.high is not None

adequate property

adequate: bool

Return whether the interval was calculated successfully.

PrecisionPlan dataclass

Fixed-design pair-count plan derived from pilot paired log ratios.

The planning estimand is the mean signed paired log ratio, a variance-based proxy rather than the ratio-of-marginal-medians estimand used by formal BCa inference. This is a precision calculation, not power analysis. Its pair-count result assumes that pilot variability is representative and that a fresh confirmatory collection uses the complete planned pair count fixed before examining its results. additional_pairs is only the arithmetic difference from the pilot size; it does not endorse reusing pilot outcomes.

Source code in src/benchmatrix/bench_statistics.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
@dataclass(frozen=True, slots=True)
class PrecisionPlan:
    """Fixed-design pair-count plan derived from pilot paired log ratios.

    The planning estimand is the mean signed paired log ratio, a variance-based
    proxy rather than the ratio-of-marginal-medians estimand used by formal BCa
    inference. This is a precision calculation, not power analysis. Its
    pair-count result assumes that pilot variability is representative and that
    a fresh confirmatory collection uses the complete planned pair count fixed
    before examining its results. ``additional_pairs`` is only the arithmetic
    difference from the pilot size; it does not endorse reusing pilot outcomes.
    """

    method: Literal["paired_log_ratio_t"]
    pilot_pairs: int
    target_half_width_percent: float
    confidence_level: float
    adjusted_confidence_level: float
    multiplicity: MultiplicityCorrection
    family_size: int
    pilot_log_ratio_standard_deviation: float | None
    critical_value: float | None
    required_pairs: int | None
    additional_pairs: int | None
    assumptions: tuple[str, ...]
    minimum_pairs: int = _MINIMUM_GROUP_SIZE
    pair_count_multiple: int = 1
    unconstrained_required_pairs: int | None = None
    strata_count: int = 1
    warnings: tuple[str, ...] = ()
    issues: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        """Validate and normalize a precision plan."""
        if self.method != "paired_log_ratio_t":
            raise ValueError(f"Unsupported precision-planning method: {self.method!r}.")
        if isinstance(self.pilot_pairs, bool) or not isinstance(self.pilot_pairs, int) or self.pilot_pairs < 0:
            raise ValueError("PrecisionPlan.pilot_pairs must be a non-negative integer.")
        if not math.isfinite(self.target_half_width_percent) or self.target_half_width_percent <= 0.0:
            raise ValueError("PrecisionPlan.target_half_width_percent must be finite and positive.")
        for field_name, value in (
            ("confidence_level", self.confidence_level),
            ("adjusted_confidence_level", self.adjusted_confidence_level),
        ):
            if not math.isfinite(value) or not 0.0 < value < 1.0:
                raise ValueError(f"PrecisionPlan.{field_name} must be finite and between zero and one.")
        if self.adjusted_confidence_level < self.confidence_level:
            raise ValueError("Adjusted confidence level must not be lower than the nominal confidence level.")
        if self.multiplicity not in {"bonferroni", "none"}:
            raise ValueError(f"Unsupported multiplicity correction: {self.multiplicity!r}.")
        if isinstance(self.family_size, bool) or not isinstance(self.family_size, int) or self.family_size <= 0:
            raise ValueError("PrecisionPlan.family_size must be a positive integer.")
        if (
            isinstance(self.minimum_pairs, bool)
            or not isinstance(self.minimum_pairs, int)
            or self.minimum_pairs < _MINIMUM_GROUP_SIZE
        ):
            raise ValueError(f"PrecisionPlan.minimum_pairs must be at least {_MINIMUM_GROUP_SIZE}.")
        if (
            isinstance(self.pair_count_multiple, bool)
            or not isinstance(self.pair_count_multiple, int)
            or self.pair_count_multiple <= 0
        ):
            raise ValueError("PrecisionPlan.pair_count_multiple must be a positive integer.")
        if isinstance(self.strata_count, bool) or not isinstance(self.strata_count, int) or self.strata_count < 0:
            raise ValueError("PrecisionPlan.strata_count must be a non-negative integer.")
        if self.multiplicity == "none" and self.adjusted_confidence_level != self.confidence_level:
            raise ValueError("Unadjusted precision plans must use the nominal confidence level.")
        if self.pilot_log_ratio_standard_deviation is not None and (
            not math.isfinite(self.pilot_log_ratio_standard_deviation) or self.pilot_log_ratio_standard_deviation < 0.0
        ):
            raise ValueError("PrecisionPlan pilot variability must be finite and non-negative or None.")
        if self.critical_value is not None and (not math.isfinite(self.critical_value) or self.critical_value <= 0.0):
            raise ValueError("PrecisionPlan.critical_value must be finite and positive or None.")
        unconstrained_required_pairs = self.unconstrained_required_pairs
        if self.required_pairs is not None and unconstrained_required_pairs is None:
            # Preserve compatibility for callers that constructed the original
            # value object directly. Planner-created values always persist the
            # independently calculated unconstrained count.
            unconstrained_required_pairs = self.required_pairs
            object.__setattr__(self, "unconstrained_required_pairs", unconstrained_required_pairs)
        result_fields = (
            self.critical_value,
            unconstrained_required_pairs,
            self.required_pairs,
            self.additional_pairs,
        )
        if any(value is not None for value in result_fields) and not all(value is not None for value in result_fields):
            raise ValueError("PrecisionPlan critical value and pair-count results must be present together.")
        if self.required_pairs is not None:
            if self.strata_count <= 0:
                raise ValueError("Complete PrecisionPlan results require at least one fitted stratum.")
            if self.pilot_log_ratio_standard_deviation is None or self.pilot_log_ratio_standard_deviation == 0.0:
                raise ValueError("Complete PrecisionPlan results require positive pilot residual variability.")
            minimum_estimable_pairs = self.strata_count + 1
            if (
                isinstance(unconstrained_required_pairs, bool)
                or not isinstance(unconstrained_required_pairs, int)
                or unconstrained_required_pairs < max(_MINIMUM_GROUP_SIZE, minimum_estimable_pairs)
            ):
                raise ValueError(
                    "PrecisionPlan.unconstrained_required_pairs must leave positive residual degrees of freedom."
                )
            if (
                isinstance(self.required_pairs, bool)
                or not isinstance(self.required_pairs, int)
                or self.required_pairs < max(_MINIMUM_GROUP_SIZE, minimum_estimable_pairs)
            ):
                raise ValueError("PrecisionPlan.required_pairs must leave positive residual degrees of freedom.")
            expected_required = _round_up_to_multiple(
                max(unconstrained_required_pairs, self.minimum_pairs),
                self.pair_count_multiple,
            )
            if self.required_pairs != expected_required:
                raise ValueError(
                    "PrecisionPlan.required_pairs is inconsistent with the unconstrained count and design constraints."
                )
            expected_unconstrained = _required_pairs_for_precision(
                self.pilot_log_ratio_standard_deviation,
                target_log_half_width=math.log1p(self.target_half_width_percent / 100.0),
                confidence_level=self.adjusted_confidence_level,
                strata_count=self.strata_count,
            )
            if unconstrained_required_pairs != expected_unconstrained:
                raise ValueError(
                    "PrecisionPlan.unconstrained_required_pairs is inconsistent with its variability and target."
                )
            expected_critical = _student_t_critical(
                self.adjusted_confidence_level,
                degrees_of_freedom=self.required_pairs - self.strata_count,
            )
            critical_value = self.critical_value
            if critical_value is None or not math.isclose(
                critical_value,
                expected_critical,
                rel_tol=1e-12,
                abs_tol=0.0,
            ):
                raise ValueError(
                    "PrecisionPlan.critical_value is inconsistent with confidence and residual degrees of freedom."
                )
            expected_additional = max(0, self.required_pairs - self.pilot_pairs)
            if self.additional_pairs != expected_additional:
                raise ValueError("PrecisionPlan.additional_pairs is inconsistent with the pilot and required counts.")
        assumptions = tuple(self.assumptions)
        warnings = tuple(self.warnings)
        issues = tuple(self.issues)
        if not assumptions or any(not isinstance(item, str) or not item for item in assumptions):
            raise ValueError("PrecisionPlan.assumptions must contain non-empty strings.")
        if any(not isinstance(item, str) or not item for item in (*warnings, *issues)):
            raise ValueError("PrecisionPlan warnings and issues must contain non-empty strings.")
        object.__setattr__(self, "assumptions", assumptions)
        object.__setattr__(self, "warnings", warnings)
        object.__setattr__(self, "issues", issues)

    @property
    def adequate(self) -> bool:
        """Return whether a complete fixed-design pair-count estimate exists."""
        return not self.issues and self.required_pairs is not None and self.additional_pairs is not None

adequate property

adequate: bool

Return whether a complete fixed-design pair-count estimate exists.

__post_init__

__post_init__() -> None

Validate and normalize a precision plan.

Source code in src/benchmatrix/bench_statistics.py
 69
 70
 71
 72
 73
 74
 75
 76
 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def __post_init__(self) -> None:
    """Validate and normalize a precision plan."""
    if self.method != "paired_log_ratio_t":
        raise ValueError(f"Unsupported precision-planning method: {self.method!r}.")
    if isinstance(self.pilot_pairs, bool) or not isinstance(self.pilot_pairs, int) or self.pilot_pairs < 0:
        raise ValueError("PrecisionPlan.pilot_pairs must be a non-negative integer.")
    if not math.isfinite(self.target_half_width_percent) or self.target_half_width_percent <= 0.0:
        raise ValueError("PrecisionPlan.target_half_width_percent must be finite and positive.")
    for field_name, value in (
        ("confidence_level", self.confidence_level),
        ("adjusted_confidence_level", self.adjusted_confidence_level),
    ):
        if not math.isfinite(value) or not 0.0 < value < 1.0:
            raise ValueError(f"PrecisionPlan.{field_name} must be finite and between zero and one.")
    if self.adjusted_confidence_level < self.confidence_level:
        raise ValueError("Adjusted confidence level must not be lower than the nominal confidence level.")
    if self.multiplicity not in {"bonferroni", "none"}:
        raise ValueError(f"Unsupported multiplicity correction: {self.multiplicity!r}.")
    if isinstance(self.family_size, bool) or not isinstance(self.family_size, int) or self.family_size <= 0:
        raise ValueError("PrecisionPlan.family_size must be a positive integer.")
    if (
        isinstance(self.minimum_pairs, bool)
        or not isinstance(self.minimum_pairs, int)
        or self.minimum_pairs < _MINIMUM_GROUP_SIZE
    ):
        raise ValueError(f"PrecisionPlan.minimum_pairs must be at least {_MINIMUM_GROUP_SIZE}.")
    if (
        isinstance(self.pair_count_multiple, bool)
        or not isinstance(self.pair_count_multiple, int)
        or self.pair_count_multiple <= 0
    ):
        raise ValueError("PrecisionPlan.pair_count_multiple must be a positive integer.")
    if isinstance(self.strata_count, bool) or not isinstance(self.strata_count, int) or self.strata_count < 0:
        raise ValueError("PrecisionPlan.strata_count must be a non-negative integer.")
    if self.multiplicity == "none" and self.adjusted_confidence_level != self.confidence_level:
        raise ValueError("Unadjusted precision plans must use the nominal confidence level.")
    if self.pilot_log_ratio_standard_deviation is not None and (
        not math.isfinite(self.pilot_log_ratio_standard_deviation) or self.pilot_log_ratio_standard_deviation < 0.0
    ):
        raise ValueError("PrecisionPlan pilot variability must be finite and non-negative or None.")
    if self.critical_value is not None and (not math.isfinite(self.critical_value) or self.critical_value <= 0.0):
        raise ValueError("PrecisionPlan.critical_value must be finite and positive or None.")
    unconstrained_required_pairs = self.unconstrained_required_pairs
    if self.required_pairs is not None and unconstrained_required_pairs is None:
        # Preserve compatibility for callers that constructed the original
        # value object directly. Planner-created values always persist the
        # independently calculated unconstrained count.
        unconstrained_required_pairs = self.required_pairs
        object.__setattr__(self, "unconstrained_required_pairs", unconstrained_required_pairs)
    result_fields = (
        self.critical_value,
        unconstrained_required_pairs,
        self.required_pairs,
        self.additional_pairs,
    )
    if any(value is not None for value in result_fields) and not all(value is not None for value in result_fields):
        raise ValueError("PrecisionPlan critical value and pair-count results must be present together.")
    if self.required_pairs is not None:
        if self.strata_count <= 0:
            raise ValueError("Complete PrecisionPlan results require at least one fitted stratum.")
        if self.pilot_log_ratio_standard_deviation is None or self.pilot_log_ratio_standard_deviation == 0.0:
            raise ValueError("Complete PrecisionPlan results require positive pilot residual variability.")
        minimum_estimable_pairs = self.strata_count + 1
        if (
            isinstance(unconstrained_required_pairs, bool)
            or not isinstance(unconstrained_required_pairs, int)
            or unconstrained_required_pairs < max(_MINIMUM_GROUP_SIZE, minimum_estimable_pairs)
        ):
            raise ValueError(
                "PrecisionPlan.unconstrained_required_pairs must leave positive residual degrees of freedom."
            )
        if (
            isinstance(self.required_pairs, bool)
            or not isinstance(self.required_pairs, int)
            or self.required_pairs < max(_MINIMUM_GROUP_SIZE, minimum_estimable_pairs)
        ):
            raise ValueError("PrecisionPlan.required_pairs must leave positive residual degrees of freedom.")
        expected_required = _round_up_to_multiple(
            max(unconstrained_required_pairs, self.minimum_pairs),
            self.pair_count_multiple,
        )
        if self.required_pairs != expected_required:
            raise ValueError(
                "PrecisionPlan.required_pairs is inconsistent with the unconstrained count and design constraints."
            )
        expected_unconstrained = _required_pairs_for_precision(
            self.pilot_log_ratio_standard_deviation,
            target_log_half_width=math.log1p(self.target_half_width_percent / 100.0),
            confidence_level=self.adjusted_confidence_level,
            strata_count=self.strata_count,
        )
        if unconstrained_required_pairs != expected_unconstrained:
            raise ValueError(
                "PrecisionPlan.unconstrained_required_pairs is inconsistent with its variability and target."
            )
        expected_critical = _student_t_critical(
            self.adjusted_confidence_level,
            degrees_of_freedom=self.required_pairs - self.strata_count,
        )
        critical_value = self.critical_value
        if critical_value is None or not math.isclose(
            critical_value,
            expected_critical,
            rel_tol=1e-12,
            abs_tol=0.0,
        ):
            raise ValueError(
                "PrecisionPlan.critical_value is inconsistent with confidence and residual degrees of freedom."
            )
        expected_additional = max(0, self.required_pairs - self.pilot_pairs)
        if self.additional_pairs != expected_additional:
            raise ValueError("PrecisionPlan.additional_pairs is inconsistent with the pilot and required counts.")
    assumptions = tuple(self.assumptions)
    warnings = tuple(self.warnings)
    issues = tuple(self.issues)
    if not assumptions or any(not isinstance(item, str) or not item for item in assumptions):
        raise ValueError("PrecisionPlan.assumptions must contain non-empty strings.")
    if any(not isinstance(item, str) or not item for item in (*warnings, *issues)):
        raise ValueError("PrecisionPlan warnings and issues must contain non-empty strings.")
    object.__setattr__(self, "assumptions", assumptions)
    object.__setattr__(self, "warnings", warnings)
    object.__setattr__(self, "issues", issues)

bootstrap_median_ratio_interval

bootstrap_median_ratio_interval(
    baseline_values: Sequence[float],
    candidate_values: Sequence[float],
    *,
    lower_is_better: bool,
    confidence_level: float,
    resamples: int,
    random_seed: int,
) -> BootstrapInterval

Estimate a direction-aware median ratio with a run-level BCa interval.

Each value is the statistic from one independently launched benchmark process. The two groups are resampled independently, so raw benchmark rounds within a process are never treated as independent observations. Input values are sorted before resampling to make seeded results invariant to the order in which run files were supplied.

Source code in src/benchmatrix/bench_statistics.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def bootstrap_median_ratio_interval(
    baseline_values: Sequence[float],
    candidate_values: Sequence[float],
    *,
    lower_is_better: bool,
    confidence_level: float,
    resamples: int,
    random_seed: int,
) -> BootstrapInterval:
    """Estimate a direction-aware median ratio with a run-level BCa interval.

    Each value is the statistic from one independently launched benchmark
    process. The two groups are resampled independently, so raw benchmark
    rounds within a process are never treated as independent observations.
    Input values are sorted before resampling to make seeded results invariant
    to the order in which run files were supplied.
    """
    try:
        baseline = tuple(sorted(float(value) for value in baseline_values))
        candidate = tuple(sorted(float(value) for value in candidate_values))
    except (OverflowError, TypeError, ValueError):
        return BootstrapInterval(
            estimate=None,
            low=None,
            high=None,
            method="bca_bootstrap",
            issues=("run statistics must be finite numeric values",),
        )
    issues = _validate_inputs(
        baseline,
        candidate,
        confidence_level=confidence_level,
        resamples=resamples,
    )
    if issues:
        return BootstrapInterval(
            estimate=None,
            low=None,
            high=None,
            method="bca_bootstrap",
            issues=issues,
        )

    try:
        estimate = _median_ratio_effect(
            baseline,
            candidate,
            lower_is_better=lower_is_better,
        )
    except OverflowError:
        estimate = math.inf
    if not math.isfinite(estimate):
        return BootstrapInterval(
            estimate=None,
            low=None,
            high=None,
            method="bca_bootstrap",
            issues=("observed median-ratio effect is not finite",),
        )
    # A deterministic pseudorandom stream is required for reproducible statistics; this is not cryptography.
    generator = random.Random(random_seed)  # nosec B311
    bootstrap_estimates_list: list[float] = []
    for _ in range(resamples):
        try:
            bootstrap_estimate = _median_ratio_effect(
                _resample(baseline, generator),
                _resample(candidate, generator),
                lower_is_better=lower_is_better,
            )
        except OverflowError:
            bootstrap_estimate = math.inf
        if not math.isfinite(bootstrap_estimate):
            return BootstrapInterval(
                estimate=None,
                low=None,
                high=None,
                method="bca_bootstrap",
                issues=("bootstrap median-ratio effect is not finite",),
            )
        bootstrap_estimates_list.append(bootstrap_estimate)
    bootstrap_estimates = tuple(bootstrap_estimates_list)
    lower_probability = (1.0 - confidence_level) / 2.0
    upper_probability = 1.0 - lower_probability
    try:
        jackknife = _jackknife_estimates(
            baseline,
            candidate,
            lower_is_better=lower_is_better,
        )
    except OverflowError:
        jackknife = ((), ())
    if not all(math.isfinite(value) for group in jackknife for value in group):
        jackknife = ((), ())
    adjusted = (
        None
        if not all(jackknife)
        else _bca_probabilities(
            bootstrap_estimates,
            estimate=estimate,
            jackknife_estimates=jackknife,
            lower_probability=lower_probability,
            upper_probability=upper_probability,
        )
    )
    warnings: tuple[str, ...] = ()
    method = "bca_bootstrap"
    if adjusted is None:
        adjusted = (lower_probability, upper_probability)
        method = "percentile_bootstrap"
        warnings = ("BCa adjustment was degenerate; used a percentile bootstrap interval.",)

    low = _quantile(bootstrap_estimates, adjusted[0])
    high = _quantile(bootstrap_estimates, adjusted[1])
    if low > high:
        low, high = high, low
    return BootstrapInterval(
        estimate=estimate,
        low=low,
        high=high,
        method=method,
        warnings=warnings,
    )

bootstrap_paired_median_ratio_interval

bootstrap_paired_median_ratio_interval(
    baseline_values: Sequence[float],
    candidate_values: Sequence[float],
    *,
    lower_is_better: bool,
    confidence_level: float,
    resamples: int,
    random_seed: int,
    strata: Sequence[str] | None = None,
) -> BootstrapInterval

Estimate a median ratio with a paired run-level BCa interval.

Values at the same position form one matched process-run pair. Complete pairs, rather than individual observations, are resampled with replacement. The point estimand remains the direction-aware ratio of the baseline and candidate marginal medians, matching independent-design inference. Pair tuples are sorted before seeded resampling, making results invariant to the order in which complete pairs were supplied without destroying pairing.

When strata contains fixed collection-design labels such as "AB" and "BA", resampling preserves the observed count in every stratum. The BCa acceleration then uses delete-one estimates grouped by stratum. Without labels, all complete pairs are treated as exchangeable and the returned interval carries an explicit warning about that assumption.

Source code in src/benchmatrix/bench_statistics.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def bootstrap_paired_median_ratio_interval(
    baseline_values: Sequence[float],
    candidate_values: Sequence[float],
    *,
    lower_is_better: bool,
    confidence_level: float,
    resamples: int,
    random_seed: int,
    strata: Sequence[str] | None = None,
) -> BootstrapInterval:
    """Estimate a median ratio with a paired run-level BCa interval.

    Values at the same position form one matched process-run pair. Complete
    pairs, rather than individual observations, are resampled with replacement.
    The point estimand remains the direction-aware ratio of the baseline and
    candidate marginal medians, matching independent-design inference. Pair
    tuples are sorted before seeded resampling, making results invariant to the
    order in which complete pairs were supplied without destroying pairing.

    When ``strata`` contains fixed collection-design labels such as ``"AB"``
    and ``"BA"``, resampling preserves the observed count in every stratum.
    The BCa acceleration then uses delete-one estimates grouped by stratum.
    Without labels, all complete pairs are treated as exchangeable and the
    returned interval carries an explicit warning about that assumption.
    """
    try:
        baseline = tuple(float(value) for value in baseline_values)
        candidate = tuple(float(value) for value in candidate_values)
    except (OverflowError, TypeError, ValueError):
        return BootstrapInterval(
            estimate=None,
            low=None,
            high=None,
            method="bca_bootstrap",
            issues=("paired run statistics must be finite numeric values",),
        )
    normalized_strata, strata_issues = _normalize_strata(
        strata,
        expected_length=len(baseline),
    )
    issues = (
        *_validate_paired_inputs(
            baseline,
            candidate,
            confidence_level=confidence_level,
            resamples=resamples,
            random_seed=random_seed,
        ),
        *strata_issues,
    )
    if issues:
        return BootstrapInterval(
            estimate=None,
            low=None,
            high=None,
            method="bca_bootstrap",
            issues=issues,
        )

    pairs = tuple(sorted(zip(baseline, candidate, strict=True)))
    pair_strata = (
        None
        if normalized_strata is None
        else _stratify_pairs(
            baseline,
            candidate,
            normalized_strata,
        )
    )
    try:
        estimate = _paired_median_ratio_effect(
            pairs,
            lower_is_better=lower_is_better,
        )
    except OverflowError:
        estimate = math.inf
    if not math.isfinite(estimate):
        return BootstrapInterval(
            estimate=None,
            low=None,
            high=None,
            method="bca_bootstrap",
            issues=("observed paired median-ratio effect is not finite",),
        )

    # A deterministic pseudorandom stream is required for reproducible statistics; this is not cryptography.
    generator = random.Random(random_seed)  # nosec B311
    bootstrap_estimates_list: list[float] = []
    for _ in range(resamples):
        try:
            bootstrap_pairs = (
                _resample_pairs(pairs, generator)
                if pair_strata is None
                else _resample_stratified_pairs(pair_strata, generator)
            )
            bootstrap_estimate = _paired_median_ratio_effect(
                bootstrap_pairs,
                lower_is_better=lower_is_better,
            )
        except OverflowError:
            bootstrap_estimate = math.inf
        if not math.isfinite(bootstrap_estimate):
            return BootstrapInterval(
                estimate=None,
                low=None,
                high=None,
                method="bca_bootstrap",
                issues=("bootstrap paired median-ratio effect is not finite",),
            )
        bootstrap_estimates_list.append(bootstrap_estimate)
    bootstrap_estimates = tuple(bootstrap_estimates_list)

    lower_probability = (1.0 - confidence_level) / 2.0
    upper_probability = 1.0 - lower_probability
    try:
        jackknife = (
            (
                _paired_jackknife_estimates(
                    pairs,
                    lower_is_better=lower_is_better,
                ),
            )
            if pair_strata is None
            else _stratified_paired_jackknife_estimates(
                pair_strata,
                lower_is_better=lower_is_better,
            )
        )
    except OverflowError:
        jackknife = ((),)
    if not all(math.isfinite(value) for group in jackknife for value in group):
        jackknife = ((),)
    adjusted = (
        None
        if not all(jackknife)
        else _bca_probabilities(
            bootstrap_estimates,
            estimate=estimate,
            jackknife_estimates=jackknife,
            lower_probability=lower_probability,
            upper_probability=upper_probability,
        )
    )
    warnings = (
        (
            "No orientation strata were supplied; paired bootstrap inference assumes all complete pairs are "
            "exchangeable and may treat fixed AB/BA order effects as random variation.",
        )
        if pair_strata is None
        else ()
    )
    method = "bca_bootstrap"
    if adjusted is None:
        adjusted = (lower_probability, upper_probability)
        method = "percentile_bootstrap"
        warnings = (
            *warnings,
            "Paired BCa adjustment was degenerate; used a percentile bootstrap interval.",
        )

    low = _quantile(bootstrap_estimates, adjusted[0])
    high = _quantile(bootstrap_estimates, adjusted[1])
    if low > high:
        low, high = high, low
    return BootstrapInterval(
        estimate=estimate,
        low=low,
        high=high,
        method=method,
        warnings=warnings,
    )

plan_paired_precision

plan_paired_precision(
    baseline_values: Sequence[float],
    candidate_values: Sequence[float],
    *,
    lower_is_better: bool,
    target_half_width_percent: float,
    confidence_level: float = 0.95,
    family_size: int = 1,
    multiplicity: MultiplicityCorrection = "bonferroni",
    strata: Sequence[str] | None = None,
    minimum_pairs: int = _MINIMUM_GROUP_SIZE,
    pair_count_multiple: int = 2,
) -> PrecisionPlan

Estimate a fixed confirmatory pair count from paired pilot runs.

The planning approximation uses the residual standard deviation of signed paired log ratios. Positive signed log ratios mean improvement, regardless of metric direction. When fixed collection-design strata such as AB and BA are supplied, a separate mean is fitted for each stratum so a fixed orientation effect is not counted as future random variation. Student-t degrees of freedom account for those fitted means.

The requested percentage half-width is converted to log1p(target / 100). This is a multiplicative mean-log-ratio proxy for the formal ratio-of-marginal-medians BCa estimand; the two targets are not identical. minimum_pairs and pair_count_multiple are then applied to the smallest unconstrained count. The default multiple of two keeps a direct AB/BA plan even. With bonferroni, confidence is adjusted across family_size cells before calculating the count.

required_pairs is the size of a fresh future confirmatory collection. additional_pairs is only its arithmetic difference from the pilot count, not a recommendation to append runs to the analyzed pilot. This calculation describes precision only: it does not estimate power, justify optional stopping, or update a confirmatory run count after results have been examined.

Source code in src/benchmatrix/bench_statistics.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def plan_paired_precision(
    baseline_values: Sequence[float],
    candidate_values: Sequence[float],
    *,
    lower_is_better: bool,
    target_half_width_percent: float,
    confidence_level: float = 0.95,
    family_size: int = 1,
    multiplicity: MultiplicityCorrection = "bonferroni",
    strata: Sequence[str] | None = None,
    minimum_pairs: int = _MINIMUM_GROUP_SIZE,
    pair_count_multiple: int = 2,
) -> PrecisionPlan:
    """Estimate a fixed confirmatory pair count from paired pilot runs.

    The planning approximation uses the residual standard deviation of signed
    paired log ratios. Positive signed log ratios mean improvement, regardless
    of metric direction. When fixed collection-design ``strata`` such as AB and
    BA are supplied, a separate mean is fitted for each stratum so a fixed
    orientation effect is not counted as future random variation. Student-t
    degrees of freedom account for those fitted means.

    The requested percentage half-width is converted to
    ``log1p(target / 100)``. This is a multiplicative mean-log-ratio proxy for
    the formal ratio-of-marginal-medians BCa estimand; the two targets are not
    identical. ``minimum_pairs`` and ``pair_count_multiple`` are then applied
    to the smallest unconstrained count. The default multiple of two keeps a
    direct AB/BA plan even. With ``bonferroni``, confidence is adjusted across
    ``family_size`` cells before calculating the count.

    ``required_pairs`` is the size of a fresh future confirmatory collection.
    ``additional_pairs`` is only its arithmetic difference from the pilot
    count, not a recommendation to append runs to the analyzed pilot. This
    calculation describes precision only: it does not estimate power, justify
    optional stopping, or update a confirmatory run count after results have
    been examined.
    """
    target = _validate_positive_number(
        target_half_width_percent,
        field_name="target_half_width_percent",
    )
    confidence = _validate_open_probability(
        confidence_level,
        field_name="confidence_level",
    )
    if isinstance(family_size, bool) or not isinstance(family_size, int):
        raise TypeError("family_size must be an integer.")
    if family_size <= 0:
        raise ValueError("family_size must be a positive integer.")
    if multiplicity not in {"bonferroni", "none"}:
        raise ValueError(f"Unsupported multiplicity correction: {multiplicity!r}.")
    if isinstance(minimum_pairs, bool) or not isinstance(minimum_pairs, int):
        raise TypeError("minimum_pairs must be an integer.")
    if minimum_pairs < _MINIMUM_GROUP_SIZE:
        raise ValueError(f"minimum_pairs must be at least {_MINIMUM_GROUP_SIZE}.")
    if isinstance(pair_count_multiple, bool) or not isinstance(pair_count_multiple, int):
        raise TypeError("pair_count_multiple must be an integer.")
    if pair_count_multiple <= 0:
        raise ValueError("pair_count_multiple must be a positive integer.")
    adjusted_confidence = 1.0 - (1.0 - confidence) / family_size if multiplicity == "bonferroni" else confidence
    if adjusted_confidence >= 1.0:
        raise ValueError("family_size is too large to represent the Bonferroni-adjusted confidence level.")

    assumptions = (
        "Pilot pairs are representative of the future fixed-design paired collection.",
        "Pairs are independent, while baseline and candidate observations remain dependent within each pair.",
        "The target is a multiplicative half-width for the mean signed paired log ratio; this is a variance-based "
        "proxy and is not the formal ratio-of-marginal-medians BCa estimand.",
        "Pilot residual log-ratio variability is representative of future residual variability; the Student-t "
        "proxy does not guarantee a BCa interval width.",
        *(
            (
                "Future collection uses a prespecified fixed stratum allocation compatible with the pair-count "
                "multiple; fitted stratum effects are not treated as random variation.",
            )
            if strata is not None
            else ("No fixed orientation strata are modeled, so all paired log ratios are treated as exchangeable.",)
        ),
        "Required pairs describe a fresh confirmatory collection; the additional-pairs field is descriptive "
        "arithmetic and does not justify reusing the pilot.",
        "The confirmatory pair count is fixed before collection; this is not power analysis or a sequential "
        "stopping rule.",
    )
    try:
        baseline = tuple(float(value) for value in baseline_values)
        candidate = tuple(float(value) for value in candidate_values)
    except (OverflowError, TypeError, ValueError):
        return _failed_precision_plan(
            pilot_pairs=0,
            target_half_width_percent=target,
            confidence_level=confidence,
            adjusted_confidence_level=adjusted_confidence,
            multiplicity=multiplicity,
            family_size=family_size,
            minimum_pairs=minimum_pairs,
            pair_count_multiple=pair_count_multiple,
            strata_count=0 if strata is not None else 1,
            assumptions=assumptions,
            issues=("paired pilot statistics must be finite numeric values",),
        )

    pilot_pairs = min(len(baseline), len(candidate))
    normalized_strata, strata_issues = _normalize_strata(
        strata,
        expected_length=len(baseline),
    )
    strata_count = 1 if normalized_strata is None and not strata_issues else 0
    if normalized_strata is not None:
        strata_count = len(set(normalized_strata))
    issues = (*_paired_measurement_issues(baseline, candidate), *strata_issues)
    if issues:
        return _failed_precision_plan(
            pilot_pairs=pilot_pairs,
            target_half_width_percent=target,
            confidence_level=confidence,
            adjusted_confidence_level=adjusted_confidence,
            multiplicity=multiplicity,
            family_size=family_size,
            minimum_pairs=minimum_pairs,
            pair_count_multiple=pair_count_multiple,
            strata_count=strata_count,
            assumptions=assumptions,
            issues=issues,
        )

    direction = -1.0 if lower_is_better else 1.0
    log_ratios = tuple(
        direction * (math.log(candidate_value) - math.log(baseline_value))
        for baseline_value, candidate_value in zip(baseline, candidate, strict=True)
    )
    try:
        variability = _residual_log_ratio_standard_deviation(
            log_ratios,
            strata=normalized_strata,
        )
    except (OverflowError, statistics.StatisticsError):
        variability = math.inf
    residual_degrees_of_freedom = pilot_pairs - strata_count
    warnings = (
        "Precision planning targets a multiplicative mean-log-ratio proxy; formal inference targets a ratio of "
        "marginal medians.",
        "The pair-count estimate treats pilot residual variability as representative and does not account for "
        "uncertainty in that estimated variability.",
        *(
            (
                "No orientation strata were supplied; planning treats fixed AB/BA order effects as random "
                "paired variation.",
            )
            if normalized_strata is None
            else ()
        ),
        *(
            (
                f"The pilot contains fewer than {_MINIMUM_STABLE_PILOT_SIZE} pairs; "
                + "its variability estimate is unstable.",
            )
            if pilot_pairs < _MINIMUM_STABLE_PILOT_SIZE
            else ()
        ),
        *(
            (
                f"The pilot has only {residual_degrees_of_freedom} residual degree(s) of freedom after fitting "
                f"{strata_count} stratum mean(s); its variability estimate is unstable.",
            )
            if normalized_strata is not None and residual_degrees_of_freedom < _MINIMUM_STABLE_PILOT_SIZE
            else ()
        ),
    )
    if not math.isfinite(variability):
        return _failed_precision_plan(
            pilot_pairs=pilot_pairs,
            target_half_width_percent=target,
            confidence_level=confidence,
            adjusted_confidence_level=adjusted_confidence,
            multiplicity=multiplicity,
            family_size=family_size,
            minimum_pairs=minimum_pairs,
            pair_count_multiple=pair_count_multiple,
            strata_count=strata_count,
            assumptions=assumptions,
            warnings=warnings,
            issues=("paired pilot log-ratio variability is not finite",),
        )
    if variability == 0.0:
        return _failed_precision_plan(
            pilot_pairs=pilot_pairs,
            target_half_width_percent=target,
            confidence_level=confidence,
            adjusted_confidence_level=adjusted_confidence,
            multiplicity=multiplicity,
            family_size=family_size,
            minimum_pairs=minimum_pairs,
            pair_count_multiple=pair_count_multiple,
            strata_count=strata_count,
            assumptions=assumptions,
            variability=variability,
            warnings=warnings,
            issues=("paired pilot residual log ratios have zero variability; required precision cannot be estimated",),
        )

    target_log_half_width = math.log1p(target / 100.0)
    unconstrained_required = _required_pairs_for_precision(
        variability,
        target_log_half_width=target_log_half_width,
        confidence_level=adjusted_confidence,
        strata_count=strata_count,
    )
    if unconstrained_required is None:
        return _failed_precision_plan(
            pilot_pairs=pilot_pairs,
            target_half_width_percent=target,
            confidence_level=confidence,
            adjusted_confidence_level=adjusted_confidence,
            multiplicity=multiplicity,
            family_size=family_size,
            minimum_pairs=minimum_pairs,
            pair_count_multiple=pair_count_multiple,
            strata_count=strata_count,
            assumptions=assumptions,
            variability=variability,
            warnings=warnings,
            issues=(f"estimated required pair count exceeds {_MAXIMUM_PLANNED_PAIRS:,}",),
        )
    required = _round_up_to_multiple(
        max(unconstrained_required, minimum_pairs),
        pair_count_multiple,
    )
    if required > _MAXIMUM_PLANNED_PAIRS:
        return _failed_precision_plan(
            pilot_pairs=pilot_pairs,
            target_half_width_percent=target,
            confidence_level=confidence,
            adjusted_confidence_level=adjusted_confidence,
            multiplicity=multiplicity,
            family_size=family_size,
            minimum_pairs=minimum_pairs,
            pair_count_multiple=pair_count_multiple,
            strata_count=strata_count,
            assumptions=assumptions,
            variability=variability,
            warnings=warnings,
            issues=(f"design-constrained required pair count exceeds {_MAXIMUM_PLANNED_PAIRS:,}",),
        )
    critical_value = _student_t_critical(
        adjusted_confidence,
        degrees_of_freedom=required - strata_count,
    )
    return PrecisionPlan(
        method="paired_log_ratio_t",
        pilot_pairs=pilot_pairs,
        target_half_width_percent=target,
        confidence_level=confidence,
        adjusted_confidence_level=adjusted_confidence,
        multiplicity=multiplicity,
        family_size=family_size,
        pilot_log_ratio_standard_deviation=variability,
        critical_value=critical_value,
        required_pairs=required,
        additional_pairs=max(0, required - pilot_pairs),
        assumptions=assumptions,
        minimum_pairs=minimum_pairs,
        pair_count_multiple=pair_count_multiple,
        unconstrained_required_pairs=unconstrained_required,
        strata_count=strata_count,
        warnings=warnings,
    )