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,125 @@
|
|
|
1
|
+
"""``paired-cuped-t-test`` — CUPED for paired arms (catalogue "PairedCupedTTest").
|
|
2
|
+
|
|
3
|
+
Legacy parity, preserved verbatim with the mixed-ddof convention (baseline fact
|
|
4
|
+
#1): θ is estimated on the per-pair DIFFERENCES — ``np.cov`` parity numerator
|
|
5
|
+
(ddof=1) over ``np.var`` parity denominator (ddof=0) — and exposed in
|
|
6
|
+
``diagnostics["theta"]`` for the golden test. As in the independent CUPED test,
|
|
7
|
+
the relative denominator is the ORIGINAL control mean and per-arm ``value``/
|
|
8
|
+
``std`` report the ORIGINAL moments (CUPED lives in the effect). The legacy
|
|
9
|
+
paired variants compute no MDE.
|
|
10
|
+
|
|
11
|
+
All CUPED quantities are exact linear-combination reads of the joint moments
|
|
12
|
+
(``w(cup_d) = w(y2−y1) − θ·w(x2−x1)``), so the raw entry reduces to ONE
|
|
13
|
+
:class:`PairedSufficientStats` and delegates — dual entry by construction.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from abkit.stats.base import COVARIATE_LOOKBACK_PARAM, TEST_TYPE_PARAM
|
|
23
|
+
from abkit.stats.effects import EffectEstimate, normal_test, relative_delta_effect
|
|
24
|
+
from abkit.stats.exceptions import SampleValidationError
|
|
25
|
+
from abkit.stats.parametric.cuped_ttest import correlation_warning
|
|
26
|
+
from abkit.stats.parametric.paired_ttest import BasePairedMethod
|
|
27
|
+
from abkit.stats.registry import register
|
|
28
|
+
from abkit.stats.result import TestResult
|
|
29
|
+
from abkit.stats.samples import PAIRED_CUPED_LABELS, JointMoments, PairedSufficientStats
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _corr(moments: JointMoments, value_label: str, cov_label: str) -> float:
|
|
33
|
+
"""``np.corrcoef`` parity (scale-free — ddof cancels) between two series."""
|
|
34
|
+
i, j = moments.index(value_label), moments.index(cov_label)
|
|
35
|
+
denominator = math.sqrt(moments.comoment[i, i] * moments.comoment[j, j])
|
|
36
|
+
if denominator == 0.0:
|
|
37
|
+
return float("nan")
|
|
38
|
+
return float(moments.comoment[i, j] / denominator)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@register
|
|
42
|
+
class PairedCupedTTest(BasePairedMethod):
|
|
43
|
+
name = "paired-cuped-t-test"
|
|
44
|
+
requires_covariate = True
|
|
45
|
+
is_paired = True
|
|
46
|
+
param_specs = (TEST_TYPE_PARAM, COVARIATE_LOOKBACK_PARAM)
|
|
47
|
+
|
|
48
|
+
def from_suffstats(self, stats_1: PairedSufficientStats, stats_2: None = None) -> TestResult:
|
|
49
|
+
joint = self._as_joint(stats_1, stats_2)
|
|
50
|
+
if not joint.has_covariate:
|
|
51
|
+
raise SampleValidationError(
|
|
52
|
+
f"{self.name}: paired CUPED requires covariates on both arms "
|
|
53
|
+
f"(joint moments over {PAIRED_CUPED_LABELS})"
|
|
54
|
+
)
|
|
55
|
+
moments = joint.moments
|
|
56
|
+
n = joint.n
|
|
57
|
+
|
|
58
|
+
method_warnings: list[str] = []
|
|
59
|
+
for fallback, arm_name, labels in (
|
|
60
|
+
("group 1", joint.name_1, ("y1", "x1")),
|
|
61
|
+
("group 2", joint.name_2, ("y2", "x2")),
|
|
62
|
+
):
|
|
63
|
+
name = arm_name if arm_name is not None else fallback
|
|
64
|
+
message = correlation_warning(self.name, name, _corr(moments, *labels))
|
|
65
|
+
if message is not None:
|
|
66
|
+
method_warnings.append(message)
|
|
67
|
+
|
|
68
|
+
weights_diff_y = joint.weights(y2=1.0, y1=-1.0)
|
|
69
|
+
weights_diff_x = joint.weights(x2=1.0, x1=-1.0)
|
|
70
|
+
# θ on the per-pair DIFFERENCES with the EXACT mixed ddof (baseline fact #1):
|
|
71
|
+
# np.cov-parity numerator (ddof=1) over np.var-parity denominator (ddof=0).
|
|
72
|
+
theta_num = moments.linear_cov1(weights_diff_y, weights_diff_x)
|
|
73
|
+
theta_den = moments.linear_var0(weights_diff_x)
|
|
74
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
75
|
+
theta = float(np.float64(theta_num) / np.float64(theta_den))
|
|
76
|
+
if not math.isfinite(theta):
|
|
77
|
+
method_warnings.append(
|
|
78
|
+
f"{self.name}: theta is non-finite (zero covariate-difference variance); "
|
|
79
|
+
"returning NaN test outputs"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
weights_cup_diff = weights_diff_y - theta * weights_diff_x
|
|
83
|
+
difference_mean = moments.linear_mean(weights_cup_diff)
|
|
84
|
+
difference_mean_var = moments.linear_var0(weights_cup_diff) / n
|
|
85
|
+
|
|
86
|
+
if self.test_type == "absolute":
|
|
87
|
+
estimate = EffectEstimate(effect=difference_mean, var=difference_mean_var)
|
|
88
|
+
else:
|
|
89
|
+
weights_y1 = joint.weights(y1=1.0)
|
|
90
|
+
estimate = relative_delta_effect(
|
|
91
|
+
mean_num=difference_mean,
|
|
92
|
+
var_num=difference_mean_var,
|
|
93
|
+
mean_den=moments.linear_mean(weights_y1), # ORIGINAL control mean
|
|
94
|
+
var_den=moments.linear_var0(weights_y1) / n,
|
|
95
|
+
# np.cov parity (ddof=1): −cov(cup_2 − cup_1, y1)/n — baseline fact #1.
|
|
96
|
+
covariance=-moments.linear_cov1(weights_cup_diff, weights_y1) / n,
|
|
97
|
+
)
|
|
98
|
+
test = normal_test(estimate, self.alpha)
|
|
99
|
+
|
|
100
|
+
index_y1 = moments.index("y1")
|
|
101
|
+
index_y2 = moments.index("y2")
|
|
102
|
+
return TestResult(
|
|
103
|
+
name_1=joint.name_1,
|
|
104
|
+
name_2=joint.name_2,
|
|
105
|
+
value_1=float(moments.mean[index_y1]),
|
|
106
|
+
value_2=float(moments.mean[index_y2]),
|
|
107
|
+
std_1=math.sqrt(moments.var0(index_y1)),
|
|
108
|
+
std_2=math.sqrt(moments.var0(index_y2)),
|
|
109
|
+
size_1=n,
|
|
110
|
+
size_2=n,
|
|
111
|
+
cov_value_1=float(moments.mean[moments.index("x1")]),
|
|
112
|
+
cov_value_2=float(moments.mean[moments.index("x2")]),
|
|
113
|
+
method_name=self.name,
|
|
114
|
+
method_params=self.identity_params,
|
|
115
|
+
alpha=self.alpha,
|
|
116
|
+
pvalue=test.pvalue,
|
|
117
|
+
effect=test.effect,
|
|
118
|
+
ci_length=test.ci_length,
|
|
119
|
+
left_bound=test.left_bound,
|
|
120
|
+
right_bound=test.right_bound,
|
|
121
|
+
reject=test.reject,
|
|
122
|
+
effect_distribution=test.distribution,
|
|
123
|
+
warnings=[*method_warnings, *test.warnings],
|
|
124
|
+
diagnostics={"theta": theta},
|
|
125
|
+
)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""``paired-t-test`` — paired/dependent comparison (baseline §4.5, catalogue "PairedTTest").
|
|
2
|
+
|
|
3
|
+
Normal approximation on the paired mean difference — legacy parity, preserved
|
|
4
|
+
verbatim including the mixed-ddof convention (baseline fact #1): variance terms
|
|
5
|
+
are ``np.var`` parity (ddof=0) while the relative-branch covariance term is
|
|
6
|
+
``np.cov`` parity (ddof=1). The legacy paired t-test computes no MDE.
|
|
7
|
+
|
|
8
|
+
Paired sufficient statistics are joint by construction: ONE
|
|
9
|
+
:class:`PairedSufficientStats` holds the joint moments of both aligned arms, so
|
|
10
|
+
the sufficient-statistics entry takes a single object. The raw entry takes two
|
|
11
|
+
position-aligned equal-size samples and reduces to it — ONE math path, so dual
|
|
12
|
+
entry holds by construction (the ``ttest.py`` exemplar pattern).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
from abc import abstractmethod
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from abkit.stats.base import TEST_TYPE_PARAM, BaseMethod, require_pair_type
|
|
23
|
+
from abkit.stats.effects import EffectEstimate, normal_test, relative_delta_effect
|
|
24
|
+
from abkit.stats.exceptions import SampleValidationError
|
|
25
|
+
from abkit.stats.registry import register
|
|
26
|
+
from abkit.stats.result import TestResult
|
|
27
|
+
from abkit.stats.samples import PairedSufficientStats, Sample
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class BasePairedMethod(BaseMethod):
|
|
31
|
+
"""Shared input routing for paired designs (paired t-test, paired CUPED).
|
|
32
|
+
|
|
33
|
+
``compare_pair`` accepts either ``(Sample, Sample)`` — reduced through
|
|
34
|
+
``from_samples`` as usual — or a single :class:`PairedSufficientStats` as
|
|
35
|
+
``group_1`` with ``group_2=None`` (the joint moments already describe both
|
|
36
|
+
arms, so there is no second group to pass).
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def compare(self, groups: Sequence[Any]) -> list[TestResult]:
|
|
40
|
+
"""Paired suffstats entry: a sequence of PairedSufficientStats is a list of
|
|
41
|
+
ready comparisons (each joint object IS one variant pair), so the generic
|
|
42
|
+
pairwise combination step is skipped — the pipeline can drive paired
|
|
43
|
+
methods through the same ``compare()`` call as every other method."""
|
|
44
|
+
if groups and all(isinstance(group, PairedSufficientStats) for group in groups):
|
|
45
|
+
return [self.from_suffstats(joint) for joint in groups]
|
|
46
|
+
return super().compare(groups)
|
|
47
|
+
|
|
48
|
+
def compare_pair(self, group_1: Any, group_2: Any | None = None) -> TestResult:
|
|
49
|
+
if group_2 is None or isinstance(group_1, PairedSufficientStats):
|
|
50
|
+
return self.from_suffstats(group_1, group_2)
|
|
51
|
+
return super().compare_pair(group_1, group_2)
|
|
52
|
+
|
|
53
|
+
def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
|
|
54
|
+
require_pair_type(self.name, sample_1, sample_2, Sample)
|
|
55
|
+
return self.from_suffstats(PairedSufficientStats.from_samples(sample_1, sample_2))
|
|
56
|
+
|
|
57
|
+
@abstractmethod
|
|
58
|
+
def from_suffstats(self, stats_1: Any, stats_2: Any | None = None) -> TestResult:
|
|
59
|
+
"""Paired signature: ONE joint PairedSufficientStats (``stats_2`` stays None)."""
|
|
60
|
+
|
|
61
|
+
def _as_joint(self, stats_1: Any, stats_2: Any) -> PairedSufficientStats:
|
|
62
|
+
"""Validate the sufficient-statistics entry: one joint object, nothing else."""
|
|
63
|
+
if stats_2 is not None:
|
|
64
|
+
raise SampleValidationError(
|
|
65
|
+
f"{self.name}: paired sufficient statistics are joint by construction — pass a "
|
|
66
|
+
"single PairedSufficientStats as group_1 (with group_2=None), not one per arm"
|
|
67
|
+
)
|
|
68
|
+
if not isinstance(stats_1, PairedSufficientStats):
|
|
69
|
+
raise SampleValidationError(
|
|
70
|
+
f"{self.name}: sufficient-statistics entry requires a PairedSufficientStats, "
|
|
71
|
+
f"got {type(stats_1).__name__}"
|
|
72
|
+
)
|
|
73
|
+
return stats_1
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@register(aliases=("paired-ttest",))
|
|
77
|
+
class PairedTTest(BasePairedMethod):
|
|
78
|
+
name = "paired-t-test"
|
|
79
|
+
is_paired = True
|
|
80
|
+
param_specs = (TEST_TYPE_PARAM,)
|
|
81
|
+
|
|
82
|
+
def from_suffstats(self, stats_1: PairedSufficientStats, stats_2: None = None) -> TestResult:
|
|
83
|
+
joint = self._as_joint(stats_1, stats_2)
|
|
84
|
+
moments = joint.moments
|
|
85
|
+
n = joint.n
|
|
86
|
+
|
|
87
|
+
weights_y1 = joint.weights(y1=1.0)
|
|
88
|
+
weights_diff = joint.weights(y2=1.0, y1=-1.0)
|
|
89
|
+
mean_1 = moments.linear_mean(weights_y1)
|
|
90
|
+
difference_mean = moments.linear_mean(weights_diff)
|
|
91
|
+
# np.var parity (ddof=0): var of the per-pair differences over n (baseline §4.5).
|
|
92
|
+
difference_mean_var = moments.linear_var0(weights_diff) / n
|
|
93
|
+
|
|
94
|
+
if self.test_type == "absolute":
|
|
95
|
+
estimate = EffectEstimate(effect=difference_mean, var=difference_mean_var)
|
|
96
|
+
else:
|
|
97
|
+
estimate = relative_delta_effect(
|
|
98
|
+
mean_num=difference_mean,
|
|
99
|
+
var_num=difference_mean_var,
|
|
100
|
+
mean_den=mean_1,
|
|
101
|
+
var_den=moments.linear_var0(weights_y1) / n,
|
|
102
|
+
# np.cov parity (ddof=1): −cov(y2−y1, y1)/n — baseline fact #1.
|
|
103
|
+
covariance=-moments.linear_cov1(weights_diff, weights_y1) / n,
|
|
104
|
+
)
|
|
105
|
+
test = normal_test(estimate, self.alpha)
|
|
106
|
+
|
|
107
|
+
index_y1 = moments.index("y1")
|
|
108
|
+
index_y2 = moments.index("y2")
|
|
109
|
+
cov_value_1 = cov_value_2 = None
|
|
110
|
+
if joint.has_covariate:
|
|
111
|
+
cov_value_1 = float(moments.mean[moments.index("x1")])
|
|
112
|
+
cov_value_2 = float(moments.mean[moments.index("x2")])
|
|
113
|
+
|
|
114
|
+
return TestResult(
|
|
115
|
+
name_1=joint.name_1,
|
|
116
|
+
name_2=joint.name_2,
|
|
117
|
+
value_1=float(moments.mean[index_y1]),
|
|
118
|
+
value_2=float(moments.mean[index_y2]),
|
|
119
|
+
std_1=math.sqrt(moments.var0(index_y1)),
|
|
120
|
+
std_2=math.sqrt(moments.var0(index_y2)),
|
|
121
|
+
size_1=n,
|
|
122
|
+
size_2=n,
|
|
123
|
+
cov_value_1=cov_value_1,
|
|
124
|
+
cov_value_2=cov_value_2,
|
|
125
|
+
method_name=self.name,
|
|
126
|
+
method_params=self.identity_params,
|
|
127
|
+
alpha=self.alpha,
|
|
128
|
+
pvalue=test.pvalue,
|
|
129
|
+
effect=test.effect,
|
|
130
|
+
ci_length=test.ci_length,
|
|
131
|
+
left_bound=test.left_bound,
|
|
132
|
+
right_bound=test.right_bound,
|
|
133
|
+
reject=test.reject,
|
|
134
|
+
effect_distribution=test.distribution,
|
|
135
|
+
warnings=test.warnings,
|
|
136
|
+
)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""``ratio-delta`` — principled delta-method ratio-metric test (statistics-changes.md §4).
|
|
2
|
+
|
|
3
|
+
A NEW method with no legacy baseline, hence no mixed-ddof debt: every variance
|
|
4
|
+
term uses ``ddof=0`` uniformly. Per arm the estimand is ``R = mean(numerator) /
|
|
5
|
+
mean(denominator)``; the per-unit linearisation ``L_u = (N_u − R·D_u) /
|
|
6
|
+
mean_den`` gives
|
|
7
|
+
|
|
8
|
+
var0_L = (m2_num − 2·R·c_nd + R²·m2_den) / (n · mean_den²)
|
|
9
|
+
var(R̂) = var0_L / n
|
|
10
|
+
|
|
11
|
+
Absolute effect ``R₂ − R₁`` with variance ``var(R̂₁) + var(R̂₂)``; relative via
|
|
12
|
+
the shared delta-method with denominator ``R₁`` and covariance ``−var(R̂₁)``
|
|
13
|
+
(the arms are independent, so numerator and denominator share only ``R̂₁``).
|
|
14
|
+
|
|
15
|
+
KNOWN-ANSWER contract (quorum must-fix): with the denominator identically 1,
|
|
16
|
+
``mean_den = 1``, ``m2_den = c_nd = 0``, so ``R_i = mean_i`` and ``var0_L_i =
|
|
17
|
+
var0_i`` — the method reproduces the t-test EXACTLY, absolute AND relative.
|
|
18
|
+
|
|
19
|
+
Hygiene H5: a zero/non-finite denominator mean in either arm yields NaN outputs
|
|
20
|
+
plus a recorded warning, never an exception.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
|
|
27
|
+
from abkit.stats.base import TEST_TYPE_PARAM, BaseMethod, require_pair_type
|
|
28
|
+
from abkit.stats.effects import absolute_effect, normal_test, relative_delta_effect
|
|
29
|
+
from abkit.stats.registry import register
|
|
30
|
+
from abkit.stats.result import TestResult
|
|
31
|
+
from abkit.stats.samples import RatioSample, RatioSufficientStats
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _arm_linearisation(
|
|
35
|
+
stats: RatioSufficientStats, fallback_name: str
|
|
36
|
+
) -> tuple[float, float, list[str]]:
|
|
37
|
+
"""Per-arm ``(R, var0_L, warnings)`` — the ratio and its per-unit linearised variance."""
|
|
38
|
+
if stats.mean_den == 0.0 or not math.isfinite(stats.mean_den):
|
|
39
|
+
name = stats.name if stats.name is not None else fallback_name
|
|
40
|
+
nan = float("nan")
|
|
41
|
+
return (
|
|
42
|
+
nan,
|
|
43
|
+
nan,
|
|
44
|
+
[
|
|
45
|
+
f"ratio undefined for {name!r}: denominator mean is zero or non-finite; "
|
|
46
|
+
"returning NaN (see statistics-changes.md H5)"
|
|
47
|
+
],
|
|
48
|
+
)
|
|
49
|
+
ratio = stats.mean_num / stats.mean_den
|
|
50
|
+
# Non-negative in exact arithmetic (it is Σ((n_u−n̄) − R(d_u−d̄))²); clamp
|
|
51
|
+
# tiny negatives from float cancellation of the three separately-rounded terms.
|
|
52
|
+
quadratic = max(stats.m2_num - 2.0 * ratio * stats.c_nd + ratio**2 * stats.m2_den, 0.0)
|
|
53
|
+
var_unit = quadratic / (stats.n * stats.mean_den**2)
|
|
54
|
+
return ratio, var_unit, []
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@register
|
|
58
|
+
class RatioDelta(BaseMethod):
|
|
59
|
+
name = "ratio-delta"
|
|
60
|
+
input_kind = "ratio"
|
|
61
|
+
param_specs = (TEST_TYPE_PARAM,)
|
|
62
|
+
|
|
63
|
+
def from_samples(self, sample_1: RatioSample, sample_2: RatioSample) -> TestResult:
|
|
64
|
+
require_pair_type(self.name, sample_1, sample_2, RatioSample)
|
|
65
|
+
return self.from_suffstats(
|
|
66
|
+
RatioSufficientStats.from_ratio_sample(sample_1),
|
|
67
|
+
RatioSufficientStats.from_ratio_sample(sample_2),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def from_suffstats(
|
|
71
|
+
self, stats_1: RatioSufficientStats, stats_2: RatioSufficientStats
|
|
72
|
+
) -> TestResult:
|
|
73
|
+
require_pair_type(self.name, stats_1, stats_2, RatioSufficientStats)
|
|
74
|
+
|
|
75
|
+
ratio_1, var_unit_1, warnings_1 = _arm_linearisation(stats_1, "group 1")
|
|
76
|
+
ratio_2, var_unit_2, warnings_2 = _arm_linearisation(stats_2, "group 2")
|
|
77
|
+
method_warnings = [*warnings_1, *warnings_2]
|
|
78
|
+
var_ratio_1 = var_unit_1 / stats_1.n
|
|
79
|
+
var_ratio_2 = var_unit_2 / stats_2.n
|
|
80
|
+
|
|
81
|
+
if self.test_type == "absolute":
|
|
82
|
+
estimate = absolute_effect(ratio_1, ratio_2, var_ratio_1, var_ratio_2)
|
|
83
|
+
else:
|
|
84
|
+
estimate = relative_delta_effect(
|
|
85
|
+
mean_num=ratio_2 - ratio_1,
|
|
86
|
+
var_num=var_ratio_1 + var_ratio_2,
|
|
87
|
+
mean_den=ratio_1,
|
|
88
|
+
var_den=var_ratio_1,
|
|
89
|
+
covariance=-var_ratio_1, # independent arms: num & denom share only R̂1
|
|
90
|
+
)
|
|
91
|
+
test = normal_test(estimate, self.alpha)
|
|
92
|
+
|
|
93
|
+
return TestResult(
|
|
94
|
+
name_1=stats_1.name,
|
|
95
|
+
name_2=stats_2.name,
|
|
96
|
+
value_1=ratio_1,
|
|
97
|
+
value_2=ratio_2,
|
|
98
|
+
std_1=math.sqrt(var_unit_1), # per-unit linearised std
|
|
99
|
+
std_2=math.sqrt(var_unit_2),
|
|
100
|
+
size_1=stats_1.n,
|
|
101
|
+
size_2=stats_2.n,
|
|
102
|
+
method_name=self.name,
|
|
103
|
+
method_params=self.identity_params,
|
|
104
|
+
alpha=self.alpha,
|
|
105
|
+
pvalue=test.pvalue,
|
|
106
|
+
effect=test.effect,
|
|
107
|
+
ci_length=test.ci_length,
|
|
108
|
+
left_bound=test.left_bound,
|
|
109
|
+
right_bound=test.right_bound,
|
|
110
|
+
reject=test.reject,
|
|
111
|
+
effect_distribution=test.distribution,
|
|
112
|
+
warnings=[*method_warnings, *test.warnings],
|
|
113
|
+
)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""``t-test`` — independent two-sample comparison (baseline §3.1).
|
|
2
|
+
|
|
3
|
+
Despite the name, the statistic uses the NORMAL distribution on the mean
|
|
4
|
+
difference (a large-sample Welch-style z-test) — legacy parity, preserved
|
|
5
|
+
verbatim. Relative effects use the delta-method linearisation with the negative
|
|
6
|
+
covariance term ``−var_mean_1`` (numerator and denominator share ``mean_1``).
|
|
7
|
+
|
|
8
|
+
This class is the exemplar for every closed-form method: ``from_samples`` reduces
|
|
9
|
+
raw arrays to :class:`SufficientStats` and delegates to ``from_suffstats`` — ONE
|
|
10
|
+
math path, so the dual-entry equivalence holds by construction.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from abkit.stats.base import (
|
|
16
|
+
CALCULATE_MDE_PARAM,
|
|
17
|
+
POWER_PARAM,
|
|
18
|
+
TEST_TYPE_PARAM,
|
|
19
|
+
BaseMethod,
|
|
20
|
+
require_pair_type,
|
|
21
|
+
)
|
|
22
|
+
from abkit.stats.effects import absolute_effect, normal_test, relative_delta_effect
|
|
23
|
+
from abkit.stats.power import get_ttest_mde
|
|
24
|
+
from abkit.stats.registry import register
|
|
25
|
+
from abkit.stats.result import TestResult
|
|
26
|
+
from abkit.stats.samples import Sample, SufficientStats
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@register(aliases=("ttest",))
|
|
30
|
+
class TTest(BaseMethod):
|
|
31
|
+
name = "t-test"
|
|
32
|
+
param_specs = (TEST_TYPE_PARAM, CALCULATE_MDE_PARAM, POWER_PARAM)
|
|
33
|
+
|
|
34
|
+
def from_samples(self, sample_1: Sample, sample_2: Sample) -> TestResult:
|
|
35
|
+
require_pair_type(self.name, sample_1, sample_2, Sample)
|
|
36
|
+
return self.from_suffstats(
|
|
37
|
+
SufficientStats.from_sample(sample_1), SufficientStats.from_sample(sample_2)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def from_suffstats(self, stats_1: SufficientStats, stats_2: SufficientStats) -> TestResult:
|
|
41
|
+
require_pair_type(self.name, stats_1, stats_2, SufficientStats)
|
|
42
|
+
|
|
43
|
+
var_mean_1 = stats_1.var / stats_1.n
|
|
44
|
+
var_mean_2 = stats_2.var / stats_2.n
|
|
45
|
+
difference_mean = stats_2.mean - stats_1.mean
|
|
46
|
+
difference_mean_var = var_mean_1 + var_mean_2
|
|
47
|
+
|
|
48
|
+
if self.test_type == "absolute":
|
|
49
|
+
estimate = absolute_effect(stats_1.mean, stats_2.mean, var_mean_1, var_mean_2)
|
|
50
|
+
else:
|
|
51
|
+
estimate = relative_delta_effect(
|
|
52
|
+
mean_num=difference_mean,
|
|
53
|
+
var_num=difference_mean_var,
|
|
54
|
+
mean_den=stats_1.mean,
|
|
55
|
+
var_den=var_mean_1,
|
|
56
|
+
covariance=-var_mean_1, # num & denom share mean_1 (baseline §3.1)
|
|
57
|
+
)
|
|
58
|
+
test = normal_test(estimate, self.alpha)
|
|
59
|
+
|
|
60
|
+
mde_1 = mde_2 = None
|
|
61
|
+
if self.params["calculate_mde"]:
|
|
62
|
+
mde_1 = get_ttest_mde(
|
|
63
|
+
stats_1.mean,
|
|
64
|
+
stats_1.std,
|
|
65
|
+
stats_1.n,
|
|
66
|
+
test_type=self.test_type,
|
|
67
|
+
alpha=self.alpha,
|
|
68
|
+
power=self.params["power"],
|
|
69
|
+
ratio=stats_2.n / stats_1.n,
|
|
70
|
+
)
|
|
71
|
+
mde_2 = get_ttest_mde(
|
|
72
|
+
stats_2.mean,
|
|
73
|
+
stats_2.std,
|
|
74
|
+
stats_2.n,
|
|
75
|
+
test_type=self.test_type,
|
|
76
|
+
alpha=self.alpha,
|
|
77
|
+
power=self.params["power"],
|
|
78
|
+
ratio=stats_1.n / stats_2.n,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return TestResult(
|
|
82
|
+
name_1=stats_1.name,
|
|
83
|
+
name_2=stats_2.name,
|
|
84
|
+
value_1=stats_1.mean,
|
|
85
|
+
value_2=stats_2.mean,
|
|
86
|
+
std_1=stats_1.std,
|
|
87
|
+
std_2=stats_2.std,
|
|
88
|
+
size_1=stats_1.n,
|
|
89
|
+
size_2=stats_2.n,
|
|
90
|
+
cov_value_1=stats_1.cov_mean,
|
|
91
|
+
cov_value_2=stats_2.cov_mean,
|
|
92
|
+
mde_1=mde_1,
|
|
93
|
+
mde_2=mde_2,
|
|
94
|
+
method_name=self.name,
|
|
95
|
+
method_params=self.identity_params,
|
|
96
|
+
alpha=self.alpha,
|
|
97
|
+
pvalue=test.pvalue,
|
|
98
|
+
effect=test.effect,
|
|
99
|
+
ci_length=test.ci_length,
|
|
100
|
+
left_bound=test.left_bound,
|
|
101
|
+
right_bound=test.right_bound,
|
|
102
|
+
reject=test.reject,
|
|
103
|
+
effect_distribution=test.distribution,
|
|
104
|
+
warnings=test.warnings,
|
|
105
|
+
)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""``z-test`` — two-proportion pooled z-test (baseline §3.2, catalogue "ZTest").
|
|
2
|
+
|
|
3
|
+
Reproduced verbatim, INCLUDING two documented legacy quirks (flagged in
|
|
4
|
+
docs/specs/statistics-changes.md §3 — never fixed silently):
|
|
5
|
+
|
|
6
|
+
- sign quirk: the z statistic uses ``prop_1 − prop_2`` while the reported effect
|
|
7
|
+
uses ``prop_2 − prop_1``. The p-value is symmetric (``2·min(cdf, sf)``) so it
|
|
8
|
+
is unaffected, but the orientations deliberately differ (legacy parity).
|
|
9
|
+
- relative branch: ``std_effect`` is naively divided by ``prop_1`` — there is NO
|
|
10
|
+
delta-method covariance term (unlike the t-test family). A delta-consistent
|
|
11
|
+
relative z-test is a possible v2 version bump if the A/A matrix shows
|
|
12
|
+
under-coverage.
|
|
13
|
+
|
|
14
|
+
:class:`Fraction` inputs ARE the sufficient statistics (count/nobs), so
|
|
15
|
+
``from_samples`` simply delegates to ``from_suffstats`` — one math path.
|
|
16
|
+
Hygiene H5: a zero control proportion under ``relative`` (and a degenerate
|
|
17
|
+
pooled proportion of 0 or 1) yields NaN outputs plus a recorded warning, never
|
|
18
|
+
an exception.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import math
|
|
24
|
+
|
|
25
|
+
import scipy.stats as sps
|
|
26
|
+
|
|
27
|
+
from abkit.stats.base import (
|
|
28
|
+
CALCULATE_MDE_PARAM,
|
|
29
|
+
POWER_PARAM,
|
|
30
|
+
TEST_TYPE_PARAM,
|
|
31
|
+
BaseMethod,
|
|
32
|
+
require_pair_type,
|
|
33
|
+
)
|
|
34
|
+
from abkit.stats.power import get_fraction_mde
|
|
35
|
+
from abkit.stats.registry import register
|
|
36
|
+
from abkit.stats.result import TestResult
|
|
37
|
+
from abkit.stats.samples import Fraction
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@register(aliases=("ztest",))
|
|
41
|
+
class ZTest(BaseMethod):
|
|
42
|
+
name = "z-test"
|
|
43
|
+
input_kind = "fraction"
|
|
44
|
+
param_specs = (TEST_TYPE_PARAM, CALCULATE_MDE_PARAM, POWER_PARAM)
|
|
45
|
+
|
|
46
|
+
def from_samples(self, sample_1: Fraction, sample_2: Fraction) -> TestResult:
|
|
47
|
+
return self.from_suffstats(sample_1, sample_2)
|
|
48
|
+
|
|
49
|
+
def from_suffstats(self, stats_1: Fraction, stats_2: Fraction) -> TestResult:
|
|
50
|
+
require_pair_type(self.name, stats_1, stats_2, Fraction)
|
|
51
|
+
result_warnings: list[str] = []
|
|
52
|
+
nan = float("nan")
|
|
53
|
+
|
|
54
|
+
prop_1, prop_2 = stats_1.prop, stats_2.prop
|
|
55
|
+
nobs_1, nobs_2 = stats_1.nobs, stats_2.nobs
|
|
56
|
+
prop_combined = (stats_1.count + stats_2.count) / (nobs_1 + nobs_2)
|
|
57
|
+
pooled_var = prop_combined * (1.0 - prop_combined) * (1.0 / nobs_1 + 1.0 / nobs_2)
|
|
58
|
+
std_effect = math.sqrt(pooled_var)
|
|
59
|
+
|
|
60
|
+
if std_effect > 0.0 and math.isfinite(std_effect):
|
|
61
|
+
# Legacy sign quirk kept verbatim: z uses prop_1 − prop_2, effect prop_2 − prop_1.
|
|
62
|
+
z_stat = (prop_1 - prop_2) / std_effect
|
|
63
|
+
pvalue = float(2.0 * min(sps.norm.cdf(z_stat), sps.norm.sf(z_stat)))
|
|
64
|
+
else:
|
|
65
|
+
result_warnings.append(
|
|
66
|
+
"pooled proportion variance is zero (pooled proportion is 0 or 1); "
|
|
67
|
+
"returning NaN test outputs"
|
|
68
|
+
)
|
|
69
|
+
pvalue = nan
|
|
70
|
+
|
|
71
|
+
effect = prop_2 - prop_1
|
|
72
|
+
if self.test_type == "relative":
|
|
73
|
+
if prop_1 == 0.0 or not math.isfinite(prop_1):
|
|
74
|
+
result_warnings.append(
|
|
75
|
+
"relative effect undefined: control proportion is zero or non-finite; "
|
|
76
|
+
"returning NaN (see statistics-changes.md H5)"
|
|
77
|
+
)
|
|
78
|
+
effect = std_effect = pvalue = nan
|
|
79
|
+
else:
|
|
80
|
+
effect /= prop_1
|
|
81
|
+
std_effect /= prop_1
|
|
82
|
+
|
|
83
|
+
if math.isfinite(effect) and math.isfinite(std_effect) and std_effect > 0.0:
|
|
84
|
+
distribution = sps.norm(effect, std_effect)
|
|
85
|
+
quantiles = sps.norm.ppf([self.alpha / 2.0, 1.0 - self.alpha / 2.0])
|
|
86
|
+
left_bound = float(quantiles[0] * std_effect + effect)
|
|
87
|
+
right_bound = float(quantiles[1] * std_effect + effect)
|
|
88
|
+
ci_length = right_bound - left_bound
|
|
89
|
+
else:
|
|
90
|
+
distribution = None
|
|
91
|
+
left_bound = right_bound = ci_length = nan
|
|
92
|
+
|
|
93
|
+
mde_1 = mde_2 = None
|
|
94
|
+
if self.params["calculate_mde"]:
|
|
95
|
+
mde_1 = get_fraction_mde(
|
|
96
|
+
prop_1,
|
|
97
|
+
stats_1.sample_size,
|
|
98
|
+
test_type=self.test_type,
|
|
99
|
+
alpha=self.alpha,
|
|
100
|
+
power=self.params["power"],
|
|
101
|
+
ratio=nobs_2 / nobs_1,
|
|
102
|
+
)
|
|
103
|
+
mde_2 = get_fraction_mde(
|
|
104
|
+
prop_2,
|
|
105
|
+
stats_2.sample_size,
|
|
106
|
+
test_type=self.test_type,
|
|
107
|
+
alpha=self.alpha,
|
|
108
|
+
power=self.params["power"],
|
|
109
|
+
ratio=nobs_1 / nobs_2,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
return TestResult(
|
|
113
|
+
name_1=stats_1.name,
|
|
114
|
+
name_2=stats_2.name,
|
|
115
|
+
value_1=prop_1,
|
|
116
|
+
value_2=prop_2,
|
|
117
|
+
std_1=stats_1.std,
|
|
118
|
+
std_2=stats_2.std,
|
|
119
|
+
size_1=stats_1.sample_size,
|
|
120
|
+
size_2=stats_2.sample_size,
|
|
121
|
+
mde_1=mde_1,
|
|
122
|
+
mde_2=mde_2,
|
|
123
|
+
method_name=self.name,
|
|
124
|
+
method_params=self.identity_params,
|
|
125
|
+
alpha=self.alpha,
|
|
126
|
+
pvalue=pvalue,
|
|
127
|
+
effect=effect,
|
|
128
|
+
ci_length=ci_length,
|
|
129
|
+
left_bound=left_bound,
|
|
130
|
+
right_bound=right_bound,
|
|
131
|
+
reject=bool(pvalue < self.alpha),
|
|
132
|
+
effect_distribution=distribution,
|
|
133
|
+
warnings=result_warnings,
|
|
134
|
+
)
|