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
abkit/stats/samples.py ADDED
@@ -0,0 +1,531 @@
1
+ """Data containers for the statistical core: raw samples and sufficient statistics.
2
+
3
+ Baseline fact #1 (docs/specs/statistics-baseline.md §1): the legacy variance
4
+ convention is MIXED, not uniform. ``np.var``/``np.std`` terms use ``ddof=0``
5
+ (population) while ``np.cov`` terms (CUPED θ, the paired/CUPED covariance
6
+ corrections) use numpy's default ``ddof=1``. The sufficient-statistics classes
7
+ here store *raw centered co-moments* and expose the exact per-term convention
8
+ through explicit accessors (``var`` → ddof=0, ``cov1_*`` → ddof=1). A blanket-ddof
9
+ rewrite is forbidden — it fails every CUPED/paired golden test.
10
+
11
+ Accumulation stability (docs/specs/statistics-changes.md §1.1): moments are built
12
+ two-pass (via numpy's stable routines) and merged Welford/Chan-style in
13
+ ``accumulate.py`` — never as ``Σx²/n − x̄²``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import warnings
19
+ from collections.abc import Sequence
20
+ from dataclasses import dataclass, field
21
+
22
+ import numpy as np
23
+ import numpy.typing as npt
24
+
25
+ from abkit.stats.exceptions import AbkitStatsWarning, SampleValidationError
26
+
27
+ FloatArray = npt.NDArray[np.float64]
28
+
29
+
30
+ def _as_float_array(values: object, *, what: str) -> FloatArray:
31
+ array = np.asarray(values, dtype=np.float64)
32
+ if array.ndim != 1:
33
+ raise SampleValidationError(f"{what} must be one-dimensional, got shape {array.shape}")
34
+ if array.size == 0:
35
+ raise SampleValidationError(f"{what} must not be empty")
36
+ return array
37
+
38
+
39
+ class Sample:
40
+ """Per-unit observations for ONE variant (the legacy ``Sample`` model).
41
+
42
+ - ``array`` — the metric value per randomisation unit.
43
+ - ``cov_array`` — optional covariate per unit (CUPED / post-normalisation),
44
+ row-aligned with ``array``.
45
+ - ``categories_array`` — optional stratum label per unit.
46
+ - ``pair_ids`` — optional pair key per unit (paired designs; see
47
+ :func:`align_paired`).
48
+
49
+ Derived statistics are eager and follow the baseline exactly:
50
+ ``std``/``var`` are population (``ddof=0``); ``corr_coef`` is
51
+ ``np.corrcoef(array, cov_array)[0, 1]``.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ array: Sequence[float] | FloatArray,
57
+ cov_array: Sequence[float] | FloatArray | None = None,
58
+ categories_array: Sequence[object] | npt.NDArray[np.generic] | None = None,
59
+ pair_ids: Sequence[object] | npt.NDArray[np.generic] | None = None,
60
+ name: str | None = None,
61
+ ) -> None:
62
+ self.array = _as_float_array(array, what="Sample.array")
63
+ self.name = name
64
+ self.sample_size = int(self.array.size)
65
+
66
+ self.mean = float(np.mean(self.array))
67
+ self.std = float(np.std(self.array)) # ddof=0 (baseline)
68
+ self.var = self.std**2
69
+
70
+ self.cov_array: FloatArray | None = None
71
+ self.cov_mean: float | None = None
72
+ self.cov_std: float | None = None
73
+ self.cov_var: float | None = None
74
+ self.corr_coef: float | None = None
75
+ if cov_array is not None:
76
+ cov = _as_float_array(cov_array, what="Sample.cov_array")
77
+ if cov.size != self.sample_size:
78
+ raise SampleValidationError(
79
+ f"cov_array length {cov.size} != array length {self.sample_size}"
80
+ )
81
+ self.cov_array = cov
82
+ self.cov_mean = float(np.mean(cov))
83
+ self.cov_std = float(np.std(cov)) # ddof=0 (baseline)
84
+ self.cov_var = self.cov_std**2
85
+ self.corr_coef = float(np.corrcoef(self.array, cov)[0, 1])
86
+
87
+ self.categories_array: npt.NDArray[np.generic] | None = None
88
+ if categories_array is not None:
89
+ categories = np.asarray(categories_array)
90
+ if categories.ndim != 1 or categories.size != self.sample_size:
91
+ raise SampleValidationError(
92
+ "categories_array must be one-dimensional and aligned with array"
93
+ )
94
+ self.categories_array = categories
95
+
96
+ self.pair_ids: npt.NDArray[np.generic] | None = None
97
+ if pair_ids is not None:
98
+ ids = np.asarray(pair_ids)
99
+ if ids.ndim != 1 or ids.size != self.sample_size:
100
+ raise SampleValidationError(
101
+ "pair_ids must be one-dimensional and aligned with array"
102
+ )
103
+ if np.unique(ids).size != ids.size:
104
+ raise SampleValidationError("pair_ids must be unique within a variant")
105
+ self.pair_ids = ids
106
+
107
+ def category_counts(self) -> dict[object, int]:
108
+ """Observed per-stratum unit counts (empty dict when unstratified)."""
109
+ if self.categories_array is None:
110
+ return {}
111
+ values, counts = np.unique(self.categories_array, return_counts=True)
112
+ return {
113
+ value.item() if hasattr(value, "item") else value: int(count)
114
+ for value, count in zip(values, counts, strict=True)
115
+ }
116
+
117
+ def __repr__(self) -> str:
118
+ return (
119
+ f"Sample(name={self.name!r}, n={self.sample_size}, mean={self.mean:.6g}, "
120
+ f"std={self.std:.6g}, covariate={self.cov_array is not None})"
121
+ )
122
+
123
+
124
+ class Fraction:
125
+ """A proportion metric for ONE variant: ``count`` successes of ``nobs`` trials.
126
+
127
+ ``count``/``nobs`` ARE the sufficient statistics for the two-proportion z-test,
128
+ so this class serves both the ``from_samples`` and ``from_suffstats`` entries.
129
+ ``std`` matches the legacy ``TestResult`` per-arm column: the standard error of
130
+ the proportion, ``sqrt(p·(1−p)/nobs)``.
131
+ """
132
+
133
+ def __init__(self, count: float, nobs: float, name: str | None = None) -> None:
134
+ if nobs <= 0:
135
+ raise SampleValidationError(f"Fraction.nobs must be positive, got {nobs}")
136
+ if count < 0 or count > nobs:
137
+ raise SampleValidationError(
138
+ f"Fraction.count must be within [0, nobs], got {count}/{nobs}"
139
+ )
140
+ self.count = float(count)
141
+ self.nobs = float(nobs)
142
+ self.name = name
143
+ self.prop = self.count / self.nobs
144
+ self.std = float(np.sqrt(self.prop * (1.0 - self.prop) / self.nobs))
145
+ self.sample_size = int(round(self.nobs))
146
+
147
+ def __repr__(self) -> str:
148
+ return f"Fraction(name={self.name!r}, count={self.count:g}, nobs={self.nobs:g}, prop={self.prop:.6g})"
149
+
150
+
151
+ class RatioSample:
152
+ """Per-unit (numerator, denominator) observations for a ratio metric.
153
+
154
+ Used by the principled ``ratio-delta`` method (docs/specs/statistics-changes.md
155
+ §4): the estimand is ``R = mean(numerator) / mean(denominator)`` per variant.
156
+ """
157
+
158
+ def __init__(
159
+ self,
160
+ numerator: Sequence[float] | FloatArray,
161
+ denominator: Sequence[float] | FloatArray,
162
+ name: str | None = None,
163
+ ) -> None:
164
+ self.numerator = _as_float_array(numerator, what="RatioSample.numerator")
165
+ self.denominator = _as_float_array(denominator, what="RatioSample.denominator")
166
+ if self.numerator.size != self.denominator.size:
167
+ raise SampleValidationError(
168
+ f"numerator length {self.numerator.size} != denominator length {self.denominator.size}"
169
+ )
170
+ self.name = name
171
+ self.sample_size = int(self.numerator.size)
172
+
173
+ def __repr__(self) -> str:
174
+ return f"RatioSample(name={self.name!r}, n={self.sample_size})"
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class JointMoments:
179
+ """Centered joint second moments of ``k`` aligned per-unit series.
180
+
181
+ ``comoment[i, j] = Σ_u (z_i,u − mean_i)(z_j,u − mean_j)`` (raw, un-normalised).
182
+ The mixed-ddof convention is applied at read time: :meth:`var0` divides by
183
+ ``n`` (``np.var`` parity) and :meth:`cov1` by ``n − 1`` (``np.cov`` parity).
184
+ Linear combinations (paired differences, CUPED adjustment) are exact:
185
+ ``comoment(w·z, v·z) = w · C · vᵀ``.
186
+ """
187
+
188
+ n: int
189
+ mean: FloatArray
190
+ comoment: FloatArray
191
+ labels: tuple[str, ...] = field(default=())
192
+
193
+ @classmethod
194
+ def from_arrays(cls, *arrays: FloatArray, labels: tuple[str, ...] = ()) -> JointMoments:
195
+ if not arrays:
196
+ raise SampleValidationError("JointMoments requires at least one array")
197
+ converted = [_as_float_array(array, what="JointMoments array") for array in arrays]
198
+ n = converted[0].size
199
+ if any(array.size != n for array in converted[1:]):
200
+ raise SampleValidationError("JointMoments arrays must be equal-length and aligned")
201
+ stacked = np.vstack(converted)
202
+ mean = stacked.mean(axis=1)
203
+ centered = stacked - mean[:, None]
204
+ comoment = centered @ centered.T
205
+ return cls(
206
+ n=int(n),
207
+ mean=mean,
208
+ comoment=comoment,
209
+ labels=labels or tuple(f"z{i}" for i in range(len(arrays))),
210
+ )
211
+
212
+ def index(self, label: str) -> int:
213
+ try:
214
+ return self.labels.index(label)
215
+ except ValueError:
216
+ raise SampleValidationError(
217
+ f"unknown series label {label!r}; have {self.labels}"
218
+ ) from None
219
+
220
+ def var0(self, i: int) -> float:
221
+ """Population variance (``np.var`` parity, ddof=0) of series ``i``."""
222
+ return float(self.comoment[i, i] / self.n)
223
+
224
+ def cov1(self, i: int, j: int) -> float:
225
+ """Sample covariance (``np.cov`` parity, ddof=1) of series ``i`` and ``j``."""
226
+ if self.n < 2:
227
+ raise SampleValidationError("cov1 requires at least two units (ddof=1)")
228
+ return float(self.comoment[i, j] / (self.n - 1))
229
+
230
+ def linear_mean(self, weights: FloatArray) -> float:
231
+ """Mean of the per-unit linear combination ``w · z``."""
232
+ return float(np.dot(weights, self.mean))
233
+
234
+ def linear_comoment(self, weights_a: FloatArray, weights_b: FloatArray) -> float:
235
+ """Raw centered co-moment between two linear combinations of the series."""
236
+ return float(weights_a @ self.comoment @ weights_b)
237
+
238
+ def linear_var0(self, weights: FloatArray) -> float:
239
+ return float(self.linear_comoment(weights, weights) / self.n)
240
+
241
+ def linear_cov1(self, weights_a: FloatArray, weights_b: FloatArray) -> float:
242
+ if self.n < 2:
243
+ raise SampleValidationError("linear_cov1 requires at least two units (ddof=1)")
244
+ return float(self.linear_comoment(weights_a, weights_b) / (self.n - 1))
245
+
246
+
247
+ class SufficientStats:
248
+ """Sufficient statistics of ONE variant for the closed-form methods.
249
+
250
+ Stores ``n``, ``mean`` and the raw centered second moment ``m2 = Σ(y−ȳ)²``,
251
+ plus (optionally) covariate moments ``cov_mean``/``cov_m2`` and the raw
252
+ Y↔X co-moment ``cross_c = Σ(y−ȳ)(x−x̄)``. Every quantity the t-test/CUPED
253
+ family needs is derivable from these six numbers per variant
254
+ (docs/specs/cumulative-intervals.md §3), preserving the exact mixed-ddof
255
+ convention:
256
+
257
+ - ``var`` (== ``np.var(y)``, ddof=0) = ``m2 / n``
258
+ - ``cov1_value_covariate`` (== ``np.cov(y, x)[0, 1]``, ddof=1) = ``cross_c / (n−1)``
259
+ """
260
+
261
+ def __init__(
262
+ self,
263
+ n: int,
264
+ mean: float,
265
+ m2: float,
266
+ cov_mean: float | None = None,
267
+ cov_m2: float | None = None,
268
+ cross_c: float | None = None,
269
+ name: str | None = None,
270
+ ) -> None:
271
+ if n <= 0:
272
+ raise SampleValidationError(f"SufficientStats.n must be positive, got {n}")
273
+ if m2 < 0:
274
+ raise SampleValidationError(f"SufficientStats.m2 must be non-negative, got {m2}")
275
+ covariate_fields = (cov_mean, cov_m2, cross_c)
276
+ if any(value is not None for value in covariate_fields) and any(
277
+ value is None for value in covariate_fields
278
+ ):
279
+ raise SampleValidationError(
280
+ "covariate moments must be provided together: cov_mean, cov_m2, cross_c"
281
+ )
282
+ self.n = int(n)
283
+ self.mean = float(mean)
284
+ self.m2 = float(m2)
285
+ self.cov_mean = None if cov_mean is None else float(cov_mean)
286
+ self.cov_m2 = None if cov_m2 is None else float(cov_m2)
287
+ self.cross_c = None if cross_c is None else float(cross_c)
288
+ self.name = name
289
+
290
+ @classmethod
291
+ def from_sample(cls, sample: Sample) -> SufficientStats:
292
+ """Build from raw arrays via numpy's stable two-pass routines."""
293
+ n = sample.sample_size
294
+ if sample.cov_array is None:
295
+ return cls(n=n, mean=sample.mean, m2=float(np.var(sample.array) * n), name=sample.name)
296
+ cov_mean = float(np.mean(sample.cov_array))
297
+ centered_y = sample.array - sample.mean
298
+ centered_x = sample.cov_array - cov_mean
299
+ return cls(
300
+ n=n,
301
+ mean=sample.mean,
302
+ m2=float(np.dot(centered_y, centered_y)),
303
+ cov_mean=cov_mean,
304
+ cov_m2=float(np.dot(centered_x, centered_x)),
305
+ cross_c=float(np.dot(centered_y, centered_x)),
306
+ name=sample.name,
307
+ )
308
+
309
+ # -- value moments -------------------------------------------------------
310
+ @property
311
+ def sample_size(self) -> int:
312
+ return self.n
313
+
314
+ @property
315
+ def var(self) -> float:
316
+ """Population variance of Y (``np.var`` parity, ddof=0)."""
317
+ return self.m2 / self.n
318
+
319
+ @property
320
+ def std(self) -> float:
321
+ return float(np.sqrt(self.var))
322
+
323
+ # -- covariate moments (mixed ddof — see module docstring) ----------------
324
+ @property
325
+ def has_covariate(self) -> bool:
326
+ return self.cov_mean is not None
327
+
328
+ def _require_covariate(self) -> None:
329
+ if not self.has_covariate:
330
+ raise SampleValidationError("this operation requires covariate moments (cov_array)")
331
+
332
+ @property
333
+ def cov_var(self) -> float:
334
+ """Population variance of X (``np.var`` parity, ddof=0)."""
335
+ self._require_covariate()
336
+ assert self.cov_m2 is not None
337
+ return self.cov_m2 / self.n
338
+
339
+ @property
340
+ def cov_std(self) -> float:
341
+ return float(np.sqrt(self.cov_var))
342
+
343
+ @property
344
+ def cov1_value_covariate(self) -> float:
345
+ """``np.cov(y, x)[0, 1]`` parity (ddof=1) — the CUPED θ numerator term."""
346
+ self._require_covariate()
347
+ assert self.cross_c is not None
348
+ if self.n < 2:
349
+ raise SampleValidationError("cov1 requires at least two units (ddof=1)")
350
+ return self.cross_c / (self.n - 1)
351
+
352
+ @property
353
+ def corr_coef(self) -> float:
354
+ """``np.corrcoef(y, x)[0, 1]`` parity (scale-free — ddof cancels)."""
355
+ self._require_covariate()
356
+ assert self.cov_m2 is not None and self.cross_c is not None
357
+ denominator = float(np.sqrt(self.m2 * self.cov_m2))
358
+ if denominator == 0.0:
359
+ return float("nan")
360
+ return self.cross_c / denominator
361
+
362
+ def __repr__(self) -> str:
363
+ return (
364
+ f"SufficientStats(name={self.name!r}, n={self.n}, mean={self.mean:.6g}, "
365
+ f"var={self.var:.6g}, covariate={self.has_covariate})"
366
+ )
367
+
368
+
369
+ class RatioSufficientStats:
370
+ """Sufficient statistics of ONE variant for the ``ratio-delta`` method.
371
+
372
+ ``{n, mean_num, m2_num, mean_den, m2_den, c_nd}`` where ``m2_*`` are raw
373
+ centered second moments and ``c_nd = Σ(n_u−n̄)(d_u−d̄)``. ``ratio-delta`` is a
374
+ NEW method (no legacy baseline), so its variance terms use ``ddof=0``
375
+ uniformly — documented in docs/specs/statistics-changes.md §4.
376
+ """
377
+
378
+ def __init__(
379
+ self,
380
+ n: int,
381
+ mean_num: float,
382
+ m2_num: float,
383
+ mean_den: float,
384
+ m2_den: float,
385
+ c_nd: float,
386
+ name: str | None = None,
387
+ ) -> None:
388
+ if n <= 0:
389
+ raise SampleValidationError(f"RatioSufficientStats.n must be positive, got {n}")
390
+ self.n = int(n)
391
+ self.mean_num = float(mean_num)
392
+ self.m2_num = float(m2_num)
393
+ self.mean_den = float(mean_den)
394
+ self.m2_den = float(m2_den)
395
+ self.c_nd = float(c_nd)
396
+ self.name = name
397
+
398
+ @classmethod
399
+ def from_ratio_sample(cls, sample: RatioSample) -> RatioSufficientStats:
400
+ centered_num = sample.numerator - float(np.mean(sample.numerator))
401
+ centered_den = sample.denominator - float(np.mean(sample.denominator))
402
+ return cls(
403
+ n=sample.sample_size,
404
+ mean_num=float(np.mean(sample.numerator)),
405
+ m2_num=float(np.dot(centered_num, centered_num)),
406
+ mean_den=float(np.mean(sample.denominator)),
407
+ m2_den=float(np.dot(centered_den, centered_den)),
408
+ c_nd=float(np.dot(centered_num, centered_den)),
409
+ name=sample.name,
410
+ )
411
+
412
+ @property
413
+ def sample_size(self) -> int:
414
+ return self.n
415
+
416
+ @property
417
+ def ratio(self) -> float:
418
+ """The per-variant estimand ``R = mean(numerator) / mean(denominator)``."""
419
+ return self.mean_num / self.mean_den
420
+
421
+ def __repr__(self) -> str:
422
+ return f"RatioSufficientStats(name={self.name!r}, n={self.n})"
423
+
424
+
425
+ #: Series labels for paired sufficient statistics, in canonical order.
426
+ PAIRED_LABELS = ("y1", "y2")
427
+ PAIRED_CUPED_LABELS = ("y1", "y2", "x1", "x2")
428
+
429
+
430
+ class PairedSufficientStats:
431
+ """Joint per-pair moments of two aligned variants (paired designs).
432
+
433
+ Wraps a :class:`JointMoments` over ``(y1, y2)`` — or ``(y1, y2, x1, x2)`` when
434
+ both variants carry a covariate — so the paired t-test / paired CUPED
435
+ formulas (variance of differences, θ on differences, the negative covariance
436
+ term against the control arm) are exact linear-combination reads.
437
+ """
438
+
439
+ def __init__(
440
+ self,
441
+ moments: JointMoments,
442
+ name_1: str | None = None,
443
+ name_2: str | None = None,
444
+ ) -> None:
445
+ if moments.labels not in (PAIRED_LABELS, PAIRED_CUPED_LABELS):
446
+ raise SampleValidationError(
447
+ f"PairedSufficientStats requires labels {PAIRED_LABELS} or {PAIRED_CUPED_LABELS}, "
448
+ f"got {moments.labels}"
449
+ )
450
+ self.moments = moments
451
+ self.name_1 = name_1
452
+ self.name_2 = name_2
453
+
454
+ @classmethod
455
+ def from_samples(cls, sample_1: Sample, sample_2: Sample) -> PairedSufficientStats:
456
+ """Build from two position-aligned samples (see :func:`align_paired`)."""
457
+ if sample_1.sample_size != sample_2.sample_size:
458
+ raise SampleValidationError(
459
+ "paired samples must be equal-size and aligned by pair: "
460
+ f"{sample_1.sample_size} != {sample_2.sample_size}"
461
+ )
462
+ has_cov_1 = sample_1.cov_array is not None
463
+ has_cov_2 = sample_2.cov_array is not None
464
+ if has_cov_1 != has_cov_2:
465
+ raise SampleValidationError(
466
+ "either both or neither paired sample may carry a covariate"
467
+ )
468
+ if has_cov_1:
469
+ assert sample_1.cov_array is not None and sample_2.cov_array is not None
470
+ moments = JointMoments.from_arrays(
471
+ sample_1.array,
472
+ sample_2.array,
473
+ sample_1.cov_array,
474
+ sample_2.cov_array,
475
+ labels=PAIRED_CUPED_LABELS,
476
+ )
477
+ else:
478
+ moments = JointMoments.from_arrays(sample_1.array, sample_2.array, labels=PAIRED_LABELS)
479
+ return cls(moments, name_1=sample_1.name, name_2=sample_2.name)
480
+
481
+ @property
482
+ def n(self) -> int:
483
+ return self.moments.n
484
+
485
+ @property
486
+ def has_covariate(self) -> bool:
487
+ return self.moments.labels == PAIRED_CUPED_LABELS
488
+
489
+ def weights(self, **coefficients: float) -> FloatArray:
490
+ """Weight vector over the labelled series, e.g. ``weights(y2=1, y1=-1)``."""
491
+ vector = np.zeros(len(self.moments.labels), dtype=np.float64)
492
+ for label, coefficient in coefficients.items():
493
+ vector[self.moments.index(label)] = coefficient
494
+ return vector
495
+
496
+
497
+ def align_paired(sample_1: Sample, sample_2: Sample) -> tuple[Sample, Sample, int]:
498
+ """Align two variants by ``pair_ids`` (legacy semantics, baseline §5).
499
+
500
+ Keeps the sorted intersection of pair ids, drops unmatched pairs with a
501
+ warning, and returns position-aligned copies plus the dropped-pair count.
502
+ """
503
+ if sample_1.pair_ids is None or sample_2.pair_ids is None:
504
+ raise SampleValidationError("align_paired requires pair_ids on both samples")
505
+ common = np.intersect1d(sample_1.pair_ids, sample_2.pair_ids)
506
+ dropped = (sample_1.sample_size - common.size) + (sample_2.sample_size - common.size)
507
+ if common.size == 0:
508
+ raise SampleValidationError("no common pair_ids between the two samples")
509
+ if dropped:
510
+ warnings.warn(
511
+ f"align_paired dropped {dropped} unmatched pair(s) " f"({common.size} pairs kept)",
512
+ AbkitStatsWarning,
513
+ stacklevel=2,
514
+ )
515
+
516
+ def _take(sample: Sample) -> Sample:
517
+ assert sample.pair_ids is not None
518
+ order = np.argsort(sample.pair_ids)
519
+ sorted_ids = sample.pair_ids[order]
520
+ positions = order[np.searchsorted(sorted_ids, common)]
521
+ return Sample(
522
+ sample.array[positions],
523
+ cov_array=None if sample.cov_array is None else sample.cov_array[positions],
524
+ categories_array=(
525
+ None if sample.categories_array is None else sample.categories_array[positions]
526
+ ),
527
+ pair_ids=common,
528
+ name=sample.name,
529
+ )
530
+
531
+ return _take(sample_1), _take(sample_2), int(dropped)
@@ -0,0 +1,18 @@
1
+ """Sequential analysis: always-valid confidence sequences (M5, opt-in).
2
+
3
+ Pure, primitive-only (docs/specs/m5-implementation-plan.md D5 — no config/DB/Jinja/
4
+ click type crosses the ``abkit.stats`` boundary). See:
5
+
6
+ - :mod:`abkit.stats.sequential.confidence_sequence` — the estimator (an asymptotic
7
+ Gaussian confidence sequence) + the CI-inversion SE recovery.
8
+ - :mod:`abkit.stats.sequential.mixture` — the fixed-by-policy mixture variance
9
+ ``tau^2`` (the single source, shared by the pipeline and the A/A column).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from abkit.stats.sequential.apply import to_always_valid
15
+ from abkit.stats.sequential.confidence_sequence import se_from_ci_length, sequentialize
16
+ from abkit.stats.sequential.mixture import mixture_tau2
17
+
18
+ __all__ = ["mixture_tau2", "se_from_ci_length", "sequentialize", "to_always_valid"]
@@ -0,0 +1,37 @@
1
+ """Apply the always-valid transform to a fixed :class:`TestResult` (M5 WP3).
2
+
3
+ The experiment-level sequential MODE (docs/specs/m5-implementation-plan.md D1): given a
4
+ fixed-horizon ``TestResult`` and the frozen mixture variance ``tau2``, widen its CI into
5
+ the always-valid confidence sequence and re-derive the p-value / reject flag from it,
6
+ stamping ``ci_kind='always_valid'``. Pure — takes a ``TestResult``, returns a new one
7
+ (``dataclasses.replace``), never mutating; consumes only the shipped ``(effect, SE)``
8
+ via CI-inversion, so it is method-agnostic and never re-derives a variance.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import replace
14
+
15
+ from abkit.stats.result import TestResult
16
+ from abkit.stats.sequential.confidence_sequence import se_from_ci_length, sequentialize
17
+
18
+
19
+ def to_always_valid(result: TestResult, tau2: float, alpha: float) -> TestResult:
20
+ """Return a copy of ``result`` with always-valid bounds, p-value, and ci_kind.
21
+
22
+ A degenerate fixed result (NaN ci_length) yields NaN always-valid bounds — the
23
+ downstream NULLs it exactly like the fixed NaN-bound path, never an exception.
24
+ ``alpha`` is the result's own effective alpha (``result.alpha``).
25
+ """
26
+ se = se_from_ci_length(result.ci_length, alpha)
27
+ lo, hi, av_pvalue = sequentialize(result.effect, se, tau2, alpha)
28
+ reject = (lo > 0.0) or (hi < 0.0) # CI-excludes-zero ≡ av_pvalue <= alpha
29
+ return replace(
30
+ result,
31
+ left_bound=lo,
32
+ right_bound=hi,
33
+ ci_length=hi - lo,
34
+ pvalue=av_pvalue,
35
+ reject=reject,
36
+ ci_kind="always_valid",
37
+ )
@@ -0,0 +1,96 @@
1
+ """The always-valid confidence sequence — a closed-form widening of the fixed CI.
2
+
3
+ M5 decision D2 (docs/specs/m5-implementation-plan.md; docs/specs/statistics-changes.md
4
+ §4): the pure ``abkit.stats`` core exposes a per-look ``(effect, SE)`` sufficient
5
+ statistic, not the raw observation stream, so the always-valid interval is the
6
+ **asymptotic Gaussian confidence sequence** (Waudby-Smith & Ramdas 2021 — the
7
+ Robbins/Howard normal mixture applied to the estimate), NOT the exact finite-sample
8
+ Robbins/Howard mSPRT (which needs running sums). It is an experiment-level MODE
9
+ transform (D1) — never a method plugin, never a name special-case — that consumes
10
+ whatever ``(effect, SE)`` the bound method already produced and **never re-derives a
11
+ variance**.
12
+
13
+ The math. With ``V = SE^2`` and a fixed mixing variance ``tau^2`` (mixture.py), the
14
+ two-sided normal-mixture confidence sequence at a look is ``effect ± r`` where
15
+
16
+ r = sqrt( (2 * V * (V + tau^2) / tau^2) * ( ln(1/alpha) + 0.5 * ln((V + tau^2)/V) ) ).
17
+
18
+ Derivation: the mixture likelihood ratio against a ``N(theta_0, tau^2)`` alternative,
19
+ ``Lambda(theta_0) = sqrt(V/(V+tau^2)) * exp( tau^2 (effect - theta_0)^2 / (2 V (V+tau^2)) )``,
20
+ is a non-negative martingale under ``theta_0``; by Ville's inequality the set
21
+ ``{ theta_0 : Lambda(theta_0) <= 1/alpha }`` covers the truth simultaneously at every
22
+ look with probability >= 1 - alpha. Inverting the inequality gives ``r`` above. The
23
+ always-valid p-value is the dual, ``min(1, 1/Lambda(0))``, so ``p <= alpha`` iff the
24
+ interval excludes zero (pinned by a test). The guarantee is finite-sample if the
25
+ estimate were exactly Gaussian and **asymptotic-anytime** otherwise (documented, never
26
+ over-claimed as exact mSPRT).
27
+
28
+ The always-valid interval always strictly contains the fixed-horizon interval (it is
29
+ wider by construction — the price of anytime validity), so an early WIN/LOSE read off
30
+ it is honest under optional stopping (the readout lifts its pre-horizon refusal only
31
+ for ``ci_kind='always_valid'``).
32
+
33
+ Purity (D5): plain primitives only.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import math
39
+
40
+ import scipy.stats as sps
41
+
42
+
43
+ def se_from_ci_length(ci_length: float, alpha: float) -> float:
44
+ """Recover the effect standard error by inverting a symmetric normal CI (D3).
45
+
46
+ Every parametric method builds its fixed CI as
47
+ ``effect ± norm.ppf(1 - alpha/2) * SE`` (``effects.normal_test``), so
48
+ ``ci_length = 2 * norm.ppf(1 - alpha/2) * SE`` and therefore
49
+
50
+ SE = ci_length / (2 * norm.ppf(1 - alpha/2)).
51
+
52
+ This CI-inversion is the ONLY sanctioned SE recovery: it preserves the
53
+ delta-method covariance already baked into ``ci_length`` (relative / CUPED /
54
+ ratio-delta), is method-agnostic, and never re-derives the per-arm variances
55
+ (which would drop the covariance term). Returns NaN for a NaN/degenerate CI
56
+ (the fixed path's NaN-bound bucket — never an exception).
57
+ """
58
+ if not math.isfinite(ci_length) or ci_length < 0.0:
59
+ return float("nan")
60
+ z = float(sps.norm.ppf(1.0 - alpha / 2.0))
61
+ return ci_length / (2.0 * z)
62
+
63
+
64
+ def sequentialize(
65
+ effect: float, se: float, tau2: float, alpha: float
66
+ ) -> tuple[float, float, float]:
67
+ """Return ``(lo, hi, av_pvalue)`` — the always-valid interval + p-value at a look.
68
+
69
+ ``se`` is the effect standard error (recover it from a fixed CI via
70
+ :func:`se_from_ci_length`); ``tau2`` is the fixed mixture variance from
71
+ :func:`abkit.stats.sequential.mixture.mixture_tau2`. A degenerate look
72
+ (non-finite ``effect``/``se`` or ``se <= 0``) returns ``(nan, nan, nan)`` — it
73
+ is tallied in the NaN-bound bucket, never a silent non-rejection and never an
74
+ exception. Programming-contract violations (``alpha`` out of range, non-positive
75
+ ``tau2``) raise ``ValueError``.
76
+ """
77
+ if not 0.0 < alpha < 1.0:
78
+ raise ValueError(f"alpha must be in (0, 1), got {alpha!r}")
79
+ if not math.isfinite(tau2) or tau2 <= 0.0:
80
+ raise ValueError(f"tau2 (mixture variance) must be finite and positive, got {tau2!r}")
81
+ if not (math.isfinite(effect) and math.isfinite(se)) or se <= 0.0:
82
+ nan = float("nan")
83
+ return (nan, nan, nan)
84
+
85
+ var = se * se
86
+ ln_inv_alpha = -math.log(alpha)
87
+ denom = 2.0 * var * (var + tau2) # 2 V (V + tau^2), shared by radius and p-value
88
+ ratio = (var + tau2) / var
89
+ radius = math.sqrt((denom / tau2) * (ln_inv_alpha + 0.5 * math.log(ratio)))
90
+ lo = effect - radius
91
+ hi = effect + radius
92
+
93
+ # Always-valid p-value = min(1, 1/Lambda(0)); p <= alpha iff 0 is excluded.
94
+ inv_lambda = math.sqrt(ratio) * math.exp(-(tau2 * effect * effect) / denom)
95
+ pvalue = inv_lambda if inv_lambda < 1.0 else 1.0
96
+ return (lo, hi, pvalue)