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,69 @@
1
+ """Bootstrap (resampling) statistical methods and the vectorised engine."""
2
+
3
+ from abkit.stats.bootstrap.applier import STAT_FUNCS, apply_stat, stat_point
4
+ from abkit.stats.bootstrap.bootstrap import (
5
+ BOOTSTRAP_PARAM_SPECS,
6
+ BaseBootstrapMethod,
7
+ BootstrapTest,
8
+ )
9
+ from abkit.stats.bootstrap.ci import (
10
+ PVALUE_KIND_PARAM,
11
+ bootstrap_pvalue,
12
+ percentile_ci,
13
+ pvalue_plugin,
14
+ pvalue_sign,
15
+ )
16
+ from abkit.stats.bootstrap.engine import (
17
+ BLOCK_QUANTUM,
18
+ DEFAULT_MAX_BLOCK_BYTES,
19
+ ResamplePlan,
20
+ bootstrap_statistics,
21
+ draw_stratum_indices,
22
+ hamilton_apportion,
23
+ iter_resample_blocks,
24
+ poisson_bootstrap_means,
25
+ poisson_unit_scale,
26
+ pooled_stratum_shares,
27
+ require_common_categories,
28
+ stratified_plan,
29
+ unstratified_plan,
30
+ )
31
+ from abkit.stats.bootstrap.paired_bootstrap import PairedBootstrapTest
32
+ from abkit.stats.bootstrap.paired_post_normed_bootstrap import PairedPostNormedBootstrapTest
33
+ from abkit.stats.bootstrap.poisson_bootstrap import (
34
+ PairedPoissonBootstrapTest,
35
+ PoissonBootstrapTest,
36
+ )
37
+ from abkit.stats.bootstrap.post_normed_bootstrap import PostNormedBootstrapTest
38
+
39
+ __all__ = [
40
+ "BLOCK_QUANTUM",
41
+ "BOOTSTRAP_PARAM_SPECS",
42
+ "BaseBootstrapMethod",
43
+ "BootstrapTest",
44
+ "DEFAULT_MAX_BLOCK_BYTES",
45
+ "PVALUE_KIND_PARAM",
46
+ "PairedBootstrapTest",
47
+ "PairedPoissonBootstrapTest",
48
+ "PairedPostNormedBootstrapTest",
49
+ "PoissonBootstrapTest",
50
+ "PostNormedBootstrapTest",
51
+ "ResamplePlan",
52
+ "STAT_FUNCS",
53
+ "apply_stat",
54
+ "bootstrap_pvalue",
55
+ "bootstrap_statistics",
56
+ "draw_stratum_indices",
57
+ "hamilton_apportion",
58
+ "iter_resample_blocks",
59
+ "percentile_ci",
60
+ "poisson_bootstrap_means",
61
+ "poisson_unit_scale",
62
+ "pooled_stratum_shares",
63
+ "pvalue_plugin",
64
+ "pvalue_sign",
65
+ "require_common_categories",
66
+ "stat_point",
67
+ "stratified_plan",
68
+ "unstratified_plan",
69
+ ]
@@ -0,0 +1,81 @@
1
+ """Statistic application over resample matrices (hygiene H3).
2
+
3
+ The legacy ``StatFuncApplier`` ran ``np.apply_along_axis(stat_func, 1, matrix)``
4
+ — a Python-level row loop that dominated bootstrap cost. H3
5
+ (docs/specs/statistics-changes.md §2): the named statistics take a vectorised
6
+ fast path (``matrix.mean(axis=1)`` / ``np.median(matrix, axis=1)``);
7
+ ``np.apply_along_axis`` remains only as the fallback for arbitrary callables
8
+ (future stats). Both are row-independent reductions, so results never depend on
9
+ how replicate rows are grouped into blocks (the H10 streaming invariant).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+
16
+ import numpy as np
17
+
18
+ from abkit.stats.exceptions import MethodParamError
19
+ from abkit.stats.samples import FloatArray
20
+
21
+ StatFunc = Callable[[FloatArray], float]
22
+
23
+ #: Named statistics available to the bootstrap methods (``STAT_PARAM`` values).
24
+ #: The legacy engine accepted arbitrary ``stat_func`` callables; abkit accepts
25
+ #: NAMES registered here instead (statistics-changes.md §7) so the statistic
26
+ #: stays part of the hashable, BI-stable method identity. Extend via
27
+ #: :func:`register_stat`.
28
+ STAT_FUNCS: dict[str, StatFunc] = {"mean": np.mean, "median": np.median}
29
+
30
+
31
+ def register_stat(name: str, func: StatFunc) -> None:
32
+ """Register a custom named statistic usable as ``stat=<name>`` in bootstrap params.
33
+
34
+ E.g. ``register_stat("p90", lambda a: float(np.quantile(a, 0.9)))``. The name
35
+ (not the callable) enters ``method_config_id``, so re-registering a DIFFERENT
36
+ function under an existing name is refused — it would silently change the
37
+ numbers behind a published series identity.
38
+ """
39
+ if not name or not isinstance(name, str):
40
+ raise MethodParamError("stat name must be a non-empty string")
41
+ existing = STAT_FUNCS.get(name)
42
+ if existing is not None and existing is not func:
43
+ raise MethodParamError(
44
+ f"stat {name!r} is already registered; pick a new name (the name is part of "
45
+ "the method identity — rebinding it would silently change published numbers)"
46
+ )
47
+ STAT_FUNCS[name] = func
48
+
49
+
50
+ def stat_point(array: FloatArray, stat: str | StatFunc) -> float:
51
+ """Apply ``stat`` to one 1-D array — the real-data point estimate (H9)."""
52
+ if isinstance(stat, str):
53
+ try:
54
+ func = STAT_FUNCS[stat]
55
+ except KeyError:
56
+ raise MethodParamError(
57
+ f"unknown stat {stat!r}; known stats: {sorted(STAT_FUNCS)}"
58
+ ) from None
59
+ return float(func(array))
60
+ return float(stat(array))
61
+
62
+
63
+ def apply_stat(matrix: FloatArray, stat: str | StatFunc) -> FloatArray:
64
+ """One statistic per resample row (baseline §4.1; vectorised fast path, H3).
65
+
66
+ The built-in names take the vectorised fast path; registered custom stats
67
+ fall back to the row-wise ``np.apply_along_axis`` (the legacy cost model —
68
+ acceptable for opt-in custom statistics).
69
+ """
70
+ if isinstance(stat, str):
71
+ if stat == "mean":
72
+ return np.asarray(matrix.mean(axis=1), dtype=np.float64)
73
+ if stat == "median":
74
+ return np.asarray(np.median(matrix, axis=1), dtype=np.float64)
75
+ try:
76
+ stat = STAT_FUNCS[stat]
77
+ except KeyError:
78
+ raise MethodParamError(
79
+ f"unknown stat {stat!r}; known stats: {sorted(STAT_FUNCS)}"
80
+ ) from None
81
+ return np.asarray(np.apply_along_axis(stat, 1, matrix), dtype=np.float64)
@@ -0,0 +1,311 @@
1
+ """``bootstrap`` — plain IID / stratified index-resampling bootstrap (baseline §4.2).
2
+
3
+ This module also hosts :class:`BaseBootstrapMethod`, the shared machinery of the
4
+ whole bootstrap family: the common parameter schema, the per-call RNG (H1/H2),
5
+ stratified resample plans (H6), boot/point effect computation (H5/H9) and the
6
+ common result assembly (percentile CI, H4 p-value, ``boot_mean`` diagnostic).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+
13
+ import numpy as np
14
+ import scipy.stats as sps
15
+
16
+ from abkit.stats.base import (
17
+ MAX_BLOCK_BYTES_PARAM,
18
+ N_SAMPLES_PARAM,
19
+ SEED_PARAM,
20
+ STAT_PARAM,
21
+ STRATIFY_PARAM,
22
+ TEST_TYPE_PARAM,
23
+ WEIGHT_METHOD_PARAM,
24
+ BaseMethod,
25
+ ParamSpec,
26
+ require_pair_type,
27
+ )
28
+ from abkit.stats.bootstrap.applier import STAT_FUNCS, stat_point
29
+ from abkit.stats.bootstrap.ci import PVALUE_KIND_PARAM, bootstrap_pvalue, percentile_ci
30
+ from abkit.stats.bootstrap.engine import (
31
+ ResamplePlan,
32
+ bootstrap_statistics,
33
+ pooled_stratum_shares,
34
+ stratified_plan,
35
+ unstratified_plan,
36
+ )
37
+ from abkit.stats.exceptions import MethodParamError, SampleValidationError
38
+ from abkit.stats.registry import register
39
+ from abkit.stats.result import TestResult
40
+ from abkit.stats.rng import make_rng
41
+ from abkit.stats.samples import FloatArray, Sample
42
+
43
+ #: The shared bootstrap-family schema (Poisson methods narrow it — no weight_method).
44
+ BOOTSTRAP_PARAM_SPECS: tuple[ParamSpec, ...] = (
45
+ TEST_TYPE_PARAM,
46
+ N_SAMPLES_PARAM,
47
+ STRATIFY_PARAM,
48
+ WEIGHT_METHOD_PARAM,
49
+ STAT_PARAM,
50
+ SEED_PARAM,
51
+ MAX_BLOCK_BYTES_PARAM,
52
+ PVALUE_KIND_PARAM,
53
+ )
54
+
55
+
56
+ class BaseBootstrapMethod(BaseMethod):
57
+ """Shared bootstrap machinery — abstract, never registered directly.
58
+
59
+ Randomness policy (H1/H2): all randomness flows from ONE
60
+ ``np.random.Generator`` built via :func:`abkit.stats.rng.make_rng` from
61
+ ``params["seed"]`` per compare call. Same seed ⇒ byte-identical
62
+ :class:`TestResult`; ``seed=None`` ⇒ nondeterministic. ``seed`` and
63
+ ``max_block_bytes`` are identity-EXCLUDED (docs/specs/declarative-config.md
64
+ §7; baseline fact #3 generalised to all bootstrap methods).
65
+
66
+ Result conventions (docs/specs/statistics-changes.md): ``effect`` is the
67
+ point estimate on the REAL data (H9); the bootstrap distribution only sets
68
+ the CI and p-value; ``diagnostics["boot_mean"]`` carries the bootstrap mean
69
+ as a bias diagnostic; non-finite replicates are kept but void the p-value
70
+ and CI (H5). No MDE in M1 (``mde_i=None``).
71
+ """
72
+
73
+ param_specs = BOOTSTRAP_PARAM_SPECS
74
+ # Percentile bootstrap CIs are asymmetric → SE is not recoverable by
75
+ # CI-inversion, so bootstrap methods are ineligible for the sequential
76
+ # transform (docs/specs/m5-implementation-plan.md D1/WP1).
77
+ supports_sequential = False
78
+
79
+ def _validate_params(self) -> None:
80
+ # n_samples/max_block_bytes ranges are enforced by their ParamSpec bounds.
81
+ if self._stat not in STAT_FUNCS:
82
+ raise MethodParamError(
83
+ f"{self.name}: unknown stat {self.params['stat']!r}; known stats: "
84
+ f"{sorted(STAT_FUNCS)} (extend via abkit.stats.bootstrap.register_stat)"
85
+ )
86
+ spec_names = {spec.name for spec in self.param_specs}
87
+ if (
88
+ "weight_method" in spec_names
89
+ and self.params["weight_method"] != WEIGHT_METHOD_PARAM.default
90
+ and not bool(self.params["stratify"])
91
+ ):
92
+ raise MethodParamError(
93
+ f"{self.name}: weight_method has no effect without stratify=true — a "
94
+ "non-default value would fork method_config_id while changing no number"
95
+ )
96
+
97
+ def from_suffstats(self, stats_1: object, stats_2: object) -> TestResult:
98
+ raise SampleValidationError(
99
+ f"{self.name}: bootstrap methods require per-unit samples; "
100
+ "use the closed-form methods for the suffstats path"
101
+ )
102
+
103
+ # --- shared accessors -----------------------------------------------------
104
+ @property
105
+ def _stat(self) -> str:
106
+ return str(self.params["stat"])
107
+
108
+ @property
109
+ def _n_samples(self) -> int:
110
+ return int(self.params["n_samples"])
111
+
112
+ @property
113
+ def _max_block_bytes(self) -> int | None:
114
+ value = self.params["max_block_bytes"]
115
+ return None if value is None else int(value)
116
+
117
+ def _make_rng(self) -> np.random.Generator:
118
+ """The ONE Generator per compare call (H1) — no global numpy state."""
119
+ return make_rng(self.params["seed"])
120
+
121
+ # --- shared validation & planning ----------------------------------------
122
+ def _validate_paired(self, sample_1: Sample, sample_2: Sample) -> None:
123
+ """Paired-design input contract: equal sizes; strata travel with the pair."""
124
+ if sample_1.sample_size != sample_2.sample_size:
125
+ raise SampleValidationError(
126
+ f"{self.name}: paired samples must be equal-size and aligned by pair: "
127
+ f"{sample_1.sample_size} != {sample_2.sample_size}"
128
+ )
129
+ if sample_1.categories_array is not None and sample_2.categories_array is not None:
130
+ if not np.array_equal(sample_1.categories_array, sample_2.categories_array):
131
+ raise SampleValidationError(
132
+ f"{self.name}: paired samples must carry elementwise-identical "
133
+ "categories_array (paired strata travel with the pair)"
134
+ )
135
+ if bool(self.params["stratify"]) and (
136
+ sample_1.categories_array is None or sample_2.categories_array is None
137
+ ):
138
+ raise SampleValidationError(
139
+ f"{self.name}: stratify=True requires categories_array on both samples"
140
+ )
141
+
142
+ def _require_covariates(self, sample_1: Sample, sample_2: Sample) -> None:
143
+ for label, sample in (("first", sample_1), ("second", sample_2)):
144
+ if sample.cov_array is None:
145
+ raise SampleValidationError(
146
+ f"{self.name}: requires cov_array on the {label} sample "
147
+ "(post-normalisation covariate)"
148
+ )
149
+
150
+ def _independent_plans(
151
+ self, sample_1: Sample, sample_2: Sample
152
+ ) -> tuple[ResamplePlan, ResamplePlan]:
153
+ """Per-variant plans; stratified plans share pooled category shares (H6)."""
154
+ if not bool(self.params["stratify"]):
155
+ return (
156
+ unstratified_plan(sample_1.sample_size),
157
+ unstratified_plan(sample_2.sample_size),
158
+ )
159
+ categories, shares = pooled_stratum_shares(
160
+ sample_1, sample_2, str(self.params["weight_method"]), self.name
161
+ )
162
+ assert sample_1.categories_array is not None and sample_2.categories_array is not None
163
+ return (
164
+ stratified_plan(sample_1.categories_array, categories, shares),
165
+ stratified_plan(sample_2.categories_array, categories, shares),
166
+ )
167
+
168
+ def _paired_plan(self, sample_1: Sample, sample_2: Sample) -> ResamplePlan:
169
+ """ONE plan for both arms (paired draws; categories elementwise-identical)."""
170
+ if not bool(self.params["stratify"]):
171
+ return unstratified_plan(sample_1.sample_size)
172
+ categories, shares = pooled_stratum_shares(
173
+ sample_1, sample_2, str(self.params["weight_method"]), self.name
174
+ )
175
+ assert sample_1.categories_array is not None
176
+ return stratified_plan(sample_1.categories_array, categories, shares)
177
+
178
+ # --- shared effect computation ---------------------------------------------
179
+ def _boot_effect(self, boot_1: FloatArray, boot_2: FloatArray) -> FloatArray:
180
+ """``boot_2 − boot_1`` (absolute) or ``boot_2/boot_1 − 1`` (relative), §4.2.
181
+
182
+ The relative division is evaluated under ``np.errstate`` suppression;
183
+ non-finite replicates are KEPT (baseline numbers preserved) and voided
184
+ in :meth:`_finalize` (H5).
185
+ """
186
+ if self.test_type == "absolute":
187
+ return boot_2 - boot_1
188
+ with np.errstate(divide="ignore", invalid="ignore"):
189
+ return boot_2 / boot_1 - 1.0
190
+
191
+ def _point_effect(self, value_1: float, value_2: float, result_warnings: list[str]) -> float:
192
+ """Real-data point effect (H9): ``v2 − v1`` or ``v2/v1 − 1`` with an H5 guard."""
193
+ if self.test_type == "absolute":
194
+ return value_2 - value_1
195
+ with np.errstate(divide="ignore", invalid="ignore"):
196
+ effect = float(np.float64(value_2) / np.float64(value_1) - 1.0)
197
+ if not math.isfinite(effect):
198
+ result_warnings.append(
199
+ "relative effect undefined: control (denominator) statistic is zero or "
200
+ "non-finite; returning NaN (see statistics-changes.md H5)"
201
+ )
202
+ return float("nan")
203
+ return effect
204
+
205
+ # --- shared result assembly -------------------------------------------------
206
+ def _finalize(
207
+ self,
208
+ sample_1: Sample,
209
+ sample_2: Sample,
210
+ boot_data: FloatArray,
211
+ effect: float,
212
+ result_warnings: list[str],
213
+ ) -> TestResult:
214
+ """Common bootstrap result computation (baseline §4; H4/H5/H9).
215
+
216
+ Percentile CI and the configured p-value from ``boot_data``; if it
217
+ contains non-finite replicates they are kept but p-value/CI become NaN,
218
+ ``reject`` False, with an explanatory warning and an ``n_non_finite``
219
+ diagnostic (H5). ``effect_distribution = norm(mean(boot), std(boot))``
220
+ (catalogue parity; omitted when degenerate/non-finite).
221
+ """
222
+ stat = self._stat
223
+ diagnostics: dict[str, float] = {}
224
+ with np.errstate(invalid="ignore"): # boot_data may carry kept non-finite entries (H5)
225
+ boot_mean = float(np.mean(boot_data))
226
+ boot_std = float(np.std(boot_data)) # ddof=0 (mixed-ddof law: np.std terms)
227
+ diagnostics["boot_mean"] = boot_mean
228
+
229
+ nan = float("nan")
230
+ n_non_finite = int(np.count_nonzero(~np.isfinite(boot_data)))
231
+ if n_non_finite:
232
+ diagnostics["n_non_finite"] = float(n_non_finite)
233
+ result_warnings.append(
234
+ f"bootstrap effect distribution contains {n_non_finite} non-finite "
235
+ "replicate(s) (division by a ~zero control statistic); p-value and CI "
236
+ "are undefined (NaN) — see statistics-changes.md H5"
237
+ )
238
+ pvalue = left_bound = right_bound = ci_length = nan
239
+ reject = False
240
+ else:
241
+ left_bound, right_bound = percentile_ci(boot_data, self.alpha)
242
+ ci_length = right_bound - left_bound
243
+ pvalue = bootstrap_pvalue(boot_data, str(self.params["pvalue_kind"]))
244
+ reject = bool(pvalue < self.alpha)
245
+
246
+ distribution = None
247
+ if math.isfinite(boot_mean) and math.isfinite(boot_std) and boot_std > 0.0:
248
+ distribution = sps.norm(boot_mean, boot_std)
249
+
250
+ return TestResult(
251
+ name_1=sample_1.name,
252
+ name_2=sample_2.name,
253
+ value_1=stat_point(sample_1.array, stat),
254
+ value_2=stat_point(sample_2.array, stat),
255
+ std_1=sample_1.std,
256
+ std_2=sample_2.std,
257
+ size_1=sample_1.sample_size,
258
+ size_2=sample_2.sample_size,
259
+ cov_value_1=(
260
+ None if sample_1.cov_array is None else stat_point(sample_1.cov_array, stat)
261
+ ),
262
+ cov_value_2=(
263
+ None if sample_2.cov_array is None else stat_point(sample_2.cov_array, stat)
264
+ ),
265
+ mde_1=None,
266
+ mde_2=None,
267
+ method_name=self.name,
268
+ method_params=self.identity_params,
269
+ alpha=self.alpha,
270
+ pvalue=pvalue,
271
+ effect=effect,
272
+ ci_length=ci_length,
273
+ left_bound=left_bound,
274
+ right_bound=right_bound,
275
+ reject=reject,
276
+ effect_distribution=distribution,
277
+ warnings=result_warnings,
278
+ diagnostics=diagnostics,
279
+ )
280
+
281
+
282
+ @register(aliases=("bootstrap-test",))
283
+ class BootstrapTest(BaseBootstrapMethod):
284
+ """Plain IID (or stratified) bootstrap of ``stat`` (baseline §4.2).
285
+
286
+ Independent index resampling per variant; variant 1 is drawn fully (all
287
+ quanta) before variant 2 (draw-order contract in ``engine.py``). Stratified
288
+ mode aligns stratum weights across variants via ``weight_method`` so both
289
+ variants resample to a common stratum mix (poststratification by design).
290
+ """
291
+
292
+ name = "bootstrap"
293
+
294
+ def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
295
+ require_pair_type(self.name, sample_1, sample_2, Sample)
296
+ plan_1, plan_2 = self._independent_plans(sample_1, sample_2)
297
+ rng = self._make_rng()
298
+ (boot_1,) = bootstrap_statistics(
299
+ rng, (sample_1.array,), plan_1, self._n_samples, self._stat, self._max_block_bytes
300
+ )
301
+ (boot_2,) = bootstrap_statistics(
302
+ rng, (sample_2.array,), plan_2, self._n_samples, self._stat, self._max_block_bytes
303
+ )
304
+ boot_data = self._boot_effect(boot_1, boot_2)
305
+ result_warnings: list[str] = []
306
+ effect = self._point_effect(
307
+ stat_point(sample_1.array, self._stat),
308
+ stat_point(sample_2.array, self._stat),
309
+ result_warnings,
310
+ )
311
+ return self._finalize(sample_1, sample_2, boot_data, effect, result_warnings)
@@ -0,0 +1,72 @@
1
+ """Bootstrap CI and p-value helpers (baseline §4; hygiene H4/H8).
2
+
3
+ The percentile CI and the sign p-value reproduce the legacy verbatim (golden
4
+ parity) and the sign p-value is the DEFAULT — statistics-changes.md §2/§6:
5
+ defaults stay baseline-faithful until the A/A matrix (M4) proves a fix helps.
6
+ H4's plug-in p-value ``(#extreme + 1)/(n + 1)`` — bounded away from an exact 0 —
7
+ ships as the opt-in, identity-bearing ``pvalue_kind: plugin``; promoting it to
8
+ the default is an ALGORITHM_VERSION bump arbitrated by the §0 process.
9
+
10
+ Tie convention (documented, conservative): replicates at exactly 0 count as
11
+ extreme on BOTH sides — they enter both the ``>= 0`` and the ``<= 0`` counts of
12
+ :func:`pvalue_plugin`. (The legacy sign p-value counted ties on neither side.)
13
+
14
+ H8: the legacy per-comparison Kolmogorov–Smirnov normality warning is DROPPED —
15
+ it tested against parameters estimated from the same data (uncalibrated
16
+ p-value); no replacement diagnostic ships in M1.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import numpy as np
22
+
23
+ from abkit.stats.base import ParamSpec
24
+ from abkit.stats.exceptions import MethodParamError
25
+ from abkit.stats.samples import FloatArray
26
+
27
+ #: p-value estimator selector for every bootstrap method. Identity-bearing: it
28
+ #: changes published p-values, so it is part of ``method_config_id``.
29
+ PVALUE_KIND_PARAM = ParamSpec(
30
+ name="pvalue_kind",
31
+ types=(str,),
32
+ default="sign",
33
+ identity=True,
34
+ choices=("plugin", "sign"),
35
+ description=(
36
+ "Bootstrap p-value estimator: 'sign' = legacy 2*min(P(boot>0), P(boot<0)) "
37
+ "(baseline-faithful default); 'plugin' = (#extreme+1)/(n+1) smoothing (H4, opt-in; "
38
+ "ties at 0 count as extreme on both sides)."
39
+ ),
40
+ )
41
+
42
+
43
+ def percentile_ci(boot_data: FloatArray, alpha: float) -> tuple[float, float]:
44
+ """Percentile bootstrap CI ``np.quantile(boot, [α/2, 1−α/2])`` (baseline §4, not BCa)."""
45
+ left_bound, right_bound = np.quantile(boot_data, [alpha / 2.0, 1.0 - alpha / 2.0])
46
+ return float(left_bound), float(right_bound)
47
+
48
+
49
+ def pvalue_sign(boot_data: FloatArray) -> float:
50
+ """Legacy sign-based p-value ``2·min(P(boot>0), P(boot<0))`` (baseline §4, golden parity)."""
51
+ return float(2.0 * min(np.mean(boot_data > 0.0), np.mean(boot_data < 0.0)))
52
+
53
+
54
+ def pvalue_plugin(boot_data: FloatArray) -> float:
55
+ """H4 plug-in p-value ``min(1, 2·min(#(boot≥0)+1, #(boot≤0)+1)/(n+1))``.
56
+
57
+ Never exactly 0 (distinguishable from ``p < 1/n_samples``); ties at exactly
58
+ 0 count as extreme on both sides (conservative — see module docstring).
59
+ """
60
+ n = int(boot_data.size)
61
+ n_at_or_above = int(np.count_nonzero(boot_data >= 0.0))
62
+ n_at_or_below = int(np.count_nonzero(boot_data <= 0.0))
63
+ return min(1.0, 2.0 * min(n_at_or_above + 1, n_at_or_below + 1) / (n + 1))
64
+
65
+
66
+ def bootstrap_pvalue(boot_data: FloatArray, kind: str) -> float:
67
+ """Dispatch on ``pvalue_kind`` (see :data:`PVALUE_KIND_PARAM`)."""
68
+ if kind == "plugin":
69
+ return pvalue_plugin(boot_data)
70
+ if kind == "sign":
71
+ return pvalue_sign(boot_data)
72
+ raise MethodParamError(f"unknown pvalue_kind {kind!r}; choices: ('plugin', 'sign')")