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.
- ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
- abkit/__init__.py +40 -0
- abkit/cli/__init__.py +1 -0
- abkit/cli/_output.py +111 -0
- abkit/cli/commands/__init__.py +1 -0
- abkit/cli/commands/_context.py +83 -0
- abkit/cli/commands/clean.py +133 -0
- abkit/cli/commands/explore.py +208 -0
- abkit/cli/commands/init.py +427 -0
- abkit/cli/commands/run.py +282 -0
- abkit/cli/commands/unlock.py +59 -0
- abkit/cli/commands/validate.py +264 -0
- abkit/cli/main.py +279 -0
- abkit/compute/__init__.py +5 -0
- abkit/compute/recompute_backend.py +140 -0
- abkit/config/__init__.py +51 -0
- abkit/config/discovery.py +168 -0
- abkit/config/experiment_config.py +511 -0
- abkit/config/method_config.py +80 -0
- abkit/config/metric_config.py +214 -0
- abkit/config/profile.py +301 -0
- abkit/config/project_config.py +244 -0
- abkit/config/validator.py +393 -0
- abkit/core/__init__.py +26 -0
- abkit/core/interval.py +148 -0
- abkit/core/models.py +121 -0
- abkit/core/period_planner.py +206 -0
- abkit/database/__init__.py +51 -0
- abkit/database/_sql_manager.py +432 -0
- abkit/database/clickhouse_manager.py +495 -0
- abkit/database/internal_tables/__init__.py +6 -0
- abkit/database/internal_tables/_aa_runs.py +53 -0
- abkit/database/internal_tables/_base.py +71 -0
- abkit/database/internal_tables/_experiments.py +82 -0
- abkit/database/internal_tables/_exposures.py +163 -0
- abkit/database/internal_tables/_maintenance.py +72 -0
- abkit/database/internal_tables/_results.py +231 -0
- abkit/database/internal_tables/_schema.py +23 -0
- abkit/database/internal_tables/_tasks.py +237 -0
- abkit/database/internal_tables/_unit_state.py +148 -0
- abkit/database/internal_tables/manager.py +30 -0
- abkit/database/manager.py +450 -0
- abkit/database/mysql_manager.py +175 -0
- abkit/database/postgres_manager.py +145 -0
- abkit/database/tables.py +326 -0
- abkit/loaders/__init__.py +28 -0
- abkit/loaders/exposure_loader.py +121 -0
- abkit/loaders/metric_loader.py +251 -0
- abkit/loaders/query_template.py +167 -0
- abkit/loaders/templates/abkit_assignment.jinja +62 -0
- abkit/pipeline/__init__.py +37 -0
- abkit/pipeline/_types.py +52 -0
- abkit/pipeline/analyze.py +223 -0
- abkit/pipeline/driver.py +477 -0
- abkit/pipeline/enrich.py +137 -0
- abkit/pipeline/readout.py +779 -0
- abkit/reporting/__init__.py +19 -0
- abkit/reporting/assets/report.js +138 -0
- abkit/reporting/builder.py +484 -0
- abkit/reporting/calibration.py +182 -0
- abkit/reporting/html_report.py +109 -0
- abkit/stats/__init__.py +94 -0
- abkit/stats/accumulate.py +82 -0
- abkit/stats/base.py +347 -0
- abkit/stats/bootstrap/__init__.py +69 -0
- abkit/stats/bootstrap/applier.py +81 -0
- abkit/stats/bootstrap/bootstrap.py +311 -0
- abkit/stats/bootstrap/ci.py +72 -0
- abkit/stats/bootstrap/engine.py +383 -0
- abkit/stats/bootstrap/paired_bootstrap.py +57 -0
- abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
- abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
- abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
- abkit/stats/correction.py +88 -0
- abkit/stats/effects.py +141 -0
- abkit/stats/exceptions.py +31 -0
- abkit/stats/factory.py +26 -0
- abkit/stats/parametric/__init__.py +10 -0
- abkit/stats/parametric/cuped_ttest.py +183 -0
- abkit/stats/parametric/paired_cuped_ttest.py +125 -0
- abkit/stats/parametric/paired_ttest.py +136 -0
- abkit/stats/parametric/ratio_delta.py +113 -0
- abkit/stats/parametric/ttest.py +105 -0
- abkit/stats/parametric/ztest.py +134 -0
- abkit/stats/power.py +278 -0
- abkit/stats/registry.py +111 -0
- abkit/stats/result.py +84 -0
- abkit/stats/rng.py +39 -0
- abkit/stats/samples.py +531 -0
- abkit/stats/sequential/__init__.py +18 -0
- abkit/stats/sequential/apply.py +37 -0
- abkit/stats/sequential/confidence_sequence.py +96 -0
- abkit/stats/sequential/mixture.py +70 -0
- abkit/stats/srm.py +221 -0
- abkit/tuning/__init__.py +59 -0
- abkit/tuning/assets/explore.js +173 -0
- abkit/tuning/config_writer.py +409 -0
- abkit/tuning/html.py +88 -0
- abkit/tuning/payload.py +122 -0
- abkit/tuning/recompute.py +1039 -0
- abkit/tuning/server.py +882 -0
- abkit/tuning/session.py +233 -0
- abkit/utils/__init__.py +27 -0
- abkit/utils/datetime_utils.py +97 -0
- abkit/utils/env_interpolation.py +50 -0
- abkit/utils/json_utils.py +38 -0
- abkit/validate/__init__.py +36 -0
- abkit/validate/_types.py +35 -0
- abkit/validate/inject.py +75 -0
- abkit/validate/load.py +160 -0
- abkit/validate/panel.py +59 -0
- abkit/validate/persistence.py +59 -0
- abkit/validate/resample.py +94 -0
- abkit/validate/result.py +60 -0
- abkit/validate/run_id.py +45 -0
- abkit/validate/runner.py +389 -0
- abkit/validate/scoring.py +544 -0
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"""Vectorised bootstrap resampling engines (baseline §4.1/§4.4; hygiene H1/H6/H10).
|
|
2
|
+
|
|
3
|
+
DRAW-ORDER CONTRACT (binding; regression-tested)
|
|
4
|
+
================================================
|
|
5
|
+
|
|
6
|
+
All randomness flows from ONE ``np.random.Generator`` (H1) built by the calling
|
|
7
|
+
method via :func:`abkit.stats.rng.make_rng` once per compare call. Replicates
|
|
8
|
+
are ALWAYS drawn in fixed quanta of :data:`BLOCK_QUANTUM` (= 128) replicates
|
|
9
|
+
from that single stream, sequentially from replicate 0 to ``n_samples`` (the
|
|
10
|
+
last quantum may be short). The memory cap (``max_block_bytes``, default
|
|
11
|
+
:data:`DEFAULT_MAX_BLOCK_BYTES`) only controls how many quanta of VALUE
|
|
12
|
+
matrices are materialised at once — it must NEVER affect the random stream, so
|
|
13
|
+
any ``max_block_bytes`` yields byte-identical results.
|
|
14
|
+
|
|
15
|
+
Index engine (:func:`bootstrap_statistics`), per variant:
|
|
16
|
+
|
|
17
|
+
- Strata are visited in ``np.unique`` order (unstratified = one stratum = the
|
|
18
|
+
whole array). Within a quantum, for each stratum the draw is exactly
|
|
19
|
+
``indices = rng.integers(0, len(stratum_values), size=(quantum_rows,
|
|
20
|
+
stratum_size))`` — see :func:`draw_stratum_indices`, kept trivial so the
|
|
21
|
+
golden-reference transcription can share the identical stream — and
|
|
22
|
+
``values_block[:, offset:offset + stratum_size] = stratum_values[indices]``.
|
|
23
|
+
- With a covariate channel (``cov_bootstrap``, baseline §4.1) the SAME indices
|
|
24
|
+
are applied to the covariate values — no extra draws — preserving the
|
|
25
|
+
per-unit (Y, X) pairing.
|
|
26
|
+
- Variant 1 is drawn fully (all quanta) before variant 2. Paired variants
|
|
27
|
+
instead share ONE set of index/weight draws by passing both arms as aligned
|
|
28
|
+
channels of a single engine call.
|
|
29
|
+
|
|
30
|
+
Poisson engine (:func:`poisson_bootstrap_means`, baseline §4.4): per quantum
|
|
31
|
+
``weights = rng.poisson(1.0, (quantum_rows, n_units))``; the replicate value is
|
|
32
|
+
``(weights_scaled @ values) / weights_scaled.sum(axis=1)`` where
|
|
33
|
+
``weights_scaled`` applies the per-unit post-stratification scale
|
|
34
|
+
(1 / count-of-its-category, :func:`poisson_unit_scale`) when stratified. Its
|
|
35
|
+
working set is a single quantum of weights regardless of the cap (already
|
|
36
|
+
minimal), and the fixed per-quantum matmul shape keeps the produced bytes
|
|
37
|
+
cap-invariant, so ``max_block_bytes`` is accepted and ignored here.
|
|
38
|
+
|
|
39
|
+
Byte-identity under any cap holds by construction: draws happen per quantum
|
|
40
|
+
and statistic application is row-wise (each replicate reduced independently),
|
|
41
|
+
so block grouping cannot change any replicate's value.
|
|
42
|
+
|
|
43
|
+
Stratification (H6): pooled per-stratum shares (baseline §4.2 ``weight_method``
|
|
44
|
+
min/mean) are apportioned with the largest-remainder (Hamilton) method
|
|
45
|
+
(:func:`hamilton_apportion`) so per-stratum resample counts sum EXACTLY to each
|
|
46
|
+
variant's ``n`` — replacing the legacy ``max(1, int(...))`` truncation drift.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
from collections.abc import Iterator, Sequence
|
|
52
|
+
from dataclasses import dataclass
|
|
53
|
+
|
|
54
|
+
import numpy as np
|
|
55
|
+
import numpy.typing as npt
|
|
56
|
+
|
|
57
|
+
from abkit.stats.bootstrap.applier import StatFunc, apply_stat
|
|
58
|
+
from abkit.stats.exceptions import MethodParamError, SampleValidationError
|
|
59
|
+
from abkit.stats.samples import FloatArray, Sample
|
|
60
|
+
|
|
61
|
+
IntArray = npt.NDArray[np.int64]
|
|
62
|
+
CategoryArray = npt.NDArray[np.generic]
|
|
63
|
+
|
|
64
|
+
#: Fixed replicate quantum of the random stream (see the draw-order contract).
|
|
65
|
+
BLOCK_QUANTUM = 128
|
|
66
|
+
#: Default memory cap for materialised value matrices (H10): 256 MiB.
|
|
67
|
+
DEFAULT_MAX_BLOCK_BYTES = 256 * 1024 * 1024
|
|
68
|
+
#: float64 value matrices / int64 Poisson weight matrices.
|
|
69
|
+
_ITEM_BYTES = 8
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def draw_stratum_indices(
|
|
73
|
+
rng: np.random.Generator, n_units: int, rows: int, stratum_size: int
|
|
74
|
+
) -> IntArray:
|
|
75
|
+
"""The single index draw of the contract: ``rng.integers(0, n_units, (rows, size))``.
|
|
76
|
+
|
|
77
|
+
Deliberately trivial (one ``rng.integers`` call) so the golden-reference
|
|
78
|
+
transcription of the legacy engine can share the identical random stream.
|
|
79
|
+
"""
|
|
80
|
+
return rng.integers(0, n_units, size=(rows, stratum_size))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def hamilton_apportion(shares: FloatArray, total: int) -> IntArray:
|
|
84
|
+
"""Largest-remainder (Hamilton) apportionment of ``total`` over ``shares`` (H6).
|
|
85
|
+
|
|
86
|
+
Per-stratum counts sum EXACTLY to ``total``. Ties on fractional remainders
|
|
87
|
+
break deterministically toward the earlier stratum (``np.unique`` order,
|
|
88
|
+
stable sort). After apportionment any zero-count stratum is bumped to 1,
|
|
89
|
+
taking one unit from the (current) largest stratum, keeping the total exact
|
|
90
|
+
— feasible because ``total >= len(shares)`` is required.
|
|
91
|
+
"""
|
|
92
|
+
share_array = np.asarray(shares, dtype=np.float64)
|
|
93
|
+
if share_array.ndim != 1 or share_array.size == 0:
|
|
94
|
+
raise SampleValidationError("hamilton_apportion: shares must be a non-empty 1-D array")
|
|
95
|
+
if not np.all(np.isfinite(share_array)) or np.any(share_array < 0.0):
|
|
96
|
+
raise SampleValidationError("hamilton_apportion: shares must be finite and non-negative")
|
|
97
|
+
share_sum = float(share_array.sum())
|
|
98
|
+
if share_sum <= 0.0:
|
|
99
|
+
raise SampleValidationError("hamilton_apportion: shares must sum to a positive value")
|
|
100
|
+
total = int(total)
|
|
101
|
+
if total < share_array.size:
|
|
102
|
+
raise SampleValidationError(
|
|
103
|
+
f"hamilton_apportion: cannot give every stratum at least one unit "
|
|
104
|
+
f"(total={total} < strata={share_array.size})"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
quotas = share_array / share_sum * total
|
|
108
|
+
counts = np.floor(quotas).astype(np.int64)
|
|
109
|
+
remainders = quotas - counts
|
|
110
|
+
missing = total - int(counts.sum())
|
|
111
|
+
while missing < 0: # float-noise overshoot only; deterministic trim from the largest
|
|
112
|
+
donor = int(np.argmax(counts))
|
|
113
|
+
counts[donor] -= 1
|
|
114
|
+
missing += 1
|
|
115
|
+
if missing > 0:
|
|
116
|
+
order = np.argsort(-remainders, kind="stable")
|
|
117
|
+
counts[order[:missing]] += 1
|
|
118
|
+
for index in np.flatnonzero(counts == 0):
|
|
119
|
+
donor = int(np.argmax(counts))
|
|
120
|
+
counts[donor] -= 1
|
|
121
|
+
counts[index] = 1
|
|
122
|
+
return counts
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def require_common_categories(
|
|
126
|
+
method_name: str, sample_1: Sample, sample_2: Sample
|
|
127
|
+
) -> CategoryArray:
|
|
128
|
+
"""Validate stratification inputs: categories on both arms, identical SETS (H6).
|
|
129
|
+
|
|
130
|
+
Returns the shared categories in ``np.unique`` (sorted) order — the stratum
|
|
131
|
+
visiting order of the draw contract.
|
|
132
|
+
"""
|
|
133
|
+
for label, sample in (("first", sample_1), ("second", sample_2)):
|
|
134
|
+
if sample.categories_array is None:
|
|
135
|
+
raise SampleValidationError(
|
|
136
|
+
f"{method_name}: stratify=True requires categories_array on the {label} sample"
|
|
137
|
+
)
|
|
138
|
+
assert sample_1.categories_array is not None and sample_2.categories_array is not None
|
|
139
|
+
categories_1 = np.unique(sample_1.categories_array)
|
|
140
|
+
categories_2 = np.unique(sample_2.categories_array)
|
|
141
|
+
if categories_1.shape != categories_2.shape or not np.array_equal(categories_1, categories_2):
|
|
142
|
+
raise SampleValidationError(
|
|
143
|
+
f"{method_name}: the two variants must have identical stratum category sets; "
|
|
144
|
+
f"got {list(categories_1)} vs {list(categories_2)}"
|
|
145
|
+
)
|
|
146
|
+
return categories_1
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def pooled_stratum_shares(
|
|
150
|
+
sample_1: Sample, sample_2: Sample, weight_method: str, method_name: str
|
|
151
|
+
) -> tuple[CategoryArray, FloatArray]:
|
|
152
|
+
"""Pool per-variant stratum shares across variants (baseline §4.2, H6).
|
|
153
|
+
|
|
154
|
+
Per-variant shares are ``counts / n`` over the (validated-identical) category
|
|
155
|
+
set; pooled elementwise by ``weight_method`` ("min" or "mean") and normalised
|
|
156
|
+
to sum 1. Both variants then resample to this common stratum mix
|
|
157
|
+
(poststratification by design).
|
|
158
|
+
"""
|
|
159
|
+
categories = require_common_categories(method_name, sample_1, sample_2)
|
|
160
|
+
assert sample_1.categories_array is not None and sample_2.categories_array is not None
|
|
161
|
+
_, counts_1 = np.unique(sample_1.categories_array, return_counts=True)
|
|
162
|
+
_, counts_2 = np.unique(sample_2.categories_array, return_counts=True)
|
|
163
|
+
shares_1 = counts_1 / sample_1.sample_size
|
|
164
|
+
shares_2 = counts_2 / sample_2.sample_size
|
|
165
|
+
if weight_method == "min":
|
|
166
|
+
pooled = np.minimum(shares_1, shares_2)
|
|
167
|
+
elif weight_method == "mean":
|
|
168
|
+
pooled = (shares_1 + shares_2) / 2.0
|
|
169
|
+
else:
|
|
170
|
+
raise MethodParamError(
|
|
171
|
+
f"{method_name}: weight_method must be 'min' or 'mean', got {weight_method!r}"
|
|
172
|
+
)
|
|
173
|
+
return categories, pooled / pooled.sum()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def poisson_unit_scale(categories_array: CategoryArray) -> FloatArray:
|
|
177
|
+
"""Per-unit Poisson post-stratification scale: 1 / count-of-its-category.
|
|
178
|
+
|
|
179
|
+
Legacy semantics (catalogue §4.4) vectorised via ``np.unique`` inverse
|
|
180
|
+
indices instead of the legacy per-column Python loop.
|
|
181
|
+
"""
|
|
182
|
+
_, inverse, counts = np.unique(categories_array, return_inverse=True, return_counts=True)
|
|
183
|
+
return 1.0 / counts[inverse]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True)
|
|
187
|
+
class ResamplePlan:
|
|
188
|
+
"""Per-variant resampling layout: strata (``np.unique`` order) and resample counts.
|
|
189
|
+
|
|
190
|
+
``strata_positions[s]`` are the unit positions of stratum ``s`` in the
|
|
191
|
+
variant's arrays; ``resample_counts[s]`` is how many units that stratum
|
|
192
|
+
contributes per replicate (Hamilton-apportioned, summing exactly to the
|
|
193
|
+
resample width). Unstratified = one stratum spanning the whole array.
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
strata_positions: tuple[IntArray, ...]
|
|
197
|
+
resample_counts: tuple[int, ...]
|
|
198
|
+
|
|
199
|
+
def __post_init__(self) -> None:
|
|
200
|
+
if len(self.strata_positions) != len(self.resample_counts):
|
|
201
|
+
raise SampleValidationError("ResamplePlan: strata_positions/resample_counts mismatch")
|
|
202
|
+
if not self.strata_positions:
|
|
203
|
+
raise SampleValidationError("ResamplePlan: at least one stratum is required")
|
|
204
|
+
for positions, count in zip(self.strata_positions, self.resample_counts, strict=True):
|
|
205
|
+
if positions.size == 0:
|
|
206
|
+
raise SampleValidationError("ResamplePlan: empty stratum")
|
|
207
|
+
if count < 1:
|
|
208
|
+
raise SampleValidationError("ResamplePlan: resample counts must be >= 1")
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def total_width(self) -> int:
|
|
212
|
+
"""Columns per replicate row (== the variant's ``n`` after apportionment)."""
|
|
213
|
+
return int(sum(self.resample_counts))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def unstratified_plan(n_units: int) -> ResamplePlan:
|
|
217
|
+
"""One stratum = the whole array; resample width = ``n_units`` (baseline §4.1)."""
|
|
218
|
+
if n_units < 1:
|
|
219
|
+
raise SampleValidationError("unstratified_plan: n_units must be >= 1")
|
|
220
|
+
return ResamplePlan(
|
|
221
|
+
strata_positions=(np.arange(n_units, dtype=np.int64),),
|
|
222
|
+
resample_counts=(int(n_units),),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def stratified_plan(
|
|
227
|
+
categories_array: CategoryArray, categories: CategoryArray, shares: FloatArray
|
|
228
|
+
) -> ResamplePlan:
|
|
229
|
+
"""Build one variant's plan from pooled shares (Hamilton-apportioned to its ``n``).
|
|
230
|
+
|
|
231
|
+
Positions come from one ``np.unique(return_inverse)`` pass + a stable argsort
|
|
232
|
+
split — O(n log n) once, instead of one O(n) equality scan per category
|
|
233
|
+
(review finding). Per-stratum position order stays ascending, identical to the
|
|
234
|
+
former ``np.flatnonzero`` output, so resample draws are unchanged.
|
|
235
|
+
"""
|
|
236
|
+
counts = hamilton_apportion(shares, int(categories_array.size))
|
|
237
|
+
unique_categories, inverse, stratum_sizes = np.unique(
|
|
238
|
+
categories_array, return_inverse=True, return_counts=True
|
|
239
|
+
)
|
|
240
|
+
if unique_categories.shape != categories.shape or not np.array_equal(
|
|
241
|
+
unique_categories, categories
|
|
242
|
+
):
|
|
243
|
+
raise SampleValidationError(
|
|
244
|
+
f"stratified_plan: categories {list(categories)} do not match the array's "
|
|
245
|
+
f"strata {list(unique_categories)}"
|
|
246
|
+
)
|
|
247
|
+
order = np.argsort(inverse, kind="stable").astype(np.int64)
|
|
248
|
+
positions = tuple(np.split(order, np.cumsum(stratum_sizes)[:-1]))
|
|
249
|
+
return ResamplePlan(
|
|
250
|
+
strata_positions=positions,
|
|
251
|
+
resample_counts=tuple(int(count) for count in counts),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _validate_channels(channels: Sequence[FloatArray], n_units: int) -> None:
|
|
256
|
+
if not channels:
|
|
257
|
+
raise SampleValidationError("resampling requires at least one channel")
|
|
258
|
+
for channel in channels:
|
|
259
|
+
if channel.ndim != 1 or channel.size != n_units:
|
|
260
|
+
raise SampleValidationError(
|
|
261
|
+
"all resampling channels must be 1-D and aligned to the same units"
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def iter_resample_blocks(
|
|
266
|
+
rng: np.random.Generator,
|
|
267
|
+
channels: Sequence[FloatArray],
|
|
268
|
+
plan: ResamplePlan,
|
|
269
|
+
n_samples: int,
|
|
270
|
+
max_block_bytes: int | None,
|
|
271
|
+
) -> Iterator[tuple[FloatArray, ...]]:
|
|
272
|
+
"""Yield resampled value matrices per channel, in blocks of whole quanta.
|
|
273
|
+
|
|
274
|
+
Implements the module draw-order contract: indices are drawn per quantum
|
|
275
|
+
(per stratum, in plan order) from the single ``rng`` stream; the cap only
|
|
276
|
+
sizes the materialised block (``>= 1`` quantum always), never the stream.
|
|
277
|
+
All channels of one stratum reuse the SAME index matrix (covariate pairing,
|
|
278
|
+
baseline §4.1).
|
|
279
|
+
"""
|
|
280
|
+
if n_samples < 1:
|
|
281
|
+
raise MethodParamError(f"n_samples must be >= 1, got {n_samples}")
|
|
282
|
+
n_units = int(channels[0].size)
|
|
283
|
+
_validate_channels(channels, n_units)
|
|
284
|
+
|
|
285
|
+
stratum_values = [
|
|
286
|
+
tuple(channel[positions] for channel in channels) for positions in plan.strata_positions
|
|
287
|
+
]
|
|
288
|
+
width = plan.total_width
|
|
289
|
+
# Working set per quantum: the value block(s) PLUS the int64 index matrix (same
|
|
290
|
+
# shape as one block) and the fancy-indexing temporary — omitting those made the
|
|
291
|
+
# cap ~3x optimistic (review finding). One quantum is the hard floor regardless
|
|
292
|
+
# of the cap; the M2 pre-flight estimate refuses/downgrades instead of OOMing.
|
|
293
|
+
bytes_per_quantum = BLOCK_QUANTUM * width * _ITEM_BYTES * (len(channels) + 2)
|
|
294
|
+
cap = DEFAULT_MAX_BLOCK_BYTES if max_block_bytes is None else int(max_block_bytes)
|
|
295
|
+
quanta_per_block = max(1, cap // max(1, bytes_per_quantum))
|
|
296
|
+
|
|
297
|
+
produced = 0
|
|
298
|
+
while produced < n_samples:
|
|
299
|
+
block_rows = min(n_samples - produced, quanta_per_block * BLOCK_QUANTUM)
|
|
300
|
+
blocks = tuple(np.empty((block_rows, width), dtype=np.float64) for _ in channels)
|
|
301
|
+
row = 0
|
|
302
|
+
while row < block_rows:
|
|
303
|
+
quantum_rows = min(BLOCK_QUANTUM, block_rows - row)
|
|
304
|
+
offset = 0
|
|
305
|
+
for positions, count, values_by_channel in zip(
|
|
306
|
+
plan.strata_positions, plan.resample_counts, stratum_values, strict=True
|
|
307
|
+
):
|
|
308
|
+
indices = draw_stratum_indices(rng, int(positions.size), quantum_rows, count)
|
|
309
|
+
for block, values in zip(blocks, values_by_channel, strict=True):
|
|
310
|
+
block[row : row + quantum_rows, offset : offset + count] = values[indices]
|
|
311
|
+
offset += count
|
|
312
|
+
row += quantum_rows
|
|
313
|
+
produced += block_rows
|
|
314
|
+
yield blocks
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def bootstrap_statistics(
|
|
318
|
+
rng: np.random.Generator,
|
|
319
|
+
channels: Sequence[FloatArray],
|
|
320
|
+
plan: ResamplePlan,
|
|
321
|
+
n_samples: int,
|
|
322
|
+
stat: str | StatFunc,
|
|
323
|
+
max_block_bytes: int | None,
|
|
324
|
+
) -> tuple[FloatArray, ...]:
|
|
325
|
+
"""Index-engine bootstrap: one length-``n_samples`` statistic vector per channel.
|
|
326
|
+
|
|
327
|
+
Streams :func:`iter_resample_blocks` and applies ``stat`` row-wise per block
|
|
328
|
+
(H3 fast path in :func:`abkit.stats.bootstrap.applier.apply_stat`).
|
|
329
|
+
"""
|
|
330
|
+
outputs = tuple(np.empty(n_samples, dtype=np.float64) for _ in channels)
|
|
331
|
+
produced = 0
|
|
332
|
+
for blocks in iter_resample_blocks(rng, channels, plan, n_samples, max_block_bytes):
|
|
333
|
+
rows = blocks[0].shape[0]
|
|
334
|
+
for output, block in zip(outputs, blocks, strict=True):
|
|
335
|
+
output[produced : produced + rows] = apply_stat(block, stat)
|
|
336
|
+
produced += rows
|
|
337
|
+
return outputs
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def poisson_bootstrap_means(
|
|
341
|
+
rng: np.random.Generator,
|
|
342
|
+
arrays: Sequence[FloatArray],
|
|
343
|
+
unit_scale: FloatArray | None,
|
|
344
|
+
n_samples: int,
|
|
345
|
+
max_block_bytes: int | None = None,
|
|
346
|
+
) -> tuple[FloatArray, ...]:
|
|
347
|
+
"""Poisson-weighted bootstrap means (baseline §4.4), one vector per array.
|
|
348
|
+
|
|
349
|
+
Per quantum: ``weights = rng.poisson(1.0, (quantum_rows, n_units))``;
|
|
350
|
+
replicate value = ``(weights_scaled @ array) / weights_scaled.sum(axis=1)``.
|
|
351
|
+
All arrays share the SAME weights per quantum (paired variants pass both
|
|
352
|
+
arms). Zero weight sums produce non-finite replicates (kept; handled under
|
|
353
|
+
H5 downstream). ``max_block_bytes`` is accepted and ignored — see the module
|
|
354
|
+
docstring (per-quantum working set is already minimal and cap-invariant).
|
|
355
|
+
"""
|
|
356
|
+
del max_block_bytes # cap-invariant by construction (module docstring)
|
|
357
|
+
if n_samples < 1:
|
|
358
|
+
raise MethodParamError(f"n_samples must be >= 1, got {n_samples}")
|
|
359
|
+
n_units = int(arrays[0].size)
|
|
360
|
+
_validate_channels(arrays, n_units)
|
|
361
|
+
if unit_scale is not None and unit_scale.size != n_units:
|
|
362
|
+
raise SampleValidationError("unit_scale must be aligned to the arrays")
|
|
363
|
+
|
|
364
|
+
outputs = tuple(np.empty(n_samples, dtype=np.float64) for _ in arrays)
|
|
365
|
+
# One reused float64 buffer: the int64 weights are converted (and scaled) into
|
|
366
|
+
# it in place, so the peak is one weights matrix + one buffer per quantum and
|
|
367
|
+
# the matmul stays on the BLAS float64 path (review finding).
|
|
368
|
+
buffer = np.empty((min(BLOCK_QUANTUM, n_samples), n_units), dtype=np.float64)
|
|
369
|
+
produced = 0
|
|
370
|
+
while produced < n_samples:
|
|
371
|
+
quantum_rows = min(BLOCK_QUANTUM, n_samples - produced)
|
|
372
|
+
weights = rng.poisson(1.0, size=(quantum_rows, n_units))
|
|
373
|
+
weights_scaled = buffer[:quantum_rows]
|
|
374
|
+
if unit_scale is None:
|
|
375
|
+
np.copyto(weights_scaled, weights)
|
|
376
|
+
else:
|
|
377
|
+
np.multiply(weights, unit_scale, out=weights_scaled)
|
|
378
|
+
weight_sums = weights_scaled.sum(axis=1)
|
|
379
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
380
|
+
for output, array in zip(outputs, arrays, strict=True):
|
|
381
|
+
output[produced : produced + quantum_rows] = (weights_scaled @ array) / weight_sums
|
|
382
|
+
produced += quantum_rows
|
|
383
|
+
return outputs
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""``paired-bootstrap`` — index-resampling bootstrap for paired designs.
|
|
2
|
+
|
|
3
|
+
Legacy semantics (catalogue "PairedBootstrapTest"): both arms are resampled with
|
|
4
|
+
the SAME index draws — here made explicit by drawing ONE set of index quanta
|
|
5
|
+
from the single Generator and applying it to both arms (the legacy achieved
|
|
6
|
+
this implicitly by seeding two generators with the same ``random_seed``).
|
|
7
|
+
|
|
8
|
+
Deliberate deviation (H9, docs/specs/statistics-changes.md): the legacy set
|
|
9
|
+
``effect = mean(boot_data)``; here ``effect`` is the real-data point estimate —
|
|
10
|
+
consistent with every other method — and the bootstrap mean stays in
|
|
11
|
+
``diagnostics["boot_mean"]`` as a bias diagnostic.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from abkit.stats.base import require_pair_type
|
|
17
|
+
from abkit.stats.bootstrap.applier import stat_point
|
|
18
|
+
from abkit.stats.bootstrap.bootstrap import BaseBootstrapMethod
|
|
19
|
+
from abkit.stats.bootstrap.engine import bootstrap_statistics
|
|
20
|
+
from abkit.stats.registry import register
|
|
21
|
+
from abkit.stats.result import TestResult
|
|
22
|
+
from abkit.stats.samples import Sample
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@register
|
|
26
|
+
class PairedBootstrapTest(BaseBootstrapMethod):
|
|
27
|
+
"""Paired bootstrap: equal-size aligned arms sharing one index stream.
|
|
28
|
+
|
|
29
|
+
Requires equal sample sizes; when both arms carry ``categories_array`` they
|
|
30
|
+
must be elementwise identical (paired strata travel with the pair), so a
|
|
31
|
+
single stratified plan serves both arms.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
name = "paired-bootstrap"
|
|
35
|
+
is_paired = True
|
|
36
|
+
|
|
37
|
+
def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
|
|
38
|
+
require_pair_type(self.name, sample_1, sample_2, Sample)
|
|
39
|
+
self._validate_paired(sample_1, sample_2)
|
|
40
|
+
plan = self._paired_plan(sample_1, sample_2)
|
|
41
|
+
rng = self._make_rng()
|
|
42
|
+
boot_1, boot_2 = bootstrap_statistics(
|
|
43
|
+
rng,
|
|
44
|
+
(sample_1.array, sample_2.array),
|
|
45
|
+
plan,
|
|
46
|
+
self._n_samples,
|
|
47
|
+
self._stat,
|
|
48
|
+
self._max_block_bytes,
|
|
49
|
+
)
|
|
50
|
+
boot_data = self._boot_effect(boot_1, boot_2)
|
|
51
|
+
result_warnings: list[str] = []
|
|
52
|
+
effect = self._point_effect(
|
|
53
|
+
stat_point(sample_1.array, self._stat),
|
|
54
|
+
stat_point(sample_2.array, self._stat),
|
|
55
|
+
result_warnings,
|
|
56
|
+
)
|
|
57
|
+
return self._finalize(sample_1, sample_2, boot_data, effect, result_warnings)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""``paired-post-normed-bootstrap`` — z-score standardised paired bootstrap.
|
|
2
|
+
|
|
3
|
+
Despite the name, the legacy method (catalogue "PairedPostNormedBootstrapTest")
|
|
4
|
+
does NOT do covariate post-norming: it z-score STANDARDISES each arm's
|
|
5
|
+
bootstrap distribution, ``boot_i_normed = (boot_i − mean(boot_i)) /
|
|
6
|
+
std(boot_i)``, then differences them. That absolute branch is reproduced
|
|
7
|
+
verbatim here over paired index draws (ONE stream applied to both arms).
|
|
8
|
+
|
|
9
|
+
QUARANTINE (quorum must-fix; docs/specs/statistics-changes.md §3): the legacy
|
|
10
|
+
RELATIVE branch takes a ratio of z-scores — the denominator is centred at ~0
|
|
11
|
+
and the ratio explodes — so ``test_type="relative"`` (the family default)
|
|
12
|
+
raises :class:`~abkit.stats.exceptions.QuarantinedMethodError` at construction.
|
|
13
|
+
|
|
14
|
+
H9 exception (documented): the standardised-difference estimand has NO
|
|
15
|
+
real-data point estimate, so ``effect = mean(boot_data)`` is kept — the only
|
|
16
|
+
method where ``effect`` is not a real-data point estimate — and every result
|
|
17
|
+
carries a warning recommending ``post-normed-bootstrap`` or ``ratio-delta``.
|
|
18
|
+
|
|
19
|
+
Legacy quirk (validation parity): ``cov_array`` is REQUIRED on both arms even
|
|
20
|
+
though the math never uses it.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from abkit.stats.base import require_pair_type
|
|
28
|
+
from abkit.stats.bootstrap.bootstrap import BaseBootstrapMethod
|
|
29
|
+
from abkit.stats.bootstrap.engine import bootstrap_statistics
|
|
30
|
+
from abkit.stats.exceptions import QuarantinedMethodError
|
|
31
|
+
from abkit.stats.registry import register
|
|
32
|
+
from abkit.stats.result import TestResult
|
|
33
|
+
from abkit.stats.samples import Sample
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@register
|
|
37
|
+
class PairedPostNormedBootstrapTest(BaseBootstrapMethod):
|
|
38
|
+
"""Paired z-score-standardised bootstrap (absolute branch only)."""
|
|
39
|
+
|
|
40
|
+
name = "paired-post-normed-bootstrap"
|
|
41
|
+
requires_covariate = True
|
|
42
|
+
is_paired = True
|
|
43
|
+
|
|
44
|
+
def _validate_params(self) -> None:
|
|
45
|
+
super()._validate_params()
|
|
46
|
+
if str(self.params["test_type"]) == "relative":
|
|
47
|
+
raise QuarantinedMethodError(
|
|
48
|
+
f"{self.name}: test_type='relative' is quarantined — the legacy relative "
|
|
49
|
+
"branch is a ratio of z-score-standardised bootstrap distributions "
|
|
50
|
+
"(denominator ~0, the ratio explodes; see statistics-changes.md §3); use "
|
|
51
|
+
"test_type='absolute', or 'post-normed-bootstrap' / 'ratio-delta' for "
|
|
52
|
+
"ratio metrics"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
|
|
56
|
+
require_pair_type(self.name, sample_1, sample_2, Sample)
|
|
57
|
+
self._require_covariates(sample_1, sample_2) # legacy quirk: required, unused
|
|
58
|
+
self._validate_paired(sample_1, sample_2)
|
|
59
|
+
plan = self._paired_plan(sample_1, sample_2)
|
|
60
|
+
rng = self._make_rng()
|
|
61
|
+
boot_1, boot_2 = bootstrap_statistics(
|
|
62
|
+
rng,
|
|
63
|
+
(sample_1.array, sample_2.array),
|
|
64
|
+
plan,
|
|
65
|
+
self._n_samples,
|
|
66
|
+
self._stat,
|
|
67
|
+
self._max_block_bytes,
|
|
68
|
+
)
|
|
69
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
70
|
+
boot_1_normed = (boot_1 - boot_1.mean()) / boot_1.std() # ddof=0 (np.std law)
|
|
71
|
+
boot_2_normed = (boot_2 - boot_2.mean()) / boot_2.std()
|
|
72
|
+
boot_data = boot_2_normed - boot_1_normed
|
|
73
|
+
|
|
74
|
+
effect = float(np.mean(boot_data))
|
|
75
|
+
result_warnings = [
|
|
76
|
+
f"{self.name} standardises each arm's bootstrap distribution (z-scores); its "
|
|
77
|
+
"effect is the mean standardised difference with NO real-data point estimate "
|
|
78
|
+
"(documented H9 exception) — prefer 'post-normed-bootstrap' or 'ratio-delta' "
|
|
79
|
+
"for ratio metrics"
|
|
80
|
+
]
|
|
81
|
+
return self._finalize(sample_1, sample_2, boot_data, effect, result_warnings)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""``poisson-bootstrap`` / ``paired-poisson-bootstrap`` — weight-based bootstrap.
|
|
2
|
+
|
|
3
|
+
Baseline §4.4 (catalogue "PoissonBootstrapTest"): the streaming-friendly engine
|
|
4
|
+
— Poisson(1) weights instead of index resampling, so the whole bootstrap is a
|
|
5
|
+
single matmul per quantum and no ``n_samples × n`` value matrix is ever built.
|
|
6
|
+
|
|
7
|
+
H7 (docs/specs/statistics-changes.md): the Poisson weighted-mean replicate is
|
|
8
|
+
only a valid bootstrap of the MEAN — ``stat`` must be ``"mean"``
|
|
9
|
+
(:class:`~abkit.stats.exceptions.MethodParamError` at construction otherwise).
|
|
10
|
+
|
|
11
|
+
Post-stratification scales each unit's weight by 1 / count-of-its-category
|
|
12
|
+
(catalogue), per variant. The paired variant applies ONE weights stream to both
|
|
13
|
+
arms (catalogue "PairedPoissonBootstrapTest").
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from abkit.stats.base import require_pair_type
|
|
19
|
+
from abkit.stats.bootstrap.applier import stat_point
|
|
20
|
+
from abkit.stats.bootstrap.bootstrap import BOOTSTRAP_PARAM_SPECS, BaseBootstrapMethod
|
|
21
|
+
from abkit.stats.bootstrap.engine import (
|
|
22
|
+
poisson_bootstrap_means,
|
|
23
|
+
poisson_unit_scale,
|
|
24
|
+
require_common_categories,
|
|
25
|
+
)
|
|
26
|
+
from abkit.stats.exceptions import MethodParamError
|
|
27
|
+
from abkit.stats.registry import register
|
|
28
|
+
from abkit.stats.result import TestResult
|
|
29
|
+
from abkit.stats.samples import Sample
|
|
30
|
+
|
|
31
|
+
#: Poisson stratification uses the 1/count unit scale, never ``weight_method`` —
|
|
32
|
+
#: accepting it would let a no-op value fork ``method_config_id`` (review finding).
|
|
33
|
+
POISSON_PARAM_SPECS = tuple(spec for spec in BOOTSTRAP_PARAM_SPECS if spec.name != "weight_method")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@register
|
|
37
|
+
class PoissonBootstrapTest(BaseBootstrapMethod):
|
|
38
|
+
"""Independent Poisson-weighted bootstrap of the mean (baseline §4.4)."""
|
|
39
|
+
|
|
40
|
+
name = "poisson-bootstrap"
|
|
41
|
+
param_specs = POISSON_PARAM_SPECS
|
|
42
|
+
|
|
43
|
+
def _validate_params(self) -> None:
|
|
44
|
+
super()._validate_params()
|
|
45
|
+
if str(self.params["stat"]) != "mean":
|
|
46
|
+
raise MethodParamError(
|
|
47
|
+
f"{self.name}: the Poisson engine is only correct for stat='mean' "
|
|
48
|
+
"(weighted-mean replicates; see statistics-changes.md H7), got "
|
|
49
|
+
f"{self.params['stat']!r}"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
|
|
53
|
+
require_pair_type(self.name, sample_1, sample_2, Sample)
|
|
54
|
+
scale_1 = scale_2 = None
|
|
55
|
+
if bool(self.params["stratify"]):
|
|
56
|
+
require_common_categories(self.name, sample_1, sample_2)
|
|
57
|
+
assert sample_1.categories_array is not None and sample_2.categories_array is not None
|
|
58
|
+
scale_1 = poisson_unit_scale(sample_1.categories_array)
|
|
59
|
+
scale_2 = poisson_unit_scale(sample_2.categories_array)
|
|
60
|
+
rng = self._make_rng()
|
|
61
|
+
# Variant 1 is drawn fully (all quanta) before variant 2 (draw-order contract).
|
|
62
|
+
(boot_1,) = poisson_bootstrap_means(
|
|
63
|
+
rng, (sample_1.array,), scale_1, self._n_samples, self._max_block_bytes
|
|
64
|
+
)
|
|
65
|
+
(boot_2,) = poisson_bootstrap_means(
|
|
66
|
+
rng, (sample_2.array,), scale_2, self._n_samples, self._max_block_bytes
|
|
67
|
+
)
|
|
68
|
+
boot_data = self._boot_effect(boot_1, boot_2)
|
|
69
|
+
result_warnings: list[str] = []
|
|
70
|
+
effect = self._point_effect(
|
|
71
|
+
stat_point(sample_1.array, self._stat),
|
|
72
|
+
stat_point(sample_2.array, self._stat),
|
|
73
|
+
result_warnings,
|
|
74
|
+
)
|
|
75
|
+
return self._finalize(sample_1, sample_2, boot_data, effect, result_warnings)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@register
|
|
79
|
+
class PairedPoissonBootstrapTest(PoissonBootstrapTest):
|
|
80
|
+
"""Paired Poisson bootstrap: ONE weights stream applied to BOTH arms (catalogue).
|
|
81
|
+
|
|
82
|
+
Requires equal sample sizes; with ``stratify=True`` both arms must carry
|
|
83
|
+
elementwise-identical ``categories_array``, so one post-stratification
|
|
84
|
+
scale vector serves both arms.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
name = "paired-poisson-bootstrap"
|
|
88
|
+
is_paired = True
|
|
89
|
+
|
|
90
|
+
def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
|
|
91
|
+
require_pair_type(self.name, sample_1, sample_2, Sample)
|
|
92
|
+
self._validate_paired(sample_1, sample_2)
|
|
93
|
+
scale = None
|
|
94
|
+
if bool(self.params["stratify"]):
|
|
95
|
+
assert sample_1.categories_array is not None
|
|
96
|
+
scale = poisson_unit_scale(sample_1.categories_array)
|
|
97
|
+
rng = self._make_rng()
|
|
98
|
+
boot_1, boot_2 = poisson_bootstrap_means(
|
|
99
|
+
rng,
|
|
100
|
+
(sample_1.array, sample_2.array),
|
|
101
|
+
scale,
|
|
102
|
+
self._n_samples,
|
|
103
|
+
self._max_block_bytes,
|
|
104
|
+
)
|
|
105
|
+
boot_data = self._boot_effect(boot_1, boot_2)
|
|
106
|
+
result_warnings: list[str] = []
|
|
107
|
+
effect = self._point_effect(
|
|
108
|
+
stat_point(sample_1.array, self._stat),
|
|
109
|
+
stat_point(sample_2.array, self._stat),
|
|
110
|
+
result_warnings,
|
|
111
|
+
)
|
|
112
|
+
return self._finalize(sample_1, sample_2, boot_data, effect, result_warnings)
|