Skip to content

tea_tasting.multiplicity #

Multiple hypothesis testing.

MultipleComparisonsResults #

Bases: UserDict[Any, ExperimentResult], PrettyDictsMixin

Multiple comparisons result.

to_pandas() #

Convert the object to a Pandas DataFrame.

Source code in src/tea_tasting/utils.py
def to_pandas(self) -> pd.DataFrame:
    """Convert the object to a Pandas DataFrame."""
    return pd.DataFrame.from_records(self.to_dicts())

to_pretty(keys=None, formatter=get_and_format_num) #

Convert the object to a Pandas Dataframe with formatted values.

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, Any], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num

Returns:

Type Description
DataFrame

Pandas Dataframe with formatted values.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def to_pretty(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> pd.DataFrame:
    """Convert the object to a Pandas Dataframe with formatted values.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.

    Returns:
        Pandas Dataframe with formatted values.

    Default formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    if keys is None:
        keys = self.default_keys
    return pd.DataFrame.from_records(
        {key: formatter(data, key) for key in keys}
        for data in self.to_dicts()
    )

to_string(keys=None, formatter=get_and_format_num) #

Convert the object to a string.

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, Any], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num

Returns:

Type Description
str

A table with results rendered as string.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def to_string(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> str:
    """Convert the object to a string.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.

    Returns:
        A table with results rendered as string.

    Default formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    return self.to_pretty(keys, formatter).to_string(index=False)

to_html(keys=None, formatter=get_and_format_num) #

Convert the object to HTML.

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, Any], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num

Returns:

Type Description
str

A table with results rendered as HTML.

Default formatting rules
  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {lower_bound}]".
Source code in src/tea_tasting/utils.py
def to_html(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> str:
    """Convert the object to HTML.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.

    Returns:
        A table with results rendered as HTML.

    Default formatting rules:
        - If a name starts with `"rel_"` or equals to `"power"` consider it
            a percentage value. Round percentage values to 2 significant digits,
            multiply by `100` and add `"%"`.
        - Round other values to 3 significant values.
        - If value is less than `0.001`, format it in exponential presentation.
        - If a name ends with `"_ci"`, consider it a confidence interval.
            Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
            and format the interval as `"[{lower_bound}, {lower_bound}]"`.
    """
    return self.to_pretty(keys, formatter).to_html(index=False)

to_dicts() #

Convert the result to a sequence of dictionaries.

Source code in src/tea_tasting/multiplicity.py
def to_dicts(self) -> tuple[dict[str, Any], ...]:
    """Convert the result to a sequence of dictionaries."""
    return tuple(
        {"comparison": str(comparison)} | metric_result
        for comparison, experiment_result in self.items()
        for metric_result in experiment_result.to_dicts()
    )

adjust_fdr(experiment_results, metrics=None, *, alpha=None, arbitrary_dependence=True) #

Adjust p-value and alpha to control the false discovery rate (FDR).

The number of hypotheses tested is the total number of metrics included in the comparison in all experiment results. For example, if there are 3 experiments with 2 metrics in each, the number of hypotheses is 6.

The function performs one of the following corrections, depending on parameters:

  • Benjamini-Yekutieli procedure, assuming arbitrary dependence between hypotheses (arbitrary_dependence=True).
  • Benjamini-Hochberg procedure, assuming non-negative correlation between hypotheses (arbitrary_dependence=False).
The function adds the following attributes to the results
  • pvalue_adj: The adjusted p-value, which should be compared with the unadjusted FDR (alpha).
  • alpha_adj: The adjusted FDR, which should be compared with the unadjusted p-value (pvalue).
  • null_rejected: A binary indicator (0 or 1) that shows whether the null hypothesis is rejected.

Parameters:

Name Type Description Default
experiment_results ExperimentResult | Mapping[Any, ExperimentResult]

Experiment results.

required
metrics str | set[str] | Sequence[str] | None

Metrics included in the comparison. If None, all metrics are included.

None
alpha float | None

Significance level. If None, the value from global settings is used.

None
arbitrary_dependence bool

If True, arbitrary dependence between hypotheses is assumed and Benjamini-Yekutieli procedure is performed. If False, non-negative correlation between hypotheses is assumed and Benjamini-Hochberg procedure is performed.

True

Returns:

Type Description
MultipleComparisonsResults

The experiments results with adjusted p-values and alphas.

Parameter defaults

Default for parameters alpha can be changed using the config_context and set_context functions. See the Global configuration reference for details.

References

Examples:

import pandas as pd
import tea_tasting as tt


data = pd.concat((
    tt.make_users_data(seed=42, orders_uplift=0.10, revenue_uplift=0.15),
    tt.make_users_data(seed=21, orders_uplift=0.15, revenue_uplift=0.20)
        .query("variant==1")
        .assign(variant=2),
))
print(data)
#>       user  variant  sessions  orders    revenue
#> 0        0        1         2       1   9.582790
#> 1        1        0         2       1   6.434079
#> 2        2        1         2       1   8.304958
#> 3        3        1         2       1  16.652705
#> 4        4        0         1       1   7.136917
#> ...    ...      ...       ...     ...        ...
#> 3989  3989        2         4       4  34.931448
#> 3991  3991        2         1       0   0.000000
#> 3992  3992        2         3       3  27.964647
#> 3994  3994        2         2       1  17.217892
#> 3998  3998        2         3       0   0.000000
#>
#> [6046 rows x 5 columns]

experiment = tt.Experiment(
    sessions_per_user=tt.Mean("sessions"),
    orders_per_session=tt.RatioOfMeans("orders", "sessions"),
    orders_per_user=tt.Mean("orders"),
    revenue_per_user=tt.Mean("revenue"),
)

# Results without correction.
results = experiment.analyze(data, control=0, all_variants=True)
print(results)
#> variants             metric control treatment rel_effect_size rel_effect_size_ci  pvalue
#>   (0, 1)  sessions_per_user    2.00      1.98          -0.66%      [-3.7%, 2.5%]   0.674
#>   (0, 1) orders_per_session   0.266     0.289            8.8%      [-0.89%, 19%]  0.0762
#>   (0, 1)    orders_per_user   0.530     0.573            8.0%       [-2.0%, 19%]   0.118
#>   (0, 1)   revenue_per_user    5.24      5.99             14%        [2.1%, 28%]  0.0212
#>   (0, 2)  sessions_per_user    2.00      2.02           0.98%      [-2.1%, 4.1%]   0.532
#>   (0, 2) orders_per_session   0.266     0.295             11%        [1.2%, 22%]  0.0273
#>   (0, 2)    orders_per_user   0.530     0.594             12%        [1.7%, 23%]  0.0213
#>   (0, 2)   revenue_per_user    5.24      6.25             19%        [6.6%, 33%] 0.00218

# Success metrics.
metrics = {"orders_per_user", "revenue_per_user"}

# Benjamini-Yekutieli procedure,
# assuming arbitrary dependence between hypotheses.
adjusted_results_fdr = tt.adjust_fdr(results, metrics)
print(adjusted_results_fdr)
#> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
#>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.245
#>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0592
#>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0592
#>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218     0.0182

# The adjusted confidence level alpha.
print(adjusted_results_fdr.to_string(keys=(
    "comparison",
    "metric",
    "control",
    "treatment",
    "rel_effect_size",
    "pvalue",
    "alpha_adj",
)))
#> comparison           metric control treatment rel_effect_size  pvalue alpha_adj
#>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118    0.0240
#>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212    0.0120
#>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0180
#>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218   0.00600

# Benjamini-Hochberg procedure,
# assuming non-negative correlation between hypotheses.
print(tt.adjust_fdr(results, metrics, arbitrary_dependence=False))
#> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
#>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.118
#>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0284
#>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0284
#>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00873
Source code in src/tea_tasting/multiplicity.py
def adjust_fdr(
    experiment_results: tea_tasting.experiment.ExperimentResult | Mapping[
        Any, tea_tasting.experiment.ExperimentResult],
    metrics: str | set[str] | Sequence[str] | None = None,
    *,
    alpha: float | None = None,
    arbitrary_dependence: bool = True,
) -> MultipleComparisonsResults:
    """Adjust p-value and alpha to control the false discovery rate (FDR).

    The number of hypotheses tested is the total number of metrics included in
    the comparison in all experiment results. For example, if there are
    3 experiments with 2 metrics in each, the number of hypotheses is 6.

    The function performs one of the following corrections, depending on parameters:

    - Benjamini-Yekutieli procedure, assuming arbitrary dependence between
        hypotheses (`arbitrary_dependence=True`).
    - Benjamini-Hochberg procedure, assuming non-negative correlation between
        hypotheses (`arbitrary_dependence=False`).

    The function adds the following attributes to the results:
        - `pvalue_adj`: The adjusted p-value, which should be compared with
            the unadjusted FDR (`alpha`).
        - `alpha_adj`: The adjusted FDR, which should be compared with the unadjusted
            p-value (`pvalue`).
        - `null_rejected`: A binary indicator (`0` or `1`) that shows whether
            the null hypothesis is rejected.

    Args:
        experiment_results: Experiment results.
        metrics: Metrics included in the comparison.
            If `None`, all metrics are included.
        alpha: Significance level. If `None`, the value from global settings is used.
        arbitrary_dependence: If `True`, arbitrary dependence between hypotheses
            is assumed and Benjamini-Yekutieli procedure is performed.
            If `False`, non-negative correlation between hypotheses is assumed
            and Benjamini-Hochberg procedure is performed.

    Returns:
        The experiments results with adjusted p-values and alphas.

    Parameter defaults:
        Default for parameters `alpha` can be changed using the `config_context`
        and `set_context` functions.
        See the [Global configuration](https://tea-tasting.e10v.me/api/config/)
        reference for details.

    References:
        - [Multiple comparisons problem](https://en.wikipedia.org/wiki/Multiple_comparisons_problem).
        - [False discovery rate](https://en.wikipedia.org/wiki/False_discovery_rate).

    Examples:
        ```python
        import pandas as pd
        import tea_tasting as tt


        data = pd.concat((
            tt.make_users_data(seed=42, orders_uplift=0.10, revenue_uplift=0.15),
            tt.make_users_data(seed=21, orders_uplift=0.15, revenue_uplift=0.20)
                .query("variant==1")
                .assign(variant=2),
        ))
        print(data)
        #>       user  variant  sessions  orders    revenue
        #> 0        0        1         2       1   9.582790
        #> 1        1        0         2       1   6.434079
        #> 2        2        1         2       1   8.304958
        #> 3        3        1         2       1  16.652705
        #> 4        4        0         1       1   7.136917
        #> ...    ...      ...       ...     ...        ...
        #> 3989  3989        2         4       4  34.931448
        #> 3991  3991        2         1       0   0.000000
        #> 3992  3992        2         3       3  27.964647
        #> 3994  3994        2         2       1  17.217892
        #> 3998  3998        2         3       0   0.000000
        #>
        #> [6046 rows x 5 columns]

        experiment = tt.Experiment(
            sessions_per_user=tt.Mean("sessions"),
            orders_per_session=tt.RatioOfMeans("orders", "sessions"),
            orders_per_user=tt.Mean("orders"),
            revenue_per_user=tt.Mean("revenue"),
        )

        # Results without correction.
        results = experiment.analyze(data, control=0, all_variants=True)
        print(results)
        #> variants             metric control treatment rel_effect_size rel_effect_size_ci  pvalue
        #>   (0, 1)  sessions_per_user    2.00      1.98          -0.66%      [-3.7%, 2.5%]   0.674
        #>   (0, 1) orders_per_session   0.266     0.289            8.8%      [-0.89%, 19%]  0.0762
        #>   (0, 1)    orders_per_user   0.530     0.573            8.0%       [-2.0%, 19%]   0.118
        #>   (0, 1)   revenue_per_user    5.24      5.99             14%        [2.1%, 28%]  0.0212
        #>   (0, 2)  sessions_per_user    2.00      2.02           0.98%      [-2.1%, 4.1%]   0.532
        #>   (0, 2) orders_per_session   0.266     0.295             11%        [1.2%, 22%]  0.0273
        #>   (0, 2)    orders_per_user   0.530     0.594             12%        [1.7%, 23%]  0.0213
        #>   (0, 2)   revenue_per_user    5.24      6.25             19%        [6.6%, 33%] 0.00218

        # Success metrics.
        metrics = {"orders_per_user", "revenue_per_user"}

        # Benjamini-Yekutieli procedure,
        # assuming arbitrary dependence between hypotheses.
        adjusted_results_fdr = tt.adjust_fdr(results, metrics)
        print(adjusted_results_fdr)
        #> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
        #>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.245
        #>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0592
        #>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0592
        #>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218     0.0182

        # The adjusted confidence level alpha.
        print(adjusted_results_fdr.to_string(keys=(
            "comparison",
            "metric",
            "control",
            "treatment",
            "rel_effect_size",
            "pvalue",
            "alpha_adj",
        )))
        #> comparison           metric control treatment rel_effect_size  pvalue alpha_adj
        #>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118    0.0240
        #>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212    0.0120
        #>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0180
        #>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218   0.00600

        # Benjamini-Hochberg procedure,
        # assuming non-negative correlation between hypotheses.
        print(tt.adjust_fdr(results, metrics, arbitrary_dependence=False))
        #> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
        #>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.118
        #>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0284
        #>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0284
        #>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00873
        ```
    """  # noqa: E501
    alpha = (
        tea_tasting.utils.auto_check(alpha, "alpha")
        if alpha is not None
        else tea_tasting.config.get_config("alpha")
    )
    arbitrary_dependence = tea_tasting.utils.check_scalar(
        arbitrary_dependence, "arbitrary_dependence", typ=bool)

    # results and metric_results refer to the same dicts.
    results, metric_results = _copy_results(experiment_results, metrics)
    method = _Benjamini(
        alpha=alpha,  # type: ignore
        m=len(metric_results),
        arbitrary_dependence=arbitrary_dependence,
    )
    # In-place update.
    _hochberg_stepup(metric_results, method.adjust)

    return MultipleComparisonsResults(results)

adjust_fwer(experiment_results, metrics=None, *, alpha=None, arbitrary_dependence=True, method='bonferroni') #

Adjust p-value and alpha to control the family-wise error rate (FWER).

The number of hypotheses tested is the total number of metrics included in the comparison in all experiment results. For example, if there are 3 experiments with 2 metrics in each, the number of hypotheses is 6.

The function performs one of the following procedures, depending on parameters:

  • Holm's step-down procedure, assuming arbitrary dependence between hypotheses (arbitrary_dependence=True).
  • Hochberg's step-up procedure, assuming non-negative correlation between hypotheses (arbitrary_dependence=False).
The function adds the following attributes to the results
  • pvalue_adj: The adjusted p-value, which should be compared with the unadjusted FDR (alpha).
  • alpha_adj: The adjusted FWER, which should be compared with the unadjusted p-value (pvalue).
  • null_rejected: A binary indicator (0 or 1) that shows whether the null hypothesis is rejected.

Parameters:

Name Type Description Default
experiment_results ExperimentResult | Mapping[Any, ExperimentResult]

Experiment results.

required
metrics str | set[str] | Sequence[str] | None

Metrics included in the comparison. If None, all metrics are included.

None
alpha float | None

Significance level. If None, the value from global settings is used.

None
arbitrary_dependence bool

If True, arbitrary dependence between hypotheses is assumed and Holm's step-down procedure is performed. If False, non-negative correlation between hypotheses is assumed and Hochberg's step-up procedure is performed.

True
method Literal['bonferroni', 'sidak']

Correction method, Bonferroni ("bonferroni") or Šidák ("sidak").

'bonferroni'

Returns:

Type Description
MultipleComparisonsResults

The experiments results with adjusted p-values and alphas.

Parameter defaults

Default for parameters alpha can be changed using the config_context and set_context functions. See the Global configuration reference for details.

References

Examples:

import pandas as pd
import tea_tasting as tt


data = pd.concat((
    tt.make_users_data(seed=42, orders_uplift=0.10, revenue_uplift=0.15),
    tt.make_users_data(seed=21, orders_uplift=0.15, revenue_uplift=0.20)
        .query("variant==1")
        .assign(variant=2),
))
print(data)
#>       user  variant  sessions  orders    revenue
#> 0        0        1         2       1   9.582790
#> 1        1        0         2       1   6.434079
#> 2        2        1         2       1   8.304958
#> 3        3        1         2       1  16.652705
#> 4        4        0         1       1   7.136917
#> ...    ...      ...       ...     ...        ...
#> 3989  3989        2         4       4  34.931448
#> 3991  3991        2         1       0   0.000000
#> 3992  3992        2         3       3  27.964647
#> 3994  3994        2         2       1  17.217892
#> 3998  3998        2         3       0   0.000000
#>
#> [6046 rows x 5 columns]

experiment = tt.Experiment(
    sessions_per_user=tt.Mean("sessions"),
    orders_per_session=tt.RatioOfMeans("orders", "sessions"),
    orders_per_user=tt.Mean("orders"),
    revenue_per_user=tt.Mean("revenue"),
)

# Results without correction.
results = experiment.analyze(data, control=0, all_variants=True)
print(results)
#> variants             metric control treatment rel_effect_size rel_effect_size_ci  pvalue
#>   (0, 1)  sessions_per_user    2.00      1.98          -0.66%      [-3.7%, 2.5%]   0.674
#>   (0, 1) orders_per_session   0.266     0.289            8.8%      [-0.89%, 19%]  0.0762
#>   (0, 1)    orders_per_user   0.530     0.573            8.0%       [-2.0%, 19%]   0.118
#>   (0, 1)   revenue_per_user    5.24      5.99             14%        [2.1%, 28%]  0.0212
#>   (0, 2)  sessions_per_user    2.00      2.02           0.98%      [-2.1%, 4.1%]   0.532
#>   (0, 2) orders_per_session   0.266     0.295             11%        [1.2%, 22%]  0.0273
#>   (0, 2)    orders_per_user   0.530     0.594             12%        [1.7%, 23%]  0.0213
#>   (0, 2)   revenue_per_user    5.24      6.25             19%        [6.6%, 33%] 0.00218

# Success metrics.
metrics = {"orders_per_user", "revenue_per_user"}

# Holm's step-down procedure with Bonferroni correction,
# assuming arbitrary dependence between hypotheses.
adjusted_results_fwer = tt.adjust_fwer(results, metrics)
print(adjusted_results_fwer)
#> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
#>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.118
#>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0635
#>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0635
#>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00873

# The adjusted confidence level alpha.
print(adjusted_results_fwer.to_string(keys=(
    "comparison",
    "metric",
    "control",
    "treatment",
    "rel_effect_size",
    "pvalue",
    "alpha_adj",
)))
#> comparison           metric control treatment rel_effect_size  pvalue alpha_adj
#>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118    0.0167
#>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212    0.0167
#>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0167
#>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.0125

# Hochberg's step-up procedure with Šidák correction,
# assuming non-negative correlation between hypotheses.
print(tt.adjust_fwer(
    results,
    metrics,
    arbitrary_dependence=False,
    method="sidak",
))
#> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
#>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.118
#>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0422
#>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0422
#>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00870
Source code in src/tea_tasting/multiplicity.py
def adjust_fwer(
    experiment_results: tea_tasting.experiment.ExperimentResult | Mapping[
        Any, tea_tasting.experiment.ExperimentResult],
    metrics: str | set[str] | Sequence[str] | None = None,
    *,
    alpha: float | None = None,
    arbitrary_dependence: bool = True,
    method: Literal["bonferroni", "sidak"] = "bonferroni",
) -> MultipleComparisonsResults:
    """Adjust p-value and alpha to control the family-wise error rate (FWER).

    The number of hypotheses tested is the total number of metrics included in
    the comparison in all experiment results. For example, if there are
    3 experiments with 2 metrics in each, the number of hypotheses is 6.

    The function performs one of the following procedures, depending on parameters:

    - Holm's step-down procedure, assuming arbitrary dependence between
        hypotheses (`arbitrary_dependence=True`).
    - Hochberg's step-up procedure, assuming non-negative correlation between
        hypotheses (`arbitrary_dependence=False`).

    The function adds the following attributes to the results:
        - `pvalue_adj`: The adjusted p-value, which should be compared with
            the unadjusted FDR (`alpha`).
        - `alpha_adj`: The adjusted FWER, which should be compared with the unadjusted
            p-value (`pvalue`).
        - `null_rejected`: A binary indicator (`0` or `1`) that shows whether
            the null hypothesis is rejected.

    Args:
        experiment_results: Experiment results.
        metrics: Metrics included in the comparison.
            If `None`, all metrics are included.
        alpha: Significance level. If `None`, the value from global settings is used.
        arbitrary_dependence: If `True`, arbitrary dependence between hypotheses
            is assumed and Holm's step-down procedure is performed.
            If `False`, non-negative correlation between hypotheses is assumed
            and Hochberg's step-up procedure is performed.
        method: Correction method, Bonferroni (`"bonferroni"`) or Šidák (`"sidak"`).

    Returns:
        The experiments results with adjusted p-values and alphas.

    Parameter defaults:
        Default for parameters `alpha` can be changed using the `config_context`
        and `set_context` functions.
        See the [Global configuration](https://tea-tasting.e10v.me/api/config/)
        reference for details.

    References:
        - [Multiple comparisons problem](https://en.wikipedia.org/wiki/Multiple_comparisons_problem).
        - [Family-wise error rate](https://en.wikipedia.org/wiki/Family-wise_error_rate).
        - [Holm–Bonferroni method](https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method).

    Examples:
        ```python
        import pandas as pd
        import tea_tasting as tt


        data = pd.concat((
            tt.make_users_data(seed=42, orders_uplift=0.10, revenue_uplift=0.15),
            tt.make_users_data(seed=21, orders_uplift=0.15, revenue_uplift=0.20)
                .query("variant==1")
                .assign(variant=2),
        ))
        print(data)
        #>       user  variant  sessions  orders    revenue
        #> 0        0        1         2       1   9.582790
        #> 1        1        0         2       1   6.434079
        #> 2        2        1         2       1   8.304958
        #> 3        3        1         2       1  16.652705
        #> 4        4        0         1       1   7.136917
        #> ...    ...      ...       ...     ...        ...
        #> 3989  3989        2         4       4  34.931448
        #> 3991  3991        2         1       0   0.000000
        #> 3992  3992        2         3       3  27.964647
        #> 3994  3994        2         2       1  17.217892
        #> 3998  3998        2         3       0   0.000000
        #>
        #> [6046 rows x 5 columns]

        experiment = tt.Experiment(
            sessions_per_user=tt.Mean("sessions"),
            orders_per_session=tt.RatioOfMeans("orders", "sessions"),
            orders_per_user=tt.Mean("orders"),
            revenue_per_user=tt.Mean("revenue"),
        )

        # Results without correction.
        results = experiment.analyze(data, control=0, all_variants=True)
        print(results)
        #> variants             metric control treatment rel_effect_size rel_effect_size_ci  pvalue
        #>   (0, 1)  sessions_per_user    2.00      1.98          -0.66%      [-3.7%, 2.5%]   0.674
        #>   (0, 1) orders_per_session   0.266     0.289            8.8%      [-0.89%, 19%]  0.0762
        #>   (0, 1)    orders_per_user   0.530     0.573            8.0%       [-2.0%, 19%]   0.118
        #>   (0, 1)   revenue_per_user    5.24      5.99             14%        [2.1%, 28%]  0.0212
        #>   (0, 2)  sessions_per_user    2.00      2.02           0.98%      [-2.1%, 4.1%]   0.532
        #>   (0, 2) orders_per_session   0.266     0.295             11%        [1.2%, 22%]  0.0273
        #>   (0, 2)    orders_per_user   0.530     0.594             12%        [1.7%, 23%]  0.0213
        #>   (0, 2)   revenue_per_user    5.24      6.25             19%        [6.6%, 33%] 0.00218

        # Success metrics.
        metrics = {"orders_per_user", "revenue_per_user"}

        # Holm's step-down procedure with Bonferroni correction,
        # assuming arbitrary dependence between hypotheses.
        adjusted_results_fwer = tt.adjust_fwer(results, metrics)
        print(adjusted_results_fwer)
        #> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
        #>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.118
        #>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0635
        #>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0635
        #>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00873

        # The adjusted confidence level alpha.
        print(adjusted_results_fwer.to_string(keys=(
            "comparison",
            "metric",
            "control",
            "treatment",
            "rel_effect_size",
            "pvalue",
            "alpha_adj",
        )))
        #> comparison           metric control treatment rel_effect_size  pvalue alpha_adj
        #>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118    0.0167
        #>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212    0.0167
        #>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0167
        #>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.0125

        # Hochberg's step-up procedure with Šidák correction,
        # assuming non-negative correlation between hypotheses.
        print(tt.adjust_fwer(
            results,
            metrics,
            arbitrary_dependence=False,
            method="sidak",
        ))
        #> comparison           metric control treatment rel_effect_size  pvalue pvalue_adj
        #>     (0, 1)  orders_per_user   0.530     0.573            8.0%   0.118      0.118
        #>     (0, 1) revenue_per_user    5.24      5.99             14%  0.0212     0.0422
        #>     (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0422
        #>     (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00870
        ```
    """  # noqa: E501, RUF002
    alpha = (
        tea_tasting.utils.auto_check(alpha, "alpha")
        if alpha is not None
        else tea_tasting.config.get_config("alpha")
    )
    method = tea_tasting.utils.check_scalar(
        method, "method", typ=str, in_={"sidak", "bonferroni"})
    arbitrary_dependence = tea_tasting.utils.check_scalar(
        arbitrary_dependence, "arbitrary_dependence", typ=bool)

    # results and metric_results refer to the same dicts.
    results, metric_results = _copy_results(experiment_results, metrics)
    method_cls = _Sidak if method == "sidak" else _Bonferroni
    method_ = method_cls(alpha=alpha, m=len(metric_results))  # type: ignore
    procedure = _holm_stepdown if arbitrary_dependence else _hochberg_stepup
    # In-place update.
    procedure(metric_results, method_.adjust)

    return MultipleComparisonsResults(results)