| import pandas as pd |
| import numpy as np |
| import os |
| import sys |
| import re |
| import math |
|
|
| from lib.utilities import serialize |
|
|
| class OutcomeIndex(): |
|
|
| normalization_csv_path = os.path.join("data","external","intermediate", "IndexNormalizationParameters.csv") |
| weight_csv_path = os.path.join("data","external","intermediate", "IndexVariableWeights.csv") |
|
|
| def __init__(self, name: str, pos_outcomes: list, neg_outcomes: list, moderators: list): |
| self.name = name |
| self.pos_outcomes = pos_outcomes |
| self.neg_outcomes = neg_outcomes |
| self.moderators = moderators |
|
|
| """will be set in add_attributes""" |
| self.phase = str() |
| self.norm_phase = str() |
| self.control_var = str() |
| self.control_val = str() |
|
|
| """will be set in _prep_index""" |
| self.unavailable_vars = [] |
| self.available_vars = [] |
|
|
| def add_attributes(self,phase,indices_constructor): |
| self.phase = phase |
| self.norm_phase = indices_constructor.norm_phase |
| self.control_var = indices_constructor.control_var |
| self.control_val = indices_constructor.control_val |
|
|
| """creates the normalization parameter before index construction""" |
| """ Input: the dataframe containing all the variables for a given phase""" |
| def get_normalization_parameters(self, df): |
| df_outcomes = self._prep_index(df) |
| self._save_mean_sd(df_outcomes) |
| df_outcomes = self._normalize_outcome_vars(df_outcomes) |
| self._get_variable_weights(df_outcomes) |
|
|
| """Creates an index""" |
| def create_index(self, df): |
| df_outcomes = self._prep_index(df) |
|
|
| |
| df_outcomes = self._normalize_outcome_vars(df_outcomes) |
|
|
| |
| var_weights_df = pd.read_csv(self.weight_csv_path, index_col='index') |
| var_weights = var_weights_df.to_dict(orient='index') |
|
|
| df_outcomes.index = df_outcomes["AppCode"] |
| df_outcomes = df_outcomes.drop(columns=["AppCode", self.control_var]) |
|
|
| |
| for index,row in df_outcomes.iterrows(): |
| non_empty_cols = [x for x in df_outcomes.columns if not math.isnan(df_outcomes.loc[index,x])] |
| df_outcomes.loc[index,"Denominator"] = sum([var_weights[x]["Weight"] for x in non_empty_cols]) |
| df_outcomes.loc[index,"Numerator"] = sum([var_weights[x]["Weight"]*row[x] for x in non_empty_cols]) |
| df_outcomes[self.name] = df_outcomes["Numerator"]/df_outcomes["Denominator"] |
| df_index = df_outcomes.reset_index()[["AppCode", self.name]] |
|
|
| |
| if self.phase == self.norm_phase: |
| df = df[["AppCode",self.control_var]].merge(df_index, how='outer', on="AppCode") |
| self._save_mean_sd(df) |
|
|
| |
| mean_sd_dic = pd.read_csv(self.normalization_csv_path, index_col='index').to_dict(orient='index') |
| mean = mean_sd_dic[self.name]["mean"] |
| sd = mean_sd_dic[self.name]["std"] |
| df_index[self.name] = df_index[self.name].apply(lambda x: (x - mean) / sd) |
| return df_index |
|
|
|
|
| """ |
| Input: |
| indices - Indices object - used for providing some attributes to the index class |
| df - will be a df without prefixes |
| |
| Output: |
| - df_outcomes - contains only AppCode,self.control_var, and the available outcome variables""" |
|
|
| def _prep_index(self, df): |
| outcome_vars = self.pos_outcomes + self.neg_outcomes |
| self.available_vars = [x for x in outcome_vars if x in df.columns] |
| self.unavailable_vars = list(set(outcome_vars) - set(self.available_vars)) |
|
|
| for unavailable_var in self.unavailable_vars: |
| print(f"\t Missing {unavailable_var}") |
|
|
| identifier_vars = ["AppCode", self.control_var] |
| keep_vars = identifier_vars + self.available_vars |
| df_outcomes = df[keep_vars] |
| for col in df_outcomes.columns: |
| if col not in identifier_vars: |
| df_outcomes[col] = pd.to_numeric(df_outcomes[col], errors = 'coerce') |
| return df_outcomes |
|
|
| """normalizes outcome vars and negates negative vars""" |
| def _normalize_outcome_vars(self, df_outcomes): |
| mean_sd_dic = pd.read_csv(self.normalization_csv_path, index_col='index').to_dict(orient='index') |
| for col in self.available_vars: |
|
|
| |
| df_outcomes[col] = pd.to_numeric(df_outcomes[col], errors='coerce') |
| if col in mean_sd_dic: |
| mean = mean_sd_dic[col]["mean"] |
| sd = mean_sd_dic[col]["std"] |
| count = mean_sd_dic[col]["count"] |
| else: |
| print(f"WARNING: no {self.norm_phase} value for {col}!!!") |
| print("ENSURE THIS IS NOT AN ERROR. This should have been created in get_normalization_parameters") |
| mean = df_outcomes[col].mean() |
| sd = df_outcomes[col].std() |
| count = df_outcomes[col].count() |
|
|
| if sd != 0 and count > 1: |
| df_outcomes[col] = df_outcomes[col].apply(lambda x: (x - mean) / sd) |
| else: |
| print(f"{col} has an sd = 0 or empty") |
| df_outcomes[col] = np.nan |
| self.available_vars.remove(col) |
| continue |
|
|
| |
| if col in self.neg_outcomes: |
| df_outcomes[col] = df_outcomes[col].apply(lambda x: -x) |
|
|
| return df_outcomes |
|
|
|
|
| def _get_variable_weights(self,df_outcomes): |
| |
| for_cov_matrix = df_outcomes[self.available_vars] |
|
|
| |
| for_cov_matrix = for_cov_matrix.fillna(0) |
| for_cov_matrix = for_cov_matrix.astype(float) |
|
|
| |
| cov = for_cov_matrix.cov() |
|
|
| |
| assert len(cov.columns) == len(self.available_vars) |
| inverse_cov = np.linalg.inv(cov.values) |
|
|
| |
| sums = inverse_cov.sum(axis=0) |
|
|
| |
| var_weights_df = pd.DataFrame.from_dict(dict(zip(self.available_vars, sums)),orient = 'index').reset_index().rename(columns = {0:"Weight"}) |
| serialize.update_csv(var_weights_df, self.weight_csv_path) |
|
|
| def _save_mean_sd(self, df): |
| df_control_outcomes = df.loc[df[self.control_var] == self.control_val].drop( |
| columns=[self.control_var, "AppCode"]) |
| df_sum = df_control_outcomes.describe().transpose().reset_index() |
| serialize.update_csv(df_sum, self.normalization_csv_path) |