ab-analysis-kit 0.0.1.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
  2. ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
  3. ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
  4. ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
  5. ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
  6. ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
  7. abkit/__init__.py +40 -0
  8. abkit/cli/__init__.py +1 -0
  9. abkit/cli/_output.py +111 -0
  10. abkit/cli/commands/__init__.py +1 -0
  11. abkit/cli/commands/_context.py +83 -0
  12. abkit/cli/commands/clean.py +133 -0
  13. abkit/cli/commands/explore.py +208 -0
  14. abkit/cli/commands/init.py +427 -0
  15. abkit/cli/commands/run.py +282 -0
  16. abkit/cli/commands/unlock.py +59 -0
  17. abkit/cli/commands/validate.py +264 -0
  18. abkit/cli/main.py +279 -0
  19. abkit/compute/__init__.py +5 -0
  20. abkit/compute/recompute_backend.py +140 -0
  21. abkit/config/__init__.py +51 -0
  22. abkit/config/discovery.py +168 -0
  23. abkit/config/experiment_config.py +511 -0
  24. abkit/config/method_config.py +80 -0
  25. abkit/config/metric_config.py +214 -0
  26. abkit/config/profile.py +301 -0
  27. abkit/config/project_config.py +244 -0
  28. abkit/config/validator.py +393 -0
  29. abkit/core/__init__.py +26 -0
  30. abkit/core/interval.py +148 -0
  31. abkit/core/models.py +121 -0
  32. abkit/core/period_planner.py +206 -0
  33. abkit/database/__init__.py +51 -0
  34. abkit/database/_sql_manager.py +432 -0
  35. abkit/database/clickhouse_manager.py +495 -0
  36. abkit/database/internal_tables/__init__.py +6 -0
  37. abkit/database/internal_tables/_aa_runs.py +53 -0
  38. abkit/database/internal_tables/_base.py +71 -0
  39. abkit/database/internal_tables/_experiments.py +82 -0
  40. abkit/database/internal_tables/_exposures.py +163 -0
  41. abkit/database/internal_tables/_maintenance.py +72 -0
  42. abkit/database/internal_tables/_results.py +231 -0
  43. abkit/database/internal_tables/_schema.py +23 -0
  44. abkit/database/internal_tables/_tasks.py +237 -0
  45. abkit/database/internal_tables/_unit_state.py +148 -0
  46. abkit/database/internal_tables/manager.py +30 -0
  47. abkit/database/manager.py +450 -0
  48. abkit/database/mysql_manager.py +175 -0
  49. abkit/database/postgres_manager.py +145 -0
  50. abkit/database/tables.py +326 -0
  51. abkit/loaders/__init__.py +28 -0
  52. abkit/loaders/exposure_loader.py +121 -0
  53. abkit/loaders/metric_loader.py +251 -0
  54. abkit/loaders/query_template.py +167 -0
  55. abkit/loaders/templates/abkit_assignment.jinja +62 -0
  56. abkit/pipeline/__init__.py +37 -0
  57. abkit/pipeline/_types.py +52 -0
  58. abkit/pipeline/analyze.py +223 -0
  59. abkit/pipeline/driver.py +477 -0
  60. abkit/pipeline/enrich.py +137 -0
  61. abkit/pipeline/readout.py +779 -0
  62. abkit/reporting/__init__.py +19 -0
  63. abkit/reporting/assets/report.js +138 -0
  64. abkit/reporting/builder.py +484 -0
  65. abkit/reporting/calibration.py +182 -0
  66. abkit/reporting/html_report.py +109 -0
  67. abkit/stats/__init__.py +94 -0
  68. abkit/stats/accumulate.py +82 -0
  69. abkit/stats/base.py +347 -0
  70. abkit/stats/bootstrap/__init__.py +69 -0
  71. abkit/stats/bootstrap/applier.py +81 -0
  72. abkit/stats/bootstrap/bootstrap.py +311 -0
  73. abkit/stats/bootstrap/ci.py +72 -0
  74. abkit/stats/bootstrap/engine.py +383 -0
  75. abkit/stats/bootstrap/paired_bootstrap.py +57 -0
  76. abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
  77. abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
  78. abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
  79. abkit/stats/correction.py +88 -0
  80. abkit/stats/effects.py +141 -0
  81. abkit/stats/exceptions.py +31 -0
  82. abkit/stats/factory.py +26 -0
  83. abkit/stats/parametric/__init__.py +10 -0
  84. abkit/stats/parametric/cuped_ttest.py +183 -0
  85. abkit/stats/parametric/paired_cuped_ttest.py +125 -0
  86. abkit/stats/parametric/paired_ttest.py +136 -0
  87. abkit/stats/parametric/ratio_delta.py +113 -0
  88. abkit/stats/parametric/ttest.py +105 -0
  89. abkit/stats/parametric/ztest.py +134 -0
  90. abkit/stats/power.py +278 -0
  91. abkit/stats/registry.py +111 -0
  92. abkit/stats/result.py +84 -0
  93. abkit/stats/rng.py +39 -0
  94. abkit/stats/samples.py +531 -0
  95. abkit/stats/sequential/__init__.py +18 -0
  96. abkit/stats/sequential/apply.py +37 -0
  97. abkit/stats/sequential/confidence_sequence.py +96 -0
  98. abkit/stats/sequential/mixture.py +70 -0
  99. abkit/stats/srm.py +221 -0
  100. abkit/tuning/__init__.py +59 -0
  101. abkit/tuning/assets/explore.js +173 -0
  102. abkit/tuning/config_writer.py +409 -0
  103. abkit/tuning/html.py +88 -0
  104. abkit/tuning/payload.py +122 -0
  105. abkit/tuning/recompute.py +1039 -0
  106. abkit/tuning/server.py +882 -0
  107. abkit/tuning/session.py +233 -0
  108. abkit/utils/__init__.py +27 -0
  109. abkit/utils/datetime_utils.py +97 -0
  110. abkit/utils/env_interpolation.py +50 -0
  111. abkit/utils/json_utils.py +38 -0
  112. abkit/validate/__init__.py +36 -0
  113. abkit/validate/_types.py +35 -0
  114. abkit/validate/inject.py +75 -0
  115. abkit/validate/load.py +160 -0
  116. abkit/validate/panel.py +59 -0
  117. abkit/validate/persistence.py +59 -0
  118. abkit/validate/resample.py +94 -0
  119. abkit/validate/result.py +60 -0
  120. abkit/validate/run_id.py +45 -0
  121. abkit/validate/runner.py +389 -0
  122. abkit/validate/scoring.py +544 -0
@@ -0,0 +1,102 @@
1
+ """``post-normed-bootstrap`` — covariate-ratio post-normalised bootstrap.
2
+
3
+ Baseline §4.3 (catalogue "PostNormedBootstrapTest"): ratio / post-normalised
4
+ metric — divides out the covariate ratio for variance reduction on ratio
5
+ metrics. Requires ``cov_array`` on both arms and resamples value and covariate
6
+ with the SAME indices (``cov_bootstrap``, baseline §4.1), so the per-unit
7
+ (Y, X) pairing is preserved.
8
+
9
+ Relative branch (the sane one, reproduced verbatim):
10
+ ``boot_data = (S2/S1) / (S2_cov/S1_cov) − 1`` per replicate.
11
+
12
+ QUARANTINE (quorum must-fix; docs/specs/statistics-changes.md §3): the legacy
13
+ ABSOLUTE branch ``S2 − (S2_cov/S1_cov)·S1`` is an unusual estimand and is NOT
14
+ reproduced — ``test_type="absolute"`` raises
15
+ :class:`~abkit.stats.exceptions.QuarantinedMethodError` at construction; use
16
+ the principled ``ratio-delta`` instead.
17
+
18
+ Baseline fact #3: the bootstrap seed is excluded from ``method_params`` — here
19
+ via the identity-excluded ``SEED_PARAM`` shared by all bootstrap methods.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import math
25
+
26
+ import numpy as np
27
+
28
+ from abkit.stats.base import require_pair_type
29
+ from abkit.stats.bootstrap.applier import stat_point
30
+ from abkit.stats.bootstrap.bootstrap import BaseBootstrapMethod
31
+ from abkit.stats.bootstrap.engine import bootstrap_statistics
32
+ from abkit.stats.exceptions import QuarantinedMethodError
33
+ from abkit.stats.registry import register
34
+ from abkit.stats.result import TestResult
35
+ from abkit.stats.samples import Sample
36
+
37
+
38
+ @register
39
+ class PostNormedBootstrapTest(BaseBootstrapMethod):
40
+ """Covariate-ratio post-normalised bootstrap (relative branch only)."""
41
+
42
+ name = "post-normed-bootstrap"
43
+ requires_covariate = True
44
+
45
+ def _validate_params(self) -> None:
46
+ super()._validate_params()
47
+ if str(self.params["test_type"]) == "absolute":
48
+ raise QuarantinedMethodError(
49
+ f"{self.name}: test_type='absolute' is quarantined — the legacy absolute "
50
+ "branch (S2 - (S2_cov/S1_cov)*S1) is an unusual estimand (see "
51
+ "statistics-changes.md §3); use test_type='relative' or the principled "
52
+ "'ratio-delta' method"
53
+ )
54
+
55
+ def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
56
+ require_pair_type(self.name, sample_1, sample_2, Sample)
57
+ self._require_covariates(sample_1, sample_2)
58
+ assert sample_1.cov_array is not None and sample_2.cov_array is not None
59
+ plan_1, plan_2 = self._independent_plans(sample_1, sample_2)
60
+ rng = self._make_rng()
61
+ # Variant 1 fully before variant 2; value and covariate share indices.
62
+ boot_1, cov_boot_1 = bootstrap_statistics(
63
+ rng,
64
+ (sample_1.array, sample_1.cov_array),
65
+ plan_1,
66
+ self._n_samples,
67
+ self._stat,
68
+ self._max_block_bytes,
69
+ )
70
+ boot_2, cov_boot_2 = bootstrap_statistics(
71
+ rng,
72
+ (sample_2.array, sample_2.cov_array),
73
+ plan_2,
74
+ self._n_samples,
75
+ self._stat,
76
+ self._max_block_bytes,
77
+ )
78
+ with np.errstate(divide="ignore", invalid="ignore"):
79
+ boot_data = (boot_2 / boot_1) / (cov_boot_2 / cov_boot_1) - 1.0
80
+
81
+ result_warnings: list[str] = []
82
+ effect = self._post_normed_effect(sample_1, sample_2, result_warnings)
83
+ return self._finalize(sample_1, sample_2, boot_data, effect, result_warnings)
84
+
85
+ def _post_normed_effect(
86
+ self, sample_1: Sample, sample_2: Sample, result_warnings: list[str]
87
+ ) -> float:
88
+ """Real-data point estimate ``(stat2/stat1)/(stat2c/stat1c) − 1`` (H9), H5-guarded."""
89
+ assert sample_1.cov_array is not None and sample_2.cov_array is not None
90
+ value_1 = np.float64(stat_point(sample_1.array, self._stat))
91
+ value_2 = np.float64(stat_point(sample_2.array, self._stat))
92
+ cov_value_1 = np.float64(stat_point(sample_1.cov_array, self._stat))
93
+ cov_value_2 = np.float64(stat_point(sample_2.cov_array, self._stat))
94
+ with np.errstate(divide="ignore", invalid="ignore"):
95
+ effect = float((value_2 / value_1) / (cov_value_2 / cov_value_1) - 1.0)
96
+ if not math.isfinite(effect):
97
+ result_warnings.append(
98
+ "post-normed relative effect undefined: a denominator statistic is zero "
99
+ "or non-finite; returning NaN (see statistics-changes.md H5)"
100
+ )
101
+ return float("nan")
102
+ return effect
@@ -0,0 +1,88 @@
1
+ """Multiple-testing corrections.
2
+
3
+ Config-time two-tier Bonferroni (baseline §6, declarative-config.md §6) plus
4
+ read-time Benjamini-Hochberg (opt-in, statistics-changes.md §4). The number of
5
+ cumulative time points is deliberately NOT part of the correction — peeking is
6
+ handled honestly by ``abk validate`` and the sequential toggle, never hidden here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+ import numpy as np
14
+ import numpy.typing as npt
15
+
16
+ from abkit.stats.exceptions import MethodParamError
17
+
18
+
19
+ def n_comparisons(groups_count: int, metrics_count: int = 1) -> float:
20
+ """``C(groups, 2) × metrics`` — the legacy pairwise comparison count."""
21
+ if groups_count < 2:
22
+ raise MethodParamError("Number of groups must be more than 1")
23
+ if metrics_count < 1:
24
+ raise MethodParamError(f"metrics_count must be >= 1, got {metrics_count}")
25
+ return groups_count * (groups_count - 1) / 2 * metrics_count
26
+
27
+
28
+ def adjust_alpha(alpha: float, groups_count: int, metrics_count: int = 1) -> float:
29
+ """Bonferroni: ``alpha / (C(groups, 2) × metrics)`` — legacy transcription."""
30
+ if not 0.0 < alpha < 1.0:
31
+ raise MethodParamError(f"alpha must be in (0, 1), got {alpha}")
32
+ return alpha / n_comparisons(groups_count, metrics_count)
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class TwoTierAlphas:
37
+ """Effective per-comparison alphas, echoed by run/validate/report (inspectable).
38
+
39
+ ``secondary`` is ``None`` for a main-metric-only experiment (``metrics_count=0``)
40
+ — there is no secondary tier to divide the budget over.
41
+ """
42
+
43
+ alpha: float
44
+ groups_count: int
45
+ metrics_count: int
46
+ main: float
47
+ secondary: float | None
48
+
49
+
50
+ def two_tier_alphas(alpha: float, groups_count: int, metrics_count: int) -> TwoTierAlphas:
51
+ """The exact legacy two-tier scheme keyed off ``is_main_metric``.
52
+
53
+ Main metric: ``adjust_alpha(alpha, groups, 1)``; every other metric:
54
+ ``adjust_alpha(alpha, groups, metrics_count)`` where ``metrics_count`` counts
55
+ the non-main metrics sharing the secondary budget (``0`` is valid — an
56
+ experiment may have only its main metric).
57
+ """
58
+ if metrics_count < 0:
59
+ raise MethodParamError(f"metrics_count must be >= 0, got {metrics_count}")
60
+ return TwoTierAlphas(
61
+ alpha=alpha,
62
+ groups_count=groups_count,
63
+ metrics_count=metrics_count,
64
+ main=adjust_alpha(alpha, groups_count, 1),
65
+ secondary=(
66
+ None if metrics_count == 0 else adjust_alpha(alpha, groups_count, metrics_count)
67
+ ),
68
+ )
69
+
70
+
71
+ def benjamini_hochberg(pvalues: npt.ArrayLike) -> npt.NDArray[np.float64]:
72
+ """BH step-up adjusted p-values (monotone, capped at 1). Read-time, opt-in.
73
+
74
+ Composition with peeking must be validated empirically via the A/A matrix
75
+ before being applied to the cumulative daily series (statistics-changes.md §4).
76
+ """
77
+ p = np.asarray(pvalues, dtype=np.float64)
78
+ if p.ndim != 1 or p.size == 0:
79
+ raise MethodParamError("benjamini_hochberg expects a non-empty 1-d array of p-values")
80
+ if np.any((p < 0) | (p > 1) | ~np.isfinite(p)):
81
+ raise MethodParamError("p-values must be finite and within [0, 1]")
82
+ m = p.size
83
+ order = np.argsort(p)
84
+ ranked = p[order] * m / np.arange(1, m + 1)
85
+ adjusted_sorted = np.minimum.accumulate(ranked[::-1])[::-1]
86
+ adjusted = np.empty(m, dtype=np.float64)
87
+ adjusted[order] = np.minimum(adjusted_sorted, 1.0)
88
+ return adjusted
abkit/stats/effects.py ADDED
@@ -0,0 +1,141 @@
1
+ """Effect estimands and the preserved delta-method linearisation.
2
+
3
+ The relative effect ``(mean_2 − mean_1) / mean_1`` is NOT a naive ratio of
4
+ variances — it is a first-order Taylor (delta-method) linearisation that keeps
5
+ the covariance between numerator and denominator (they share ``mean_1``). This is
6
+ the single most important formula to preserve (docs/specs/statistics-baseline.md
7
+ §2–§3):
8
+
9
+ relative_mu = mean_num / mean_den
10
+ relative_var = var_num / mean_den²
11
+ + var_den · mean_num² / mean_den⁴
12
+ − 2 · (mean_num / mean_den³) · covariance
13
+
14
+ Hygiene fix H5 (docs/specs/statistics-changes.md): division by a zero control
15
+ mean yields NaN plus a recorded warning instead of silent ±inf.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ from dataclasses import dataclass, field
22
+ from typing import Any
23
+
24
+ import numpy as np
25
+ import scipy.stats as sps
26
+
27
+
28
+ @dataclass
29
+ class EffectEstimate:
30
+ """A point effect with its (delta-method) variance and any diagnostics."""
31
+
32
+ effect: float
33
+ var: float
34
+ warnings: list[str] = field(default_factory=list)
35
+
36
+
37
+ def absolute_effect(
38
+ mean_1: float, mean_2: float, var_mean_1: float, var_mean_2: float
39
+ ) -> EffectEstimate:
40
+ """Absolute estimand: ``mean_2 − mean_1`` (variant minus control)."""
41
+ return EffectEstimate(effect=mean_2 - mean_1, var=var_mean_1 + var_mean_2)
42
+
43
+
44
+ def relative_delta_effect(
45
+ mean_num: float,
46
+ var_num: float,
47
+ mean_den: float,
48
+ var_den: float,
49
+ covariance: float,
50
+ ) -> EffectEstimate:
51
+ """The preserved delta-method relative effect (baseline §3.1/§3.3).
52
+
53
+ ``covariance`` is the covariance between the numerator and denominator
54
+ estimators — for the plain t-test relative effect it is ``−var_mean_1``
55
+ (numerator ``mean_2 − mean_1`` and denominator ``mean_1`` share ``mean_1``).
56
+ """
57
+ result_warnings: list[str] = []
58
+ if mean_den == 0.0 or not math.isfinite(mean_den):
59
+ result_warnings.append(
60
+ "relative effect undefined: control (denominator) mean is zero or non-finite; "
61
+ "returning NaN (see statistics-changes.md H5)"
62
+ )
63
+ return EffectEstimate(effect=float("nan"), var=float("nan"), warnings=result_warnings)
64
+
65
+ relative_mu = mean_num / mean_den
66
+ relative_var = (
67
+ var_num / mean_den**2
68
+ + var_den * (mean_num**2 / mean_den**4)
69
+ - 2.0 * (mean_num / mean_den**3) * covariance
70
+ )
71
+ if not (math.isfinite(relative_mu) and math.isfinite(relative_var)):
72
+ result_warnings.append(
73
+ "relative effect numerically unstable (near-zero control mean); "
74
+ "returning NaN (see statistics-changes.md H5)"
75
+ )
76
+ return EffectEstimate(effect=float("nan"), var=float("nan"), warnings=result_warnings)
77
+ return EffectEstimate(effect=relative_mu, var=relative_var, warnings=result_warnings)
78
+
79
+
80
+ @dataclass
81
+ class NormalTest:
82
+ """CI, p-value and reject flag from a Normal effect distribution."""
83
+
84
+ effect: float
85
+ left_bound: float
86
+ right_bound: float
87
+ ci_length: float
88
+ pvalue: float
89
+ reject: bool
90
+ distribution: Any | None
91
+ warnings: list[str] = field(default_factory=list)
92
+
93
+
94
+ def normal_test(estimate: EffectEstimate, alpha: float) -> NormalTest:
95
+ """The shared parametric result computation (baseline §3.1).
96
+
97
+ ``left, right = norm(mu, sqrt(var)).ppf([alpha/2, 1 − alpha/2])``;
98
+ ``pvalue = 2 · min(cdf(0), sf(0))``; ``reject = pvalue < alpha``.
99
+ """
100
+ result_warnings = list(estimate.warnings)
101
+ if not (math.isfinite(estimate.effect) and math.isfinite(estimate.var)) or estimate.var <= 0.0:
102
+ if estimate.var == 0.0 and math.isfinite(estimate.effect):
103
+ result_warnings.append(
104
+ "effect variance is zero (degenerate samples); returning NaN test outputs"
105
+ )
106
+ elif math.isfinite(estimate.var) and estimate.var < 0.0:
107
+ result_warnings.append(
108
+ "effect variance is negative (anomalous covariance term — possible with the "
109
+ "mixed-ddof convention on adversarial data); returning NaN test outputs"
110
+ )
111
+ elif not result_warnings:
112
+ result_warnings.append(
113
+ "effect or its variance is non-finite; returning NaN test outputs"
114
+ )
115
+ nan = float("nan")
116
+ return NormalTest(
117
+ effect=estimate.effect,
118
+ left_bound=nan,
119
+ right_bound=nan,
120
+ ci_length=nan,
121
+ pvalue=nan,
122
+ reject=False,
123
+ distribution=None,
124
+ warnings=result_warnings,
125
+ )
126
+
127
+ distribution = sps.norm(loc=estimate.effect, scale=float(np.sqrt(estimate.var)))
128
+ left_bound, right_bound = (
129
+ float(bound) for bound in distribution.ppf([alpha / 2.0, 1.0 - alpha / 2.0])
130
+ )
131
+ pvalue = float(2.0 * min(distribution.cdf(0.0), distribution.sf(0.0)))
132
+ return NormalTest(
133
+ effect=estimate.effect,
134
+ left_bound=left_bound,
135
+ right_bound=right_bound,
136
+ ci_length=right_bound - left_bound,
137
+ pvalue=pvalue,
138
+ reject=bool(pvalue < alpha),
139
+ distribution=distribution,
140
+ warnings=result_warnings,
141
+ )
@@ -0,0 +1,31 @@
1
+ """Exceptions and warnings raised by the pure statistical core."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class StatsError(Exception):
7
+ """Base class for every error raised by ``abkit.stats``."""
8
+
9
+
10
+ class SampleValidationError(StatsError):
11
+ """The provided samples/statistics cannot be analysed by this method."""
12
+
13
+
14
+ class MethodParamError(StatsError):
15
+ """A method parameter is unknown, has the wrong type, or an invalid value."""
16
+
17
+
18
+ class UnknownMethodError(StatsError):
19
+ """The requested method name is not in the registry."""
20
+
21
+
22
+ class QuarantinedMethodError(StatsError):
23
+ """The requested method (or branch) is quarantined as broken.
24
+
25
+ See docs/specs/statistics-changes.md §3 — these legacy methods are known-broken
26
+ or mislabeled and are never silently substituted.
27
+ """
28
+
29
+
30
+ class AbkitStatsWarning(UserWarning):
31
+ """Warning category for statistical diagnostics (also recorded on TestResult)."""
abkit/stats/factory.py ADDED
@@ -0,0 +1,26 @@
1
+ """Factory: build a configured method instance from (name, params).
2
+
3
+ This is the single construction path used by the pipeline, the explore cockpit
4
+ and the A/A harness — parameter validation and identity hashing happen here (in
5
+ the method constructor), never downstream.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from abkit.stats.base import BaseMethod
13
+ from abkit.stats.registry import get_method_class
14
+
15
+
16
+ def create_method(
17
+ name: str, alpha: float = 0.05, params: dict[str, Any] | None = None
18
+ ) -> BaseMethod:
19
+ """Instantiate a registered method with validated params.
20
+
21
+ ``alpha`` is the effective (post-correction) per-comparison alpha — it is an
22
+ experiment-level setting, not a method param, and never enters
23
+ ``method_config_id`` (docs/specs/declarative-config.md §6–§7).
24
+ """
25
+ method_cls = get_method_class(name)
26
+ return method_cls(alpha=alpha, **(params or {}))
@@ -0,0 +1,10 @@
1
+ """Closed-form (delta-method, normal-approximation) statistical methods."""
2
+
3
+ from abkit.stats.parametric.cuped_ttest import CupedTTest
4
+ from abkit.stats.parametric.paired_cuped_ttest import PairedCupedTTest
5
+ from abkit.stats.parametric.paired_ttest import PairedTTest
6
+ from abkit.stats.parametric.ratio_delta import RatioDelta
7
+ from abkit.stats.parametric.ttest import TTest
8
+ from abkit.stats.parametric.ztest import ZTest
9
+
10
+ __all__ = ["CupedTTest", "PairedCupedTTest", "PairedTTest", "RatioDelta", "TTest", "ZTest"]
@@ -0,0 +1,183 @@
1
+ """``cuped-t-test`` — CUPED variance reduction, independent arms (baseline §3.3).
2
+
3
+ THE mixed-ddof method (baseline fact #1, quorum must-fix): the pooled θ
4
+ numerator is ``np.cov`` parity (ddof=1) while its denominator and every variance
5
+ term are ``np.var`` parity (ddof=0). The convention is encoded per term — never
6
+ normalised to one ddof — and θ itself is exposed in ``diagnostics["theta"]`` for
7
+ the golden test.
8
+
9
+ Baseline subtleties preserved verbatim:
10
+
11
+ - θ is pooled across both arms and estimated on the same data used for the test
12
+ (baseline fact #2 — no cross-fitting; a cross-fitted variant is v2);
13
+ - the relative denominator is the ORIGINAL control mean (not CUPED-adjusted),
14
+ while the numerator uses the CUPED-adjusted means;
15
+ - per-arm ``value``/``std`` report the ORIGINAL mean/std (the dashboard shows
16
+ raw values; CUPED lives in the effect).
17
+
18
+ CUPED moments are derived exactly from the raw co-moments, so ``from_samples``
19
+ reduces to :class:`SufficientStats` and delegates — ONE math path (dual entry by
20
+ construction, the ``ttest.py`` exemplar pattern).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ import warnings
27
+
28
+ import numpy as np
29
+
30
+ from abkit.stats.base import (
31
+ CALCULATE_MDE_PARAM,
32
+ COVARIATE_LOOKBACK_PARAM,
33
+ POWER_PARAM,
34
+ TEST_TYPE_PARAM,
35
+ BaseMethod,
36
+ require_pair_type,
37
+ )
38
+ from abkit.stats.effects import absolute_effect, normal_test, relative_delta_effect
39
+ from abkit.stats.exceptions import AbkitStatsWarning, SampleValidationError
40
+ from abkit.stats.power import get_cuped_ttest_mde
41
+ from abkit.stats.registry import register
42
+ from abkit.stats.result import TestResult
43
+ from abkit.stats.samples import Sample, SufficientStats
44
+
45
+ #: Legacy CUPED guard: warn when the value↔covariate correlation is below this.
46
+ MIN_CORR_COEF = 0.5
47
+
48
+
49
+ def correlation_warning(method_name: str, arm_name: str, corr_coef: float) -> str | None:
50
+ """Emit and return the legacy low-correlation warning, or ``None`` when adequate.
51
+
52
+ A NaN correlation (degenerate covariate) intentionally does not trigger —
53
+ the non-finite-θ warning covers that case.
54
+ """
55
+ if not corr_coef < MIN_CORR_COEF: # NaN-safe: NaN comparisons are False
56
+ return None
57
+ message = (
58
+ f"{method_name}: covariate correlation for {arm_name!r} is {corr_coef:.4f} < "
59
+ f"{MIN_CORR_COEF} — CUPED variance reduction will be small (legacy guard)"
60
+ )
61
+ warnings.warn(message, AbkitStatsWarning, stacklevel=3)
62
+ return message
63
+
64
+
65
+ @register(aliases=("cuped-ttest",))
66
+ class CupedTTest(BaseMethod):
67
+ name = "cuped-t-test"
68
+ requires_covariate = True
69
+ param_specs = (
70
+ TEST_TYPE_PARAM,
71
+ CALCULATE_MDE_PARAM,
72
+ POWER_PARAM,
73
+ COVARIATE_LOOKBACK_PARAM,
74
+ )
75
+
76
+ def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
77
+ require_pair_type(self.name, sample_1, sample_2, Sample)
78
+ return self.from_suffstats(
79
+ SufficientStats.from_sample(sample_1), SufficientStats.from_sample(sample_2)
80
+ )
81
+
82
+ def from_suffstats(self, stats_1: SufficientStats, stats_2: SufficientStats) -> TestResult:
83
+ require_pair_type(self.name, stats_1, stats_2, SufficientStats)
84
+ for stats in (stats_1, stats_2):
85
+ if not stats.has_covariate:
86
+ raise SampleValidationError(
87
+ f"{self.name}: CUPED requires covariate moments (cov_array) on both groups"
88
+ )
89
+ assert stats_1.cov_mean is not None and stats_1.cov_m2 is not None
90
+ assert stats_1.cross_c is not None
91
+ assert stats_2.cov_mean is not None and stats_2.cov_m2 is not None
92
+ assert stats_2.cross_c is not None
93
+
94
+ method_warnings: list[str] = []
95
+ for fallback, stats in (("group 1", stats_1), ("group 2", stats_2)):
96
+ arm_name = stats.name if stats.name is not None else fallback
97
+ message = correlation_warning(self.name, arm_name, stats.corr_coef)
98
+ if message is not None:
99
+ method_warnings.append(message)
100
+
101
+ # Pooled θ with the EXACT mixed ddof (baseline fact #1): np.cov-parity
102
+ # numerator (ddof=1) over np.var-parity denominator (ddof=0).
103
+ theta_num = stats_1.cov1_value_covariate + stats_2.cov1_value_covariate
104
+ theta_den = stats_1.cov_var + stats_2.cov_var
105
+ with np.errstate(divide="ignore", invalid="ignore"):
106
+ theta = float(np.float64(theta_num) / np.float64(theta_den))
107
+ if not math.isfinite(theta):
108
+ method_warnings.append(
109
+ f"{self.name}: theta is non-finite (zero pooled covariate variance); "
110
+ "returning NaN test outputs"
111
+ )
112
+
113
+ n_1, n_2 = stats_1.n, stats_2.n
114
+ mean_cup_1 = stats_1.mean - theta * stats_1.cov_mean
115
+ mean_cup_2 = stats_2.mean - theta * stats_2.cov_mean
116
+ # var0(cup_i) exactly from raw co-moments: Σ(y−θx − mean)² = m2 − 2θ·cross + θ²·cov_m2.
117
+ var_cup_1 = (stats_1.m2 - 2.0 * theta * stats_1.cross_c + theta**2 * stats_1.cov_m2) / n_1
118
+ var_cup_2 = (stats_2.m2 - 2.0 * theta * stats_2.cross_c + theta**2 * stats_2.cov_m2) / n_2
119
+
120
+ if self.test_type == "absolute":
121
+ estimate = absolute_effect(mean_cup_1, mean_cup_2, var_cup_1 / n_1, var_cup_2 / n_2)
122
+ else:
123
+ # np.cov parity (ddof=1): cov(cup_1, y1) = (m2 − θ·cross_c)/(n1 − 1);
124
+ # n1 ≥ 2 is guaranteed — cov1_value_covariate above raised otherwise.
125
+ cov1_cup_value = (stats_1.m2 - theta * stats_1.cross_c) / (n_1 - 1)
126
+ estimate = relative_delta_effect(
127
+ mean_num=mean_cup_2 - mean_cup_1,
128
+ var_num=var_cup_2 / n_2 + var_cup_1 / n_1,
129
+ mean_den=stats_1.mean, # ORIGINAL control mean (baseline §3.3 subtlety)
130
+ var_den=stats_1.var / n_1,
131
+ covariance=-cov1_cup_value / n_1,
132
+ )
133
+ test = normal_test(estimate, self.alpha)
134
+
135
+ mde_1 = mde_2 = None
136
+ if self.params["calculate_mde"]:
137
+ mde_1 = get_cuped_ttest_mde(
138
+ stats_1.mean,
139
+ stats_1.std,
140
+ stats_1.corr_coef,
141
+ n_1,
142
+ test_type=self.test_type,
143
+ alpha=self.alpha,
144
+ power=self.params["power"],
145
+ ratio=n_2 / n_1,
146
+ )
147
+ mde_2 = get_cuped_ttest_mde(
148
+ stats_2.mean,
149
+ stats_2.std,
150
+ stats_2.corr_coef,
151
+ n_2,
152
+ test_type=self.test_type,
153
+ alpha=self.alpha,
154
+ power=self.params["power"],
155
+ ratio=n_1 / n_2,
156
+ )
157
+
158
+ return TestResult(
159
+ name_1=stats_1.name,
160
+ name_2=stats_2.name,
161
+ value_1=stats_1.mean,
162
+ value_2=stats_2.mean,
163
+ std_1=stats_1.std,
164
+ std_2=stats_2.std,
165
+ size_1=n_1,
166
+ size_2=n_2,
167
+ cov_value_1=stats_1.cov_mean,
168
+ cov_value_2=stats_2.cov_mean,
169
+ mde_1=mde_1,
170
+ mde_2=mde_2,
171
+ method_name=self.name,
172
+ method_params=self.identity_params,
173
+ alpha=self.alpha,
174
+ pvalue=test.pvalue,
175
+ effect=test.effect,
176
+ ci_length=test.ci_length,
177
+ left_bound=test.left_bound,
178
+ right_bound=test.right_bound,
179
+ reject=test.reject,
180
+ effect_distribution=test.distribution,
181
+ warnings=[*method_warnings, *test.warnings],
182
+ diagnostics={"theta": theta},
183
+ )