Mimic4Dataset / dataset_utils.py
thbndi's picture
Update dataset_utils.py
105bc7d
raw
history blame
13.6 kB
import pandas as pd
import pickle
import numpy as np
import torch
################################################################################
################################################################################
## ##
## MIMIC IV DATASET UTILITY FUNCTIONS ##
## ##
################################################################################
################################################################################
def create_vocab(file,task):
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
condVocab = pickle.load(fp)
condVocabDict={}
condVocabDict[0]=0
for val in range(len(condVocab)):
condVocabDict[condVocab[val]]= val+1
return condVocabDict
def gender_vocab():
genderVocabDict={}
genderVocabDict['<PAD>']=0
genderVocabDict['M']=1
genderVocabDict['F']=2
return genderVocabDict
def vocab(task,diag_flag,proc_flag,out_flag,chart_flag,med_flag,lab_flag):
condVocabDict={}
procVocabDict={}
medVocabDict={}
outVocabDict={}
chartVocabDict={}
labVocabDict={}
ethVocabDict={}
ageVocabDict={}
genderVocabDict={}
insVocabDict={}
ethVocabDict=create_vocab('ethVocab',task)
with open('./data/dict/'+task+'/ethVocabDict', 'wb') as fp:
pickle.dump(ethVocabDict, fp)
ageVocabDict=create_vocab('ageVocab',task)
with open('./data/dict/'+task+'/ageVocabDict', 'wb') as fp:
pickle.dump(ageVocabDict, fp)
genderVocabDict=gender_vocab()
with open('./data/dict/'+task+'/genderVocabDict', 'wb') as fp:
pickle.dump(genderVocabDict, fp)
insVocabDict=create_vocab('insVocab',task)
with open('./data/dict/'+task+'/insVocabDict', 'wb') as fp:
pickle.dump(insVocabDict, fp)
if diag_flag:
file='condVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
condVocabDict = pickle.load(fp)
if proc_flag:
file='procVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
procVocabDict = pickle.load(fp)
if med_flag:
file='medVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
medVocabDict = pickle.load(fp)
if out_flag:
file='outVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
outVocabDict = pickle.load(fp)
if chart_flag:
file='chartVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
chartVocabDict = pickle.load(fp)
if lab_flag:
file='labsVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
labVocabDict = pickle.load(fp)
return (len(condVocabDict),len(procVocabDict),len(medVocabDict),len(outVocabDict),len(chartVocabDict),len(labVocabDict),
ethVocabDict,genderVocabDict,ageVocabDict,insVocabDict,condVocabDict,procVocabDict,medVocabDict,outVocabDict,chartVocabDict,labVocabDict)
###################################
# CONCATENATE DATA FROM #
# DICT TO CREATE CSV FILES #
###################################
def concat_data(data,interval,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab,condDict, procDict, outDict, chartDict, medDict):
meds=data['Med']
proc = data['Proc']
out = data['Out']
charts = data['Chart']
cond= data['Cond']['fids']
proc_df=pd.DataFrame()
out_df=pd.DataFrame()
cond_df=pd.DataFrame()
chart_df=pd.DataFrame()
meds_df=pd.DataFrame()
#demographic
demo=pd.DataFrame(columns=['Age','gender','ethnicity','label','insurance'])
new_row = {'Age': data['age'], 'gender': data['gender'], 'ethnicity': data['ethnicity'], 'label': data['label'], 'insurance': data['insurance']}
demo = demo.append(new_row, ignore_index=True)
##########COND#########
if (feat_cond):
cond_df=pd.DataFrame(np.zeros([1,len(condDict)]),columns=condDict)
if cond:
for c in cond : cond_df[c]=1
##########PROC#########
if (feat_proc):
if proc :
feat=proc.keys()
proc_val=[proc[key] for key in feat]
proc_df=pd.DataFrame(np.zeros([interval,len(procDict)]),columns=procDict)
for p,v in zip(feat,proc_val):
proc_df[p]=v
proc_df.columns=pd.MultiIndex.from_product([["PROC"], proc_df.columns])
else:
procedures=pd.DataFrame(procDict,columns=['PROC'])
features=pd.DataFrame(np.zeros([interval,len(procedures)]),columns=procedures['PROC'])
features.columns=pd.MultiIndex.from_product([["PROC"], features.columns])
proc_df=features.fillna(0)
##########OUT#########
if (feat_out):
if out :
feat=out.keys()
out_val=[out[key] for key in feat]
out_df=pd.DataFrame(np.zeros([interval,len(outDict)]),columns=outDict)
for o,v in zip(feat,out_val):
out_df[o]=v
out_df.columns=pd.MultiIndex.from_product([["OUT"], out_df.columns])
else:
outputs=pd.DataFrame(outDict,columns=['OUT'])
features=pd.DataFrame(np.zeros([interval,len(outputs)]),columns=outputs['OUT'])
features.columns=pd.MultiIndex.from_product([["OUT"], features.columns])
out_df=features.fillna(0)
##########CHART#########
if (feat_chart):
if charts:
charts=charts['val']
feat=charts.keys()
chart_val=[charts[key] for key in feat]
chart_df=pd.DataFrame(np.zeros([interval,len(chartDict)]),columns=chartDict)
for c,v in zip(feat,chart_val):
chart_df[c]=v
chart_df.columns=pd.MultiIndex.from_product([["CHART"], chart_df.columns])
else:
charts=pd.DataFrame(chartDict,columns=['CHART'])
features=pd.DataFrame(np.zeros([interval,len(charts)]),columns=charts['CHART'])
features.columns=pd.MultiIndex.from_product([["CHART"], features.columns])
chart_df=features.fillna(0)
##########LAB#########
if (feat_lab):
if charts:
feat=charts.keys()
chart_val=[charts[key] for key in feat]
chart_df=pd.DataFrame(np.zeros([interval,len(chartDict)]),columns=chartDict)
for c,v in zip(feat,chart_val):
chart_df[c]=v
chart_df.columns=pd.MultiIndex.from_product([["LAB"], chart_df.columns])
else:
charts=pd.DataFrame(chartDict,columns=['LAB'])
features=pd.DataFrame(np.zeros([interval,len(charts)]),columns=charts['LAB'])
features.columns=pd.MultiIndex.from_product([["LAB"], features.columns])
chart_df=features.fillna(0)
###MEDS
if (feat_meds):
if meds:
feat=meds['signal'].keys()
med_val=[meds['amount'][key] for key in feat]
meds_df=pd.DataFrame(np.zeros([interval,len(medDict)]),columns=medDict)
for m,v in zip(feat,med_val):
meds_df[m]=v
meds_df.columns=pd.MultiIndex.from_product([["MEDS"], meds_df.columns])
else:
meds=pd.DataFrame(medDict,columns=['MEDS'])
features=pd.DataFrame(np.zeros([interval,len(meds)]),columns=meds['MEDS'])
features.columns=pd.MultiIndex.from_product([["MEDS"], features.columns])
meds_df=features.fillna(0)
dyn_df = pd.concat([meds_df,proc_df,out_df,chart_df], axis=1)
return dyn_df,cond_df,demo
###################################
# CALLED FOR "tensor" ENCODING #
###################################
def generate_deep(data,interval,task,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab,condDict, procDict, outDict, chartDict, medDict, eth_vocab,gender_vocab,age_vocab,ins_vocab):
meds = []
charts = []
proc = []
out = []
lab = []
stat = []
demo = []
dyn,cond_df,demo=concat_data(data,interval,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab,condDict, procDict, outDict, chartDict, medDict)
if feat_chart:
charts = dyn['CHART'].fillna(0).values
if feat_meds:
meds = dyn['MEDS'].fillna(0).values
if feat_proc:
proc = dyn['PROC'].fillna(0).values
if feat_out:
out = dyn['OUT'].fillna(0).values
if feat_lab:
lab = dyn['LAB'].fillna(0).values
if feat_cond:
stat=cond_df.values[0]
y = int(demo['label'])
demo["gender"].replace(gender_vocab, inplace=True)
demo["ethnicity"].replace(eth_vocab, inplace=True)
demo["insurance"].replace(ins_vocab, inplace=True)
demo["Age"].replace(age_vocab, inplace=True)
demo=demo[["gender","ethnicity","insurance","Age"]]
demo = demo.values[0]
return stat, demo, meds, charts, out, proc, lab, y
###################################
# CALLED FOR "aggreg" OR #
# "concat" ENCODING #
###################################
def generate_ml(dyn, stat, demo, concat_cols, concat):
X_df = pd.DataFrame()
if concat:
dyna=dyn.copy()
dyna.columns=dyna.columns.droplevel(0)
dyna=dyna.to_numpy()
dyna=np.nan_to_num(dyna, copy=False)
dyna=dyna.reshape(1,-1)
dyn_df=pd.DataFrame(data=dyna,columns=concat_cols)
else:
dyn_df=pd.DataFrame()
for key in dyn.columns.levels[0]:
dyn_temp=dyn[key]
if ((key=="CHART") or (key=="MEDS")):
agg=dyn_temp.aggregate("mean")
agg=agg.reset_index()
else:
agg=dyn_temp.aggregate("max")
agg=agg.reset_index()
if dyn_df.empty:
dyn_df=agg
else:
dyn_df=pd.concat([dyn_df,agg],axis=0)
dyn_df=dyn_df.T
dyn_df.columns = dyn_df.iloc[0]
dyn_df=dyn_df.iloc[1:,:]
X_df = pd.concat([dyn_df, stat, demo], axis=1)
return X_df
###################################
# CALLED FOR "text" ENCODING #
###################################
def generate_text(data,icd,items,feat_cond,feat_chart,feat_meds, feat_proc, feat_out):
#Demographics
age = data['age']
gender = data['gender']
if gender=='F':
gender='female'
elif gender=='M':
gender='male'
else:
gender='unknown'
ethn=data['ethnicity'].lower()
ins=data['insurance']
#Diagnosis
if feat_cond:
conds = data.get('Cond', {}).get('fids', [])
conds=[icd[icd['icd_code'] == code]['long_title'].to_string(index=False) for code in conds if not icd[icd['icd_code'] == code].empty]
cond_text = '; '.join(conds)
cond_text = f"The patient ({ethn} {gender}, {age} years old, covered by {ins}) was diagnosed with {cond_text}. " if cond_text else ''
else:
cond_text = ''
#chart
if feat_chart:
chart = data.get('Chart', {})
if chart:
charts = chart.get('val', {})
feat = charts.keys()
chart_val = [charts[key] for key in feat]
chart_mean = [round(np.mean(c), 3) for c in chart_val]
feat_text = [(items[items['itemid'] == f]['label']).to_string(index=False) for f in feat]
chart_text = '; '.join(f"{mean_val} for {feat_label}" for mean_val, feat_label in zip(chart_mean, feat_text))
chart_text = f"The chart events measured were: {chart_text}. "
else:
chart_text = 'No chart events were measured. '
else:
chart_text = ''
#meds
if feat_meds:
meds = data.get('Med', {})
if meds:
feat = meds['signal'].keys()
meds_val = [meds['amount'][key] for key in feat]
meds_mean = [round(np.mean(c), 3) for c in meds_val]
feat_text = [(items[items['itemid'] == f]['label']).to_string(index=False) for f in feat]
meds_text = '; '.join(f"{mean_val} of {feat_label}" for mean_val, feat_label in zip(meds_mean, feat_text))
meds_text = f"The mean amounts of medications administered during the episode were: {meds_text}. "
else:
meds_text = 'No medications were administered. '
else:
meds_text = ''
#proc
if feat_proc:
proc = data['Proc']
if proc:
feat=proc.keys()
feat_text = [(items[items['itemid']==f]['label']).to_string(index=False) for f in feat]
template = 'The procedures performed were: {}. '
proc_text= template.format('; '.join(feat_text))
else:
proc_text='No procedures were performed. '
else:
proc_text=''
#out
if feat_out:
out = data['Out']
if out:
feat=out.keys()
feat_text = [(items[items['itemid']==f]['label']).to_string(index=False) for f in feat]
template ='The outputs collected were: {}.'
out_text = template.format('; '.join(feat_text))
else:
out_text='No outputs were collected.'
else:
out_text=''
return cond_text,chart_text,meds_text,proc_text,out_text