File size: 7,276 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
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
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:

            # don't expand label if col is a main column or if we don't want the codebook to have expanded labels
            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 it's an intermediate variable or a text message survey variable, don't bother printing
            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 no manual specs, then no fancy labelling
        if var not in self.manual_var_df["VariableName"]:
            # if a survey variable
            if prefix == "Survey":
                new_label = survey + ": " + label

            # if a phase variable; i.e. the encoding is "NewPhase" or "OldPhase"
            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"

        # fancy labelling
        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