Skip to content

from cluster_experiments.perturbator import *

BetaRelativePerturbator

Bases: NormalPerturbator, RelativePositivePerturbator

A stochastic Perturbator for continuous targets that applies a sampled effect from a scaled Beta distribution. It applies the effect multiplicatively.

The sampled effect is defined for values in the specified range (range_min, range_max). It's recommended to set -1<range_min<0 and range_max>0 in a "symmetric way" around 0, such that log(1 + range_min) = -log(1 + range_max). This ensures to have an "symmetric range" of perturbations that relatively decrease the target as perturbations that relatively increase the target. By "symmetry" of relative effects we mean that for an effect c > 0, an increase of the target t via t*(1 + c) is "symmetric" to a decrease of t via t/(1 + c). For example, an increase of 5x (i.e. by +400%, corresponding to c_inc=4) is "symmetric" to a decrease of 5x (i.e. a decrease of -80%, corresponding to c_dec = -0.8). In this case, 1 + c_dec = 1/(1 + c_inc), so the relative effects c_inc and c_dec are "symmetric" in the sense that they are inverse to each other.

The number of samples with 0 as target remains unchanged.

The stochastic effect is sampled from a beta distribution with parameters mean and variance, which is linearly scaled to the range (range_min, range_max). If variance is not provided, the variance is abs(mean).

target -> target * (1 + effect), where effect ~ Beta(a, b)

The common beta parameters are derived from the mean and scale parameters, combined with linear transformations to ensure the support in the given range. The resulting beta parameters are scaled by abs(mu) to narrow the beta distribution around the mean.

mu_transformed <- (mu - range_min) / (range_max - range_min)
scale_transformed <- (scale - range_min) / (range_max - range_min)
a <- mu_transformed / (scale_transformed * scale_transformed)
b <- (1-mu_transformed) / (scale_transformed * scale_transformed)
effect_transformed ~ beta(a/abs(mu), b/abs(mu))
effect = effect_transformed * (range_max - range_min) + range_min

Parameters:

Name Type Description Default
average_effect Optional[float]

the average effect of the treatment. Defaults to None.

None
target_col str

name of the target_col to use as the outcome. Defaults to "target".

'target'
treatment_col str

the name of the column that contains the treatment. Defaults to "treatment".

'treatment'
treatment str

name of the treatment to use as the treated group. Defaults to "B".

'B'
scale Optional[float]

the scale of the effect distribution. Defaults to None. If not provided, the variance of the beta distribution is abs(mean).

None
range_min float

the minimum value of the target range, must be >-1. Defaults to -0.8, which allows for up to 5x decreases of the target.

None
range_max float

the maximum value of the target range. Defaults to 4, which allows for up to 5x increases of the target.

None
reduce_variance Optional[bool]

if True and if abs(average_effect)<1, we reduce the variance of the beta distribution by multiplying the beta parameters by 1/abs(average_effect). Defaults to None, which is equivalent to True.

None
Source code in cluster_experiments/perturbator.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
class BetaRelativePerturbator(NormalPerturbator, RelativePositivePerturbator):
    """
    A stochastic Perturbator for continuous targets that applies a  sampled
    effect from a scaled Beta distribution. It applies the effect multiplicatively.

    The sampled effect is defined for values in the specified range
    (range_min, range_max). It's recommended to set -1<range_min<0 and
    range_max>0 in a "symmetric way" around 0, such that
    log(1 + range_min) = -log(1 + range_max).
    This ensures to have an "symmetric range" of perturbations that relatively
    decrease the target as perturbations that relatively increase the target.
    By "symmetry" of relative effects we mean that for an effect c > 0, an
    increase of the target t via t*(1 + c) is "symmetric" to a decrease of t
    via t/(1 + c). For example, an increase of 5x (i.e. by +400%, corresponding
    to c_inc=4) is "symmetric" to a decrease of 5x (i.e. a decrease of -80%,
    corresponding to c_dec = -0.8). In this case, 1 + c_dec = 1/(1 + c_inc), so
    the relative effects c_inc and c_dec are "symmetric" in the sense that they
    are inverse to each other.

    The number of samples with 0 as target remains unchanged.

    The stochastic effect is sampled from a beta distribution with parameters
    mean and variance, which is linearly scaled to the range
    (range_min, range_max).
    If variance is not provided, the variance is abs(mean).

    ```
    target -> target * (1 + effect), where effect ~ Beta(a, b)
    ```

    The common beta parameters are derived from the mean and scale parameters,
    combined with linear transformations to ensure the support in the given
    range. The resulting beta parameters are scaled by abs(mu) to narrow the
    beta distribution around the mean.

    ```
    mu_transformed <- (mu - range_min) / (range_max - range_min)
    scale_transformed <- (scale - range_min) / (range_max - range_min)
    a <- mu_transformed / (scale_transformed * scale_transformed)
    b <- (1-mu_transformed) / (scale_transformed * scale_transformed)
    effect_transformed ~ beta(a/abs(mu), b/abs(mu))
    effect = effect_transformed * (range_max - range_min) + range_min
    ```

    Arguments:
        average_effect (Optional[float], optional): the average effect of the treatment. Defaults to None.
        target_col (str, optional): name of the target_col to use as the outcome. Defaults to "target".
        treatment_col (str, optional): the name of the column that contains the treatment. Defaults to "treatment".
        treatment (str, optional): name of the treatment to use as the treated group. Defaults to "B".
        scale (Optional[float], optional): the scale of the effect distribution. Defaults to None.
            If not provided, the variance of the beta distribution is abs(mean).
        range_min (float, optional): the minimum value of the target range, must be >-1.
            Defaults to -0.8, which allows for up to 5x decreases of the target.
        range_max (float, optional): the maximum value of the target range.
            Defaults to 4, which allows for up to 5x increases of the target.
        reduce_variance (Optional[bool], optional): if True and if abs(average_effect)<1, we reduce
            the variance of the beta distribution by multiplying the beta parameters by 1/abs(average_effect).
            Defaults to None, which is equivalent to True.
    """

    def __init__(
        self,
        average_effect: Optional[float] = None,
        target_col: str = "target",
        treatment_col: str = "treatment",
        treatment: str = "B",
        scale: Optional[float] = None,
        range_min: Optional[float] = None,
        range_max: Optional[float] = None,
        reduce_variance: Optional[bool] = None,
    ):
        self._check_range(range_min, range_max)
        super().__init__(average_effect, target_col, treatment_col, treatment, scale)
        self._range_min = range_min or -0.8
        self._range_max = range_max or 4
        self._reduce_variance = reduce_variance or True

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Usage:
        ```python
        from cluster_experiments.perturbator import BetaRelativePerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
        perturbator = BetaRelativePerturbator(range_min = -0.5, range_max = 2)
        # Increase target metric by 20% on average
        perturbator.perturbate(df, average_effect=0.2)
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        self.check_relative_effect_bounds(average_effect)
        scale = self.get_scale(average_effect)
        self.check_relative_effect_bounds(scale)
        n = self.get_number_of_treated(df)
        sampled_effect = self._sample_scaled_beta_effect(average_effect, scale, n)
        df = self.apply_multiplicative_effect(df, sampled_effect)
        return df

    @staticmethod
    def _check_range(range_min: float, range_max: float):
        if range_min < -1:
            raise ValueError(f"range_min needs to be greater than -1, got {range_min}")
        if range_min >= range_max:
            raise ValueError(
                f"range_min needs to be smaller than range_max, got "
                f"{range_min = } and {range_max = }"
            )

    def check_relative_effect_bounds(self, average_effect: float) -> None:
        self.check_average_effect_greater_than(average_effect, x=self._range_min)
        self.check_average_effect_smaller_than(average_effect, x=self._range_max)

    def check_average_effect_greater_than(
        self, average_effect: float, x: float
    ) -> Optional[NoReturn]:
        if average_effect <= x:
            raise ValueError(
                f"Simulated effect needs to be greater than range_min={x}, got {average_effect}"
            )

    def check_average_effect_smaller_than(
        self, average_effect: float, x: float
    ) -> Optional[NoReturn]:
        if average_effect >= x:
            raise ValueError(
                f"Simulated effect needs to be smaller than range_max={x}, got {average_effect}"
            )

    def _reduce_variance_beta_params(
        self, average_effect: float, a: float, b: float
    ) -> Tuple[float, float]:
        """
        Multiplying the parameters of the beta distribution with a factor >1
        reduces variance
        """
        if abs(average_effect) < 1:
            a *= 1 / abs(average_effect)
            b *= 1 / abs(average_effect)
        return a, b

    def _sample_scaled_beta_effect(
        self, average_effect: float, scale: float, n: int
    ) -> np.ndarray:
        average_effect_inv_transf = self._inv_transform_to_range(average_effect)
        scale_inv_transf = self._inv_transform_to_range(scale)
        a = average_effect_inv_transf / (scale_inv_transf * scale_inv_transf)
        b = (1 - average_effect_inv_transf) / (scale_inv_transf * scale_inv_transf)

        if self._reduce_variance:
            a, b = self._reduce_variance_beta_params(average_effect, a, b)
        beta = np.random.beta(a, b, n)

        return self._transform_to_range(beta)

    def _transform_to_range(self, x: Union[float, np.ndarray]):
        return x * (self._range_max - self._range_min) + self._range_min

    def _inv_transform_to_range(self, x: Union[float, np.ndarray]):
        return (x - self._range_min) / (self._range_max - self._range_min)

    @classmethod
    def from_config(cls, config):
        """Creates a Perturbator object from a PowerConfig object"""
        return cls(
            average_effect=config.average_effect,
            target_col=config.target_col,
            treatment_col=config.treatment_col,
            treatment=config.treatment,
            scale=config.scale,
            range_min=config.range_min,
            range_max=config.range_max,
        )

from_config(config) classmethod

Creates a Perturbator object from a PowerConfig object

Source code in cluster_experiments/perturbator.py
561
562
563
564
565
566
567
568
569
570
571
572
@classmethod
def from_config(cls, config):
    """Creates a Perturbator object from a PowerConfig object"""
    return cls(
        average_effect=config.average_effect,
        target_col=config.target_col,
        treatment_col=config.treatment_col,
        treatment=config.treatment,
        scale=config.scale,
        range_min=config.range_min,
        range_max=config.range_max,
    )

perturbate(df, average_effect=None)

Usage:

from cluster_experiments.perturbator import BetaRelativePerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
perturbator = BetaRelativePerturbator(range_min = -0.5, range_max = 2)
# Increase target metric by 20% on average
perturbator.perturbate(df, average_effect=0.2)

Source code in cluster_experiments/perturbator.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Usage:
    ```python
    from cluster_experiments.perturbator import BetaRelativePerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
    perturbator = BetaRelativePerturbator(range_min = -0.5, range_max = 2)
    # Increase target metric by 20% on average
    perturbator.perturbate(df, average_effect=0.2)
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    self.check_relative_effect_bounds(average_effect)
    scale = self.get_scale(average_effect)
    self.check_relative_effect_bounds(scale)
    n = self.get_number_of_treated(df)
    sampled_effect = self._sample_scaled_beta_effect(average_effect, scale, n)
    df = self.apply_multiplicative_effect(df, sampled_effect)
    return df

BetaRelativePositivePerturbator

Bases: NormalPerturbator, RelativePositivePerturbator

A stochastic Perturbator for continuous, positively-defined targets that applies a sampled effect from the Beta distribution. It applies the effect multiplicatively.

WARNING: the average effect is only defined for values between 0 and 1 (not included). Therefore, it only increments the target for the treated samples.

The number of samples with 0 as target remains unchanged.

The stochastic effect is sampled from a beta distribution with parameters mean and variance. If variance is not provided, the variance is abs(mean). Hence, the effect is bounded by 0 and 1.

target -> target * (1 + effect), where effect ~ Beta(a, b); a, b > 0
                                   and target > 0 for all samples

The common beta parameters are derived from the mean and scale parameters (see how below). That's why the average effect is only defined for values between 0 and 1, otherwise one of the beta parameters would be negative or zero:

a <- mu / (scale * scale)
b <- (1-mu) / (scale * scale)
effect ~ beta(a, b)
source: https://stackoverflow.com/a/51143208

Example: a mean = 0.2 and variance = 0.1, give a = 20 and b = 80 Plot: https://www.wolframalpha.com/input?i=plot+distribution+of+beta%2820%2C+80%29

Parameters:

Name Type Description Default
average_effect Optional[float]

the average effect of the treatment. Defaults to None.

None
target_col str

name of the target_col to use as the outcome. Defaults to "target".

'target'
treatment_col str

the name of the column that contains the treatment. Defaults to "treatment".

'treatment'
treatment str

name of the treatment to use as the treated group. Defaults to "B".

'B'
scale Optional[float]

the scale of the effect distribution. Defaults to None.

None
Source code in cluster_experiments/perturbator.py
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
class BetaRelativePositivePerturbator(NormalPerturbator, RelativePositivePerturbator):
    """
    A stochastic Perturbator for continuous, positively-defined targets that applies a
    sampled effect from the Beta distribution. It applies the effect multiplicatively.

    *WARNING*: the average effect is only defined for values between 0 and 1 (not
    included). Therefore, it only increments the target for the treated samples.

    The number of samples with 0 as target remains unchanged.

    The stochastic effect is sampled from a beta distribution with parameters mean and
    variance. If variance is not provided, the variance is abs(mean). Hence, the effect
    is bounded by 0 and 1.

    ```
    target -> target * (1 + effect), where effect ~ Beta(a, b); a, b > 0
                                       and target > 0 for all samples
    ```

    The common beta parameters are derived from the mean and scale parameters (see
    how below). That's why the average effect is only defined for values between 0
    and 1, otherwise one of the beta parameters would be negative or zero:

    ```
    a <- mu / (scale * scale)
    b <- (1-mu) / (scale * scale)
    effect ~ beta(a, b)
    ```
    source: https://stackoverflow.com/a/51143208

    Example: a mean = 0.2 and variance = 0.1, give a = 20 and b = 80
    Plot: https://www.wolframalpha.com/input?i=plot+distribution+of+beta%2820%2C+80%29

    Arguments:
        average_effect (Optional[float], optional): the average effect of the treatment. Defaults to None.
        target_col (str, optional): name of the target_col to use as the outcome. Defaults to "target".
        treatment_col (str, optional): the name of the column that contains the treatment. Defaults to "treatment".
        treatment (str, optional): name of the treatment to use as the treated group. Defaults to "B".
        scale (Optional[float], optional): the scale of the effect distribution. Defaults to None.
    """

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Usage:
        ```python
        from cluster_experiments.perturbator import BetaRelativePositivePerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
        perturbator = BetaRelativePositivePerturbator()
        # Increase target metric by 20%
        perturbator.perturbate(df, average_effect=0.2)
        # returns pd.DataFrame({"target": [1, 3, 3], "treatment": ["A", "B", "A"]})
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        self.check_beta_positive_effect(df, average_effect)
        scale = self.get_scale(average_effect)
        n = self.get_number_of_treated(df)
        sampled_effect = self._sample_beta_effect(average_effect, scale, n)
        df = self.apply_multiplicative_effect(df, sampled_effect)
        return df

    def check_beta_positive_effect(self, df, average_effect):
        self.check_average_effect_greater_than(average_effect, x=0)
        self.check_average_effect_less_than(average_effect, x=1)
        self.check_target_is_not_negative(df)
        self.check_target_is_not_constant_zero(df, average_effect)

    def check_average_effect_less_than(
        self, average_effect: float, x: float
    ) -> Optional[NoReturn]:
        if average_effect >= x:
            raise ValueError(
                f"Simulated effect needs to be less than {x*100:.0f}%, got "
                f"{average_effect*100:.1f}%"
            )

    def _sample_beta_effect(
        self, average_effect: float, scale: float, n: int
    ) -> np.ndarray:
        a = average_effect / (scale * scale)
        b = (1 - average_effect) / (scale * scale)
        return np.random.beta(a, b, n)

perturbate(df, average_effect=None)

Usage:

from cluster_experiments.perturbator import BetaRelativePositivePerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
perturbator = BetaRelativePositivePerturbator()
# Increase target metric by 20%
perturbator.perturbate(df, average_effect=0.2)
# returns pd.DataFrame({"target": [1, 3, 3], "treatment": ["A", "B", "A"]})

Source code in cluster_experiments/perturbator.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Usage:
    ```python
    from cluster_experiments.perturbator import BetaRelativePositivePerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
    perturbator = BetaRelativePositivePerturbator()
    # Increase target metric by 20%
    perturbator.perturbate(df, average_effect=0.2)
    # returns pd.DataFrame({"target": [1, 3, 3], "treatment": ["A", "B", "A"]})
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    self.check_beta_positive_effect(df, average_effect)
    scale = self.get_scale(average_effect)
    n = self.get_number_of_treated(df)
    sampled_effect = self._sample_beta_effect(average_effect, scale, n)
    df = self.apply_multiplicative_effect(df, sampled_effect)
    return df

BinaryPerturbator

Bases: Perturbator

BinaryPerturbator is a Perturbator that adds is used to deal with binary outcome variables. It randomly selects some treated instances and flips their outcome from 0 to 1 or 1 to 0, depending on the effect being positive or negative

Source code in cluster_experiments/perturbator.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
class BinaryPerturbator(Perturbator):
    """
    BinaryPerturbator is a Perturbator that adds is used to deal with binary outcome variables.
    It randomly selects some treated instances and flips their outcome from 0 to 1 or 1 to 0, depending on the effect being positive or negative
    """

    def _sample_max(self, df: pd.DataFrame, n: int) -> pd.DataFrame:
        """Like sample without replacement,
        but if you are to sample more than 100% of the data,
        it just returns the whole dataframe."""
        if n >= len(df):
            return df
        return df.sample(n=n)

    def _data_checks(self, df: pd.DataFrame, average_effect: float) -> None:
        """Check that outcome is indeed binary, and average effect is in (-1, 1)"""

        if set(df[self.target_col].unique()) - {0, 1}:
            raise ValueError(
                f"Target column must be binary, found {set(df[self.target_col].unique())}"
            )

        if average_effect > 1 or average_effect < -1:
            raise ValueError(
                f"Average effect must be in (-1, 1), found {average_effect}"
            )

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Usage:

        ```python
        from cluster_experiments.perturbator import BinaryPerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 0, 1], "treatment": ["A", "B", "A"]})
        perturbator = BinaryPerturbator()
        perturbator.perturbate(df, average_effect=0.1)
        ```
        """

        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)

        self._data_checks(df, average_effect)

        from_target, to_target = 1, 0
        if average_effect > 0:
            from_target, to_target = 0, 1

        n_transformed = abs(int(average_effect * len(df.query(self.treated_query))))
        idx = list(
            # Sample of negative cases in group B
            df.query(f"{self.target_col} == {from_target} & {self.treated_query}")
            .pipe(self._sample_max, n=n_transformed)
            .index.drop_duplicates()
        )
        df.loc[idx, self.target_col] = to_target
        return df

perturbate(df, average_effect=None)

Usage:

from cluster_experiments.perturbator import BinaryPerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 0, 1], "treatment": ["A", "B", "A"]})
perturbator = BinaryPerturbator()
perturbator.perturbate(df, average_effect=0.1)
Source code in cluster_experiments/perturbator.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Usage:

    ```python
    from cluster_experiments.perturbator import BinaryPerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 0, 1], "treatment": ["A", "B", "A"]})
    perturbator = BinaryPerturbator()
    perturbator.perturbate(df, average_effect=0.1)
    ```
    """

    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)

    self._data_checks(df, average_effect)

    from_target, to_target = 1, 0
    if average_effect > 0:
        from_target, to_target = 0, 1

    n_transformed = abs(int(average_effect * len(df.query(self.treated_query))))
    idx = list(
        # Sample of negative cases in group B
        df.query(f"{self.target_col} == {from_target} & {self.treated_query}")
        .pipe(self._sample_max, n=n_transformed)
        .index.drop_duplicates()
    )
    df.loc[idx, self.target_col] = to_target
    return df

ConstantPerturbator

Bases: Perturbator

ConstantPerturbator is a Perturbator that adds a constant effect to the target column of the treated instances.

Source code in cluster_experiments/perturbator.py
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
class ConstantPerturbator(Perturbator):
    """
    ConstantPerturbator is a Perturbator that adds a constant effect to the target column of the treated instances.
    """

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Usage:

        ```python
        from cluster_experiments.perturbator import ConstantPerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
        perturbator = ConstantPerturbator()
        perturbator.perturbate(df, average_effect=1)
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        df = self.apply_additive_effect(df, average_effect)
        return df

    def apply_additive_effect(
        self, df: pd.DataFrame, effect: Union[float, np.ndarray]
    ) -> pd.DataFrame:
        df.loc[df[self.treatment_col] == self.treatment, self.target_col] += effect
        return df

perturbate(df, average_effect=None)

Usage:

from cluster_experiments.perturbator import ConstantPerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
perturbator = ConstantPerturbator()
perturbator.perturbate(df, average_effect=1)
Source code in cluster_experiments/perturbator.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Usage:

    ```python
    from cluster_experiments.perturbator import ConstantPerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
    perturbator = ConstantPerturbator()
    perturbator.perturbate(df, average_effect=1)
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    df = self.apply_additive_effect(df, average_effect)
    return df

NormalPerturbator

Bases: ConstantPerturbator

The NormalPerturbator class implements a perturbator that adds a stochastic effect to the target column of the treated instances. The stochastic effect is sampled from a normal distribution with mean average_effect and variance scale. If scale is not provided, the variance is abs(average_effect). If scale is provided, a value not much bigger than the average_effect is suggested.

target -> target + effect, where effect ~ Normal(average_effect, scale)

Parameters:

Name Type Description Default
average_effect Optional[float]

the average effect of the treatment. Defaults to None.

None
target_col str

name of the target_col to use as the outcome. Defaults to "target".

'target'
treatment_col str

the name of the column that contains the treatment. Defaults to "treatment".

'treatment'
treatment str

name of the treatment to use as the treated group. Defaults to "B".

'B'
scale Optional[float]

the scale of the effect distribution. Defaults to None.

None
Source code in cluster_experiments/perturbator.py
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
219
220
221
222
223
224
225
226
227
228
229
230
231
class NormalPerturbator(ConstantPerturbator):
    """The NormalPerturbator class implements a perturbator that adds a stochastic effect
    to the target column of the treated instances. The stochastic effect is sampled from a
    normal distribution with mean average_effect and variance scale. If scale is not
    provided, the variance is abs(average_effect). If scale is provided, a
    value not much bigger than the average_effect is suggested.

    ```
    target -> target + effect, where effect ~ Normal(average_effect, scale)
    ```

    Arguments:
        average_effect (Optional[float], optional): the average effect of the treatment. Defaults to None.
        target_col (str, optional): name of the target_col to use as the outcome. Defaults to "target".
        treatment_col (str, optional): the name of the column that contains the treatment. Defaults to "treatment".
        treatment (str, optional): name of the treatment to use as the treated group. Defaults to "B".
        scale (Optional[float], optional): the scale of the effect distribution. Defaults to None.
    """

    def __init__(
        self,
        average_effect: Optional[float] = None,
        target_col: str = "target",
        treatment_col: str = "treatment",
        treatment: str = "B",
        scale: Optional[float] = None,
    ):
        super().__init__(average_effect, target_col, treatment_col, treatment)
        self._scale = scale

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """Perturbate with a normal effect with mean average_effect and
        std abs(average_effect).

        Arguments:
            df (pd.DataFrame): the dataframe to perturbate.
            average_effect (Optional[float], optional): the average effect. Defaults to None.

        Returns:
            pd.DataFrame: the perturbated dataframe.

        Usage:

        ```python
        from cluster_experiments.perturbator import NormalPerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
        perturbator = NormalPerturbator()
        perturbator.perturbate(df, average_effect=1)
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        scale = self.get_scale(average_effect)
        n = self.get_number_of_treated(df)
        sampled_effect = self._sample_normal_effect(average_effect, scale, n)
        df = self.apply_additive_effect(df, sampled_effect)
        return df

    def get_scale(self, average_effect: float) -> float:
        """Get the scale of the normal distribution. If scale is not provided, the
        variance is abs(average_effect). Raises a ValueError if scale is not positive.
        """
        scale = abs(average_effect) if self._scale is None else self._scale
        if scale <= 0:
            raise ValueError(f"scale must be positive, got {scale}")
        return scale

    def get_number_of_treated(self, df: pd.DataFrame) -> int:
        """Get the number of treated instances in the dataframe"""
        return (df[self.treatment_col] == self.treatment).sum()

    def _sample_normal_effect(
        self, average_effect: float, scale: float, n: int
    ) -> np.ndarray:
        return np.random.normal(average_effect, scale, n)

    @classmethod
    def from_config(cls, config):
        """Creates a Perturbator object from a PowerConfig object"""
        return cls(
            average_effect=config.average_effect,
            target_col=config.target_col,
            treatment_col=config.treatment_col,
            treatment=config.treatment,
            scale=config.scale,
        )

from_config(config) classmethod

Creates a Perturbator object from a PowerConfig object

Source code in cluster_experiments/perturbator.py
222
223
224
225
226
227
228
229
230
231
@classmethod
def from_config(cls, config):
    """Creates a Perturbator object from a PowerConfig object"""
    return cls(
        average_effect=config.average_effect,
        target_col=config.target_col,
        treatment_col=config.treatment_col,
        treatment=config.treatment,
        scale=config.scale,
    )

get_number_of_treated(df)

Get the number of treated instances in the dataframe

Source code in cluster_experiments/perturbator.py
213
214
215
def get_number_of_treated(self, df: pd.DataFrame) -> int:
    """Get the number of treated instances in the dataframe"""
    return (df[self.treatment_col] == self.treatment).sum()

get_scale(average_effect)

Get the scale of the normal distribution. If scale is not provided, the variance is abs(average_effect). Raises a ValueError if scale is not positive.

Source code in cluster_experiments/perturbator.py
204
205
206
207
208
209
210
211
def get_scale(self, average_effect: float) -> float:
    """Get the scale of the normal distribution. If scale is not provided, the
    variance is abs(average_effect). Raises a ValueError if scale is not positive.
    """
    scale = abs(average_effect) if self._scale is None else self._scale
    if scale <= 0:
        raise ValueError(f"scale must be positive, got {scale}")
    return scale

perturbate(df, average_effect=None)

Perturbate with a normal effect with mean average_effect and std abs(average_effect).

Parameters:

Name Type Description Default
df DataFrame

the dataframe to perturbate.

required
average_effect Optional[float]

the average effect. Defaults to None.

None

Returns:

Type Description
DataFrame

pd.DataFrame: the perturbated dataframe.

Usage:

from cluster_experiments.perturbator import NormalPerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
perturbator = NormalPerturbator()
perturbator.perturbate(df, average_effect=1)
Source code in cluster_experiments/perturbator.py
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
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """Perturbate with a normal effect with mean average_effect and
    std abs(average_effect).

    Arguments:
        df (pd.DataFrame): the dataframe to perturbate.
        average_effect (Optional[float], optional): the average effect. Defaults to None.

    Returns:
        pd.DataFrame: the perturbated dataframe.

    Usage:

    ```python
    from cluster_experiments.perturbator import NormalPerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
    perturbator = NormalPerturbator()
    perturbator.perturbate(df, average_effect=1)
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    scale = self.get_scale(average_effect)
    n = self.get_number_of_treated(df)
    sampled_effect = self._sample_normal_effect(average_effect, scale, n)
    df = self.apply_additive_effect(df, sampled_effect)
    return df

Perturbator

Bases: ABC

Abstract perturbator. Perturbators are used to simulate a fictitious effect when running a power analysis.

The idea is that, when running a power analysis, we split our instances according to a RandomSplitter, and the instances that got the treatment, are perturbated with a fictional effect via the Perturbator.

In order to create your own perturbator, you should create a derived class that implements the perturbate method. The perturbate method should add the average effect in the desired way and return the dataframe with the extra average effect, without affecting the initial dataframe. Keep in mind to use df = df.copy() in the first line of the perturbate method.

Parameters:

Name Type Description Default
average_effect Optional[float]

The average effect of the treatment

None
target_col str

name of the target_col to use as the outcome

'target'
treatment_col str

The name of the column that contains the treatment

'treatment'
treatment str

name of the treatment to use as the treated group

'B'
Source code in cluster_experiments/perturbator.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Perturbator(ABC):
    """
    Abstract perturbator. Perturbators are used to simulate a fictitious effect when running a power analysis.

    The idea is that, when running a power analysis, we split our instances according to a RandomSplitter, and the
    instances that got the treatment, are perturbated with a fictional effect via the Perturbator.

    In order to create your own perturbator, you should create a derived class that implements the perturbate method.
    The perturbate method should add the average effect in the desired way and return the dataframe with the extra average effect,
    without affecting the initial dataframe. Keep in mind to use `df = df.copy()` in the first line of the perturbate method.

    Arguments:
        average_effect: The average effect of the treatment
        target_col: name of the target_col to use as the outcome
        treatment_col: The name of the column that contains the treatment
        treatment: name of the treatment to use as the treated group

    """

    def __init__(
        self,
        average_effect: Optional[float] = None,
        target_col: str = "target",
        treatment_col: str = "treatment",
        treatment: str = "B",
    ):
        self.average_effect = average_effect
        self.target_col = target_col
        self.treatment_col = treatment_col
        self.treatment = treatment
        self.treated_query = f"{self.treatment_col} == '{self.treatment}'"

    def get_average_effect(self, average_effect: Optional[float] = None) -> float:
        average_effect = (
            average_effect if average_effect is not None else self.average_effect
        )
        if average_effect is None:
            raise ValueError(
                "average_effect must be provided, either in the constructor or in the method call"
            )
        return average_effect

    @abstractmethod
    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """Method to perturbate a dataframe"""

    @classmethod
    def from_config(cls, config):
        """Creates a Perturbator object from a PowerConfig object"""
        return cls(
            average_effect=config.average_effect,
            target_col=config.target_col,
            treatment_col=config.treatment_col,
            treatment=config.treatment,
        )

from_config(config) classmethod

Creates a Perturbator object from a PowerConfig object

Source code in cluster_experiments/perturbator.py
57
58
59
60
61
62
63
64
65
@classmethod
def from_config(cls, config):
    """Creates a Perturbator object from a PowerConfig object"""
    return cls(
        average_effect=config.average_effect,
        target_col=config.target_col,
        treatment_col=config.treatment_col,
        treatment=config.treatment,
    )

perturbate(df, average_effect=None) abstractmethod

Method to perturbate a dataframe

Source code in cluster_experiments/perturbator.py
51
52
53
54
55
@abstractmethod
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """Method to perturbate a dataframe"""

RelativeMixedPerturbator

Bases: Perturbator

RelativeMixedPerturbator is a Perturbator that applies a multiplicative effect to the target column of treated instances, modifying their values by a relative factor depending on whether they are positive or negative.

Source code in cluster_experiments/perturbator.py
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
class RelativeMixedPerturbator(Perturbator):
    """
    RelativeMixedPerturbator is a Perturbator that applies a multiplicative effect to the target column
    of treated instances, modifying their values by a relative factor depending on whether they are positive
    or negative.
    """

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Apply the multiplicative effect to the target column of the treated instances. The effect is calculated
        as a factor of (1 + effect) for non-negative values, and (1 - effect) for negative values.

        Usage:

        ```python
        from cluster_experiments.perturbator import RelativeMixedPerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, -2, 3], "treatment": ["A", "B", "A"]})
        perturbator = RelativeMixedPerturbator()
        perturbator.perturbate(df, average_effect=0.1)
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        df = self.apply_multiplicative_effect(df, average_effect)
        return df

    def apply_multiplicative_effect(
        self, df: pd.DataFrame, effect: Union[float, np.ndarray]
    ) -> pd.DataFrame:
        """
        Apply the relative multiplicative effect to the target column, adjusting values based on whether
        they are positive or negative.
        """
        mask = df[self.treatment_col] == self.treatment
        original_values = df.loc[mask, self.target_col]

        # Calculate new values: apply (1 + effect) for non-negative, (1 - effect) for negative values
        new_values = np.where(
            original_values >= 0,
            original_values * (1 + effect),
            original_values * (1 - effect),
        )

        # The round is required to avoid float imprecision
        df.loc[mask, self.target_col] = np.round(new_values, 2)

        return df

apply_multiplicative_effect(df, effect)

Apply the relative multiplicative effect to the target column, adjusting values based on whether they are positive or negative.

Source code in cluster_experiments/perturbator.py
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
def apply_multiplicative_effect(
    self, df: pd.DataFrame, effect: Union[float, np.ndarray]
) -> pd.DataFrame:
    """
    Apply the relative multiplicative effect to the target column, adjusting values based on whether
    they are positive or negative.
    """
    mask = df[self.treatment_col] == self.treatment
    original_values = df.loc[mask, self.target_col]

    # Calculate new values: apply (1 + effect) for non-negative, (1 - effect) for negative values
    new_values = np.where(
        original_values >= 0,
        original_values * (1 + effect),
        original_values * (1 - effect),
    )

    # The round is required to avoid float imprecision
    df.loc[mask, self.target_col] = np.round(new_values, 2)

    return df

perturbate(df, average_effect=None)

Apply the multiplicative effect to the target column of the treated instances. The effect is calculated as a factor of (1 + effect) for non-negative values, and (1 - effect) for negative values.

Usage:

from cluster_experiments.perturbator import RelativeMixedPerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, -2, 3], "treatment": ["A", "B", "A"]})
perturbator = RelativeMixedPerturbator()
perturbator.perturbate(df, average_effect=0.1)
Source code in cluster_experiments/perturbator.py
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Apply the multiplicative effect to the target column of the treated instances. The effect is calculated
    as a factor of (1 + effect) for non-negative values, and (1 - effect) for negative values.

    Usage:

    ```python
    from cluster_experiments.perturbator import RelativeMixedPerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, -2, 3], "treatment": ["A", "B", "A"]})
    perturbator = RelativeMixedPerturbator()
    perturbator.perturbate(df, average_effect=0.1)
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    df = self.apply_multiplicative_effect(df, average_effect)
    return df

RelativePositivePerturbator

Bases: Perturbator

A Perturbator for continuous, positively-defined targets applies a simulated effect multiplicatively for the treated samples, ie. proportional to the target value for each sample. The number of samples with 0 as target remains unchanged.

target -> target * (1 + average_effect), where -1 < average_effect < inf
                                           and target > 0 for all samples
Source code in cluster_experiments/perturbator.py
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
class RelativePositivePerturbator(Perturbator):
    """
    A Perturbator for continuous, positively-defined targets
    applies a simulated effect multiplicatively for the treated samples, ie.
    proportional to the target value for each sample. The number of samples with 0
    as target remains unchanged.

    ```
    target -> target * (1 + average_effect), where -1 < average_effect < inf
                                               and target > 0 for all samples
    ```
    """

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Usage:
        ```python
        from cluster_experiments.perturbator import RelativePositivePerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
        perturbator = RelativePositivePerturbator()
        # Increase target metric by 50%
        perturbator.perturbate(df, average_effect=0.5)
        # returns pd.DataFrame({"target": [1, 3, 3], "treatment": ["A", "B", "A"]})
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        self.check_relative_positive_effect(df, average_effect)
        df = self.apply_multiplicative_effect(df, average_effect)
        return df

    def check_relative_positive_effect(
        self, df: pd.DataFrame, average_effect: float
    ) -> None:
        self.check_average_effect_greater_than(average_effect, x=-1)
        self.check_target_is_not_negative(df)
        self.check_target_is_not_constant_zero(df, average_effect)

    def check_target_is_not_constant_zero(
        self, df: pd.DataFrame, average_effect: float
    ) -> Optional[NoReturn]:
        treatment_zeros = (
            (df[self.treatment_col] != self.treatment) | (df[self.target_col] == 0)
        ).mean()
        if 1.0 == treatment_zeros:
            raise ValueError(
                f"All treatment samples have {self.target_col} = 0, relative effect "
                f"{average_effect} will have no effect"
            )

    def check_target_is_not_negative(self, df: pd.DataFrame) -> Optional[NoReturn]:
        if any(df[self.target_col] < 0):
            raise ValueError(
                f"All {self.target_col} values need to be positive or 0, "
                f"got {df[self.target_col].min()}"
            )

    def check_average_effect_greater_than(
        self, average_effect: float, x: float
    ) -> Optional[NoReturn]:
        if average_effect <= x:
            raise ValueError(
                f"Simulated effect needs to be greater than {x*100:.0f}%, got "
                f"{average_effect*100:.1f}%"
            )

    def apply_multiplicative_effect(
        self, df: pd.DataFrame, effect: Union[float, np.ndarray]
    ) -> pd.DataFrame:
        df.loc[df[self.treatment_col] == self.treatment, self.target_col] *= 1 + effect
        return df

perturbate(df, average_effect=None)

Usage:

from cluster_experiments.perturbator import RelativePositivePerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
perturbator = RelativePositivePerturbator()
# Increase target metric by 50%
perturbator.perturbate(df, average_effect=0.5)
# returns pd.DataFrame({"target": [1, 3, 3], "treatment": ["A", "B", "A"]})

Source code in cluster_experiments/perturbator.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Usage:
    ```python
    from cluster_experiments.perturbator import RelativePositivePerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
    perturbator = RelativePositivePerturbator()
    # Increase target metric by 50%
    perturbator.perturbate(df, average_effect=0.5)
    # returns pd.DataFrame({"target": [1, 3, 3], "treatment": ["A", "B", "A"]})
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    self.check_relative_positive_effect(df, average_effect)
    df = self.apply_multiplicative_effect(df, average_effect)
    return df

SegmentedBetaRelativePerturbator

Bases: BetaRelativePositivePerturbator

A stochastic Perturbator for continuous targets that applies a sampled effect from the Beta distribution. It applies the effect multiplicatively and based on given segments. For each segment, the average segment effect is sampled from a beta distribution with support in (0, 1). Within each segment, the individual effects are sampled from a beta distribution with mean equal to the segment average effect and support in (range_min, range_max).

The number of samples with 0 as target remains unchanged.

For additional details and recommendations on the parameters, see the documentation for the BetaRelativePerturbator class.

Parameters:

Name Type Description Default
average_effect Optional[float]

the average effect of the treatment. Defaults to None.

None
target_col str

name of the target_col to use as the outcome. Defaults to "target".

'target'
treatment_col str

the name of the column that contains the treatment. Defaults to "treatment".

'treatment'
treatment str

name of the treatment to use as the treated group. Defaults to "B".

'B'
scale Optional[float]

the scale of the effect distribution. Defaults to None.

None
range_min float

the minimum value of the target range, must be >-1. Defaults to -0.8, which allows for up to 5x decreases of the target.

None
range_max float

the maximum value of the target range. Defaults to 4, which allows for up to 5x increases of the target.

None
segment_cols Optional[List[str]]

the columns to use for segmenting. Defaults to None.

required
Source code in cluster_experiments/perturbator.py
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
class SegmentedBetaRelativePerturbator(BetaRelativePositivePerturbator):
    """
    A stochastic Perturbator for continuous targets that applies a sampled
    effect from the Beta distribution. It applies the effect multiplicatively
    and based on given segments.
    For each segment, the average segment effect is sampled from a beta
    distribution with support in (0, 1). Within each segment, the individual
    effects are sampled from a beta distribution with mean equal to the segment
    average effect and support in (range_min, range_max).

    The number of samples with 0 as target remains unchanged.

    For additional details and recommendations on the parameters, see the
    documentation for the `BetaRelativePerturbator` class.

    Arguments:
        average_effect (Optional[float], optional): the average effect of the treatment. Defaults to None.
        target_col (str, optional): name of the target_col to use as the outcome. Defaults to "target".
        treatment_col (str, optional): the name of the column that contains the treatment. Defaults to "treatment".
        treatment (str, optional): name of the treatment to use as the treated group. Defaults to "B".
        scale (Optional[float], optional): the scale of the effect distribution. Defaults to None.
        range_min (float, optional): the minimum value of the target range, must be >-1.
            Defaults to -0.8, which allows for up to 5x decreases of the target.
        range_max (float, optional): the maximum value of the target range.
            Defaults to 4, which allows for up to 5x increases of the target.
        segment_cols (Optional[List[str]], optional): the columns to use for segmenting. Defaults to None.
    """

    def __init__(
        self,
        segment_cols: List[str],
        average_effect: Optional[float] = None,
        target_col: str = "target",
        treatment_col: str = "treatment",
        treatment: str = "B",
        scale: Optional[float] = None,
        range_min: Optional[float] = None,
        range_max: Optional[float] = None,
    ):
        super().__init__(average_effect, target_col, treatment_col, treatment, scale)
        self._range_min = range_min or -0.8
        self._range_max = range_max or 4
        self._segment_cols = segment_cols
        self.segment_col = self._get_segment_col_name(segment_cols)

    @staticmethod
    def _get_segment_col_name(segment_cols: List[str]):
        if not isinstance(segment_cols, list):
            raise ValueError(
                f"segment_cols must be of type List[str], got type {type(segment_cols)}"
            )
        return "_cluster_" + "_".join(segment_cols)

    def _set_segment_col_values(self, df: pd.DataFrame):
        if self.segment_col in df.columns:
            raise ValueError(
                f"Cannot use {self.segment_col=} as perturbator clustering "
                f"column, as it already exists in the input dataframe!"
            )
        return df.copy().assign(
            **{self.segment_col: df[self._segment_cols].astype(str).sum(axis=1)}
        )

    def get_cluster_perturbator_fixed_params(
        self, average_effect: Optional[float] = None
    ) -> Dict[str, Any]:
        average_effect = self.get_average_effect(average_effect)
        self.check_average_effect_greater_than(average_effect, x=0)
        self.check_average_effect_less_than(average_effect, x=1)
        scale = self.get_scale(average_effect)
        return {
            "average_effect": average_effect,
            "scale": scale,
        }

    def get_cluster_perturbator(self, **kwargs) -> Perturbator:
        sampled_effect = self._sample_beta_effect(
            kwargs["average_effect"], kwargs["scale"], 1
        )
        cluster_perturbator = BetaRelativePerturbator(
            average_effect=sampled_effect,
            target_col=self.target_col,
            treatment_col=self.treatment_col,
            treatment=self.treatment,
            range_min=self._range_min,
            range_max=self._range_max,
        )
        return cluster_perturbator

    def perturbate(
        self,
        df: pd.DataFrame,
        average_effect: Optional[float] = None,
    ) -> pd.DataFrame:
        df = df.copy().reset_index(drop=True)
        df = self._set_segment_col_values(df)

        cluster_perturbator_params = self.get_cluster_perturbator_fixed_params(
            average_effect
        )
        df_perturbed = pd.concat(
            [
                self.get_cluster_perturbator(**cluster_perturbator_params).perturbate(
                    df=df[df[self.segment_col] == cluster].copy()
                )
                for cluster in df[self.segment_col].unique()
            ]
        )
        return df_perturbed.drop(columns=self.segment_col).reset_index(drop=True)

    @classmethod
    def from_config(cls, config):
        """Creates a Perturbator object from a PowerConfig object"""
        return cls(
            average_effect=config.average_effect,
            target_col=config.target_col,
            treatment_col=config.treatment_col,
            treatment=config.treatment,
            scale=config.scale,
            range_min=config.range_min,
            range_max=config.range_max,
            segment_cols=config.segment_cols,
        )

from_config(config) classmethod

Creates a Perturbator object from a PowerConfig object

Source code in cluster_experiments/perturbator.py
685
686
687
688
689
690
691
692
693
694
695
696
697
@classmethod
def from_config(cls, config):
    """Creates a Perturbator object from a PowerConfig object"""
    return cls(
        average_effect=config.average_effect,
        target_col=config.target_col,
        treatment_col=config.treatment_col,
        treatment=config.treatment,
        scale=config.scale,
        range_min=config.range_min,
        range_max=config.range_max,
        segment_cols=config.segment_cols,
    )

UniformPerturbator

Bases: Perturbator

UniformPerturbator is a Perturbator that adds a constant effect to the target column of the treated instances.

Source code in cluster_experiments/perturbator.py
 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
class UniformPerturbator(Perturbator):
    """
    UniformPerturbator is a Perturbator that adds a constant effect to the target column of the treated instances.
    """

    def __init__(
        self,
        average_effect: Optional[float] = None,
        target_col: str = "target",
        treatment_col: str = "treatment",
        treatment: str = "B",
    ):
        super().__init__(average_effect, target_col, treatment_col, treatment)
        logging.warning(
            "UniformPerturbator is deprecated and will be removed in future versions. "
            "Use ConstantPerturbator instead."
        )

    def perturbate(
        self, df: pd.DataFrame, average_effect: Optional[float] = None
    ) -> pd.DataFrame:
        """
        Usage:

        ```python
        from cluster_experiments.perturbator import UniformPerturbator
        import pandas as pd
        df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
        perturbator = UniformPerturbator()
        perturbator.perturbate(df, average_effect=1)
        ```
        """
        df = df.copy().reset_index(drop=True)
        average_effect = self.get_average_effect(average_effect)
        df = self.apply_additive_effect(df, average_effect)
        return df

    def apply_additive_effect(
        self, df: pd.DataFrame, effect: Union[float, np.ndarray]
    ) -> pd.DataFrame:
        df.loc[df[self.treatment_col] == self.treatment, self.target_col] += effect
        return df

perturbate(df, average_effect=None)

Usage:

from cluster_experiments.perturbator import UniformPerturbator
import pandas as pd
df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
perturbator = UniformPerturbator()
perturbator.perturbate(df, average_effect=1)
Source code in cluster_experiments/perturbator.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def perturbate(
    self, df: pd.DataFrame, average_effect: Optional[float] = None
) -> pd.DataFrame:
    """
    Usage:

    ```python
    from cluster_experiments.perturbator import UniformPerturbator
    import pandas as pd
    df = pd.DataFrame({"target": [1, 2, 3], "treatment": ["A", "B", "A"]})
    perturbator = UniformPerturbator()
    perturbator.perturbate(df, average_effect=1)
    ```
    """
    df = df.copy().reset_index(drop=True)
    average_effect = self.get_average_effect(average_effect)
    df = self.apply_additive_effect(df, average_effect)
    return df