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,544 @@
1
+ """A/A scoring: FPR / cumulative-peeking FPR / power / achieved-MDE / coverage /
2
+ effect-exaggeration-at-stop from a placebo panel (docs/specs/m4-implementation-plan.md
3
+ D2, D3, D16).
4
+
5
+ The scorer runs ``iterations`` placebo splits through a method's ``from_suffstats``
6
+ path over the panel's cadence grid. The significance primitive is **CI-excludes-zero**
7
+ — the readout's own rule (``pipeline/readout.py`` ``_build_sig_map``), not the raw
8
+ ``reject`` flag — so z-test / bootstrap edge disagreements follow the readout.
9
+
10
+ Two passes per cell:
11
+
12
+ - **Null** (no injection) → single-look FPR (horizon cutoff only, the official
13
+ fixed-horizon rate) and the **cumulative-peeking FPR**: the naive optional-stopping
14
+ hazard — the share of placebos that cross significance at *any* look across the grid,
15
+ the analyst who stops the first time the chart's CI excludes zero (aa-fpr §3; D3).
16
+ Requiring the readout's full stabilization-persistence here would measure the tool's
17
+ *defense*, not the *hazard*, and empirically drops below the single-look rate — the
18
+ opposite of the column's purpose; the stabilized rule stays the official verdict
19
+ (with pre-horizon refusal), and the single-look FPR is reported beside the peeking
20
+ FPR so the jump is visible. Effect-exaggeration-at-stop is the |effect| at that first
21
+ crossing (the winner's curse against a true effect of zero).
22
+ - **Injected** (``inject_effect`` δ into the treatment arm) → power (horizon
23
+ CI-excludes-zero), CI coverage of the true effect, and the analytic achieved MDE at
24
+ ``target_power`` from the horizon control arm.
25
+
26
+ Degenerate cutoffs (an arm too small, or NaN CI bounds from zero variance) are gaps,
27
+ never zeros — tallied separately so they can never silently deflate the FPR.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ from dataclasses import dataclass, field
34
+
35
+ import numpy as np
36
+
37
+ from abkit.stats.base import BaseMethod
38
+ from abkit.stats.power import cuped_adjusted_std, get_fraction_mde, get_ttest_mde
39
+ from abkit.stats.rng import derive_seed
40
+ from abkit.stats.samples import Fraction, RatioSufficientStats, SufficientStats
41
+ from abkit.stats.sequential import mixture_tau2, se_from_ci_length, sequentialize
42
+ from abkit.validate._types import ValidateError
43
+ from abkit.validate.inject import inject_multiplicative, injection_clamped
44
+ from abkit.validate.panel import PlaceboPanel
45
+ from abkit.validate.resample import ArmStats, build_arm, placebo_mask, present_positions
46
+
47
+ #: Default target power for the achieved-MDE column.
48
+ DEFAULT_TARGET_POWER = 0.8
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class CellScore:
53
+ """One scored (metric × method × alpha) matrix cell (docs/specs/aa-false-positive-matrix.md §2)."""
54
+
55
+ iterations: int
56
+ #: Iterations with a usable (non-degenerate) horizon cutoff — the FPR/power denominator.
57
+ valid_iterations: int
58
+ #: Single-look FPR at the horizon cutoff (null pass), or None if never usable.
59
+ fpr: float | None
60
+ #: Cumulative-peeking FPR: share of null iterations whose CI excludes zero at ANY
61
+ #: look across the grid (optional stopping — the peeking hazard, aa-fpr §3 / D3).
62
+ peeking_fpr: float | None
63
+ #: The peeking curve — one ``(elapsed_days, cumulative_fpr)`` point per grid look,
64
+ #: cumulative_fpr = share of iterations that have first-crossed significance by that
65
+ #: look (monotone non-decreasing; the final look equals ``peeking_fpr``). Empty when
66
+ #: no iteration was scorable. THIS is the "nominal α vs real peeking FPR" story (R10).
67
+ peeking_curve: tuple[tuple[float, float], ...]
68
+ #: Power at the horizon under the injected effect, or None when no injection.
69
+ power: float | None
70
+ #: CI coverage of the injected truth at the horizon, or None when no injection.
71
+ coverage: float | None
72
+ #: Analytic achieved MDE at ``target_power`` from the horizon control arm, or None.
73
+ achieved_mde: float | None
74
+ #: Winner's curse: mean |effect| at the first false crossing (null pass), or None
75
+ #: when no null iteration ever crosses significance across the grid.
76
+ effect_exaggeration: float | None
77
+ #: Injected multiplicative δ (None on a pure FPR run).
78
+ injected_effect: float | None
79
+ #: Cutoffs where an arm was too small or the CI degenerate (a gap, not a zero).
80
+ degenerate_horizon: int
81
+ kept_grid_points: int
82
+ total_grid_points: int
83
+ # ── The M5 D8 always-valid sequential column (measured side-by-side, never
84
+ # asserted — cumulative-intervals §6.5). Same denominators as the fixed columns,
85
+ # computed off the always-valid CI (sequential.sequentialize over the SAME
86
+ # per-look (effect, SE)). None when the method is ineligible
87
+ # (supports_sequential=False) or τ² could not be anchored. ──
88
+ #: The frozen per-cell mixture variance τ² (provenance; anchored to the horizon).
89
+ tau2: float | None = None
90
+ #: Single-look FPR at the horizon under the always-valid CI (should sit near α).
91
+ fpr_sequential: float | None = None
92
+ #: Cumulative-peeking FPR under the always-valid CI — the honest completion of the
93
+ #: peeking story: this should return to ≈α where ``peeking_fpr`` broke budget.
94
+ peeking_fpr_sequential: float | None = None
95
+ #: The always-valid peeking curve (one point per look), for the side-by-side chart.
96
+ peeking_curve_sequential: tuple[tuple[float, float], ...] = ()
97
+ #: Power at the horizon under the always-valid CI (guards a τ² that "fixes" FPR by
98
+ #: never rejecting — must stay materially above α on the injected fixture).
99
+ power_sequential: float | None = None
100
+ #: Always-valid CI coverage of the injected truth at the horizon.
101
+ coverage_sequential: float | None = None
102
+ #: Winner's curse under the always-valid CI (mean |effect| at first crossing).
103
+ effect_exaggeration_sequential: float | None = None
104
+ #: Mean fixed-horizon CI width (the side-by-side baseline for the widening).
105
+ ci_width: float | None = None
106
+ #: Mean always-valid horizon CI width (the anytime price — always ≥ ``ci_width``).
107
+ ci_width_sequential: float | None = None
108
+ warnings: tuple[str, ...] = field(default_factory=tuple)
109
+
110
+
111
+ def _significance(left: float, right: float) -> tuple[bool, int] | None:
112
+ """CI-excludes-zero significance (readout ``_build_sig_map`` rule, readout.py:195–205).
113
+
114
+ Returns ``(significant, sign)`` — ``sign`` is +1 if the whole CI is above zero,
115
+ −1 if below, 0 if it straddles zero. ``None`` when either bound is non-finite
116
+ (a degenerate cutoff — a gap, never a clean non-rejection).
117
+ """
118
+ if not (math.isfinite(left) and math.isfinite(right)):
119
+ return None
120
+ if left > 0:
121
+ return (True, 1)
122
+ if right < 0:
123
+ return (True, -1)
124
+ return (False, 0)
125
+
126
+
127
+ def _cell_tau2(
128
+ panel: PlaceboPanel,
129
+ method: BaseMethod,
130
+ *,
131
+ share_a: float,
132
+ anchor_seed: int,
133
+ ) -> float | None:
134
+ """The frozen per-cell mixture variance τ², anchored to the first usable look.
135
+
136
+ τ² MUST be a single constant for the cell (Ville's inequality needs a prior fixed
137
+ in advance), so it is computed ONCE — never per iteration or per look. It is
138
+ anchored to the **first usable grid cutoff** (D-Seq-anchor): scan looks from the
139
+ earliest, build the arms under a canonical anchor split, and take the first one
140
+ with a finite positive ``SE`` (recovered by CI-inversion); pass ``SE²`` to the
141
+ shared :func:`abkit.stats.sequential.mixture_tau2` (the SAME helper the pipeline
142
+ uses — the parity requirement). ``None`` when the method is sequential-ineligible
143
+ (``supports_sequential=False``) or no look is usable → the cell has no sequential
144
+ column. Validity is robust to the anchor; τ² only sets where the sequence is
145
+ tightest (here: early, aligned with the impatient-experimenter use-case).
146
+ """
147
+ if not method.supports_sequential:
148
+ return None
149
+ mask = placebo_mask(panel.n_units, share_a, anchor_seed)
150
+ for cut in panel.cutoffs:
151
+ pos_a, pos_b = present_positions(mask, cut.unit_idx)
152
+ arm_a = build_arm(
153
+ panel.input_kind, cut.values, cut.secondary, panel.covariate, cut.unit_idx, pos_a
154
+ )
155
+ arm_b = build_arm(
156
+ panel.input_kind, cut.values, cut.secondary, panel.covariate, cut.unit_idx, pos_b
157
+ )
158
+ if arm_a is None or arm_b is None:
159
+ continue
160
+ se = se_from_ci_length(method.from_suffstats(arm_a, arm_b).ci_length, method.alpha)
161
+ if math.isfinite(se) and se > 0.0:
162
+ return mixture_tau2(se * se, method.alpha)
163
+ return None
164
+
165
+
166
+ def _always_valid_sig(
167
+ result: object, tau2: float, alpha: float
168
+ ) -> tuple[tuple[bool, int] | None, float]:
169
+ """Always-valid significance + CI width for a fixed ``TestResult`` at a look.
170
+
171
+ Recovers ``SE`` from the fixed CI (CI-inversion), widens it into the always-valid
172
+ interval (:func:`sequentialize`), and applies the same CI-excludes-zero primitive.
173
+ Returns ``(significance_or_None, ci_width)`` — width is NaN on a degenerate look.
174
+ """
175
+ se = se_from_ci_length(result.ci_length, alpha) # type: ignore[attr-defined]
176
+ lo, hi, _ = sequentialize(result.effect, se, tau2, alpha) # type: ignore[attr-defined]
177
+ return _significance(lo, hi), hi - lo
178
+
179
+
180
+ def _analytic_mde(
181
+ control: ArmStats,
182
+ method: BaseMethod,
183
+ *,
184
+ ratio: float,
185
+ target_power: float,
186
+ ) -> float | None:
187
+ """Achieved MDE at ``target_power`` from the horizon control arm (best-effort).
188
+
189
+ Closed-form t-test / z-test / CUPED families have an analytic MDE; ratio-delta
190
+ and the bootstrap family do not (no power capability) → ``None``. Reporting-only:
191
+ never feeds the FPR/power counts.
192
+ """
193
+ test_type = method.test_type if "test_type" in method.params else "relative"
194
+ if isinstance(control, Fraction):
195
+ mde = get_fraction_mde(
196
+ control.prop, control.sample_size, test_type, method.alpha, target_power, ratio
197
+ )
198
+ return None if not math.isfinite(mde) else float(mde)
199
+ if isinstance(control, SufficientStats):
200
+ std = control.std
201
+ if control.has_covariate:
202
+ corr = control.corr_coef
203
+ if math.isfinite(corr):
204
+ std = cuped_adjusted_std(std, corr)
205
+ mde = get_ttest_mde(
206
+ control.mean, std, control.sample_size, test_type, method.alpha, target_power, ratio
207
+ )
208
+ return None if not math.isfinite(mde) else float(mde)
209
+ return None # ratio-delta and other families: no analytic MDE
210
+
211
+
212
+ def score_cell(
213
+ panel: PlaceboPanel,
214
+ method: BaseMethod,
215
+ *,
216
+ iterations: int,
217
+ seed_parts: tuple[object, ...],
218
+ share_a: float = 0.5,
219
+ inject_effect: float | None = None,
220
+ target_power: float = DEFAULT_TARGET_POWER,
221
+ ) -> CellScore:
222
+ """Score one matrix cell over ``iterations`` deterministic placebo splits.
223
+
224
+ ``seed_parts`` are the identity parts hashed into each iteration's placebo seed
225
+ (``derive_seed(*seed_parts, i)``) — pass ``(experiment, metric, method_config_id)``
226
+ so re-runs are byte-reproducible (D13). ``share_a`` is arm A's split share.
227
+ """
228
+ if iterations <= 0:
229
+ raise ValidateError(f"iterations must be positive, got {iterations}")
230
+ if not panel.cutoffs:
231
+ raise ValidateError("panel has no cutoffs")
232
+
233
+ horizon_pos = _horizon_index(panel)
234
+ ratio = (1.0 - share_a) / share_a # n_treatment / n_control at the split
235
+ warnings: list[str] = []
236
+
237
+ # τ² is frozen once for the cell (D4) — the always-valid column is measured on the
238
+ # SAME per-look (effect, SE) the fixed column uses, only widened. None ⇒ no column.
239
+ tau2 = _cell_tau2(
240
+ panel,
241
+ method,
242
+ share_a=share_a,
243
+ anchor_seed=derive_seed(*seed_parts, "tau2-anchor"),
244
+ )
245
+
246
+ # Absolute-effect coverage anchors the injected truth (δ·μ̂) on a FIXED,
247
+ # split-invariant estimate of the shared population mean — the pooled point
248
+ # estimate over ALL present horizon units, computed once. Anchoring on the
249
+ # realized control mean (value_1) instead biases coverage low, because value_1
250
+ # co-varies with the effect estimate (m4 exit-gate review, F2). None only for a
251
+ # degenerate horizon or a non-finite pooled ratio (then the caller falls back).
252
+ horizon_pooled: float | None = None
253
+ if inject_effect is not None:
254
+ hc = panel.cutoffs[horizon_pos]
255
+ pooled_arm = build_arm(
256
+ panel.input_kind,
257
+ hc.values,
258
+ hc.secondary,
259
+ panel.covariate,
260
+ hc.unit_idx,
261
+ np.arange(hc.unit_idx.size),
262
+ )
263
+ if pooled_arm is not None:
264
+ horizon_pooled = _point_estimate(pooled_arm)
265
+
266
+ single_look_hits = 0
267
+ peek_hits = 0
268
+ valid_iterations = 0
269
+ degenerate_horizon = 0
270
+ power_hits = 0
271
+ coverage_hits = 0
272
+ coverage_n = 0
273
+ exagg_values: list[float] = []
274
+ mde_values: list[float] = []
275
+ clamp_warned = False
276
+ # per-grid-look tally of iterations whose FIRST significant crossing lands at that
277
+ # look — cumulative-summed into the peeking curve after the loop (D3).
278
+ first_cross_at_look = [0] * len(panel.cutoffs)
279
+
280
+ # ── Parallel always-valid (sequential) tallies — same denominators as the fixed
281
+ # columns, populated only when τ² anchored (D8/WP2). ──
282
+ single_look_hits_seq = 0
283
+ peek_hits_seq = 0
284
+ power_hits_seq = 0
285
+ coverage_hits_seq = 0
286
+ exagg_values_seq: list[float] = []
287
+ first_cross_at_look_seq = [0] * len(panel.cutoffs)
288
+ width_fixed_sum = 0.0 # mean horizon CI width (fixed) — the side-by-side baseline
289
+ width_seq_sum = 0.0 # mean horizon CI width (always-valid) — the anytime price
290
+ width_n = 0
291
+
292
+ for i in range(iterations):
293
+ seed = derive_seed(*seed_parts, i)
294
+ mask = placebo_mask(panel.n_units, share_a, seed)
295
+
296
+ # ── Null pass over the grid ──────────────────────────────────────────
297
+ sig_stream: list[tuple[int, tuple[bool, int], float]] = [] # (look_idx, sig, effect)
298
+ sig_stream_seq: list[tuple[int, tuple[bool, int], float]] = [] # always-valid twin
299
+ horizon_control: ArmStats | None = None
300
+ horizon_sig: tuple[bool, int] | None = None
301
+ horizon_sig_seq: tuple[bool, int] | None = None
302
+ horizon_width_fixed = float("nan")
303
+ horizon_width_seq = float("nan")
304
+
305
+ for k, cut in enumerate(panel.cutoffs):
306
+ pos_a, pos_b = present_positions(mask, cut.unit_idx)
307
+ arm_a = build_arm(
308
+ panel.input_kind, cut.values, cut.secondary, panel.covariate, cut.unit_idx, pos_a
309
+ )
310
+ arm_b = build_arm(
311
+ panel.input_kind, cut.values, cut.secondary, panel.covariate, cut.unit_idx, pos_b
312
+ )
313
+ if arm_a is None or arm_b is None:
314
+ if k == horizon_pos:
315
+ degenerate_horizon += 1
316
+ continue
317
+ result = method.from_suffstats(arm_a, arm_b)
318
+ sig = _significance(result.left_bound, result.right_bound)
319
+ if sig is None:
320
+ if k == horizon_pos:
321
+ degenerate_horizon += 1
322
+ continue
323
+ sig_stream.append((k, sig, result.effect))
324
+ if tau2 is not None:
325
+ sig_seq, width_seq = _always_valid_sig(result, tau2, method.alpha)
326
+ if sig_seq is not None:
327
+ sig_stream_seq.append((k, sig_seq, result.effect))
328
+ if k == horizon_pos:
329
+ horizon_sig_seq = sig_seq
330
+ horizon_width_fixed = result.ci_length
331
+ horizon_width_seq = width_seq
332
+ if k == horizon_pos:
333
+ horizon_control = arm_a
334
+ horizon_sig = sig
335
+
336
+ # Single-look FPR + achieved MDE need a usable horizon.
337
+ if horizon_sig is not None and horizon_control is not None:
338
+ valid_iterations += 1
339
+ if horizon_sig[0]:
340
+ single_look_hits += 1
341
+ mde = _analytic_mde(horizon_control, method, ratio=ratio, target_power=target_power)
342
+ if mde is not None:
343
+ mde_values.append(mde)
344
+ # Always-valid single-look FPR + the width side-by-side (same valid horizon).
345
+ # A None seq horizon is the measure-zero SE=0 edge → counted as non-significant.
346
+ if tau2 is not None:
347
+ if horizon_sig_seq is not None and horizon_sig_seq[0]:
348
+ single_look_hits_seq += 1
349
+ if math.isfinite(horizon_width_fixed) and math.isfinite(horizon_width_seq):
350
+ width_fixed_sum += horizon_width_fixed
351
+ width_seq_sum += horizon_width_seq
352
+ width_n += 1
353
+
354
+ # Cumulative-peeking FPR: optional stopping — the first look whose CI excludes
355
+ # zero (a false winner under the A/A null). The horizon look is included, so
356
+ # peeking is monotonically ≥ the single-look FPR.
357
+ first_call = _first_significant_look(sig_stream)
358
+ if first_call is not None:
359
+ first_idx, first_effect = first_call
360
+ peek_hits += 1
361
+ first_cross_at_look[first_idx] += 1
362
+ exagg_values.append(abs(first_effect))
363
+
364
+ # The always-valid peeking twin — the honest completion: this should return to
365
+ # ≈α where the fixed peeking FPR broke budget.
366
+ if tau2 is not None:
367
+ first_call_seq = _first_significant_look(sig_stream_seq)
368
+ if first_call_seq is not None:
369
+ first_idx_seq, first_effect_seq = first_call_seq
370
+ peek_hits_seq += 1
371
+ first_cross_at_look_seq[first_idx_seq] += 1
372
+ exagg_values_seq.append(abs(first_effect_seq))
373
+
374
+ # ── Injected pass (horizon only — fixed-horizon power/coverage) ──────
375
+ if inject_effect is not None and horizon_control is not None:
376
+ cut = panel.cutoffs[horizon_pos]
377
+ pos_a, pos_b = present_positions(mask, cut.unit_idx)
378
+ arm_a = build_arm(
379
+ panel.input_kind, cut.values, cut.secondary, panel.covariate, cut.unit_idx, pos_a
380
+ )
381
+ arm_b = build_arm(
382
+ panel.input_kind, cut.values, cut.secondary, panel.covariate, cut.unit_idx, pos_b
383
+ )
384
+ if arm_a is not None and arm_b is not None:
385
+ if injection_clamped(arm_b, inject_effect) and not clamp_warned:
386
+ warnings.append(
387
+ "injected effect saturated a proportion arm (count > nobs) — MDE unreachable"
388
+ )
389
+ clamp_warned = True
390
+ arm_b_inj = inject_multiplicative(arm_b, inject_effect)
391
+ result = method.from_suffstats(arm_a, arm_b_inj)
392
+ sig = _significance(result.left_bound, result.right_bound)
393
+ if sig is not None:
394
+ coverage_n += 1
395
+ if sig[0]:
396
+ power_hits += 1
397
+ # absolute-effect truth = δ·μ̂ on the FIXED pooled horizon estimate
398
+ # (split-invariant); relative truth ignores the anchor. Fall back to
399
+ # value_1 only on a degenerate horizon where no pooled arm was built.
400
+ anchor = horizon_pooled if horizon_pooled is not None else result.value_1
401
+ truth = _injected_truth(method, inject_effect, anchor)
402
+ if result.left_bound <= truth <= result.right_bound:
403
+ coverage_hits += 1
404
+ # Always-valid power + coverage on the SAME injected result (same
405
+ # coverage_n denominator; the always-valid CI must still detect a
406
+ # real effect — the guard against a τ² that never rejects).
407
+ if tau2 is not None:
408
+ se_inj = se_from_ci_length(result.ci_length, method.alpha)
409
+ lo_seq, hi_seq, _ = sequentialize(result.effect, se_inj, tau2, method.alpha)
410
+ sig_seq = _significance(lo_seq, hi_seq)
411
+ if sig_seq is not None and sig_seq[0]:
412
+ power_hits_seq += 1
413
+ if lo_seq <= truth <= hi_seq:
414
+ coverage_hits_seq += 1
415
+
416
+ fpr = single_look_hits / valid_iterations if valid_iterations else None
417
+ peeking_fpr = peek_hits / valid_iterations if valid_iterations else None
418
+ # cumulative first-crossings per look ÷ valid_iterations — monotone, ending at
419
+ # peeking_fpr (the horizon look). Empty when nothing was scorable.
420
+ peeking_curve: tuple[tuple[float, float], ...] = ()
421
+ if valid_iterations:
422
+ cumulative = 0
423
+ curve: list[tuple[float, float]] = []
424
+ for k, cut in enumerate(panel.cutoffs):
425
+ cumulative += first_cross_at_look[k]
426
+ curve.append((float(cut.elapsed_days), cumulative / valid_iterations))
427
+ peeking_curve = tuple(curve)
428
+ power = power_hits / coverage_n if coverage_n else None
429
+ coverage = coverage_hits / coverage_n if coverage_n else None
430
+ achieved_mde = float(np.mean(mde_values)) if mde_values else None
431
+ effect_exaggeration = float(np.mean(exagg_values)) if exagg_values else None
432
+
433
+ # ── Always-valid column (all None when τ² was not anchored) ──
434
+ has_seq = tau2 is not None
435
+ fpr_sequential = (
436
+ single_look_hits_seq / valid_iterations if (has_seq and valid_iterations) else None
437
+ )
438
+ peeking_fpr_sequential = (
439
+ peek_hits_seq / valid_iterations if (has_seq and valid_iterations) else None
440
+ )
441
+ power_sequential = power_hits_seq / coverage_n if (has_seq and coverage_n) else None
442
+ coverage_sequential = coverage_hits_seq / coverage_n if (has_seq and coverage_n) else None
443
+ effect_exaggeration_sequential = (
444
+ float(np.mean(exagg_values_seq)) if (has_seq and exagg_values_seq) else None
445
+ )
446
+ ci_width = width_fixed_sum / width_n if (has_seq and width_n) else None
447
+ ci_width_sequential = width_seq_sum / width_n if (has_seq and width_n) else None
448
+ peeking_curve_sequential: tuple[tuple[float, float], ...] = ()
449
+ if has_seq and valid_iterations:
450
+ cumulative_seq = 0
451
+ curve_seq: list[tuple[float, float]] = []
452
+ for k, cut in enumerate(panel.cutoffs):
453
+ cumulative_seq += first_cross_at_look_seq[k]
454
+ curve_seq.append((float(cut.elapsed_days), cumulative_seq / valid_iterations))
455
+ peeking_curve_sequential = tuple(curve_seq)
456
+
457
+ if valid_iterations == 0:
458
+ warnings.append(
459
+ "no iteration produced a usable horizon cutoff — the population is too small to score"
460
+ )
461
+ if method.supports_sequential and not has_seq and valid_iterations:
462
+ warnings.append(
463
+ "always-valid column skipped — τ² could not be anchored (degenerate horizon)"
464
+ )
465
+
466
+ return CellScore(
467
+ iterations=iterations,
468
+ valid_iterations=valid_iterations,
469
+ fpr=fpr,
470
+ peeking_fpr=peeking_fpr,
471
+ power=power,
472
+ coverage=coverage,
473
+ achieved_mde=achieved_mde,
474
+ effect_exaggeration=effect_exaggeration,
475
+ injected_effect=inject_effect,
476
+ degenerate_horizon=degenerate_horizon,
477
+ kept_grid_points=panel.kept_grid_points,
478
+ total_grid_points=panel.total_grid_points,
479
+ peeking_curve=peeking_curve,
480
+ tau2=tau2,
481
+ fpr_sequential=fpr_sequential,
482
+ peeking_fpr_sequential=peeking_fpr_sequential,
483
+ peeking_curve_sequential=peeking_curve_sequential,
484
+ power_sequential=power_sequential,
485
+ coverage_sequential=coverage_sequential,
486
+ effect_exaggeration_sequential=effect_exaggeration_sequential,
487
+ ci_width=ci_width,
488
+ ci_width_sequential=ci_width_sequential,
489
+ warnings=tuple(warnings),
490
+ )
491
+
492
+
493
+ def _horizon_index(panel: PlaceboPanel) -> int:
494
+ """The horizon cutoff's index (the flagged one, else the last)."""
495
+ for k, cut in enumerate(panel.cutoffs):
496
+ if cut.is_horizon:
497
+ return k
498
+ return len(panel.cutoffs) - 1
499
+
500
+
501
+ def _first_significant_look(
502
+ sig_stream: list[tuple[int, tuple[bool, int], float]],
503
+ ) -> tuple[int, float] | None:
504
+ """The first informative cutoff whose CI excludes zero (D3).
505
+
506
+ Optional stopping: the naive peeker stops the first time the chart's CI clears
507
+ zero, in whichever direction. Returns ``(grid_look_index, effect)`` at that
508
+ crossing (the index feeds the cumulative peeking curve; the effect the winner's
509
+ curse), or ``None`` if the placebo never crosses significance across the grid.
510
+ """
511
+ for look_idx, sig, effect in sig_stream:
512
+ if sig[0]:
513
+ return (look_idx, effect)
514
+ return None
515
+
516
+
517
+ def _point_estimate(arm: object) -> float | None:
518
+ """The arm's scalar point estimate: mean (sample), proportion (fraction), ratio.
519
+
520
+ ``ratio-delta`` DOES expose ``test_type`` and a live ``absolute`` branch, so the
521
+ ratio kind is anchored too (the pooled ``mean_num/mean_den``). Returns ``None`` on a
522
+ non-finite pooled ratio (zero denominator) so the caller falls back safely.
523
+ """
524
+ if isinstance(arm, Fraction):
525
+ return float(arm.prop)
526
+ if isinstance(arm, SufficientStats):
527
+ return float(arm.mean)
528
+ if isinstance(arm, RatioSufficientStats):
529
+ return float(arm.ratio) if math.isfinite(arm.ratio) else None
530
+ return None
531
+
532
+
533
+ def _injected_truth(method: BaseMethod, delta: float, pooled_estimate: float) -> float:
534
+ """The true effect a multiplicative δ induces, in the method's estimand units (D2).
535
+
536
+ Relative test_type → δ exactly (δ *is* the estimand). Absolute → δ·μ̂ where μ̂ is
537
+ a FIXED, split-invariant estimate of the shared population mean (the pooled point
538
+ estimate over all present horizon units) — NOT the realized control mean, which
539
+ co-varies with the effect estimate and biases coverage low (m4 exit-gate review).
540
+ """
541
+ test_type = method.test_type if "test_type" in method.params else "relative"
542
+ if test_type == "relative":
543
+ return float(delta)
544
+ return float(delta) * pooled_estimate