anonymous-submission-acl2025's picture
add 17
8a79f2e
raw
history blame
3.75 kB
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