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,389 @@
1
+ """The validate runner: enumerate cells → load → score → select (m4 WP3, D6/D16).
2
+
3
+ Pure of persistence — it reads the warehouse (through the backend's loaders) and
4
+ returns an :class:`AaValidateResult`; the CLI (WP4) takes the lock and writes the rows.
5
+ By default it scores the experiment's *declared* comparisons (D6); ``extra_methods``
6
+ adds registered methods to the grid (the ``--method`` surface, WP4). Every row carries
7
+ the **effective post-correction per-comparison alpha** (``comparison_alpha ∘
8
+ effective_alphas``) so the D3 calibration chip matches (recompute.py:245–315).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+
15
+ from abkit.compute.recompute_backend import RecomputeBackend
16
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
17
+ from abkit.config.method_config import MethodConfig
18
+ from abkit.config.metric_config import MetricConfig
19
+ from abkit.config.project_config import ProjectConfig
20
+ from abkit.pipeline.analyze import comparison_alpha, effective_alphas
21
+ from abkit.stats.exceptions import StatsError
22
+ from abkit.stats.registry import get_method_class
23
+ from abkit.validate._types import DecisionEntry, ValidateError
24
+ from abkit.validate.load import DEFAULT_GRID_CAP, load_placebo_panel
25
+ from abkit.validate.panel import PlaceboPanel
26
+ from abkit.validate.result import AaValidateResult, CellResult
27
+ from abkit.validate.run_id import run_stamp
28
+ from abkit.validate.scoring import CellScore, score_cell
29
+
30
+ DEFAULT_ITERATIONS = 2000
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class ValidateSettings:
35
+ """Resolved knobs for one validate invocation (the donor ``TuneSettings`` split)."""
36
+
37
+ iterations: int = DEFAULT_ITERATIONS
38
+ inject_effect: float | None = None
39
+ mode: str = "fpr" # fpr | power | mde — the selection objective (D16)
40
+ grid_cap: int = DEFAULT_GRID_CAP
41
+ target_power: float = 0.8
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class _CellSpec:
46
+ metric: str
47
+ comparison: ComparisonConfig
48
+ method: MethodConfig
49
+ alpha: float
50
+
51
+
52
+ def _budget(project: ProjectConfig, alpha: float, metric: MetricConfig | None) -> float:
53
+ """The one aa_fpr_budget resolver (metric → project → α×1.5), reused from M3.
54
+
55
+ Imported lazily so ``abkit.validate`` and ``abkit.tuning`` never form an import
56
+ cycle (WP6 has the server call this package).
57
+ """
58
+ from abkit.tuning.recompute import resolve_fpr_budget
59
+
60
+ return resolve_fpr_budget(project, alpha, metric)
61
+
62
+
63
+ def _share_a(experiment: ExperimentConfig) -> float:
64
+ """Arm-A split share from the first variant's ``expected_split`` (default 0.5)."""
65
+ variants = experiment.assignment.variants
66
+ split = experiment.assignment.expected_split
67
+ if variants and split:
68
+ first = float(split.get(variants[0], 0.5))
69
+ total = float(sum(split.values())) or 1.0
70
+ share = first / total
71
+ return min(max(share, 0.01), 0.99)
72
+ return 0.5
73
+
74
+
75
+ def _method_fits(
76
+ method: MethodConfig, metric: MetricConfig | None, log: list[DecisionEntry] | None
77
+ ) -> bool:
78
+ """D6: an extra ``--method`` must match the metric's ``input_kind``, not be paired,
79
+ and not be quarantined/unknown — else it can never score in A/A (placebo arms are
80
+ unpaired). Skip-and-log rather than enqueue a doomed cell that persists as a
81
+ confusing ``status='failed'`` row (m4 exit-gate review). Mirrors the knob-surface
82
+ filter (recompute.py ``knob_surface``)."""
83
+ if metric is None:
84
+ return True # a missing metric is reported downstream by the runner
85
+ try:
86
+ method_cls = get_method_class(method.name)
87
+ except StatsError as exc: # quarantined or unknown
88
+ if log is not None:
89
+ log.append(DecisionEntry("enumerate", f"--method {method.name!r} skipped: {exc}"))
90
+ return False
91
+ if method_cls.input_kind != metric.type or method_cls.is_paired:
92
+ if log is not None:
93
+ reason = "paired" if method_cls.is_paired else f"needs {method_cls.input_kind}"
94
+ log.append(
95
+ DecisionEntry(
96
+ "enumerate",
97
+ f"--method {method.name!r} skipped for {metric.name!r} "
98
+ f"({metric.type} metric): {reason}",
99
+ )
100
+ )
101
+ return False
102
+ return True
103
+
104
+
105
+ def enumerate_cells(
106
+ experiment: ExperimentConfig,
107
+ project: ProjectConfig,
108
+ metrics: dict[str, MetricConfig] | None = None,
109
+ extra_methods: list[MethodConfig] | None = None,
110
+ log: list[DecisionEntry] | None = None,
111
+ ) -> list[_CellSpec]:
112
+ """One cell per declared comparison + compatible extra methods on each metric (D6).
113
+
114
+ Extra ``--method`` methods are filtered per metric (``_method_fits``) and de-duped
115
+ against cells already enqueued for that metric (same ``method_config_id``), so a
116
+ ``--method`` that repeats a declared method — or can't run on the metric — never
117
+ produces a duplicate or a doomed cell."""
118
+ alphas = effective_alphas(experiment, project)
119
+ cells: list[_CellSpec] = []
120
+ seen: set[tuple[str, str]] = set()
121
+
122
+ def _add(metric_name: str, comparison: ComparisonConfig, method: MethodConfig, alpha: float):
123
+ key = (metric_name, method.method_config_id)
124
+ if key in seen:
125
+ return
126
+ seen.add(key)
127
+ cells.append(_CellSpec(metric_name, comparison, method, alpha))
128
+
129
+ for comparison in experiment.comparisons:
130
+ alpha = comparison_alpha(comparison, alphas)
131
+ _add(comparison.metric, comparison, comparison.method, alpha)
132
+ metric = metrics.get(comparison.metric) if metrics else None
133
+ for method in extra_methods or []:
134
+ if _method_fits(method, metric, log):
135
+ _add(comparison.metric, comparison, method, alpha)
136
+ return cells
137
+
138
+
139
+ def _verdict(method_name: str, metric: str, score: CellScore, budget: float, alpha: float) -> str:
140
+ """A plain-language per-method verdict (aa-fpr §4.3 / R15)."""
141
+ if score.fpr is None:
142
+ return f"{method_name} on {metric}: could not measure FPR (degenerate/insufficient data)"
143
+ if score.fpr <= budget:
144
+ verdict = f"{method_name} on {metric}: well-calibrated, FPR {score.fpr:.1%}"
145
+ else:
146
+ verdict = (
147
+ f"{method_name} on {metric}: FPR inflated to {score.fpr:.1%} "
148
+ f"(budget {budget:.1%}), do not use"
149
+ )
150
+ if score.peeking_fpr is not None and score.peeking_fpr > 2 * alpha:
151
+ verdict += f"; peeking FPR {score.peeking_fpr:.1%} vs nominal α={alpha:g}"
152
+ return verdict
153
+
154
+
155
+ def _select_recommended(cells: list[CellResult]) -> tuple[str | None, str]:
156
+ """FPR-closest-to-nominal while maximizing power (aa-fpr §2 / R5, R14).
157
+
158
+ Returns ``(recommended method_config_id, rationale)``. Prefers cells whose FPR is
159
+ within budget; among those, the highest power, then the tightest achieved MDE.
160
+ """
161
+ scored = [c for c in cells if c.fpr is not None and c.status == "success"]
162
+ if not scored:
163
+ return None, "no cell produced a usable FPR"
164
+ in_budget = [c for c in scored if c.budget is not None and c.fpr <= c.budget]
165
+ pool = in_budget or scored
166
+
167
+ def key(c: CellResult) -> tuple:
168
+ power = c.power if c.power is not None else -1.0
169
+ mde = c.achieved_mde if c.achieved_mde is not None else float("inf")
170
+ return (power, -mde, -(c.fpr or 0.0))
171
+
172
+ best = max(pool, key=key)
173
+ if in_budget:
174
+ rationale = "highest power among methods with FPR within budget"
175
+ else:
176
+ rationale = "no method is within the FPR budget; highest-power fallback (use with caution)"
177
+ return best.method_config_id, rationale
178
+
179
+
180
+ def run_validation(
181
+ backend: RecomputeBackend,
182
+ experiment: ExperimentConfig,
183
+ project: ProjectConfig,
184
+ metrics: dict[str, MetricConfig],
185
+ metric_sqls: dict[str, str],
186
+ grid,
187
+ settings: ValidateSettings,
188
+ *,
189
+ now_iso: str,
190
+ extra_methods: list[MethodConfig] | None = None,
191
+ metric_filter: str | None = None,
192
+ ) -> AaValidateResult:
193
+ """Score every cell and return the per-cell results + the recommendation.
194
+
195
+ Reads the warehouse (never writes); the caller persists. Panels are cached by
196
+ ``(metric, covariate_lookback)`` — methods sharing a metric and lookback reuse
197
+ one load. ``metric_filter`` restricts scoring to a single metric (``--metric``).
198
+ """
199
+ log: list[DecisionEntry] = []
200
+ specs = enumerate_cells(experiment, project, metrics, extra_methods, log)
201
+ if metric_filter is not None:
202
+ specs = [s for s in specs if s.metric == metric_filter]
203
+ share_a = _share_a(experiment)
204
+ panel_cache: dict[tuple[str, object], PlaceboPanel] = {}
205
+ cells: list[CellResult] = []
206
+
207
+ for spec in specs:
208
+ metric = metrics.get(spec.metric)
209
+ if metric is None:
210
+ log.append(DecisionEntry("enumerate", f"metric '{spec.metric}' not found — skipped"))
211
+ continue
212
+ cell = _score_one(
213
+ backend,
214
+ experiment,
215
+ project,
216
+ metric,
217
+ metric_sqls,
218
+ grid,
219
+ spec,
220
+ settings,
221
+ share_a,
222
+ panel_cache,
223
+ log,
224
+ )
225
+ cells.append(cell)
226
+
227
+ # per-metric recommendation
228
+ by_metric: dict[str, list[CellResult]] = {}
229
+ for cell in cells:
230
+ by_metric.setdefault(cell.metric, []).append(cell)
231
+ # (metric, method_config_id) -> the ACTUAL selection rationale (in-budget max-power
232
+ # OR the over-budget fallback warning) so the report never contradicts the verdict.
233
+ recommended: dict[tuple[str, str], str] = {}
234
+ for metric_name, metric_cells in by_metric.items():
235
+ rec_id, rationale = _select_recommended(metric_cells)
236
+ if rec_id is not None:
237
+ recommended[(metric_name, rec_id)] = rationale
238
+ log.append(
239
+ DecisionEntry("select", f"{metric_name}: {rationale}", {"method_config_id": rec_id})
240
+ )
241
+
242
+ cells = [
243
+ _mark_recommended(cell, recommended.get((cell.metric, cell.method_config_id)))
244
+ for cell in cells
245
+ ]
246
+
247
+ return AaValidateResult(
248
+ experiment=experiment.name,
249
+ run_stamp=run_stamp(
250
+ experiment.name,
251
+ now_iso,
252
+ {
253
+ "iterations": settings.iterations,
254
+ "inject_effect": settings.inject_effect,
255
+ "mode": settings.mode,
256
+ },
257
+ ),
258
+ cells=tuple(cells),
259
+ decision_log=tuple(log),
260
+ )
261
+
262
+
263
+ def _score_one(
264
+ backend,
265
+ experiment,
266
+ project,
267
+ metric,
268
+ metric_sqls,
269
+ grid,
270
+ spec,
271
+ settings,
272
+ share_a,
273
+ panel_cache,
274
+ log,
275
+ ) -> CellResult:
276
+ method_id = spec.method.method_config_id
277
+ method_params = spec.method.canonical_params_json
278
+ base = {
279
+ "metric": spec.metric,
280
+ "method_name": spec.method.name,
281
+ "method_params": method_params,
282
+ "method_config_id": method_id,
283
+ "mode": settings.mode,
284
+ "alpha": spec.alpha,
285
+ "iterations": settings.iterations,
286
+ "injected_effect": settings.inject_effect,
287
+ }
288
+ budget = _budget(project, spec.alpha, metric)
289
+ try:
290
+ metric_sql = metric_sqls[spec.metric]
291
+ cache_key = (spec.metric, spec.method.covariate_lookback)
292
+ panel = panel_cache.get(cache_key)
293
+ if panel is None:
294
+ panel = load_placebo_panel(
295
+ backend,
296
+ spec.comparison,
297
+ metric,
298
+ metric_sql,
299
+ grid,
300
+ input_kind=metric.type,
301
+ cap=settings.grid_cap,
302
+ )
303
+ panel_cache[cache_key] = panel
304
+ method = spec.method.bind(alpha=spec.alpha)
305
+ score = score_cell(
306
+ panel,
307
+ method,
308
+ iterations=settings.iterations,
309
+ seed_parts=("aa", experiment.name, spec.metric, method_id),
310
+ share_a=share_a,
311
+ inject_effect=settings.inject_effect,
312
+ target_power=settings.target_power,
313
+ )
314
+ except (ValidateError, StatsError, KeyError, ValueError) as exc:
315
+ # StatsError covers QuarantinedMethodError AND the bootstrap-family / degenerate
316
+ # SampleValidationError — a single unscoreable cell fails only ITS row (R37),
317
+ # never aborting the whole experiment's matrix (m4 exit-gate review, F1).
318
+ log.append(DecisionEntry("score", f"{spec.metric}/{spec.method.name}: failed — {exc}"))
319
+ return CellResult(
320
+ **base,
321
+ fpr=None,
322
+ peeking_fpr=None,
323
+ power=None,
324
+ achieved_mde=None,
325
+ coverage=None,
326
+ effect_exaggeration=None,
327
+ verdict=f"{spec.method.name} on {spec.metric}: failed ({exc})",
328
+ budget=budget,
329
+ recommended=False,
330
+ details={},
331
+ status="failed",
332
+ error_message=str(exc),
333
+ )
334
+
335
+ details = {
336
+ "kept_grid_points": score.kept_grid_points,
337
+ "total_grid_points": score.total_grid_points,
338
+ "degenerate_horizon": score.degenerate_horizon,
339
+ "valid_iterations": score.valid_iterations,
340
+ "single_look_fpr": score.fpr,
341
+ "peeking_fpr": score.peeking_fpr,
342
+ # (elapsed_days, cumulative_fpr) per look — the peeking-vs-looks curve (R10)
343
+ "peeking_curve": [list(point) for point in score.peeking_curve],
344
+ # M5 D8: the always-valid twin curve + scalar (None-safe; empty when no column)
345
+ "single_look_fpr_sequential": score.fpr_sequential,
346
+ "peeking_fpr_sequential": score.peeking_fpr_sequential,
347
+ "peeking_curve_sequential": [list(point) for point in score.peeking_curve_sequential],
348
+ "warnings": list(score.warnings),
349
+ }
350
+ return CellResult(
351
+ **base,
352
+ fpr=score.fpr,
353
+ peeking_fpr=score.peeking_fpr,
354
+ power=score.power,
355
+ achieved_mde=score.achieved_mde,
356
+ coverage=score.coverage,
357
+ effect_exaggeration=score.effect_exaggeration,
358
+ verdict=_verdict(spec.method.name, spec.metric, score, budget, spec.alpha),
359
+ budget=budget,
360
+ recommended=False,
361
+ details=details,
362
+ status="success",
363
+ tau2=score.tau2,
364
+ fpr_sequential=score.fpr_sequential,
365
+ peeking_fpr_sequential=score.peeking_fpr_sequential,
366
+ power_sequential=score.power_sequential,
367
+ coverage_sequential=score.coverage_sequential,
368
+ effect_exaggeration_sequential=score.effect_exaggeration_sequential,
369
+ ci_width=score.ci_width,
370
+ ci_width_sequential=score.ci_width_sequential,
371
+ )
372
+
373
+
374
+ def _mark_recommended(cell: CellResult, rationale: str | None) -> CellResult:
375
+ """Flag the recommended cell, storing the ACTUAL ``_select_recommended`` rationale.
376
+
377
+ ``rationale`` is the real selection reason — the in-budget max-power line OR the
378
+ over-budget "highest-power fallback (use with caution)" warning — never a hardcode,
379
+ so the report's Recommended row can't claim an over-budget fallback was "in budget"
380
+ (WP5 review finding). ``None`` means this cell is not the recommendation.
381
+ """
382
+ from dataclasses import replace
383
+
384
+ if rationale is not None:
385
+ details = {**cell.details, "recommended_rationale": rationale}
386
+ return replace(cell, recommended=True, details=details)
387
+ if cell.recommended:
388
+ return replace(cell, recommended=False)
389
+ return cell