|
|
import os |
|
|
import re |
|
|
import sys |
|
|
import numpy as np |
|
|
import pandas as pd |
|
|
from lib.utilities import codebook |
|
|
from lib.utilities import serialize |
|
|
from lib.experiment_specs import study_config |
|
|
|
|
|
|
|
|
""" Class that contains functions that |
|
|
- labels the values of certain categorical variables specified in lib.{experiment_name}_specs.value_labels.yaml |
|
|
- labels the variables of an expanded dataframe right before it becomes a stata file """ |
|
|
|
|
|
class Labeler: |
|
|
|
|
|
def __init__(self, codebook_dict: dict, sheet: str, is_wide: bool): |
|
|
self.label_codes = ["[PreviousSurvey]", "[Survey]", "[NextSurvey]", "[OldPhase]", "[NewPhase]"] |
|
|
self.is_wide = is_wide |
|
|
self.label_code_dic = Labeler._create_encode_dic() |
|
|
self.codebook = codebook_dict |
|
|
|
|
|
names = [x for x in study_config.surveys.keys()] |
|
|
codes = [study_config.surveys[x]["Code"] for x in study_config.surveys.keys()] |
|
|
self.code_survey_dic = dict(zip(codes, names)) |
|
|
self.manual_var_df = pd.read_excel(codebook.manual_specs_path) |
|
|
|
|
|
|
|
|
""" creates a new first row in the dataframe which will contain the variable labels, as specified in the data\intermediate\mastercodebook""" |
|
|
def add_labels_to_df(self,df): |
|
|
df = df.reset_index(drop=True) |
|
|
df.index = df.index + 1 |
|
|
df.loc[0] = "" |
|
|
df = df.sort_index() |
|
|
|
|
|
for col in df.columns: |
|
|
|
|
|
|
|
|
if (col in study_config.main_cols+study_config.embedded_main_cols) or (self.is_wide == False): |
|
|
if col in self.codebook: |
|
|
new_label = self.codebook[col]["VariableLabel"] |
|
|
|
|
|
else: |
|
|
print(f"{col} not in codebook (main column) !!!") |
|
|
new_label = col |
|
|
|
|
|
else: |
|
|
new_label = self._expand_label(col) |
|
|
|
|
|
df.loc[0, col] = new_label |
|
|
return df |
|
|
|
|
|
""" Expands the label for a given variable specified in the master codebook. Specifically: |
|
|
- if none of the label_codes are in the label, then a default expander is used |
|
|
- if a label_code is in the label, then they are substituted using the dictionary created in _create_encode_dic, also visualized in |
|
|
lib.tempation_specs.label_code_dic.json """ |
|
|
def _expand_label(self, variable): |
|
|
try: |
|
|
code, var = variable.split("_",1) |
|
|
except: |
|
|
print(f"Error extracting {variable} prefix") |
|
|
return variable |
|
|
|
|
|
survey = self.code_survey_dic[code] |
|
|
|
|
|
if var not in self.codebook: |
|
|
|
|
|
|
|
|
if ("_str" in var) or ("T" == var[0]): |
|
|
return variable |
|
|
else: |
|
|
print(f"{var} not in codebook!") |
|
|
return variable |
|
|
|
|
|
label = str(self.codebook[var]["VariableLabel"]) |
|
|
prefix = str(self.codebook[var]["PrefixEncoding"]) |
|
|
|
|
|
|
|
|
if var not in self.manual_var_df["VariableName"]: |
|
|
|
|
|
if prefix == "Survey": |
|
|
new_label = survey + ": " + label |
|
|
|
|
|
|
|
|
else: |
|
|
try: |
|
|
phase = study_config.surveys[survey][prefix] |
|
|
phase_label = study_config.phases[phase]["Label"] |
|
|
new_label = phase_label + ": " + label |
|
|
except: |
|
|
print( |
|
|
f"survey ({survey}) or phase label ({label}) not correctly specified in study config") |
|
|
new_label = "BLAH" |
|
|
|
|
|
|
|
|
else: |
|
|
for label_code in self.label_codes: |
|
|
if label_code in label: |
|
|
label = label.replace(label_code,self.label_code_dic[survey][label_code]) |
|
|
new_label = label |
|
|
|
|
|
return new_label |
|
|
|
|
|
"""Creates a dictionary that will map macros in the compressed codebook to actual values in the expanded codebook. For example, |
|
|
if a label in the compressed codebook contains '[PreviousSurvey]', the label for M_MobileUseMinutes well end up containing 'Baseline' """ |
|
|
@staticmethod |
|
|
def _create_encode_dic(): |
|
|
label_code_dic = {} |
|
|
for phase, specs in study_config.phases.items(): |
|
|
start_survey = specs["StartSurvey"]["Name"] |
|
|
|
|
|
old_phase = study_config.surveys[start_survey]["OldPhase"] |
|
|
new_phase = study_config.surveys[start_survey]["NewPhase"] |
|
|
survey = start_survey |
|
|
|
|
|
try: |
|
|
old_survey = study_config.phases[old_phase]["StartSurvey"]["Name"] |
|
|
except: |
|
|
old_survey = "Doesn't Exist" |
|
|
|
|
|
try: |
|
|
new_survey = study_config.phases[new_phase]["EndSurvey"]["Name"] |
|
|
except: |
|
|
new_survey = "Doesn't Exist" |
|
|
|
|
|
label_code_dic[survey] = { |
|
|
"[PreviousSurvey]": old_survey, |
|
|
"[Survey]": survey, |
|
|
"[NextSurvey]": new_survey, |
|
|
"[OldPhase]": old_phase, |
|
|
"[NewPhase]": new_phase |
|
|
} |
|
|
import json |
|
|
|
|
|
with open(os.path.join('lib','experiment_specs','label_code_dic.json'), 'w') as fp: |
|
|
json.dump(label_code_dic, fp) |
|
|
|
|
|
return label_code_dic |
|
|
|
|
|
|
|
|
"""Encodes all values for variables listed in lib.experiment_specs.value_labels, and adds these value labels to codebook""" |
|
|
|
|
|
@staticmethod |
|
|
def label_values(df): |
|
|
label_dic = serialize.open_yaml(codebook.value_label_path) |
|
|
for encoding, chars in label_dic.items(): |
|
|
if encoding == "Scale": |
|
|
for var_suffix in chars["VariableList"]: |
|
|
for prefix in [x["Code"] for x in study_config.surveys.values()]: |
|
|
var = prefix + "_" + var_suffix |
|
|
if var in df.columns: |
|
|
df[var] = df[var].astype(str).replace("nan", "") |
|
|
df[f"{var}_num"] = df[var].apply(lambda x: re.sub("[^0-9]", "", x)).replace(" ", "") |
|
|
df = df.rename(columns={var: var + "_str", var + "_num": var}) |
|
|
else: |
|
|
for var_suffix in chars["VariableList"]: |
|
|
for prefix in set([study_config.surveys[x]["Code"] for x in study_config.surveys.keys()]): |
|
|
var = prefix + "_" + var_suffix |
|
|
if var in df.columns: |
|
|
try: |
|
|
df[var] = df[var].astype(str).replace("nan", np.nan).replace("", np.nan) |
|
|
df.loc[df[var].notnull(), var + "_num"] = df.loc[df[var].notnull(), |
|
|
var].apply( |
|
|
lambda x: chars["ValueLabels"][x]).astype(float) |
|
|
df = df.rename(columns={var: var + "_str", var + "_num": var}) |
|
|
except: |
|
|
print(f"{var} was not properly encoded!") |
|
|
codebook.add_labels_to_codebook() |
|
|
return df |
|
|
|
|
|
|
|
|
|
|
|
|