File size: 3,754 Bytes
8a79f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
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

import pandas as pd
from stochatreat import stochatreat

import random
from functools import reduce
random.seed(13984759)


"""Assigns treatments in prep for the assignment Survey. If there is a used_cl, the assign_treatment function will use
ActualUse data from the used CL
 - Treatment Assignment will use data from the old_phase
 - New treatment assignment will take effect in the new_phase"""

class Treatment():

    def __init__(self,seed):
        self.i = seed

    def prepare_strat(self, df,continuous_strat,discrete_strat):
        #discretize continuous strat
        for var in continuous_strat:
            df[var] = df[var].astype(float)
            median = df[var].median()
            df.loc[df[var] >= median,var+"Strat"] = f"{var}High"
            df.loc[df[var] < median, var + "Strat"] = f"{var}Low"

            #If var is missing a strat value, put in low
            df.loc[df[var].isnull(), var + "Strat"] = f"{var}Low"

        #label discrete strat
        for var in discrete_strat:
            df[var+"Strat"] = df[var].astype(str).apply(lambda x: var+x)

        #compose strat var
        strat_vars = [x+"Strat" for x in discrete_strat+continuous_strat]
        df["Stratifier"] = df[strat_vars].values.tolist()
        df["Stratifier"] = df["Stratifier"].apply(lambda x: 'X'.join(x))
        return df

    """ Used to assign randomly assign treatment to a subset of the data. The varname should already be in the data set. The function only modifies the values for the subset

         Input:
          - df: the full dataframe
          - subset_var: the categorical vairable used to subset
          - subset_val: the value of subset_var we will keep
          - inputs to _assign_treat_var

          Outpu:
          - the full df with the varname randomly filled"""

    def subset_treat_var_wrapper(self,df, subset_var, subset_val, rand_dict: dict, stratum_cols: list, varname):
        r_varname = "Randomized" + varname
        df_dl = self.assign_treat_var(df=df.loc[df[subset_var] == subset_val],
                                       rand_dict=rand_dict,
                                       stratum_cols=stratum_cols,
                                       varname=r_varname)

        df = df.merge(df_dl[["AppCode", r_varname]], how='left', on="AppCode")
        df.loc[df[subset_var] == subset_val, varname] = df.loc[
            df[subset_var] == subset_val, r_varname]
        df = df.drop(columns=[r_varname])
        return df

    def assign_treat_var(self, df: pd.DataFrame, rand_dict: dict, stratum_cols: list, varname: str):
        treats = stochatreat(data=df,
                             stratum_cols=stratum_cols,
                             treats=len(rand_dict.keys()),
                             probs=list(rand_dict.values()),
                             idx_col='AppCode',
                             random_state= self.i,
                             misfit_strategy='stratum'
                             )

        self.i = self.i * 2

        raw_treat_values = range(len(rand_dict.keys()))
        treat_labels = list(rand_dict.keys())
        translate_dict = dict(zip(raw_treat_values, treat_labels))
        treats[varname] = treats["treat"].apply(lambda x: translate_dict[x])

        treat_tab = pd.crosstab(treats["stratum_id"], treats[varname], margins=True).reset_index()

        df = df.merge(treats[["AppCode", varname]], on="AppCode")
        # Assert that the number of strata equal the number of rows when group the treatment df by strata
        value_len = [len(df[x].unique()) for x in stratum_cols]
        number_of_strata = reduce(lambda x, y: x * y, value_len)

        assert len(treats["stratum_id"].unique()) == number_of_strata
        return df