Mimic4Dataset / Mimic4Dataset.py
thbndi's picture
Update Mimic4Dataset.py
1c4c7b5
raw
history blame
13.6 kB
import csv
import json
import os
import pandas as pd
import datasets
import sys
import pickle
import subprocess
import shutil
from urllib.request import urlretrieve
_DESCRIPTION = """\
Dataset for mimic4 data, by default for the Mortality task.
Available tasks are: Mortality, Length of Stay, Readmission, Phenotype, Mortality Custom, Length of Stay Custom, Readmission Custom, Phenotype Custom.
The data is extracted from the mimic4 database using this pipeline: 'https://github.com/healthylaife/MIMIC-IV-Data-Pipeline/tree/main'
mimic path should have this form : "path/to/mimic4data/from/username/mimiciv/2.2"
If you choose a Custom task provide a configuration file for the Time series.
"""
_HOMEPAGE = "https://huggingface.co/datasets/thbndi/Mimic4Dataset"
_CITATION = "https://proceedings.mlr.press/v193/gupta22a.html"
_URL = "https://github.com/healthylaife/MIMIC-IV-Data-Pipeline"
_DATA_GEN = 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/data_generation_icu_modify.py'
_DAY_INT= 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/day_intervals_cohort_v22.py'
_COHORT = 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/cohort.py'
_CONFIG_URLS = {'los' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/los.config',
'mortality' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/mortality.config',
'phenotype' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/phenotype.config',
'readmission' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/readmission.config'
}
class Mimic4DatasetConfig(datasets.BuilderConfig):
"""BuilderConfig for Mimic4Dataset."""
def __init__(
self,
**kwargs,
):
super().__init__(**kwargs)
class Mimic4Dataset(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.0.0")
def __init__(self, **kwargs):
self.mimic_path = kwargs.pop("mimic_path", None)
self.config_path = kwargs.pop("config_path",None)
super().__init__(**kwargs)
BUILDER_CONFIGS = [
Mimic4DatasetConfig(
name="Phenotype",
version=VERSION,
description="Dataset for mimic4 Phenotype task"
),
Mimic4DatasetConfig(
name="Readmission",
version=VERSION,
description="Dataset for mimic4 Readmission task"
),
Mimic4DatasetConfig(
name="Length of Stay",
version=VERSION,
description="Dataset for mimic4 Length of Stay task"
),
Mimic4DatasetConfig(
name="Mortality",
version=VERSION,
description="Dataset for mimic4 Mortality task"
),
Mimic4DatasetConfig(
name="Phenotype Custom",
version=VERSION,
description="Dataset for mimic4 Custom Phenotype task"
),
Mimic4DatasetConfig(
name="Readmission Custom",
version=VERSION,
description="Dataset for mimic4 Custom Readmission task"
),
Mimic4DatasetConfig(
name="Length of Stay Custom",
version=VERSION,
description="Dataset for mimic4 Custom Length of Stay task"
),
Mimic4DatasetConfig(
name="Mortality Custom",
version=VERSION,
description="Dataset for mimic4 Custom Mortality task"
),
]
DEFAULT_CONFIG_NAME = "Mortality"
def _info(self):
features = datasets.Features(
{
"label": datasets.ClassLabel(names=["0", "1"]),
"gender": datasets.Value("string"),
"ethnicity": datasets.Value("string"),
"insurance": datasets.Value("string"),
"age": datasets.Value("int32"),
"COND": datasets.Sequence(datasets.Value("string")),
"MEDS": {
"signal":
{
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
}
,
"rate":
{
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
}
,
"amount":
{
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
}
},
"PROC": {
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
},
"CHART":
{
"signal" : {
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
},
"val" : {
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
},
},
"OUT": {
"id": datasets.Sequence(datasets.Value("int32")),
"value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
},
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager: datasets.DownloadManager()):
if self.config.name == 'Phenotype' : self.config_path = _CONFIG_URLS['phenotype']
if self.config.name == 'Readmission' : self.config_path = _CONFIG_URLS['readmission']
if self.config.name == 'Length of Stay' : self.config_path = _CONFIG_URLS['los']
if self.config.name == 'Mortality' : self.config_path = _CONFIG_URLS['mortality']
if self.config.name in ['Phenotype Custom','Readmission Custom','Length of Stay Custom','Mortality Custom'] and self.config.name==None:
raise ValueError('Please select a config file')
version = self.mimic_path.split('/')[-1]
m = self.mimic_path.split('/')[-2]
s='/'+m+'/'+version
current_directory = os.getcwd()
if os.path.exists(os.path.dirname(current_directory)+'/MIMIC-IV-Data-Pipeline-main'):
dir =os.path.dirname(current_directory)
os.chdir(dir)
else:
#move to parent directory of mimic data
dir = self.mimic_path.replace(s,'')
if dir[-1]!='/':
dir=dir+'/'
elif dir=='':
dir="./"
parent_dir = os.path.dirname(self.mimic_path)
os.chdir(parent_dir)
#clone git repo if doesnt exists
repo_url='https://github.com/healthylaife/MIMIC-IV-Data-Pipeline'
if os.path.exists('MIMIC-IV-Data-Pipeline-main'):
path_bench = './MIMIC-IV-Data-Pipeline-main'
else:
path_bench ='./MIMIC-IV-Data-Pipeline-main'
subprocess.run(["git", "clone", repo_url, path_bench])
os.makedirs(path_bench+'/mimic-iv')
shutil.move(version,path_bench+'/mimic-iv')
os.chdir(path_bench)
self.mimic_path = './mimic-iv/'+version
#download config file if not custom
if self.config_path[0:4] == 'http':
c = self.config_path.split('/')[-1]
file_path, head = urlretrieve(self.config_path,c)
else :
file_path = self.config_path
#create config folder
if not os.path.exists('./config'):
os.makedirs('config')
#save config file in config folder
conf='./config/'+file_path.split('/')[-1]
if not os.path.exists(conf):
shutil.move(file_path,'./config')
#downloads modules from hub
if not os.path.exists('./model/data_generation_icu_modify.py'):
file_path, head = urlretrieve(_DATA_GEN, "data_generation_icu_modify.py")
shutil.move(file_path, './model')
if not os.path.exists('./preprocessing/day_intervals_preproc/day_intervals_cohort_v22.py'):
file_path, head = urlretrieve(_DAY_INT, "day_intervals_cohort_v22.py")
shutil.move(file_path, './preprocessing/day_intervals_preproc')
file_path, head = urlretrieve(_COHORT, "cohort.py")
if not os.path.exists('cohort.py'):
shutil.move(file_path, './')
data_dir = "./data/dict/"+self.config.name.replace(" ","_")+"/dataDic"
sys.path.append(path_bench)
config = self.config_path.split('/')[-1]
script = 'python cohort.py '+ self.config.name.replace(" ","_") +" "+ self.mimic_path+ " "+path_bench+ " "+config
print(script)
if not os.path.exists(data_dir) :
os.system(script)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_dir}),
]
def _generate_examples(self, filepath):
with open(filepath, 'rb') as fp:
dataDic = pickle.load(fp)
for hid, data in dataDic.items():
proc_features = data['Proc']
chart_features = data['Chart']
meds_features = data['Med']
out_features = data['Out']
cond_features = data['Cond']['fids']
eth= data['ethnicity']
age = data['age']
gender = data['gender']
label = data['label']
insurance=data['insurance']
items = list(proc_features.keys())
values =[proc_features[i] for i in items ]
procs = {"id" : items,
"value": values}
items_outs = list(out_features.keys())
values_outs =[out_features[i] for i in items_outs ]
outs = {"id" : items_outs,
"value": values_outs}
#chart signal
if ('signal' in chart_features):
items_chart_sig = list(chart_features['signal'].keys())
values_chart_sig =[chart_features['signal'][i] for i in items_chart_sig ]
chart_sig = {"id" : items_chart_sig,
"value": values_chart_sig}
else:
chart_sig = {"id" : [],
"value": []}
#chart val
if ('val' in chart_features):
items_chart_val = list(chart_features['val'].keys())
values_chart_val =[chart_features['val'][i] for i in items_chart_val ]
chart_val = {"id" : items_chart_val,
"value": values_chart_val}
else:
chart_val = {"id" : [],
"value": []}
charts = {"signal" : chart_sig,
"val" : chart_val}
#meds signal
if ('signal' in meds_features):
items_meds_sig = list(meds_features['signal'].keys())
values_meds_sig =[meds_features['signal'][i] for i in items_meds_sig ]
meds_sig = {"id" : items_meds_sig,
"value": values_meds_sig}
else:
meds_sig = {"id" : [],
"value": []}
#meds rate
if ('rate' in meds_features):
items_meds_rate = list(meds_features['rate'].keys())
values_meds_rate =[meds_features['rate'][i] for i in items_meds_rate ]
meds_rate = {"id" : items_meds_rate,
"value": values_meds_rate}
else:
meds_rate = {"id" : [],
"value": []}
#meds amount
if ('amount' in meds_features):
items_meds_amount = list(meds_features['amount'].keys())
values_meds_amount =[meds_features['amount'][i] for i in items_meds_amount ]
meds_amount = {"id" : items_meds_amount,
"value": values_meds_amount}
else:
meds_amount = {"id" : [],
"value": []}
meds = {"signal" : meds_sig,
"rate" : meds_rate,
"amount" : meds_amount}
yield int(hid), {
"label" : label,
"gender" : gender,
"ethnicity" : eth,
"insurance" : insurance,
"age" : age,
"COND" : cond_features,
"PROC" : procs,
"CHART" : charts,
"OUT" : outs,
"MEDS" : meds
}