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/power.py ADDED
@@ -0,0 +1,278 @@
1
+ """Power / MDE / sample-size solves (baseline §6 — legacy transcription).
2
+
3
+ Built on statsmodels ``TTestIndPower`` / ``NormalIndPower`` exactly as the legacy
4
+ ``sample_utils.py`` / ``fraction_utils.py``:
5
+
6
+ - continuous metrics: solve the standardized effect size at the target power,
7
+ convert to a relative/absolute MDE; CUPED deflates the std by
8
+ ``sqrt(1 − corr²)`` before the same solve;
9
+ - proportions: Cohen's h via ``proportion_effectsize`` (arcsine transform) and
10
+ the inverse arcsine back-transform for the MDE.
11
+
12
+ Legacy conventions preserved: ``size <= 1 or std == 0`` → ``inf`` MDE; the
13
+ continuous MDE is rounded to 4 decimals; numpy division semantics (a zero mean
14
+ under ``relative`` yields ±inf, never an exception).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from functools import lru_cache
20
+
21
+ import numpy as np
22
+ from statsmodels.stats.power import NormalIndPower, TTestIndPower
23
+ from statsmodels.stats.proportion import proportion_effectsize
24
+
25
+ from abkit.stats.exceptions import MethodParamError
26
+
27
+
28
+ def _as_scalar(value: object) -> float:
29
+ """Extract a Python float from a statsmodels ``solve_power`` return.
30
+
31
+ statsmodels' internal ``fsolve`` fallback (used when brentq bracketing
32
+ fails, which happens for a data-dependent ~few-percent of ordinary
33
+ ``(nobs, ratio)`` inputs) returns a shape-``(1,)`` ndarray rather than a
34
+ scalar. ``float(ndarray-of-size-1)`` raised silently under numpy < 2.0 and
35
+ now *raises* under numpy ≥ 2.0 — crashing the readout/report MDE path on
36
+ plain sizes (e.g. n=139, ratio=1.0). Extracting element 0 is
37
+ value-preserving (same number the scalar path yields); no statistical
38
+ number changes (golden-tested)."""
39
+ array = np.asarray(value, dtype=float).reshape(-1)
40
+ if array.size != 1:
41
+ raise ValueError(f"solve_power returned {array.size} values, expected 1")
42
+ return float(array[0])
43
+
44
+
45
+ @lru_cache(maxsize=4096)
46
+ def _ttest_effect_size_at_power(size: int, alpha: float, power: float, ratio: float) -> float:
47
+ """Cached MDE-side solve: the effect size depends only on (n, α, power, ratio),
48
+ so cumulative runs (same sizes every day, many metrics) hit the cache instead
49
+ of re-running the brentq root-solve per call (review finding)."""
50
+ return _as_scalar(
51
+ TTestIndPower().solve_power(
52
+ effect_size=None,
53
+ nobs1=size,
54
+ alpha=alpha,
55
+ power=power,
56
+ ratio=ratio,
57
+ alternative="two-sided",
58
+ )
59
+ )
60
+
61
+
62
+ @lru_cache(maxsize=4096)
63
+ def _normal_effect_size_at_power(size: int, alpha: float, power: float, ratio: float) -> float:
64
+ return _as_scalar(
65
+ NormalIndPower().solve_power(
66
+ effect_size=None,
67
+ nobs1=size,
68
+ alpha=alpha,
69
+ power=power,
70
+ ratio=ratio,
71
+ alternative="two-sided",
72
+ )
73
+ )
74
+
75
+
76
+ def _check_test_type(test_type: str) -> None:
77
+ if test_type not in ("relative", "absolute"):
78
+ raise MethodParamError(f"test_type must be 'relative' or 'absolute', got {test_type!r}")
79
+
80
+
81
+ def _adjusted_mean(mean: float, mde: float, test_type: str) -> float:
82
+ return mean * (1.0 + mde) if test_type == "relative" else mean + mde
83
+
84
+
85
+ # --- continuous metrics (legacy sample_utils.py) ---------------------------------
86
+
87
+
88
+ def get_ttest_mde(
89
+ mean: float,
90
+ std: float,
91
+ size: int,
92
+ test_type: str = "relative",
93
+ alpha: float = 0.05,
94
+ power: float = 0.8,
95
+ ratio: float = 1.0,
96
+ ) -> float:
97
+ """MDE at the given power for the (normal-approx) t-test; ``ratio = n_other / n_this``."""
98
+ _check_test_type(test_type)
99
+ if size <= 1 or std == 0:
100
+ return float("inf")
101
+ effect_size = _ttest_effect_size_at_power(int(size), float(alpha), float(power), float(ratio))
102
+ mean_adjusted = mean + effect_size * std
103
+ with np.errstate(divide="ignore", invalid="ignore"):
104
+ if test_type == "relative":
105
+ mde = float(np.float64(mean_adjusted - mean) / np.float64(mean))
106
+ else:
107
+ mde = mean_adjusted - mean
108
+ if not np.isfinite(mde):
109
+ return mde
110
+ return round(mde, 4)
111
+
112
+
113
+ def get_ttest_power(
114
+ mean: float,
115
+ std: float,
116
+ size: int,
117
+ mde: float,
118
+ test_type: str = "relative",
119
+ alpha: float = 0.05,
120
+ ratio: float = 1.0,
121
+ ) -> float:
122
+ """Achieved power for detecting ``mde`` at the given sample size."""
123
+ _check_test_type(test_type)
124
+ mean_adjusted = _adjusted_mean(mean, mde, test_type)
125
+ effect_size = abs(mean - mean_adjusted) / std
126
+ return float(
127
+ TTestIndPower().solve_power(
128
+ effect_size=effect_size,
129
+ nobs1=size,
130
+ alpha=alpha,
131
+ power=None,
132
+ ratio=ratio,
133
+ alternative="two-sided",
134
+ )
135
+ )
136
+
137
+
138
+ def get_ttest_sample_size(
139
+ mean: float,
140
+ std: float,
141
+ mde: float,
142
+ test_type: str = "relative",
143
+ alpha: float = 0.05,
144
+ power: float = 0.8,
145
+ ratio: float = 1.0,
146
+ ) -> int:
147
+ """Required per-group-1 sample size to detect ``mde`` at the given power."""
148
+ _check_test_type(test_type)
149
+ mean_adjusted = _adjusted_mean(mean, mde, test_type)
150
+ effect_size = abs(mean - mean_adjusted) / std
151
+ size = TTestIndPower().solve_power(
152
+ effect_size=effect_size,
153
+ nobs1=None,
154
+ alpha=alpha,
155
+ power=power,
156
+ ratio=ratio,
157
+ alternative="two-sided",
158
+ )
159
+ return int(round(float(size)))
160
+
161
+
162
+ # --- CUPED variants: variance shrunk by the covariate correlation ----------------
163
+
164
+
165
+ def cuped_adjusted_std(std: float, corr_coef: float) -> float:
166
+ """``std · sqrt(1 − corr²)`` — CUPED's variance-reduction effect on the solve."""
167
+ return float(std * np.sqrt(1.0 - corr_coef**2))
168
+
169
+
170
+ def get_cuped_ttest_mde(
171
+ mean: float,
172
+ std: float,
173
+ corr_coef: float,
174
+ size: int,
175
+ test_type: str = "relative",
176
+ alpha: float = 0.05,
177
+ power: float = 0.8,
178
+ ratio: float = 1.0,
179
+ ) -> float:
180
+ return get_ttest_mde(
181
+ mean, cuped_adjusted_std(std, corr_coef), size, test_type, alpha, power, ratio
182
+ )
183
+
184
+
185
+ def get_cuped_ttest_power(
186
+ mean: float,
187
+ std: float,
188
+ corr_coef: float,
189
+ size: int,
190
+ mde: float,
191
+ test_type: str = "relative",
192
+ alpha: float = 0.05,
193
+ ratio: float = 1.0,
194
+ ) -> float:
195
+ return get_ttest_power(
196
+ mean, cuped_adjusted_std(std, corr_coef), size, mde, test_type, alpha, ratio
197
+ )
198
+
199
+
200
+ def get_cuped_ttest_sample_size(
201
+ mean: float,
202
+ std: float,
203
+ corr_coef: float,
204
+ mde: float,
205
+ test_type: str = "relative",
206
+ alpha: float = 0.05,
207
+ power: float = 0.8,
208
+ ratio: float = 1.0,
209
+ ) -> int:
210
+ return get_ttest_sample_size(
211
+ mean, cuped_adjusted_std(std, corr_coef), mde, test_type, alpha, power, ratio
212
+ )
213
+
214
+
215
+ # --- proportions (legacy fraction_utils.py) ---------------------------------------
216
+
217
+
218
+ def get_fraction_mde(
219
+ prop: float,
220
+ size: int,
221
+ test_type: str = "relative",
222
+ alpha: float = 0.05,
223
+ power: float = 0.8,
224
+ ratio: float = 1.0,
225
+ ) -> float:
226
+ """MDE for a proportion via the inverse arcsine (Cohen's h) back-transform."""
227
+ _check_test_type(test_type)
228
+ effect_size = _normal_effect_size_at_power(int(size), float(alpha), float(power), float(ratio))
229
+ mde_absolute = float(np.sin(np.arcsin(np.sqrt(prop)) + effect_size / 2.0) ** 2 - prop)
230
+ with np.errstate(divide="ignore", invalid="ignore"):
231
+ if test_type == "relative":
232
+ return float(np.float64(mde_absolute) / np.float64(prop))
233
+ return mde_absolute
234
+
235
+
236
+ def get_fraction_power(
237
+ prop: float,
238
+ size: int,
239
+ mde: float,
240
+ test_type: str = "relative",
241
+ alpha: float = 0.05,
242
+ ratio: float = 1.0,
243
+ ) -> float:
244
+ _check_test_type(test_type)
245
+ mde_absolute = prop * mde if test_type == "relative" else mde
246
+ effect_size = proportion_effectsize(prop, prop + mde_absolute)
247
+ return float(
248
+ NormalIndPower().solve_power(
249
+ effect_size=effect_size,
250
+ nobs1=size,
251
+ alpha=alpha,
252
+ power=None,
253
+ ratio=ratio,
254
+ alternative="two-sided",
255
+ )
256
+ )
257
+
258
+
259
+ def get_fraction_sample_size(
260
+ prop: float,
261
+ mde: float,
262
+ test_type: str = "relative",
263
+ alpha: float = 0.05,
264
+ power: float = 0.8,
265
+ ratio: float = 1.0,
266
+ ) -> int:
267
+ _check_test_type(test_type)
268
+ mde_absolute = prop * mde if test_type == "relative" else mde
269
+ effect_size = proportion_effectsize(prop, prop + mde_absolute)
270
+ size = NormalIndPower().solve_power(
271
+ effect_size=effect_size,
272
+ nobs1=None,
273
+ alpha=alpha,
274
+ power=power,
275
+ ratio=ratio,
276
+ alternative="two-sided",
277
+ )
278
+ return int(round(float(size)))
@@ -0,0 +1,111 @@
1
+ """Method registry: name → class, plus the quarantine list for broken legacy methods.
2
+
3
+ The pipeline/DB/CLI never special-case a method name — everything routes through
4
+ :func:`get_method_class`. Quarantined names (docs/specs/statistics-changes.md §3)
5
+ raise a hard, explanatory error and are never silently substituted.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Iterable
11
+ from typing import overload
12
+
13
+ from abkit.stats.base import BaseMethod
14
+ from abkit.stats.exceptions import QuarantinedMethodError, UnknownMethodError
15
+
16
+ _REGISTRY: dict[str, type[BaseMethod]] = {}
17
+ _ALIASES: dict[str, str] = {}
18
+
19
+ #: Legacy methods verified broken — hard error, never a silent substitution
20
+ #: (quorum must-fix "quarantine broken ratio methods").
21
+ QUARANTINED_METHODS: dict[str, str] = {
22
+ "poisson-post-normed-bootstrap": (
23
+ "the legacy PoissonPostNormedBootstrapTest performs NO post-normalisation — it is a "
24
+ "verbatim copy of PoissonBootstrapTest. Use 'poisson-bootstrap' (identical behaviour) "
25
+ "or the principled 'ratio-delta' for ratio metrics. See statistics-changes.md §3."
26
+ ),
27
+ }
28
+
29
+
30
+ def normalize_method_name(name: str) -> str:
31
+ return name.strip().lower().replace("_", "-")
32
+
33
+
34
+ def _same_class(a: type, b: type) -> bool:
35
+ """Same class re-created by a module re-import (importlib.reload / %autoreload)."""
36
+ return a.__module__ == b.__module__ and a.__qualname__ == b.__qualname__
37
+
38
+
39
+ @overload
40
+ def register(cls: type[BaseMethod]) -> type[BaseMethod]: ...
41
+
42
+
43
+ @overload
44
+ def register(*, aliases: Iterable[str] = ()) -> Callable[[type[BaseMethod]], type[BaseMethod]]: ...
45
+
46
+
47
+ def register(
48
+ cls: type[BaseMethod] | None = None, *, aliases: Iterable[str] = ()
49
+ ) -> type[BaseMethod] | Callable[[type[BaseMethod]], type[BaseMethod]]:
50
+ """Class decorator: ``@register`` or ``@register(aliases=("ttest",))``."""
51
+
52
+ def _register(method_cls: type[BaseMethod]) -> type[BaseMethod]:
53
+ name = getattr(method_cls, "name", None)
54
+ if not name or not isinstance(name, str):
55
+ raise ValueError(f"{method_cls.__name__} must define a class-level registry `name`")
56
+ canonical = normalize_method_name(name)
57
+ if canonical != name:
58
+ raise ValueError(f"registry name must be canonical kebab-case, got {name!r}")
59
+ if canonical in _ALIASES:
60
+ raise ValueError(
61
+ f"method name {canonical!r} collides with an alias of {_ALIASES[canonical]!r} "
62
+ "(aliases are resolved before registry lookup, so this class would be unreachable)"
63
+ )
64
+ existing = _REGISTRY.get(canonical)
65
+ if (
66
+ existing is not None
67
+ and existing is not method_cls
68
+ and not _same_class(existing, method_cls)
69
+ ):
70
+ raise ValueError(f"method name {canonical!r} already registered by {existing.__name__}")
71
+ if canonical in QUARANTINED_METHODS:
72
+ raise ValueError(f"method name {canonical!r} is quarantined and cannot be registered")
73
+ _REGISTRY[canonical] = method_cls
74
+ for alias in aliases:
75
+ alias_canonical = normalize_method_name(alias)
76
+ if alias_canonical in QUARANTINED_METHODS:
77
+ raise ValueError(f"alias {alias_canonical!r} is quarantined and cannot be reused")
78
+ if alias_canonical in _REGISTRY:
79
+ raise ValueError(f"alias {alias_canonical!r} collides with a registered method")
80
+ if _ALIASES.get(alias_canonical, canonical) != canonical:
81
+ raise ValueError(
82
+ f"alias {alias_canonical!r} already points to {_ALIASES[alias_canonical]!r}"
83
+ )
84
+ _ALIASES[alias_canonical] = canonical
85
+ return method_cls
86
+
87
+ if cls is not None:
88
+ return _register(cls)
89
+ return _register
90
+
91
+
92
+ def get_method_class(name: str) -> type[BaseMethod]:
93
+ canonical = normalize_method_name(name)
94
+ # Quarantine is checked BEFORE and after alias resolution so no alias can
95
+ # ever route around it.
96
+ for candidate in (canonical, _ALIASES.get(canonical, canonical)):
97
+ if candidate in QUARANTINED_METHODS:
98
+ raise QuarantinedMethodError(
99
+ f"method {name!r} is quarantined: {QUARANTINED_METHODS[candidate]}"
100
+ )
101
+ canonical = _ALIASES.get(canonical, canonical)
102
+ try:
103
+ return _REGISTRY[canonical]
104
+ except KeyError:
105
+ raise UnknownMethodError(
106
+ f"unknown method {name!r}; available: {', '.join(available_methods())}"
107
+ ) from None
108
+
109
+
110
+ def available_methods() -> tuple[str, ...]:
111
+ return tuple(sorted(_REGISTRY))
abkit/stats/result.py ADDED
@@ -0,0 +1,84 @@
1
+ """The per-comparison output record (legacy ``TestResult`` parity, baseline §1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, field, fields
7
+ from typing import Any, ClassVar
8
+
9
+
10
+ @dataclass
11
+ class TestResult:
12
+ """One pairwise variant comparison — maps 1:1 onto the ``_ab_results`` row.
13
+
14
+ Field semantics follow docs/specs/statistics-baseline.md §1 exactly:
15
+ ``name_1``/``*_1`` is the control arm (first variant), ``*_2`` the treatment.
16
+ ``effect`` is always the point estimate on the REAL data (hygiene fix H9);
17
+ bootstrap methods report ``boot_mean`` in :attr:`diagnostics` as a bias
18
+ diagnostic instead of overloading ``effect``.
19
+
20
+ ``method_params`` is the identity-bearing, non-default params dict — the same
21
+ object that is canonically serialised and hashed into ``method_config_id``
22
+ (docs/specs/declarative-config.md §7), so BI series filters and identity can
23
+ never disagree.
24
+ """
25
+
26
+ # The class name matches pytest's Test* collection pattern; it is a result
27
+ # record, not a test case.
28
+ __test__: ClassVar[bool] = False
29
+
30
+ name_1: str | None
31
+ name_2: str | None
32
+ value_1: float
33
+ value_2: float
34
+ std_1: float
35
+ std_2: float
36
+ size_1: int
37
+ size_2: int
38
+ method_name: str
39
+ method_params: dict[str, Any]
40
+ alpha: float
41
+ pvalue: float
42
+ effect: float
43
+ ci_length: float
44
+ left_bound: float
45
+ right_bound: float
46
+ reject: bool
47
+ # "fixed" (default, legacy parity) | "always_valid" (the M5 sequential mode —
48
+ # an always-valid confidence sequence; docs/specs/m5-implementation-plan.md D7).
49
+ # A row FIELD, never part of method_config_id (sequential is a mode, not identity).
50
+ ci_kind: str = "fixed"
51
+ cov_value_1: float | None = None
52
+ cov_value_2: float | None = None
53
+ mde_1: float | None = None
54
+ mde_2: float | None = None
55
+ effect_distribution: Any | None = field(default=None, repr=False, compare=False)
56
+ warnings: list[str] = field(default_factory=list)
57
+ diagnostics: dict[str, float] = field(default_factory=dict)
58
+
59
+ def to_dict(self) -> dict[str, Any]:
60
+ """JSON-safe flat dict (drops ``effect_distribution``; NaN/inf → None).
61
+
62
+ Derived from ``dataclasses.fields`` so a future field cannot be silently
63
+ forgotten in serialisation (review finding).
64
+ """
65
+
66
+ def _clean(value: Any) -> Any:
67
+ if isinstance(value, float) and not math.isfinite(value):
68
+ return None
69
+ return value
70
+
71
+ result: dict[str, Any] = {}
72
+ for spec in fields(self):
73
+ if spec.name == "effect_distribution":
74
+ continue
75
+ value = getattr(self, spec.name)
76
+ if spec.name == "reject":
77
+ result[spec.name] = bool(value)
78
+ elif spec.name == "warnings":
79
+ result[spec.name] = list(value)
80
+ elif isinstance(value, dict) and spec.name == "diagnostics":
81
+ result[spec.name] = {key: _clean(entry) for key, entry in value.items()}
82
+ else:
83
+ result[spec.name] = _clean(value)
84
+ return result
abkit/stats/rng.py ADDED
@@ -0,0 +1,39 @@
1
+ """Randomness policy for the statistical core.
2
+
3
+ Legacy hygiene fixes H1/H2 (docs/specs/statistics-changes.md §2):
4
+
5
+ - Never mutate global numpy state (``np.random.seed``): every consumer receives an
6
+ explicit ``np.random.Generator``, so the core is reentrant and process-safe.
7
+ - Bootstrap re-runs must be byte-stable: the pipeline derives a deterministic
8
+ per-row seed from the row identity ``(experiment, metric, name_1, name_2,
9
+ end_date, n_samples)`` via :func:`derive_seed`. The seed is *excluded* from
10
+ ``method_config_id`` (docs/specs/declarative-config.md §7).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+
17
+ import numpy as np
18
+
19
+ #: Separator between seed parts (ASCII unit separator — cannot appear in dates,
20
+ #: experiment/metric/variant names), so ("ab", "c") and ("a", "bc") differ.
21
+ _PART_SEPARATOR = "\x1f"
22
+
23
+
24
+ def derive_seed(*parts: object) -> int:
25
+ """Derive a deterministic 63-bit seed from identity parts.
26
+
27
+ Parts are joined by their ``str()`` form — pass plain values (strings, dates,
28
+ ints), e.g. ``derive_seed(experiment, metric, name_1, name_2, end_date,
29
+ n_samples)``. The mapping is pinned by a known-answer test and must never
30
+ change (it would silently re-draw every published bootstrap CI).
31
+ """
32
+ payload = _PART_SEPARATOR.join(str(part) for part in parts)
33
+ digest = hashlib.sha256(payload.encode("utf-8")).digest()
34
+ return int.from_bytes(digest[:8], "big") >> 1 # 63 bits, non-negative
35
+
36
+
37
+ def make_rng(seed: int | None = None) -> np.random.Generator:
38
+ """Return a fresh, local ``Generator`` (never the global numpy RNG)."""
39
+ return np.random.default_rng(seed)