Skip to content

tea_tasting.multiplicity #

Multiple hypothesis testing.

MultipleComparisonsResults #

Bases: UserDict[Any, ExperimentResult], DictsReprMixin

Multiple comparisons result.

to_arrow() #

Convert the object to a PyArrow Table.

Source code in src/tea_tasting/utils.py
247
248
249
def to_arrow(self) -> pa.Table:
    """Convert the object to a PyArrow Table."""
    return pa.Table.from_pylist(self.to_dicts())

to_dicts() #

Convert the result to a sequence of dictionaries.

Source code in src/tea_tasting/multiplicity.py
37
38
39
40
41
42
43
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()
    )

to_html(keys=None, formatter=get_and_format_num, *, indent=None) #

Convert the object to 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 or is greater than or equal to 10_000_000, 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}, {upper_bound}]".

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
indent str | None

Whitespace to insert for each indentation level. If None, do not indent.

None

Returns:

Type Description
str

A table with results rendered as HTML.

Source code in src/tea_tasting/utils.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def to_html(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
    *,
    indent: str | None = None,
) -> str:
    """Convert the object to 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` or is greater than or equal to `10_000_000`,
        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}, {upper_bound}]"`.

    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.
        indent: Whitespace to insert for each indentation level. If `None`,
            do not indent.

    Returns:
        A table with results rendered as HTML.
    """
    if keys is None:
        keys = self.default_keys
    table = ET.Element(
        "table",
        {"class": "dataframe", "style": "text-align: right;"},
    )
    thead = ET.SubElement(table, "thead")
    thead_tr = ET.SubElement(thead, "tr")
    for key in keys:
        th = ET.SubElement(thead_tr, "th")
        th.text = key
    tbody = ET.SubElement(table, "tbody")
    for data in self.to_dicts():
        tr = ET.SubElement(tbody, "tr")
        for key in keys:
            td = ET.SubElement(tr, "td")
            td.text = formatter(data, key)
    if indent is not None:
        ET.indent(table, space=indent)
    return ET.tostring(table, encoding="unicode", method="html")

to_pandas() #

Convert the object to a Pandas DataFrame.

Source code in src/tea_tasting/utils.py
251
252
253
254
def to_pandas(self) -> PandasDataFrame:
    """Convert the object to a Pandas DataFrame."""
    import pandas as pd
    return pd.DataFrame.from_records(self.to_dicts())

to_polars() #

Convert the object to a Polars DataFrame.

Source code in src/tea_tasting/utils.py
256
257
258
259
def to_polars(self) -> PolarsDataFrame:
    """Convert the object to a Polars DataFrame."""
    import polars as pl
    return pl.from_dicts(self.to_dicts())

to_pretty_dicts(keys=None, formatter=get_and_format_num) #

Convert the object to a list of dictionaries 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 or is greater than or equal to 10_000_000, 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}, {upper_bound}]".

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
list[dict[str, str]]

List of dictionaries with formatted values.

Source code in src/tea_tasting/utils.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def to_pretty_dicts(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, Any], str], str] = get_and_format_num,
) -> list[dict[str, str]]:
    """Convert the object to a list of dictionaries 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` or is greater than or equal to `10_000_000`,
        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}, {upper_bound}]"`.

    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:
        List of dictionaries with formatted values.
    """
    if keys is None:
        keys = self.default_keys
    return [{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.

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 or is greater than or equal to 10_000_000, 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}, {upper_bound}]".

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.

Source code in src/tea_tasting/utils.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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.

    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` or is greater than or equal to `10_000_000`,
        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}, {upper_bound}]"`.

    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.
    """
    if keys is None:
        keys = self.default_keys
    widths = {key: len(key) for key in keys}

    pretty_dicts = []
    for data in self.to_dicts():
        pretty_dict = {}
        for key in keys:
            val = formatter(data, key)
            widths[key] = max(widths[key], len(val))
            pretty_dict |= {key: val}
        pretty_dicts.append(pretty_dict)

    sep = " "
    rows = [sep.join(key.rjust(widths[key]) for key in keys)]
    rows.extend(
        sep.join(pretty_dict[key].rjust(widths[key]) for key in keys)
        for pretty_dict in pretty_dicts
    )
    return "\n".join(rows)

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

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-Hochberg procedure, assuming non-negative correlation between hypotheses (arbitrary_dependence=False).
  • Benjamini-Yekutieli procedure, assuming arbitrary dependence between hypotheses (arbitrary_dependence=True).

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.

False

Returns:

Type Description
MultipleComparisonsResults

The experiments results with adjusted p-values and alphas.

Parameter defaults

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

References

Examples:

>>> import polars as pl
>>> import tea_tasting as tt

>>> data = pl.concat((
...     tt.make_users_data(
...         seed=42,
...         orders_uplift=0.10,
...         revenue_uplift=0.15,
...         return_type="polars",
...     ),
...     tt.make_users_data(
...         seed=21,
...         orders_uplift=0.15,
...         revenue_uplift=0.20,
...         return_type="polars",
...     )
...         .filter(pl.col("variant").eq(1))
...         .with_columns(variant=pl.lit(2, pl.Int64)),
... ))
>>> print(data)
shape: (6_046, 5)
┌──────┬─────────┬──────────┬────────┬─────────┐
│ user ┆ variant ┆ sessions ┆ orders ┆ revenue │
│ ---  ┆ ---     ┆ ---      ┆ ---    ┆ ---     │
│ i64  ┆ i64     ┆ i64      ┆ i64    ┆ f64     │
╞══════╪═════════╪══════════╪════════╪═════════╡
│ 0    ┆ 1       ┆ 2        ┆ 1      ┆ 9.58    │
│ 1    ┆ 0       ┆ 2        ┆ 1      ┆ 6.43    │
│ 2    ┆ 1       ┆ 2        ┆ 1      ┆ 8.3     │
│ 3    ┆ 1       ┆ 2        ┆ 1      ┆ 16.65   │
│ 4    ┆ 0       ┆ 1        ┆ 1      ┆ 7.14    │
│ …    ┆ …       ┆ …        ┆ …      ┆ …       │
│ 3989 ┆ 2       ┆ 4        ┆ 4      ┆ 34.93   │
│ 3991 ┆ 2       ┆ 1        ┆ 0      ┆ 0.0     │
│ 3992 ┆ 2       ┆ 3        ┆ 3      ┆ 27.96   │
│ 3994 ┆ 2       ┆ 2        ┆ 1      ┆ 17.22   │
│ 3998 ┆ 2       ┆ 3        ┆ 0      ┆ 0.0     │
└──────┴─────────┴──────────┴────────┴─────────┘

>>> 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.0211
  (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-Hochberg procedure,
>>> # assuming non-negative correlation 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.118
    (0, 1) revenue_per_user    5.24      5.99             14%  0.0211     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.00872

>>> # 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.0500
    (0, 1) revenue_per_user    5.24      5.99             14%  0.0211    0.0375
    (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0375
    (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.0375

>>> # Benjamini-Yekutieli procedure,
>>> # assuming arbitrary dependence between hypotheses.
>>> print(tt.adjust_fdr(results, metrics, arbitrary_dependence=True))
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.0211     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
Source code in src/tea_tasting/multiplicity.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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 = False,
) -> 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-Hochberg procedure, assuming non-negative correlation between
        hypotheses (`arbitrary_dependence=False`).
    - Benjamini-Yekutieli procedure, assuming arbitrary dependence between
        hypotheses (`arbitrary_dependence=True`).

    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 parameter `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:
        ```pycon
        >>> import polars as pl
        >>> import tea_tasting as tt

        >>> data = pl.concat((
        ...     tt.make_users_data(
        ...         seed=42,
        ...         orders_uplift=0.10,
        ...         revenue_uplift=0.15,
        ...         return_type="polars",
        ...     ),
        ...     tt.make_users_data(
        ...         seed=21,
        ...         orders_uplift=0.15,
        ...         revenue_uplift=0.20,
        ...         return_type="polars",
        ...     )
        ...         .filter(pl.col("variant").eq(1))
        ...         .with_columns(variant=pl.lit(2, pl.Int64)),
        ... ))
        >>> print(data)
        shape: (6_046, 5)
        ┌──────┬─────────┬──────────┬────────┬─────────┐
        │ user ┆ variant ┆ sessions ┆ orders ┆ revenue │
        │ ---  ┆ ---     ┆ ---      ┆ ---    ┆ ---     │
        │ i64  ┆ i64     ┆ i64      ┆ i64    ┆ f64     │
        ╞══════╪═════════╪══════════╪════════╪═════════╡
        │ 0    ┆ 1       ┆ 2        ┆ 1      ┆ 9.58    │
        │ 1    ┆ 0       ┆ 2        ┆ 1      ┆ 6.43    │
        │ 2    ┆ 1       ┆ 2        ┆ 1      ┆ 8.3     │
        │ 3    ┆ 1       ┆ 2        ┆ 1      ┆ 16.65   │
        │ 4    ┆ 0       ┆ 1        ┆ 1      ┆ 7.14    │
        │ …    ┆ …       ┆ …        ┆ …      ┆ …       │
        │ 3989 ┆ 2       ┆ 4        ┆ 4      ┆ 34.93   │
        │ 3991 ┆ 2       ┆ 1        ┆ 0      ┆ 0.0     │
        │ 3992 ┆ 2       ┆ 3        ┆ 3      ┆ 27.96   │
        │ 3994 ┆ 2       ┆ 2        ┆ 1      ┆ 17.22   │
        │ 3998 ┆ 2       ┆ 3        ┆ 0      ┆ 0.0     │
        └──────┴─────────┴──────────┴────────┴─────────┘

        >>> 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.0211
          (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-Hochberg procedure,
        >>> # assuming non-negative correlation 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.118
            (0, 1) revenue_per_user    5.24      5.99             14%  0.0211     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.00872

        >>> # 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.0500
            (0, 1) revenue_per_user    5.24      5.99             14%  0.0211    0.0375
            (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0375
            (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.0375

        >>> # Benjamini-Yekutieli procedure,
        >>> # assuming arbitrary dependence between hypotheses.
        >>> print(tt.adjust_fdr(results, metrics, arbitrary_dependence=True))
        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.0211     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

        ```
    """  # 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=False, method='sidak') #

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:

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

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.

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

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

'sidak'

Returns:

Type Description
MultipleComparisonsResults

The experiments results with adjusted p-values and alphas.

Parameter defaults

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

References

Examples:

>>> import polars as pl
>>> import tea_tasting as tt

>>> data = pl.concat((
...     tt.make_users_data(
...         seed=42,
...         orders_uplift=0.10,
...         revenue_uplift=0.15,
...         return_type="polars",
...     ),
...     tt.make_users_data(
...         seed=21,
...         orders_uplift=0.15,
...         revenue_uplift=0.20,
...         return_type="polars",
...     )
...         .filter(pl.col("variant").eq(1))
...         .with_columns(variant=pl.lit(2, pl.Int64)),
... ))
>>> print(data)
shape: (6_046, 5)
┌──────┬─────────┬──────────┬────────┬─────────┐
│ user ┆ variant ┆ sessions ┆ orders ┆ revenue │
│ ---  ┆ ---     ┆ ---      ┆ ---    ┆ ---     │
│ i64  ┆ i64     ┆ i64      ┆ i64    ┆ f64     │
╞══════╪═════════╪══════════╪════════╪═════════╡
│ 0    ┆ 1       ┆ 2        ┆ 1      ┆ 9.58    │
│ 1    ┆ 0       ┆ 2        ┆ 1      ┆ 6.43    │
│ 2    ┆ 1       ┆ 2        ┆ 1      ┆ 8.3     │
│ 3    ┆ 1       ┆ 2        ┆ 1      ┆ 16.65   │
│ 4    ┆ 0       ┆ 1        ┆ 1      ┆ 7.14    │
│ …    ┆ …       ┆ …        ┆ …      ┆ …       │
│ 3989 ┆ 2       ┆ 4        ┆ 4      ┆ 34.93   │
│ 3991 ┆ 2       ┆ 1        ┆ 0      ┆ 0.0     │
│ 3992 ┆ 2       ┆ 3        ┆ 3      ┆ 27.96   │
│ 3994 ┆ 2       ┆ 2        ┆ 1      ┆ 17.22   │
│ 3998 ┆ 2       ┆ 3        ┆ 0      ┆ 0.0     │
└──────┴─────────┴──────────┴────────┴─────────┘

>>> 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.0211
  (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"}

>>> # Hochberg's step-up procedure with Šidák correction,
>>> # assuming non-negative correlation 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.0211     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.00869

>>> # 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.0500
    (0, 1) revenue_per_user    5.24      5.99             14%  0.0211    0.0253
    (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0253
    (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.0253

>>> # Holm's step-down procedure with Bonferroni correction,
>>> # assuming arbitrary dependence between hypotheses.
>>> print(tt.adjust_fwer(
...     results,
...     metrics,
...     arbitrary_dependence=True,
...     method="bonferroni",
... ))
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.0211     0.0634
    (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0634
    (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00872
Source code in src/tea_tasting/multiplicity.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
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 = False,
    method: Literal["bonferroni", "sidak"] = "sidak",
) -> 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:

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

    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 parameter `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:
        ```pycon
        >>> import polars as pl
        >>> import tea_tasting as tt

        >>> data = pl.concat((
        ...     tt.make_users_data(
        ...         seed=42,
        ...         orders_uplift=0.10,
        ...         revenue_uplift=0.15,
        ...         return_type="polars",
        ...     ),
        ...     tt.make_users_data(
        ...         seed=21,
        ...         orders_uplift=0.15,
        ...         revenue_uplift=0.20,
        ...         return_type="polars",
        ...     )
        ...         .filter(pl.col("variant").eq(1))
        ...         .with_columns(variant=pl.lit(2, pl.Int64)),
        ... ))
        >>> print(data)
        shape: (6_046, 5)
        ┌──────┬─────────┬──────────┬────────┬─────────┐
        │ user ┆ variant ┆ sessions ┆ orders ┆ revenue │
        │ ---  ┆ ---     ┆ ---      ┆ ---    ┆ ---     │
        │ i64  ┆ i64     ┆ i64      ┆ i64    ┆ f64     │
        ╞══════╪═════════╪══════════╪════════╪═════════╡
        │ 0    ┆ 1       ┆ 2        ┆ 1      ┆ 9.58    │
        │ 1    ┆ 0       ┆ 2        ┆ 1      ┆ 6.43    │
        │ 2    ┆ 1       ┆ 2        ┆ 1      ┆ 8.3     │
        │ 3    ┆ 1       ┆ 2        ┆ 1      ┆ 16.65   │
        │ 4    ┆ 0       ┆ 1        ┆ 1      ┆ 7.14    │
        │ …    ┆ …       ┆ …        ┆ …      ┆ …       │
        │ 3989 ┆ 2       ┆ 4        ┆ 4      ┆ 34.93   │
        │ 3991 ┆ 2       ┆ 1        ┆ 0      ┆ 0.0     │
        │ 3992 ┆ 2       ┆ 3        ┆ 3      ┆ 27.96   │
        │ 3994 ┆ 2       ┆ 2        ┆ 1      ┆ 17.22   │
        │ 3998 ┆ 2       ┆ 3        ┆ 0      ┆ 0.0     │
        └──────┴─────────┴──────────┴────────┴─────────┘

        >>> 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.0211
          (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"}

        >>> # Hochberg's step-up procedure with Šidák correction,
        >>> # assuming non-negative correlation 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.0211     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.00869

        >>> # 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.0500
            (0, 1) revenue_per_user    5.24      5.99             14%  0.0211    0.0253
            (0, 2)  orders_per_user   0.530     0.594             12%  0.0213    0.0253
            (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.0253

        >>> # Holm's step-down procedure with Bonferroni correction,
        >>> # assuming arbitrary dependence between hypotheses.
        >>> print(tt.adjust_fwer(
        ...     results,
        ...     metrics,
        ...     arbitrary_dependence=True,
        ...     method="bonferroni",
        ... ))
        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.0211     0.0634
            (0, 2)  orders_per_user   0.530     0.594             12%  0.0213     0.0634
            (0, 2) revenue_per_user    5.24      6.25             19% 0.00218    0.00872

        ```
    """  # 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)