File size: 6,630 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
import pandas as pd
import numpy as np
import os
import sys

from lib.experiment_specs import study_config
from lib.utilities import serialize


main_codebook_path = os.path.join("data","external","intermediate","CompressedCodebook.csv")
final_codebook_path = os.path.join("data","external","final","CodebookFinal.csv")
manual_specs_path = os.path.join("lib","experiment_specs","ManualCodebookSpecs.xlsx")
value_label_path = os.path.join("lib","experiment_specs","value_labels.yaml")

phase_encode_options = ["Survey","OldPhase","NewPhase"]
codebook_vars = ["VariableName","VariableLabel","RawVariableName","DataType","PrefixEncoding","ValueLabels"]


"""
Function which saves over previous codebook and creates new codebook starting with master_codebook. It only reads the codebook sheet you input.
"""
def initialize_main_codebook():
    cb = pd.read_excel(manual_specs_path,sheet_name = "User")
    new_cols = [x for x in codebook_vars if x not in cb.columns]
    for new_col in new_cols:
        cb[new_col] = ""
    cb.to_csv(main_codebook_path, index = False)

"""
Function which adds all non-empty values in the manual_specs to the codebook on disk. This is a substitute for initialize codebook, when we don't 
want to reread all the survey names
"""
def update_master_specs():
    #try:
    cb = pd.read_csv(main_codebook_path, index_col = "VariableName").to_dict(orient = 'index')
    ms = pd.read_excel(manual_specs_path, index_col = "VariableName", sheet_name= "User").to_dict(orient = 'index')
    for col,chars in ms.items():
        #if col not in codebook, add all specs
        try:
            if col not in cb:
                cb[col] = ms[col]
                cb[col]["ValueLabels"] = None

            #if col in codebook, add all specs that are NOT Empty in the manual specs
            else:
                for char, val in chars.items():
                    #if not ((type(val) == float) and (np.isnan(val))):
                    cb[col][char] = ms[col][char]
        except:
            print(f"error updating {col} in codebook")

        pd.DataFrame.from_dict(cb, orient='index').to_csv(main_codebook_path, index_label="VariableName")

"""
changes variable names in the dataframe according to all vars in the master codebook for which the raw name is different from the regular name 
(this function should only be applied to surveys)
"""
def rename_vars(df):
    specs = pd.read_excel(manual_specs_path)
    new_vars = specs.loc[(specs["VariableName"] != specs["RawVariableName"]) &
                         (specs["VariableName"].notnull()) &
                         (specs["RawVariableName"].notnull())]

    var_dic = dict(zip(new_vars["RawVariableName"], new_vars["VariableName"]))
    for var in df.columns.values:
        if var in var_dic.keys():
            df = df.rename(columns = {var : var_dic[var]})
    return df

"""
Adds raw variable names and labels form surveys to codebook
"""
def add_vardic_to_codebook(vardic):
    cb = pd.read_csv(main_codebook_path,index_col = "VariableName").to_dict(orient = 'index')
    for col, chars in vardic.items():

        # If var is already specified in code book (i.e. the var is manually specified)
        if col in cb:

            #Only modify a char if it is empty
            for cb_var in ["VariableLabel","DataType","PrefixEncoding"]:
                val = cb[col][cb_var]
                if type(val) == float and np.isnan(val):
                    cb[col][cb_var] = vardic[col][cb_var]

        # Add the var to the codebook
        else:
            cb[col] = {
                "VariableLabel": chars["VariableLabel"],
                "RawVariableName": None,
                "DataType": chars["DataType"],
                "PrefixEncoding": chars["PrefixEncoding"],
                "ValueLabels": None
            }

    pd.DataFrame.from_dict(cb, orient = 'index').to_csv(main_codebook_path, index_label = "VariableName" )

"""
Reads in dictionary from value_labels.yaml and populates the ValueLabels column in the master codebook
"""
def add_labels_to_codebook():
    cb = pd.read_csv(main_codebook_path, index_col="VariableName").to_dict(orient='index')
    label_dic = serialize.open_yaml(value_label_path)
    for label, chars in label_dic.items():
        for variable in chars["VariableList"]:
            if variable in cb:
                cb[variable]["ValueLabels"] = chars["ValueLabels"]
    pd.DataFrame.from_dict(cb, orient = 'index').to_csv(main_codebook_path, index_label = "VariableName")



def create_expanded_codebook(df):
    cb_e = df.iloc[0,:].transpose().reset_index()
    cb_e.columns = ["VariableName","VariableLabel"]
    cb_e.index = cb_e["VariableName"]
    cb_e["ValueLabels"] = ""
    cb_e = cb_e.drop(columns = "VariableName").to_dict(orient='index')

    label_dic = serialize.open_yaml(value_label_path)
    for label, chars in label_dic.items():
        for variable in chars["VariableList"]:
            for code in [study_config.surveys[x]["Code"] for x in study_config.surveys.keys()]:
                full_var = code+"_"+variable
                if full_var in cb_e:
                    cb_e[full_var]["ValueLabels"] = chars["ValueLabels"]

    pd.DataFrame.from_dict(cb_e, orient = 'index').to_csv(final_codebook_path, index_label = "VariableName")

"""given the treatment phase and the codebook dic, this function inputs a varname and outputs
    the varname with a prefix"""
def add_prefix_var(var,phase,codebook_dic,):
    start_code = study_config.phases[phase]["StartSurvey"]["Code"]
    end_code = study_config.phases[phase]["EndSurvey"]["Code"]

    if var in study_config.main_cols+study_config.embedded_main_cols:
        return var

    elif var not in codebook_dic:
        print(f"{var} not in codebook!!")
        return start_code + "_" + var

    elif codebook_dic[var]["PrefixEncoding"] == "Survey":
        "if it's a survey variable, assume that it's phrased as 'in the past three weeks' "

        if phase == "Phase1":
            "for phase1 the survey vars focus on the 3 weeks BEFORE the baseline(start) survey"
            return start_code + "_" + var

        else:
            "For phase 2 and 3, the survey vars focus on the 3 weeks AFTER the start survey"
            return end_code + "_" + var

    elif codebook_dic[var]["PrefixEncoding"] == "NewPhase":
        "If it's a variable on use in the future, always use the start survey"
        return start_code + "_" + var

    elif codebook_dic[var]["PrefixEncoding"] == "OldPhase":
        """These variables collect use data that are reported in the end survey (i.e. Web Data) """
        return end_code + "_" + var