Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(experiments): delete unreachable code from the stats module (#100801)

Andersc7a99db36f33
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 4d334e24d5f3..ba8b30b6df65 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -125,9 +125,6 @@
1 products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py
1 products/experiments/backend/hogql_queries/metric_source.py
1 products/experiments/backend/running_time_calculator.py
-1 products/experiments/stats/bayesian/method.py
-1 products/experiments/stats/bayesian/priors.py
-1 products/experiments/stats/bayesian/tests.py
1 products/experiments/stats/frequentist/method.py
1 products/experiments/stats/frequentist/tests.py
1 products/exports/backend/models/subscription.py
diff --git a/products/experiments/backend/hogql_queries/README.md b/products/experiments/backend/hogql_queries/README.md
index e58d9e116bbf..f1f08ce443ec 100644
--- a/products/experiments/backend/hogql_queries/README.md
+++ b/products/experiments/backend/hogql_queries/README.md
@@ -116,8 +116,7 @@ The `stats_config` field is a JSON object with method-specific keys:
{
"bayesian": {
"ci_level": 0.95,
- "difference_type": "RELATIVE",
- "prior_type": "RELATIVE"
+ "difference_type": "RELATIVE"
},
"frequentist": {
"alpha": 0.05,
@@ -132,9 +131,6 @@ The `stats_config` field is a JSON object with method-specific keys:
- **`difference_type`** (string, default: "RELATIVE"): Type of difference calculation
- `"RELATIVE"`: Percentage change from baseline
- `"ABSOLUTE"`: Absolute difference from baseline
-- **`prior_type`** (string, default: "RELATIVE"): Type of prior to use
- - `"RELATIVE"`: Prior relative to baseline
- - `"ABSOLUTE"`: Absolute prior
### Frequentist parameters
diff --git a/products/experiments/backend/hogql_queries/utils.py b/products/experiments/backend/hogql_queries/utils.py
index 5896cfc8a27c..909aaf56a669 100644
--- a/products/experiments/backend/hogql_queries/utils.py
+++ b/products/experiments/backend/hogql_queries/utils.py
@@ -30,7 +30,6 @@ from posthog.models import Team, User
from products.experiments.backend.hogql_queries import CONTROL_VARIANT_KEY
from products.experiments.backend.hogql_queries.cuped_config import CupedQueryConfig, get_cuped_config
-from products.experiments.stats.bayesian.enums import PriorType
from products.experiments.stats.bayesian.method import BayesianConfig, BayesianMethod
from products.experiments.stats.frequentist.method import (
DEFAULT_SEQUENTIAL_TUNING_PARAMETER,
@@ -626,7 +625,6 @@ def get_bayesian_experiment_result(
difference_type=_parse_enum_config(
bayesian_config.get("difference_type", "RELATIVE"), DifferenceType, DifferenceType.RELATIVE
),
- prior_type=_parse_enum_config(bayesian_config.get("prior_type", "RELATIVE"), PriorType, PriorType.RELATIVE),
)
method = BayesianMethod(config)
diff --git a/products/experiments/stats/bayesian/enums.py b/products/experiments/stats/bayesian/enums.py
deleted file mode 100644
index 5fb88763edd4..000000000000
--- a/products/experiments/stats/bayesian/enums.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""
-Enumeration types for the Bayesian stats module.
-"""
-
-from enum import Enum
-
-
-class PriorType(Enum):
- """Types of prior distributions for effect sizes."""
-
- RELATIVE = "relative"
- ABSOLUTE = "absolute"
diff --git a/products/experiments/stats/bayesian/method.py b/products/experiments/stats/bayesian/method.py
index 6ec675377f82..b0c5389985a9 100644
--- a/products/experiments/stats/bayesian/method.py
+++ b/products/experiments/stats/bayesian/method.py
@@ -7,16 +7,15 @@ and difference types.
"""
from dataclasses import dataclass
-from typing import Any, Optional
+from typing import Optional
from ..shared.enums import DifferenceType
from ..shared.statistics import ProportionStatistic, RatioStatistic, SampleMeanStatistic, StatisticError
-from .enums import PriorType
from .priors import GaussianPrior
from .tests import BayesianGaussianTest, BayesianMeanTest, BayesianProportionTest, BayesianResult, BayesianTest
-@dataclass
+@dataclass(frozen=True)
class BayesianConfig:
"""Configuration for Bayesian testing."""
@@ -26,7 +25,6 @@ class BayesianConfig:
difference_type: DifferenceType = DifferenceType.RELATIVE
# Prior configuration
- prior_type: PriorType = PriorType.RELATIVE
prior_mean: float = 0.0 # Prior belief about effect size
prior_variance: float = 1.0 # Uncertainty in prior belief
proper_prior: bool = False # Whether to use informative prior
@@ -154,125 +152,3 @@ class BayesianMethod:
)
except Exception as e:
raise StatisticError(f"Bayesian test execution failed: {str(e)}") from e
-
- def get_summary(self, result: BayesianResult) -> dict[str, Any]:
- """
- Get human-readable summary of Bayesian test result.
-
- Args:
- result: BayesianResult object
-
- Returns:
- Dict with summary information
- """
- summary: dict[str, Any] = {
- "preferred_variation": result.preferred_variation,
- "chance_to_win": result.chance_to_win,
- "confidence_in_decision": result.confidence_in_decision,
- "effect_size": result.effect_size,
- "credible_interval": result.credible_interval,
- "is_decisive": result.is_decisive,
- "difference_type": result.difference_type,
- "ci_level": result.ci_level,
- }
-
- # Add effect size interpretation
- if "relative" in result.difference_type:
- summary["interpretation"] = {
- "effect_size": f"{result.effect_size:.1%}",
- "effect_direction": "positive" if result.effect_size > 0 else "negative",
- "magnitude": self._interpret_effect_magnitude(abs(result.effect_size)),
- }
- else: # absolute
- summary["interpretation"] = {
- "effect_size": result.effect_size,
- "effect_direction": "positive" if result.effect_size > 0 else "negative",
- }
-
- # Add risk assessment
- summary["risk_assessment"] = {
- "risk_choosing_control": result.risk_control,
- "risk_choosing_treatment": result.risk_treatment,
- "safer_choice": "control" if result.risk_control < result.risk_treatment else "treatment",
- }
-
- # Add prior information
- summary["prior_info"] = {
- "prior_mean": result.prior_mean,
- "prior_variance": result.prior_variance,
- "informative_prior": result.proper_prior,
- }
-
- # Add decision recommendation
- summary["recommendation"] = self._make_recommendation(result)
-
- return summary
-
- def _interpret_effect_magnitude(self, abs_effect: float) -> str:
- """Interpret the magnitude of a relative effect size."""
- if abs_effect < 0.01:
- return "negligible"
- elif abs_effect < 0.05:
- return "small"
- elif abs_effect < 0.15:
- return "moderate"
- elif abs_effect < 0.30:
- return "large"
- else:
- return "very_large"
-
- def _make_recommendation(self, result: BayesianResult) -> str:
- """Make a business recommendation based on the test result."""
- chance_to_win = result.chance_to_win
- preferred_variation = result.preferred_variation
-
- if chance_to_win > 0.95:
- return f"Strong evidence for {preferred_variation}. Safe to proceed."
- elif chance_to_win > 0.85:
- return f"Good evidence for {preferred_variation}. Consider proceeding with monitoring."
- elif chance_to_win > 0.65:
- return f"Weak evidence for {preferred_variation}. Consider collecting more data."
- else:
- return "Inconclusive evidence. Collect more data before making a decision."
-
- @classmethod
- def create_simple_config(
- cls,
- ci_level: float = 0.95,
- inverse: bool = False,
- difference_type: str = "relative",
- prior_mean: float = 0.0,
- prior_variance: float = 1.0,
- proper_prior: bool = False,
- ) -> BayesianConfig:
- """
- Create a simple configuration with basic parameters.
-
- Args:
- ci_level: Credible interval level (default: 0.95 for 95% CI)
- inverse: Whether "lower is better" (default: False)
- difference_type: Difference type string (default: "relative")
- prior_mean: Prior belief about effect size (default: 0.0)
- prior_variance: Prior uncertainty (default: 1.0)
- proper_prior: Whether to use informative prior (default: False)
-
- Returns:
- BayesianConfig object
- """
- # Convert string difference type
- difference_type_map = {
- "relative": DifferenceType.RELATIVE,
- "absolute": DifferenceType.ABSOLUTE,
- }
-
- if difference_type not in difference_type_map:
- raise StatisticError(f"Unknown difference type: {difference_type}")
-
- return BayesianConfig(
- ci_level=ci_level,
- inverse=inverse,
- difference_type=difference_type_map[difference_type],
- prior_mean=prior_mean,
- prior_variance=prior_variance,
- proper_prior=proper_prior,
- )
diff --git a/products/experiments/stats/bayesian/priors.py b/products/experiments/stats/bayesian/priors.py
index 0c4a77ee45a2..d70e9fd10357 100644
--- a/products/experiments/stats/bayesian/priors.py
+++ b/products/experiments/stats/bayesian/priors.py
@@ -8,7 +8,7 @@ focusing on Gaussian priors for effect sizes.
from dataclasses import dataclass
-@dataclass
+@dataclass(frozen=True)
class GaussianPrior:
"""
Gaussian prior distribution for effect sizes.
@@ -47,28 +47,6 @@ class GaussianPrior:
"""
return self.proper
- def make_informative(self, mean: float, variance: float) -> "GaussianPrior":
- """
- Create a new informative prior with specified parameters.
-
- Args:
- mean: Prior mean for effect size
- variance: Prior variance (uncertainty)
-
- Returns:
- New GaussianPrior instance with proper=True
- """
- return GaussianPrior(mean=mean, variance=variance, proper=True)
-
- def make_noninformative(self) -> "GaussianPrior":
- """
- Create a new non-informative prior.
-
- Returns:
- New GaussianPrior instance with proper=False
- """
- return GaussianPrior(mean=0.0, variance=1.0, proper=False)
-
def __str__(self) -> str:
"""String representation of the prior."""
if not self.is_proper():
diff --git a/products/experiments/stats/bayesian/tests.py b/products/experiments/stats/bayesian/tests.py
index 08b31789f434..0118e3a22f21 100644
--- a/products/experiments/stats/bayesian/tests.py
+++ b/products/experiments/stats/bayesian/tests.py
@@ -2,8 +2,7 @@
Bayesian test implementations for A/B testing.
This module provides Bayesian statistical test implementations that
-output probabilistic results including chance to win, credible intervals,
-and risk assessments.
+output probabilistic results including chance to win and credible intervals.
"""
from abc import ABC, abstractmethod
@@ -17,14 +16,13 @@ from .priors import GaussianPrior
from .utils import (
calculate_effect_size_and_variance,
calculate_posterior,
- calculate_risk,
chance_to_win,
credible_interval,
validate_inputs,
)
-@dataclass
+@dataclass(frozen=False) # BayesianMeanTest and BayesianProportionTest rewrite difference_type
class BayesianResult:
"""
Result of a Bayesian statistical test.
@@ -39,10 +37,6 @@ class BayesianResult:
# Probabilities
chance_to_win: float # P(treatment > control | data)
- # Risk assessment
- risk_control: float # Expected loss if we choose control
- risk_treatment: float # Expected loss if we choose treatment
-
# Posterior distribution parameters
posterior_variance: float # Variance of posterior distribution
@@ -66,19 +60,6 @@ class BayesianResult:
"""Whether result shows clear preference (chance to win > ci_level or < 1 - ci_level)."""
return self.chance_to_win > self.ci_level or self.chance_to_win < 1 - self.ci_level
- @property
- def preferred_variation(self) -> str:
- """Which variation is preferred based on chance to win."""
- if self.chance_to_win > 0.5:
- return "treatment"
- else:
- return "control"
-
- @property
- def confidence_in_decision(self) -> float:
- """Confidence in the preferred variation."""
- return max(self.chance_to_win, 1 - self.chance_to_win)
-
class BayesianTest(ABC):
"""Abstract base class for Bayesian statistical tests."""
@@ -195,15 +176,10 @@ class BayesianGaussianTest(BayesianTest):
alpha = 1 - self.ci_level
ci_lower, ci_upper = credible_interval(posterior_mean, posterior_std, alpha)
- # Risk assessment
- risk_control, risk_treatment = calculate_risk(posterior_mean, posterior_std)
-
return BayesianResult(
effect_size=posterior_mean,
credible_interval=(ci_lower, ci_upper),
chance_to_win=chance_win,
- risk_control=risk_control,
- risk_treatment=risk_treatment,
posterior_variance=posterior_variance,
ci_level=self.ci_level,
difference_type=difference_type.value,
diff --git a/products/experiments/stats/bayesian/utils.py b/products/experiments/stats/bayesian/utils.py
index 6cfdb6991a5c..854bc2156884 100644
--- a/products/experiments/stats/bayesian/utils.py
+++ b/products/experiments/stats/bayesian/utils.py
@@ -2,11 +2,10 @@
Core Bayesian calculation utilities for A/B testing.
This module provides fundamental Bayesian statistical calculations including
-posterior updates, credible intervals, probability calculations, and risk assessment.
+posterior updates, credible intervals, and probability calculations.
"""
-import numpy as np
-from scipy.stats import norm, truncnorm
+from scipy.stats import norm
from ..shared.enums import DifferenceType
from ..shared.statistics import ProportionStatistic, RatioStatistic, SampleMeanStatistic, StatisticError
@@ -202,81 +201,6 @@ def credible_interval(posterior_mean: float, posterior_std: float, alpha: float
return (float(bounds[0]), float(bounds[1]))
-def calculate_risk(posterior_mean: float, posterior_std: float) -> tuple[float, float]:
- """
- Calculate expected loss (risk) for each decision.
-
- Risk represents the expected loss if we make the wrong decision:
- - Risk of choosing control: E[θ | θ > 0] x P(θ > 0)
- - Risk of choosing treatment: E[|θ|] x P(θ < 0)
-
- Args:
- posterior_mean: Posterior mean of effect size
- posterior_std: Posterior standard deviation
-
- Returns:
- Tuple of (risk_control, risk_treatment)
- """
- if posterior_std <= 0:
- raise StatisticError("Posterior standard deviation must be positive")
-
- # Probability that control is better (effect < 0)
- prob_control_better = norm.cdf(0, loc=posterior_mean, scale=posterior_std)
-
- # Probability that treatment is better (effect > 0)
- prob_treatment_better = 1 - prob_control_better
-
- # Expected effect given treatment is better (truncated normal mean for θ > 0)
- if prob_treatment_better > 1e-10:
- expected_effect_positive = truncated_normal_mean(posterior_mean, posterior_std, 0, np.inf)
- else:
- expected_effect_positive = 0
-
- # Expected absolute effect given control is better (truncated normal mean for θ < 0)
- if prob_control_better > 1e-10:
- expected_effect_negative = abs(truncated_normal_mean(posterior_mean, posterior_std, -np.inf, 0))
- else:
- expected_effect_negative = 0
-
- # Risk calculations
- risk_control = prob_treatment_better * expected_effect_positive
- risk_treatment = prob_control_better * expected_effect_negative
-
- return float(risk_control), float(risk_treatment)
-
-
-def truncated_normal_mean(mu: float, sigma: float, lower_bound: float, upper_bound: float) -> float:
- """
- Calculate expected value of truncated normal distribution.
-
- For X ~ N(μ, σ²) truncated to [a, b], computes E[X | a ≤ X ≤ b].
-
- Args:
- mu: Original normal distribution mean
- sigma: Original normal distribution standard deviation
- lower_bound: Lower truncation bound (-np.inf for no lower bound)
- upper_bound: Upper truncation bound (np.inf for no upper bound)
-
- Returns:
- Expected value of truncated distribution
- """
- if sigma <= 0:
- raise StatisticError("Standard deviation must be positive")
-
- # Standardize bounds
- lower_std = (lower_bound - mu) / sigma if not np.isinf(lower_bound) else lower_bound
- upper_std = (upper_bound - mu) / sigma if not np.isinf(upper_bound) else upper_bound
-
- # Use scipy's truncated normal
- try:
- return float(truncnorm.mean(lower_std, upper_std, loc=mu, scale=sigma))
- except Exception as e:
- # Handle numerical issues
- if np.isfinite(lower_bound) and np.isfinite(upper_bound):
- return mu # Fallback to original mean
- raise StatisticError(f"Failed to calculate truncated normal mean: {e}")
-
-
def validate_inputs(
treatment_stat: SampleMeanStatistic | ProportionStatistic | RatioStatistic,
control_stat: SampleMeanStatistic | ProportionStatistic | RatioStatistic,
diff --git a/products/experiments/stats/frequentist/method.py b/products/experiments/stats/frequentist/method.py
index 7e6cd1666f82..2879f143a4f0 100644
--- a/products/experiments/stats/frequentist/method.py
+++ b/products/experiments/stats/frequentist/method.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from enum import Enum
-from typing import Any, Optional
+from typing import Optional
from ..shared.enums import DifferenceType
from ..shared.statistics import AnyStatistic, StatisticError
@@ -100,37 +100,3 @@ class FrequentistMethod:
)
except Exception as e:
raise StatisticError(f"Test execution failed: {str(e)}") from e
-
- def get_summary(self, result: TestResult) -> dict[str, Any]:
- """
- Get human-readable summary of test result.
-
- Args:
- result: TestResult object
-
- Returns:
- Dict with summary information
- """
- summary: dict[str, Any] = {
- "test_type": result.test_type,
- "point_estimate": result.point_estimate,
- "confidence_interval": result.confidence_interval,
- "p_value": result.p_value,
- "is_significant": result.is_significant,
- "alpha": result.alpha,
- "degrees_of_freedom": result.degrees_of_freedom,
- }
-
- # Add interpretation
- if self.config.difference_type == DifferenceType.RELATIVE:
- summary["interpretation"] = {
- "effect_size": f"{result.point_estimate:.1%}",
- "effect_direction": "positive" if result.point_estimate > 0 else "negative",
- }
- elif self.config.difference_type == DifferenceType.ABSOLUTE:
- summary["interpretation"] = {
- "effect_size": result.point_estimate,
- "effect_direction": "positive" if result.point_estimate > 0 else "negative",
- }
-
- return summary
diff --git a/products/experiments/stats/frequentist/utils.py b/products/experiments/stats/frequentist/utils.py
index c9e5d49cca1f..458d81e49ed7 100644
--- a/products/experiments/stats/frequentist/utils.py
+++ b/products/experiments/stats/frequentist/utils.py
@@ -4,7 +4,7 @@ from scipy import stats
from products.experiments.stats.shared.enums import DifferenceType
from products.experiments.stats.shared.utils import get_mean, get_sample_size, get_variance
-from ..shared.statistics import AnyStatistic, ProportionStatistic, StatisticError
+from ..shared.statistics import AnyStatistic, StatisticError
def calculate_point_estimate(
@@ -160,17 +160,13 @@ def calculate_p_value(t_statistic: float, degrees_of_freedom: float, test_type:
Args:
t_statistic: Calculated t-statistic
degrees_of_freedom: Degrees of freedom
- test_type: Type of test ("two_sided", "greater", "less")
+ test_type: Type of test (only "two_sided" is supported)
Returns:
P-value
"""
if test_type == "two_sided":
return float(2 * (1 - stats.t.cdf(abs(t_statistic), degrees_of_freedom)))
- elif test_type == "greater":
- return float(1 - stats.t.cdf(t_statistic, degrees_of_freedom))
- elif test_type == "less":
- return float(stats.t.cdf(t_statistic, degrees_of_freedom))
else:
raise StatisticError(f"Unknown test type: {test_type}")
@@ -348,25 +344,3 @@ def sequential_p_value(
if log_evalue <= 0:
return 1.0
return float(min(np.exp(-log_evalue), 1.0))
-
-
-def check_normal_approximation_validity(statistic: AnyStatistic) -> bool:
- """
- Check if normal approximation is valid for the given statistic.
-
- For proportions: requires np > 5 and n(1-p) > 5
- For other statistics: requires n >= 30 (rule of thumb)
-
- Args:
- statistic: Statistic to check
-
- Returns:
- True if normal approximation is likely valid
- """
- n = get_sample_size(statistic)
-
- if isinstance(statistic, ProportionStatistic):
- p = statistic.proportion
- return n * p >= 5 and n * (1 - p) >= 5
- else:
- return n >= 30
diff --git a/products/experiments/stats/shared/enums.py b/products/experiments/stats/shared/enums.py
index 000034ba8237..fc88d806331e 100644
--- a/products/experiments/stats/shared/enums.py
+++ b/products/experiments/stats/shared/enums.py
@@ -12,9 +12,3 @@ class DifferenceType(Enum):
RELATIVE = "relative"
ABSOLUTE = "absolute"
-
-
-class TestType(Enum):
- """Available test types."""
-
- TWO_SIDED = "two_sided"
diff --git a/products/experiments/stats/shared/utils.py b/products/experiments/stats/shared/utils.py
index cbc4bb33d5d4..e661024faabb 100644
--- a/products/experiments/stats/shared/utils.py
+++ b/products/experiments/stats/shared/utils.py
@@ -110,38 +110,13 @@ def _validate_proportion(stat: ProportionStatistic) -> list[str]:
return errors
-def check_sample_size_adequacy(treatment_stat: AnyStatistic, control_stat: AnyStatistic, min_size: int = 30) -> None:
- """
- Check if sample sizes are adequate for statistical testing.
-
- Args:
- treatment_stat: Treatment group statistic
- control_stat: Control group statistic
- min_size: Minimum required sample size
-
- Raises:
- StatisticError: If sample sizes are too small
- """
- treatment_n = get_sample_size(treatment_stat)
- control_n = get_sample_size(control_stat)
-
- if treatment_n < min_size:
- raise StatisticError(f"Treatment sample size ({treatment_n}) below minimum ({min_size})")
-
- if control_n < min_size:
- raise StatisticError(f"Control sample size ({control_n}) below minimum ({min_size})")
-
-
-def validate_test_inputs(
- treatment_stat: AnyStatistic, control_stat: AnyStatistic, check_sample_size: bool = False
-) -> None:
+def validate_test_inputs(treatment_stat: AnyStatistic, control_stat: AnyStatistic) -> None:
"""
Comprehensive validation of test inputs.
Args:
treatment_stat: Treatment group statistic
control_stat: Control group statistic
- check_sample_size: Whether to enforce minimum sample size requirements
Raises:
StatisticError: If validation fails
@@ -158,7 +133,3 @@ def validate_test_inputs(
# Check compatibility
if type(treatment_stat) is not type(control_stat):
raise StatisticError("Treatment and control statistics must be the same type")
-
- # Additional checks (optional for different methods)
- if check_sample_size:
- check_sample_size_adequacy(treatment_stat, control_stat)
diff --git a/products/experiments/stats/tests/test_bayesian.py b/products/experiments/stats/tests/test_bayesian.py
index cba7cea62306..ad15bd6b8e2a 100644
--- a/products/experiments/stats/tests/test_bayesian.py
+++ b/products/experiments/stats/tests/test_bayesian.py
@@ -5,20 +5,19 @@ This module tests all Bayesian classes for correctness of calculations,
validation, and edge case handling.
"""
-from typing import Any, cast
+from typing import Any
import pytest
from unittest import TestCase
import numpy as np
-from products.experiments.stats.bayesian.method import BayesianConfig, BayesianMethod, PriorType
+from products.experiments.stats.bayesian.method import BayesianConfig, BayesianMethod
from products.experiments.stats.bayesian.priors import GaussianPrior
from products.experiments.stats.bayesian.tests import BayesianGaussianTest, BayesianResult
from products.experiments.stats.bayesian.utils import (
calculate_effect_size_and_variance,
calculate_posterior,
- calculate_risk,
chance_to_win,
credible_interval,
)
@@ -65,7 +64,6 @@ class TestBayesianConfig(TestCase):
assert config.ci_level == 0.95
assert config.inverse is False
assert config.difference_type == DifferenceType.RELATIVE
- assert config.prior_type == PriorType.RELATIVE
assert config.prior_mean == 0.0
assert config.prior_variance == 1.0
assert config.proper_prior is False
@@ -175,17 +173,6 @@ class TestBayesianUtils(TestCase):
lower_99, upper_99 = credible_interval(0.1, 0.05, alpha=0.01)
assert upper_99 - lower_99 > upper - lower
- def test_risk_calculation(self):
- """Test risk assessment calculation."""
-
- # Positive effect with some uncertainty
- risk_control, risk_treatment = calculate_risk(0.05, 0.02)
-
- # Risk of choosing control should be higher (we're missing positive effect)
- assert risk_control > risk_treatment
- assert risk_control > 0
- assert risk_treatment >= 0 # Can be zero if effect is clearly positive
-
class TestBayesianGaussianTest(TestCase):
"""Tests for BayesianGaussianTest class."""
@@ -237,10 +224,6 @@ class TestBayesianGaussianTest(TestCase):
class TestBayesianMethod(TestCase):
- @staticmethod
- def _credible_interval(result_dict: dict[str, Any]) -> list[Any]:
- return cast(list[Any], result_dict["credible_interval"])
-
"""Tests for BayesianMethod class."""
def test_basic_method_usage(self):
@@ -271,35 +254,6 @@ class TestBayesianMethod(TestCase):
assert result.prior_mean == 0.05
assert result.prior_variance == 0.01
- def test_summary_generation(self):
- """Test summary generation."""
- method = BayesianMethod()
-
- treatment = ProportionStatistic(n=1000, sum=110)
- control = ProportionStatistic(n=1000, sum=100)
- result = method.run_test(treatment, control)
-
- summary = method.get_summary(result)
-
- # Check required summary fields
- assert "preferred_variation" in summary
- assert "chance_to_win" in summary
- assert "confidence_in_decision" in summary
- assert "interpretation" in summary
- assert "risk_assessment" in summary
- assert "recommendation" in summary
-
- def test_create_simple_config(self):
- """Test simple config creation."""
- config = BayesianMethod.create_simple_config(
- ci_level=0.99, difference_type="absolute", prior_mean=0.1, proper_prior=True
- )
-
- assert config.ci_level == 0.99
- assert config.difference_type == DifferenceType.ABSOLUTE
- assert config.prior_mean == 0.1
- assert config.proper_prior is True
-
def test_realistic_example(self):
"""Test basic two-sided t-test with sample mean statistics."""
treatment = SampleMeanStatistic(sum=1922.7, sum_squares=94698.29, n=2461)
@@ -309,7 +263,6 @@ class TestBayesianMethod(TestCase):
method = BayesianMethod(config)
result = method.run_test(treatment, control)
- result_dict = method.get_summary(result)
expected_dict: dict[str, Any] = {
"effect_size": 0.63646,
"credible_interval": [-0.0873, 1.36026],
@@ -318,11 +271,11 @@ class TestBayesianMethod(TestCase):
}
# Compare the key values
- self.assertAlmostEqual(result_dict["effect_size"], expected_dict["effect_size"], places=4)
- credible_interval_result = self._credible_interval(result_dict)
+ self.assertAlmostEqual(result.effect_size, expected_dict["effect_size"], places=4)
+ credible_interval_result = result.credible_interval
self.assertAlmostEqual(credible_interval_result[0], expected_dict["credible_interval"][0], places=4)
self.assertAlmostEqual(credible_interval_result[1], expected_dict["credible_interval"][1], places=4)
- self.assertAlmostEqual(result_dict["chance_to_win"], expected_dict["chance_to_win"], places=4)
+ self.assertAlmostEqual(result.chance_to_win, expected_dict["chance_to_win"], places=4)
def test_two_sided_ttest_with_ratio_statistic(self):
"""Test basic two-sided t-test with ratio statistics."""
@@ -346,7 +299,6 @@ class TestBayesianMethod(TestCase):
method = BayesianMethod(config)
result = method.run_test(treatment, control)
- result_dict = method.get_summary(result)
expected_dict: dict[str, Any] = {
"effect_size": 0.041333,
"credible_interval": [0.01378609, 0.0689],
@@ -355,9 +307,9 @@ class TestBayesianMethod(TestCase):
}
# Compare the key values
- self.assertAlmostEqual(result_dict["effect_size"], expected_dict["effect_size"], places=4)
- self.assertAlmostEqual(result_dict["chance_to_win"], expected_dict["chance_to_win"], places=4)
- credible_interval_result = self._credible_interval(result_dict)
+ self.assertAlmostEqual(result.effect_size, expected_dict["effect_size"], places=4)
+ self.assertAlmostEqual(result.chance_to_win, expected_dict["chance_to_win"], places=4)
+ credible_interval_result = result.credible_interval
self.assertAlmostEqual(credible_interval_result[0], expected_dict["credible_interval"][0], places=4)
self.assertAlmostEqual(credible_interval_result[1], expected_dict["credible_interval"][1], places=4)
@@ -370,10 +322,10 @@ class TestConvenienceFunctions:
treatment = ProportionStatistic(n=1000, sum=110)
control = ProportionStatistic(n=1000, sum=100)
- config = BayesianMethod.create_simple_config(
+ config = BayesianConfig(
ci_level=0.95,
inverse=False,
- difference_type="relative",
+ difference_type=DifferenceType.RELATIVE,
prior_mean=0.05,
prior_variance=0.01,
proper_prior=True,