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,223 @@
1
+ """The analyze stage: loaded role arrays → stats-core containers → TestResults.
2
+
3
+ Pure orchestration over ``abkit.stats`` — no DB, no SQL. Dispatch is
4
+ declarative (plan R8): ``method.input_kind`` selects the container family,
5
+ ``is_paired`` gates unsupported designs, and the presence of a ``seed`` param
6
+ spec marks resampling methods that need the deterministic per-row seed
7
+ (``seed`` is identity-excluded, so injecting it never changes
8
+ ``method_config_id``; re-runs are byte-stable).
9
+
10
+ Small-sample demotion (cumulative-intervals §6.1.4): below
11
+ ``min_units_per_arm`` the pair is still recorded — counts and SRM stay
12
+ visible — but inference is withheld (``result=None`` → the enrich stage
13
+ writes NULLed test columns with ``insufficient_data=1``).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import warnings as _warnings
19
+ from dataclasses import dataclass
20
+ from datetime import datetime
21
+ from itertools import combinations
22
+ from typing import Any
23
+
24
+ from abkit.config.experiment_config import ComparisonConfig, ExperimentConfig
25
+ from abkit.config.metric_config import MetricConfig
26
+ from abkit.config.project_config import ProjectConfig
27
+ from abkit.loaders.metric_loader import MetricLoadResult
28
+ from abkit.stats import (
29
+ AbkitStatsWarning,
30
+ Fraction,
31
+ RatioSample,
32
+ Sample,
33
+ TestResult,
34
+ TwoTierAlphas,
35
+ create_method,
36
+ derive_seed,
37
+ get_method_class,
38
+ two_tier_alphas,
39
+ )
40
+ from abkit.stats.sequential import to_always_valid
41
+
42
+
43
+ class AnalyzeError(Exception):
44
+ """Raised when a comparison cannot be computed from the loaded data."""
45
+
46
+
47
+ @dataclass
48
+ class PairOutcome:
49
+ """One variant pair at one cutoff: a TestResult or a demoted placeholder."""
50
+
51
+ name_1: str
52
+ name_2: str
53
+ size_1: int
54
+ size_2: int
55
+ result: TestResult | None # None => insufficient_data demotion
56
+ warnings: list[str]
57
+
58
+
59
+ def effective_alphas(experiment: ExperimentConfig, project: ProjectConfig) -> TwoTierAlphas:
60
+ """The inspectable two-tier scheme (declarative-config §6).
61
+
62
+ Guardrails count as tests: every non-main comparison shares the secondary
63
+ budget. ``correction: none`` collapses both tiers to the raw alpha.
64
+ """
65
+ alpha = experiment.alpha if experiment.alpha is not None else project.statistics.alpha
66
+ correction = (
67
+ experiment.correction
68
+ if experiment.correction is not None
69
+ else project.statistics.correction
70
+ )
71
+ groups = len(experiment.assignment.variants)
72
+ non_main = sum(1 for c in experiment.comparisons if not c.is_main_metric)
73
+ if correction == "bonferroni":
74
+ return two_tier_alphas(alpha, groups_count=groups, metrics_count=non_main)
75
+ # none / benjamini_hochberg (BH is read-time): raw alpha at compute time
76
+ return TwoTierAlphas(
77
+ alpha=alpha, groups_count=groups, metrics_count=non_main, main=alpha, secondary=alpha
78
+ )
79
+
80
+
81
+ def comparison_alpha(comparison: ComparisonConfig, alphas: TwoTierAlphas) -> float:
82
+ if comparison.is_main_metric or alphas.secondary is None:
83
+ return alphas.main
84
+ return alphas.secondary
85
+
86
+
87
+ def build_container(
88
+ kind: str,
89
+ variant: str,
90
+ loaded: MetricLoadResult,
91
+ ) -> Any:
92
+ """One variant's loaded role arrays → the stats-core container for ``kind``.
93
+
94
+ Shared with the explore recompute engine (m3-implementation-plan.md WP4) —
95
+ the Tier-S cache path must build byte-identical containers to the pipeline.
96
+ """
97
+ roles = loaded.roles_by_variant.get(variant, {})
98
+ if kind == "sample":
99
+ return Sample(
100
+ roles["value"],
101
+ cov_array=roles.get("covariate"),
102
+ categories_array=loaded.strata_by_variant.get(variant),
103
+ name=variant,
104
+ )
105
+ if kind == "fraction":
106
+ return Fraction(
107
+ count=float(roles["count"].sum()),
108
+ nobs=float(roles["nobs"].sum()),
109
+ name=variant,
110
+ )
111
+ if kind == "ratio":
112
+ return RatioSample(roles["numerator"], roles["denominator"], name=variant)
113
+ raise AnalyzeError(f"unknown method input_kind: {kind!r}")
114
+
115
+
116
+ def analyze_cutoff(
117
+ experiment: ExperimentConfig,
118
+ comparison: ComparisonConfig,
119
+ metric: MetricConfig,
120
+ loaded: MetricLoadResult,
121
+ end_ts: datetime,
122
+ alphas: TwoTierAlphas,
123
+ project: ProjectConfig,
124
+ sequential_tau2: dict[tuple[str, str], float] | None = None,
125
+ ) -> list[PairOutcome]:
126
+ """All pairwise variant outcomes for one (comparison, cutoff).
127
+
128
+ Pairs follow the declared variant order (first = control = ``name_1``,
129
+ baseline §5 ``combinations`` semantics). Stats-core warnings are captured
130
+ per pair and routed into the row (plan R7), never to stderr.
131
+
132
+ ``sequential_tau2`` (M5 WP3): when the experiment's sequential mode is on,
133
+ ``{(name_1, name_2): tau2}`` (the frozen per-pair mixture variance, anchored to the
134
+ first usable look) widens each supported pair's fixed CI into the always-valid one
135
+ (``ci_kind='always_valid'``). ``None`` / a missing pair / a sequential-ineligible
136
+ method ⇒ the fixed CI is kept unchanged.
137
+ """
138
+ method_cls = get_method_class(comparison.method.name)
139
+ if method_cls.is_paired:
140
+ raise AnalyzeError(
141
+ f"method '{comparison.method.name}' is a paired design — the v1 "
142
+ "pipeline serves independent-arm experiments (use the notebook API "
143
+ "for paired data)"
144
+ )
145
+ if method_cls.input_kind != metric.type:
146
+ raise AnalyzeError(
147
+ f"method '{comparison.method.name}' expects a '{method_cls.input_kind}' "
148
+ f"metric, got '{metric.type}' — declared in metrics/{metric.name}.yml"
149
+ )
150
+ needs_seed = any(spec.name == "seed" for spec in method_cls.param_specs)
151
+ alpha = comparison_alpha(comparison, alphas)
152
+ min_units = project.limits.min_units_per_arm
153
+
154
+ reusable = None
155
+ if not needs_seed:
156
+ reusable = create_method(
157
+ comparison.method.name, alpha=alpha, params=dict(comparison.method.params)
158
+ )
159
+
160
+ outcomes: list[PairOutcome] = []
161
+ variant_order = experiment.assignment.variants
162
+ for name_1, name_2 in combinations(variant_order, 2):
163
+ size_1 = loaded.size(name_1)
164
+ size_2 = loaded.size(name_2)
165
+ if size_1 < min_units or size_2 < min_units:
166
+ outcomes.append(
167
+ PairOutcome(
168
+ name_1=name_1,
169
+ name_2=name_2,
170
+ size_1=size_1,
171
+ size_2=size_2,
172
+ result=None,
173
+ warnings=[
174
+ f"insufficient data: {size_1}/{size_2} units vs "
175
+ f"min_units_per_arm={min_units} — inference withheld"
176
+ ],
177
+ )
178
+ )
179
+ continue
180
+
181
+ group_1 = build_container(method_cls.input_kind, name_1, loaded)
182
+ group_2 = build_container(method_cls.input_kind, name_2, loaded)
183
+
184
+ if needs_seed:
185
+ # Deterministic per-row seed: byte-stable re-runs; identity-excluded.
186
+ params = dict(comparison.method.params)
187
+ params["seed"] = derive_seed(
188
+ experiment.name,
189
+ metric.name,
190
+ name_1,
191
+ name_2,
192
+ end_ts,
193
+ params.get("n_samples", 1000),
194
+ )
195
+ method = create_method(comparison.method.name, alpha=alpha, params=params)
196
+ else:
197
+ method = reusable
198
+
199
+ with _warnings.catch_warnings(record=True) as caught:
200
+ _warnings.simplefilter("always", AbkitStatsWarning)
201
+ result = method.compare_pair(group_1, group_2)
202
+ pair_warnings = [
203
+ str(w.message) for w in caught if issubclass(w.category, AbkitStatsWarning)
204
+ ]
205
+
206
+ # M5 WP3: widen into the always-valid CI when the sequential mode is on and the
207
+ # method is eligible (a symmetric-normal fixed CI). Never re-derives a variance.
208
+ if sequential_tau2 is not None and method_cls.supports_sequential:
209
+ tau2 = sequential_tau2.get((name_1, name_2))
210
+ if tau2 is not None:
211
+ result = to_always_valid(result, tau2, alpha)
212
+
213
+ outcomes.append(
214
+ PairOutcome(
215
+ name_1=name_1,
216
+ name_2=name_2,
217
+ size_1=size_1,
218
+ size_2=size_2,
219
+ result=result,
220
+ warnings=pair_warnings,
221
+ )
222
+ )
223
+ return outcomes