-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathMIMIC_IV_HAIM_API.py
2104 lines (1726 loc) · 106 KB
/
MIMIC_IV_HAIM_API.py
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# %%
###########################################################################################################
# __ __ ___ __ .___ ___.
# | | | | / \ | | | \/ |
# | |__| | / ^ \ | | | \ / |
# | __ | / /_\ \ | | | |\/| |
# | | | | / _____ \ | | | | | |
# |__| |__| /__/ \__\ |__| |__| |__|
#
# HOLISTIC ARTIFICIAL INTELLIGENCE IN MEDICINE
#
###########################################################################################################
#
# Licensed under the Apache License, Version 2.0**
# You may not use this file except in compliance with the License. You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing permissions and limitations under the License.
#-> Authors:
# Luis R Soenksen (<[email protected]>),
# Yu Ma (<[email protected]>),
# Cynthia Zeng (<[email protected]>),
# Leonard David Jean Boussioux (<[email protected]>),
# Kimberly M Villalobos Carballo (<[email protected]>),
# Liangyuan Na (<[email protected]>),
# Holly Mika Wiberg (<[email protected]>),
# Michael Lingzhi Li (<[email protected]>),
# Ignacio Fuentes (<[email protected]>),
# Dimitris J Bertsimas (<[email protected]>),
# -> Last Update: Dec 30th, 2021
# -> Changes:
# * Added embeddings extraction wrappers
# * Added Code for Patient parsing towards Multi-Input AI/ML to predict value of Next Lab/X-Ray with MIMIC-IV
# * Add Model helper functions
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# PREREQUISITS |
# |
## -> To run this code, we first need to install serveral required packages
#!pip install tensorflow
#!pip install tqdm==4.19.9
#!pip install dask
#!pip install sklearn
#!pip install tsfresh
#!pip install missingno
#!pip install transformers
#!pip install torch==1.0.1
#!pip install torchvision==0.2.2
#!pip install torchxrayvision
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# IMPORTS |
# System
import os
import sys
# Base
import cv2
import math
import copy
import pickle
import numpy as np
import pandas as pd
import pandas.io.sql as psql
import datetime as dt
import plotly.express as px
import matplotlib.pyplot as plt
import missingno as msno
from tqdm import tqdm
from glob import glob
from shutil import copyfile
from dask import dataframe as dd
from dask.diagnostics import ProgressBar
ProgressBar().register()
# Core AI/ML
import tensorflow as tf
import torch
import torch.nn.functional as F
import torchvision, torchvision.transforms
from torch.utils.data import Dataset, DataLoader
# Scipy
from scipy.stats import ks_2samp
from scipy.signal import find_peaks
# Scikit-learn
from sklearn.preprocessing import scale
from sklearn.preprocessing import MinMaxScaler, QuantileTransformer
# TSFresh
# from tsfresh import extract_features, select_features
# from tsfresh.utilities.dataframe_functions import impute
#TS (Manual) module
# from ts_embeddings import *
# NLP
from transformers import AutoTokenizer, AutoModel, logging
logging.set_verbosity_error()
# biobert_path = '../pretrained_models/bio_clinical_bert/biobert_pretrain_output_all_notes_150000/'
biobert_path = 'pretrained_bert_tf/biobert_pretrain_output_all_notes_150000/'
biobert_tokenizer = AutoTokenizer.from_pretrained(biobert_path)
biobert_model = AutoModel.from_pretrained(biobert_path)
# biobert_tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
# biobert_model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
# os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Computer Vision
import cv2
import skimage, skimage.io
import torchxrayvision as xrv
# Deep Fusion for MIMIC-IV
# Warning handling
import warnings
warnings.filterwarnings("ignore")
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# Initializations & Data Loading |
# |
"""
Resources to identify tables and variables of interest can be found in the MIMIC-IV official API (https://mimic-iv.mit.edu/docs/)
"""
# Define MIMIC IV Data Location
core_mimiciv_path = '../data/HAIM/physionet/files/mimiciv/1.0/'
# Define MIMIC IV Image Data Location (usually external drive)
core_mimiciv_imgcxr_path = '../data/HAIM/physionet/files/mimiciv/1.0/mimic-cxr-jpg/2.0.0.'
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# Helper functions |
#
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# HAIM-MIMICIV specific Patient Representation Function |
# |
# MIMICIV PATIENT CLASS STRUCTURE
class Patient_ICU(object):
def __init__(self, admissions, demographics, transfers, core,\
diagnoses_icd, drgcodes, emar, emar_detail, hcpcsevents,\
labevents, microbiologyevents, poe, poe_detail,\
prescriptions, procedures_icd, services, procedureevents,\
outputevents, inputevents, icustays, datetimeevents,\
chartevents, cxr, imcxr, noteevents, dsnotes, ecgnotes, \
echonotes, radnotes):
## CORE
self.admissions = admissions
self.demographics = demographics
self.transfers = transfers
self.core = core
## HOSP
self.diagnoses_icd = diagnoses_icd
self.drgcodes = drgcodes
self.emar = emar
self.emar_detail = emar_detail
self.hcpcsevents = hcpcsevents
self.labevents = labevents
self.microbiologyevents = microbiologyevents
self.poe = poe
self.poe_detail = poe_detail
self.prescriptions = prescriptions
self.procedures_icd = procedures_icd
self.services = services
## ICU
self.procedureevents = procedureevents
self.outputevents = outputevents
self.inputevents = inputevents
self.icustays = icustays
self.datetimeevents = datetimeevents
self.chartevents = chartevents
## CXR
self.cxr = cxr
self.imcxr = imcxr
## NOTES
self.noteevents = noteevents
self.dsnotes = dsnotes
self.ecgnotes = ecgnotes
self.echonotes = echonotes
self.radnotes = radnotes
# GET FULL MIMIC IV PATIENT RECORD USING DATABASE KEYS
def get_patient_icustay(key_subject_id, key_hadm_id, key_stay_id):
# Inputs:
# key_subject_id -> subject_id is unique to a patient
# key_hadm_id -> hadm_id is unique to a patient hospital stay
# key_stay_id -> stay_id is unique to a patient ward stay
#
# NOTES: Identifiers which specify the patient. More information about
# these identifiers is available at https://mimic-iv.mit.edu/basics/identifiers
# Outputs:
# Patient_ICUstay -> ICU patient stay structure
#-> FILTER data
##-> CORE
f_df_base_core = df_base_core[(df_base_core.subject_id == key_subject_id) & (df_base_core.hadm_id == key_hadm_id)]
f_df_admissions = df_admissions[(df_admissions.subject_id == key_subject_id) & (df_admissions.hadm_id == key_hadm_id)]
f_df_patients = df_patients[(df_patients.subject_id == key_subject_id)]
f_df_transfers = df_transfers[(df_transfers.subject_id == key_subject_id) & (df_transfers.hadm_id == key_hadm_id)]
###-> Merge data into single patient structure
f_df_core = f_df_base_core
f_df_core = f_df_core.merge(f_df_admissions, how='left')
f_df_core = f_df_core.merge(f_df_patients, how='left')
f_df_core = f_df_core.merge(f_df_transfers, how='left')
##-> HOSP
f_df_diagnoses_icd = df_diagnoses_icd[(df_diagnoses_icd.subject_id == key_subject_id)]
f_df_drgcodes = df_drgcodes[(df_drgcodes.subject_id == key_subject_id) & (df_drgcodes.hadm_id == key_hadm_id)]
f_df_emar = df_emar[(df_emar.subject_id == key_subject_id) & (df_emar.hadm_id == key_hadm_id)]
f_df_emar_detail = df_emar_detail[(df_emar_detail.subject_id == key_subject_id)]
f_df_hcpcsevents = df_hcpcsevents[(df_hcpcsevents.subject_id == key_subject_id) & (df_hcpcsevents.hadm_id == key_hadm_id)]
f_df_labevents = df_labevents[(df_labevents.subject_id == key_subject_id) & (df_labevents.hadm_id == key_hadm_id)]
f_df_microbiologyevents = df_microbiologyevents[(df_microbiologyevents.subject_id == key_subject_id) & (df_microbiologyevents.hadm_id == key_hadm_id)]
f_df_poe = df_poe[(df_poe.subject_id == key_subject_id) & (df_poe.hadm_id == key_hadm_id)]
f_df_poe_detail = df_poe_detail[(df_poe_detail.subject_id == key_subject_id)]
f_df_prescriptions = df_prescriptions[(df_prescriptions.subject_id == key_subject_id) & (df_prescriptions.hadm_id == key_hadm_id)]
f_df_procedures_icd = df_procedures_icd[(df_procedures_icd.subject_id == key_subject_id) & (df_procedures_icd.hadm_id == key_hadm_id)]
f_df_services = df_services[(df_services.subject_id == key_subject_id) & (df_services.hadm_id == key_hadm_id)]
###-> Merge content from dictionaries
f_df_diagnoses_icd = f_df_diagnoses_icd.merge(df_d_icd_diagnoses, how='left')
f_df_procedures_icd = f_df_procedures_icd.merge(df_d_icd_procedures, how='left')
f_df_hcpcsevents = f_df_hcpcsevents.merge(df_d_hcpcs, how='left')
f_df_labevents = f_df_labevents.merge(df_d_labitems, how='left')
##-> ICU
f_df_procedureevents = df_procedureevents[(df_procedureevents.subject_id == key_subject_id) & (df_procedureevents.hadm_id == key_hadm_id) & (df_procedureevents.stay_id == key_stay_id)]
f_df_outputevents = df_outputevents[(df_outputevents.subject_id == key_subject_id) & (df_outputevents.hadm_id == key_hadm_id) & (df_outputevents.stay_id == key_stay_id)]
f_df_inputevents = df_inputevents[(df_inputevents.subject_id == key_subject_id) & (df_inputevents.hadm_id == key_hadm_id) & (df_inputevents.stay_id == key_stay_id)]
f_df_icustays = df_icustays[(df_icustays.subject_id == key_subject_id) & (df_icustays.hadm_id == key_hadm_id) & (df_icustays.stay_id == key_stay_id)]
f_df_datetimeevents = df_datetimeevents[(df_datetimeevents.subject_id == key_subject_id) & (df_datetimeevents.hadm_id == key_hadm_id) & (df_datetimeevents.stay_id == key_stay_id)]
f_df_chartevents = df_chartevents[(df_chartevents.subject_id == key_subject_id) & (df_chartevents.hadm_id == key_hadm_id) & (df_chartevents.stay_id == key_stay_id)]
###-> Merge content from dictionaries
f_df_procedureevents = f_df_procedureevents.merge(df_d_items, how='left')
f_df_outputevents = f_df_outputevents.merge(df_d_items, how='left')
f_df_inputevents = f_df_inputevents.merge(df_d_items, how='left')
f_df_datetimeevents = f_df_datetimeevents.merge(df_d_items, how='left')
f_df_chartevents = f_df_chartevents.merge(df_d_items, how='left')
##-> CXR
f_df_mimic_cxr_split = df_mimic_cxr_split[(df_mimic_cxr_split.subject_id == key_subject_id)]
f_df_mimic_cxr_chexpert = df_mimic_cxr_chexpert[(df_mimic_cxr_chexpert.subject_id == key_subject_id)]
f_df_mimic_cxr_metadata = df_mimic_cxr_metadata[(df_mimic_cxr_metadata.subject_id == key_subject_id)]
f_df_mimic_cxr_negbio = df_mimic_cxr_negbio[(df_mimic_cxr_negbio.subject_id == key_subject_id)]
###-> Merge data into single patient structure
f_df_cxr = f_df_mimic_cxr_split
f_df_cxr = f_df_cxr.merge(f_df_mimic_cxr_chexpert, how='left')
f_df_cxr = f_df_cxr.merge(f_df_mimic_cxr_metadata, how='left')
f_df_cxr = f_df_cxr.merge(f_df_mimic_cxr_negbio, how='left')
###-> Get images of that timebound patient
f_df_imcxr = []
for img_idx, img_row in f_df_cxr.iterrows():
img_path = core_mimiciv_imgcxr_path + str(img_row['Img_Folder']) + '/' + str(img_row['Img_Filename'])
img_cxr_shape = [224, 224]
img_cxr = cv2.resize(cv2.imread(img_path, cv2.IMREAD_GRAYSCALE), (img_cxr_shape[0], img_cxr_shape[1]))
f_df_imcxr.append(np.array(img_cxr))
##-> NOTES
f_df_noteevents = df_noteevents[(df_noteevents.subject_id == key_subject_id) & (df_noteevents.hadm_id == key_hadm_id)]
f_df_dsnotes = df_dsnotes[(df_dsnotes.subject_id == key_subject_id) & (df_dsnotes.hadm_id == key_hadm_id) & (df_dsnotes.stay_id == key_stay_id)]
f_df_ecgnotes = df_ecgnotes[(df_ecgnotes.subject_id == key_subject_id) & (df_ecgnotes.hadm_id == key_hadm_id) & (df_ecgnotes.stay_id == key_stay_id)]
f_df_echonotes = df_echonotes[(df_echonotes.subject_id == key_subject_id) & (df_echonotes.hadm_id == key_hadm_id) & (df_echonotes.stay_id == key_stay_id)]
f_df_radnotes = df_radnotes[(df_radnotes.subject_id == key_subject_id) & (df_radnotes.hadm_id == key_hadm_id) & (df_radnotes.stay_id == key_stay_id)]
###-> Merge data into single patient structure
#--None
# -> Create & Populate patient structure
## CORE
admissions = f_df_admissions
demographics = f_df_patients
transfers = f_df_transfers
core = f_df_core
## HOSP
diagnoses_icd = f_df_diagnoses_icd
drgcodes = f_df_diagnoses_icd
emar = f_df_emar
emar_detail = f_df_emar_detail
hcpcsevents = f_df_hcpcsevents
labevents = f_df_labevents
microbiologyevents = f_df_microbiologyevents
poe = f_df_poe
poe_detail = f_df_poe_detail
prescriptions = f_df_prescriptions
procedures_icd = f_df_procedures_icd
services = f_df_services
## ICU
procedureevents = f_df_procedureevents
outputevents = f_df_outputevents
inputevents = f_df_inputevents
icustays = f_df_icustays
datetimeevents = f_df_datetimeevents
chartevents = f_df_chartevents
## CXR
cxr = f_df_cxr
imcxr = f_df_imcxr
## NOTES
noteevents = f_df_noteevents
dsnotes = f_df_dsnotes
ecgnotes = f_df_ecgnotes
echonotes = f_df_echonotes
radnotes = f_df_radnotes
# Create patient object and return
Patient_ICUstay = Patient_ICU(admissions, demographics, transfers, core, \
diagnoses_icd, drgcodes, emar, emar_detail, hcpcsevents, \
labevents, microbiologyevents, poe, poe_detail, \
prescriptions, procedures_icd, services, procedureevents, \
outputevents, inputevents, icustays, datetimeevents, \
chartevents, cxr, imcxr, noteevents, dsnotes, ecgnotes, \
echonotes, radnotes)
return Patient_ICUstay
# DELTA TIME CALCULATOR FROM TWO TIMESTAMPS
def date_diff_hrs(t1, t0):
# Inputs:
# t1 -> Final timestamp in a patient hospital stay
# t0 -> Initial timestamp in a patient hospital stay
# Outputs:
# delta_t -> Patient stay structure bounded by allowed timestamps
try:
delta_t = (t1-t0).total_seconds()/3600 # Result in hrs
except:
delta_t = math.nan
return delta_t
# GET TIMEBOUND MIMIC-IV PATIENT RECORD BY DATABASE KEYS AND TIMESTAMPS
def get_timebound_patient_icustay(Patient_ICUstay, start_hr = None, end_hr = None):
# Inputs:
# Patient_ICUstay -> Patient ICU stay structure
# start_hr -> start_hr indicates the first valid time (in hours) from the admition time "admittime" for all retreived features, input "None" to avoid time bounding
# end_hr -> end_hr indicates the last valid time (in hours) from the admition time "admittime" for all retreived features, input "None" to avoid time bounding
#
# NOTES: Identifiers which specify the patient. More information about
# these identifiers is available at https://mimic-iv.mit.edu/basics/identifiers
# Outputs:
# Patient_ICUstay -> Timebound ICU patient stay structure filtered by max_time_stamp or min_time_stamp if any
# %% EXAMPLE OF USE
## Let's select a single patient
'''
key_subject_id = 10000032
key_hadm_id = 29079034
key_stay_id = 39553978
start_hr = 0
end_hr = 24
patient = get_patient_icustay(key_subject_id, key_hadm_id, key_stay_id)
dt_patient = get_timebound_patient_icustay(patient, start_hr , end_hr)
'''
# Create a deep copy so that it is not the same object
# Patient_ICUstay = copy.deepcopy(Patient_ICUstay)
## --> Process Event Structure Calculations
admittime = Patient_ICUstay.core['admittime'].values[0]
dischtime = Patient_ICUstay.core['dischtime'].values[0]
Patient_ICUstay.emar['deltacharttime'] = Patient_ICUstay.emar.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.labevents['deltacharttime'] = Patient_ICUstay.labevents.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.microbiologyevents['deltacharttime'] = Patient_ICUstay.microbiologyevents.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.outputevents['deltacharttime'] = Patient_ICUstay.outputevents.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.datetimeevents['deltacharttime'] = Patient_ICUstay.datetimeevents.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.chartevents['deltacharttime'] = Patient_ICUstay.chartevents.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.noteevents['deltacharttime'] = Patient_ICUstay.noteevents.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.dsnotes['deltacharttime'] = Patient_ICUstay.dsnotes.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.ecgnotes['deltacharttime'] = Patient_ICUstay.ecgnotes.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.echonotes['deltacharttime'] = Patient_ICUstay.echonotes.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
Patient_ICUstay.radnotes['deltacharttime'] = Patient_ICUstay.radnotes.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
# Re-calculate times of CXR database
Patient_ICUstay.cxr['StudyDateForm'] = pd.to_datetime(Patient_ICUstay.cxr['StudyDate'], format='%Y%m%d')
Patient_ICUstay.cxr['StudyTimeForm'] = Patient_ICUstay.cxr.apply(lambda x : '%#010.3f' % x['StudyTime'] ,1)
Patient_ICUstay.cxr['StudyTimeForm'] = pd.to_datetime(Patient_ICUstay.cxr['StudyTimeForm'], format='%H%M%S.%f').dt.time
Patient_ICUstay.cxr['charttime'] = Patient_ICUstay.cxr.apply(lambda r : dt.datetime.combine(r['StudyDateForm'],r['StudyTimeForm']),1)
Patient_ICUstay.cxr['charttime'] = Patient_ICUstay.cxr['charttime'].dt.floor('Min')
Patient_ICUstay.cxr['deltacharttime'] = Patient_ICUstay.cxr.apply(lambda x: date_diff_hrs(x['charttime'],admittime) if not x.empty else None, axis=1)
## --> Filter by allowable time stamps
if not (start_hr == None):
Patient_ICUstay.emar = Patient_ICUstay.emar[(Patient_ICUstay.emar.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.emar.deltacharttime)]
Patient_ICUstay.labevents = Patient_ICUstay.labevents[(Patient_ICUstay.labevents.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.labevents.deltacharttime)]
Patient_ICUstay.microbiologyevents = Patient_ICUstay.microbiologyevents[(Patient_ICUstay.microbiologyevents.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.microbiologyevents.deltacharttime)]
Patient_ICUstay.outputevents = Patient_ICUstay.outputevents[(Patient_ICUstay.outputevents.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.outputevents.deltacharttime)]
Patient_ICUstay.datetimeevents = Patient_ICUstay.datetimeevents[(Patient_ICUstay.datetimeevents.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.datetimeevents.deltacharttime)]
Patient_ICUstay.chartevents = Patient_ICUstay.chartevents[(Patient_ICUstay.chartevents.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.chartevents.deltacharttime)]
Patient_ICUstay.cxr = Patient_ICUstay.cxr[(Patient_ICUstay.cxr.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.cxr.deltacharttime)]
Patient_ICUstay.imcxr = [Patient_ICUstay.imcxr[i] for i, x in enumerate((Patient_ICUstay.cxr.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.cxr.deltacharttime)) if x]
#Notes
Patient_ICUstay.noteevents = Patient_ICUstay.noteevents[(Patient_ICUstay.noteevents.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.noteevents.deltacharttime)]
Patient_ICUstay.dsnotes = Patient_ICUstay.dsnotes[(Patient_ICUstay.dsnotes.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.dsnotes.deltacharttime)]
Patient_ICUstay.ecgnotes = Patient_ICUstay.ecgnotes[(Patient_ICUstay.ecgnotes.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.ecgnotes.deltacharttime)]
Patient_ICUstay.echonotes = Patient_ICUstay.echonotes[(Patient_ICUstay.echonotes.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.echonotes.deltacharttime)]
Patient_ICUstay.radnotes = Patient_ICUstay.radnotes[(Patient_ICUstay.radnotes.deltacharttime >= start_hr) | pd.isnull(Patient_ICUstay.radnotes.deltacharttime)]
if not (end_hr == None):
Patient_ICUstay.emar = Patient_ICUstay.emar[(Patient_ICUstay.emar.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.emar.deltacharttime)]
Patient_ICUstay.labevents = Patient_ICUstay.labevents[(Patient_ICUstay.labevents.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.labevents.deltacharttime)]
Patient_ICUstay.microbiologyevents = Patient_ICUstay.microbiologyevents[(Patient_ICUstay.microbiologyevents.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.microbiologyevents.deltacharttime)]
Patient_ICUstay.outputevents = Patient_ICUstay.outputevents[(Patient_ICUstay.outputevents.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.outputevents.deltacharttime)]
Patient_ICUstay.datetimeevents = Patient_ICUstay.datetimeevents[(Patient_ICUstay.datetimeevents.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.datetimeevents.deltacharttime)]
Patient_ICUstay.chartevents = Patient_ICUstay.chartevents[(Patient_ICUstay.chartevents.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.chartevents.deltacharttime)]
Patient_ICUstay.cxr = Patient_ICUstay.cxr[(Patient_ICUstay.cxr.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.cxr.deltacharttime)]
Patient_ICUstay.imcxr = [Patient_ICUstay.imcxr[i] for i, x in enumerate((Patient_ICUstay.cxr.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.cxr.deltacharttime)) if x]
#Notes
Patient_ICUstay.noteevents = Patient_ICUstay.noteevents[(Patient_ICUstay.noteevents.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.noteevents.deltacharttime)]
Patient_ICUstay.dsnotes = Patient_ICUstay.dsnotes[(Patient_ICUstay.dsnotes.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.dsnotes.deltacharttime)]
Patient_ICUstay.ecgnotes = Patient_ICUstay.ecgnotes[(Patient_ICUstay.ecgnotes.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.ecgnotes.deltacharttime)]
Patient_ICUstay.echonotes = Patient_ICUstay.echonotes[(Patient_ICUstay.echonotes.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.echonotes.deltacharttime)]
Patient_ICUstay.radnotes = Patient_ICUstay.radnotes[(Patient_ICUstay.radnotes.deltacharttime <= end_hr) | pd.isnull(Patient_ICUstay.radnotes.deltacharttime)]
# Filter CXR to match allowable patient stay
Patient_ICUstay.cxr = Patient_ICUstay.cxr[(Patient_ICUstay.cxr.charttime <= dischtime)]
return Patient_ICUstay
# LOAD MASTER DICTIONARY OF MIMIC IV EVENTS
def load_haim_event_dictionaries(core_mimiciv_path):
# Inputs:
# df_d_items -> MIMIC chartevent items dictionary
# df_d_labitems -> MIMIC labevent items dictionary
# df_d_hcpcs -> MIMIC hcpcs items dictionary
#
# Outputs:
# df_patientevents_categorylabels_dict -> Dictionary with all possible event types
# Generate dictionary for chartevents, labevents and HCPCS
df_patientevents_categorylabels_dict = pd.DataFrame(columns = ['eventtype', 'category', 'label'])
# Load dictionaries
df_d_items = pd.read_csv(core_mimiciv_path + 'icu/d_items.csv')
df_d_labitems = pd.read_csv(core_mimiciv_path + 'hosp/d_labitems.csv')
df_d_hcpcs = pd.read_csv(core_mimiciv_path + 'hosp/d_hcpcs.csv')
# Get Chartevent items with labels & category
df = df_d_items
for category_idx, category in enumerate(sorted((df.category.astype(str).unique()))):
#print(category)
category_list = df[df['category']==category]
for item_idx, item in enumerate(sorted(category_list.label.astype(str).unique())):
df_patientevents_categorylabels_dict = df_patientevents_categorylabels_dict.append({'eventtype': 'chart', 'category': category, 'label': item}, ignore_index=True)
# Get Lab items with labels & category
df = df_d_labitems
for category_idx, category in enumerate(sorted((df.category.astype(str).unique()))):
#print(category)
category_list = df[df['category']==category]
for item_idx, item in enumerate(sorted(category_list.label.astype(str).unique())):
df_patientevents_categorylabels_dict = df_patientevents_categorylabels_dict.append({'eventtype': 'lab', 'category': category, 'label': item}, ignore_index=True)
# Get HCPCS items with labels & category
df = df_d_hcpcs
for category_idx, category in enumerate(sorted((df.category.astype(str).unique()))):
#print(category)
category_list = df[df['category']==category]
for item_idx, item in enumerate(sorted(category_list.long_description.astype(str).unique())):
df_patientevents_categorylabels_dict = df_patientevents_categorylabels_dict.append({'eventtype': 'hcpcs', 'category': category, 'label': item}, ignore_index=True)
return df_patientevents_categorylabels_dict
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# Data filtering by condition and outcome |
# |
"""
Resources to identify tables and variables of interest can be found in the MIMIC-IV official API
(https://mimic-iv.mit.edu/docs/)
"""
# QUERY IN ALL SINGLE PATIENT ICU STAY RECORD FOR KEYWORD MATCHING
def is_haim_patient_keyword_match(patient, keywords, verbose = 0):
# Inputs:
# patient -> Timebound ICU patient stay structure filtered by max_time_stamp or min_time_stamp if any
# keywords -> List of string keywords to attempt to match in an "OR" basis
# verbose -> Flag to print found keyword outputs (0,1,2)
#
# Outputs:
# is_key -> Boolean flag indicating if any of the input Keywords are present
# keyword_mask -> Array indicating which of the input Keywords are present (0-Absent, 1-Present)
# Retrieve list of all the contents of patient datastructures
patient_dfs_list = [## CORE
patient.core,
## HOSP
patient.diagnoses_icd,
patient.drgcodes,
patient.emar,
patient.emar_detail,
patient.hcpcsevents,
patient.labevents,
patient.microbiologyevents,
patient.poe,
patient.poe_detail,
patient.prescriptions,
patient.procedures_icd,
patient.services,
## ICU
patient.procedureevents,
patient.outputevents,
patient.inputevents,
patient.icustays,
patient.datetimeevents,
patient.chartevents,
## CXR
patient.cxr,
patient.imcxr,
## NOTES
patient.noteevents,
patient.dsnotes,
patient.ecgnotes,
patient.echonotes,
patient.radnotes
]
patient_dfs_dict = ['core', 'diagnoses_icd', 'drgcodes', 'emar', 'emar_detail', 'hcpcsevents', 'labevents', 'microbiologyevents', 'poe',
'poe_detail', 'prescriptions', 'procedures_icd', 'services', 'procedureevents', 'outputevents', 'inputevents', 'icustays',
'datetimeevents', 'chartevents', 'cxr', 'imcxr', 'noteevents', 'dsnotes', 'ecgnotes', 'echonotes', 'radnotes']
# Initialize query mask
keyword_mask = np.zeros([len(patient_dfs_list), len(keywords)])
for idx_df, patient_df in enumerate(patient_dfs_list):
for idx_keyword, keyword in enumerate(keywords):
try:
patient_df_text = patient_df.astype(str)
is_df_key = patient_df_text.sum(axis=1).str.contains(keyword, case=False).any()
if is_df_key:
keyword_mask[idx_df, idx_keyword]=1
if (verbose >= 2):
print('')
print('Keyword: ' + '"' + keyword + ' " ' + '(Found in "' + patient_dfs_dict[idx_df] + '" table )')
print(patient_df_text)
else:
keyword_mask[idx_df, idx_keyword]=0
except:
is_df_key = False
keyword_mask[idx_df, idx_keyword]=0
# Create final keyword mask
if keyword_mask.any():
is_key = True
else:
is_key = False
return is_key, keyword_mask
# QUERY IN ALL SINGLE PATIENT ICU STAY RECORD FOR INCLUSION CRITERIA MATCHING
def is_haim_patient_inclusion_criteria_match(patient, inclusion_criteria, verbose = 0):
# Inputs:
# patient -> Timebound ICU patient stay structure filtered by max_time_stamp or min_time_stamp if any
# inclusion_criteria -> Inclusion criteria in groups of keywords.
# Keywords in groups are follow and "OR" logic,
# while an "AND" logic is stablished among groups
# verbose -> Flag to print found keyword outputs (0,1,2)
#
# Outputs:
# is_included -> Boolean flag if inclusion criteria is found in patient
# inclusion_criteria_mask -> Binary mask of inclusion criteria found in patient
# Clean out process bar before starting
inclusion_criteria_mask = np.zeros(len(inclusion_criteria))
for idx_keywords, keywords in enumerate(inclusion_criteria):
is_included_flag, _ = is_haim_patient_keyword_match(patient, keywords, verbose)
inclusion_criteria_mask[idx_keywords] = is_included_flag
if inclusion_criteria_mask.all():
is_included = True
else:
is_included = False
# Print if patient has to be included
if (verbose >=2):
print('')
print('Inclusion Criteria: ' + str(inclusion_criteria))
print('Inclusion Vector: ' + str(inclusion_criteria_mask) + ' , To include: ' + str(is_included))
return is_included, inclusion_criteria_mask
# GENERATE ALL SINGLE PATIENT ICU STAY RECORDS FOR ENTIRE MIMIC-IV DATABASE
def search_key_mimiciv_patients(df_haim_ids, core_mimiciv_path, inclusion_criteria, verbose = 0):
# Inputs:
# df_haim_ids -> Dataframe with all unique available HAIM_MIMICIV records by key identifiers
# core_mimiciv_path -> Path to structured MIMIC IV databases in CSV files
#
# Outputs:
# nfiles -> Number of single patient HAIM files produced
# Clean out process bar before starting
sys.stdout.flush()
# List of key patients
key_haim_patient_ids = []
# Extract information for patient
nfiles = len(df_haim_ids)
with tqdm(total = nfiles) as pbar:
# Update process bar
nbase= 0
pbar.update(nbase)
#Iterate through all patients
for haim_patient_idx in range(nbase, nfiles):
#Load precomputed patient file
filename = f"{haim_patient_idx:08d}" + '.pkl'
patient = load_patient_object(core_mimiciv_path + 'pickle/' + filename)
#Check if patient fits keywords
is_key, _ = is_haim_patient_inclusion_criteria_match(patient, keywords, verbose)
if is_key:
key_haim_patient_ids.append(haim_patient_idx)
# Update process bar
pbar.update(1)
return key_haim_patient_ids
# GET MIMIC IV PATIENT LIST FILTERED BY DESIRED CONDITION
def get_haim_ids_only_by_condition(condition_tokens, core_mimiciv_path):
# Inputs:
# condition_tokens -> string identifier of the condition you want to isolate (condition_tokens= ['heart failure','chronic'])
# outcome_tokens -> string identifier of the outcome you want to isolate
# core_mimiciv_path -> path to folder where the base MIMIC IV dataset files are located
# Outputs:
# condition_outcome_df -> Dataframe including patients IDs with desired Condition, indicating the Outcome.
# Load necessary ICD diagnostic lists and general patient information
d_icd_diagnoses = pd.read_csv(core_mimiciv_path + 'hosp/d_icd_diagnoses.csv')
d_icd_diagnoses['long_title'] = d_icd_diagnoses['long_title'].str.lower()
diagnoses_icd['icd_code'] = diagnoses_icd['icd_code'].str.replace(' ', '')
admissions = pd.read_csv(core_mimiciv_path + 'core/admissions.csv')
patients = pd.read_csv(core_mimiciv_path + 'core/patients.csv')
admissions = pd.merge(admissions, patients, on = 'subject_id')
#list of unique hadm id with conditions specified
condition_list = []
condition_list = d_icd_diagnoses[d_icd_diagnoses['long_title'].str.contains(condition_keywords[0])]
for i in condition_keywords[1:]:
condition_list = condition_list[condition_list['long_title'].str.contains('chronic')]
icd_list = condition_list['icd_code'].unique().tolist()
hid_list_chf = diagnoses_icd[diagnoses_icd['icd_code'].isin(icd_list) &
(diagnoses_icd['seq_num']<=3)]['hadm_id'].unique().tolist()
pkl_id = pd.read_csv(core_mimiciv_path + 'pickle/haim_mimiciv_key_ids.csv')
id_hf = pkl_id[pkl_id['hadm_id'].isin(hid_list_chf)].drop_duplicates(subset='hadm_id')
# delete all pkl files with only less than 1 day recorded
pkl_list_adm = admissions[admissions['hadm_id'].isin(id_hf['hadm_id'])]
pkl_list_adm['dischtime'] = pd.to_datetime(pkl_list_adm['dischtime'])
pkl_list_adm['admittime'] = pd.to_datetime(pkl_list_adm['admittime'])
pkl_list_adm['deltatime'] = (pkl_list_adm['dischtime'] - pkl_list_adm['admittime']).astype('timedelta64[D]').values
pkl_no_zero = pkl_list_adm[pkl_list_adm['deltatime'] != 0]['hadm_id']
no_zero_id = pkl_id[pkl_id['hadm_id'].isin(pkl_no_zero)].drop_duplicates(subset='hadm_id')
haim_ids_list = no_zero_id['haim_id_pickle'].values
return haim_ids_list
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# Core embeddings for MIMIC-IV Deep Fusion |
#
'''
'''
# LOAD CORE INFO OF MIMIC IV PATIENTS
def load_core_mimic_haim_info(core_mimiciv_path, df_haim_ids):
# Inputs:
# core_mimiciv_path -> Base path of mimiciv
# df_haim_ids -> Table of HAIM ids and corresponding keys
#
# Outputs:
# df_haim_ids_core_info -> Updated dataframe with integer representations of core data
# %% EXAMPLE OF USE
# df_haim_ids_core_info = load_core_mimic_haim_info(core_mimiciv_path)
# Load core table
df_mimiciv_core = pd.read_csv(core_mimiciv_path + 'core/core.csv')
# Generate integer representations of categorical variables in core
core_var_select_list = ['gender', 'ethnicity', 'marital_status', 'language','insurance']
core_var_select_int_list = ['gender_int', 'ethnicity_int', 'marital_status_int', 'language_int','insurance_int']
df_mimiciv_core[core_var_select_list] = df_mimiciv_core[core_var_select_list].astype('category')
df_mimiciv_core[core_var_select_int_list] = df_mimiciv_core[core_var_select_list].apply(lambda x: x.cat.codes)
# Combine HAIM IDs with core data
df_haim_ids_core_info = pd.merge(df_haim_ids, df_mimiciv_core, on=["subject_id", "hadm_id"])
return df_haim_ids_core_info
# GET DEMOGRAPHICS EMBEDDINGS OF MIMIC IV PATIENT
def get_demographic_embeddings(dt_patient, verbose=0):
# Inputs:
# dt_patient -> Timebound mimic patient structure
# verbose -> Flag to print found keyword outputs (0,1,2)
#
# Outputs:
# base_embeddings -> Core base embeddings for the selected patient
# %% EXAMPLE OF USE
# base_embeddings = get_demographic_embeddings(dt_patient, df_haim_ids_core_info, verbose=2)
# Retrieve dt_patient and get embeddings
demo_embeddings = dt_patient.core.loc[0, ['anchor_age', 'gender_int', 'ethnicity_int', 'marital_status_int', 'language_int', 'insurance_int']]
if verbose >= 1:
print(demo_embeddings)
demo_embeddings = demo_embeddings.values
return demo_embeddings
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# TSFresh embeddings for MIMIC-IV Deep Fusion |
#
'''
## -> DEEP FUSION REPRESENTATION OF MIMIC-IV EHR USING TSFRESH
"tsfresh" is a python package. It automatically calculates a large number of time series
characteristics, the so called features. Further the package contains methods to evaluate
the explaining power and importance of such characteristics for regression or classification
tasks. https://tsfresh.readthedocs.io/en/latest/
'''
# TSFRESH FEATURE EXTRACTOR OF MIMICIV CHARTEVENTS
def get_chartevent_tsfresh_timeseries_embeddings(dt_patient, df_patientevents_categorylabels_dict, verbose=0):
# Inputs:
# dt_patient -> Timebound Patient ICU stay structure
# df_patientevents_categorylabels_dict -> MIMIC IV Event dictionary
# verbose -> Flag to print generated outputs (0,1,2)
#
# Outputs:
# evs_features -> TSfresh generated chart event features for each timeseries
# %% EXAMPLE OF USE
# evs_features = extract_chartevent_tsfresh_timeseries_embeddings(dt_patient, df_patientevents_categorylabels_dict, event_type, verbose=1)
# Stablish dynamics of progressbar
if verbose <= 1: disable_progressbar=True
else: disable_progressbar=False
# Prep features of empty timeseries features from TSFresh in the context of clinical data
fc_parameters = {"length": None,
"absolute_sum_of_changes": None,
"maximum": None,
"mean": None,
"mean_abs_change": None,
"mean_change": None,
"median": None,
"minimum": None,
"standard_deviation": None,
"variance": None,
"large_standard_deviation": [{"r": r * 0.2} for r in range(1, 5)],
# Comment by Yu: don't think we need the 1 for quntile?
"quantile": [{"q": q} for q in [.25, .5, .75, 1]],
"linear_trend": [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"},{"attr": "slope"}, {"attr": "stderr"}]}
x_hr =[0]
y_hr = np.arange(len(x_hr))
# Extract Features with TSFresh
timeseries = pd.DataFrame({'id': np.zeros_like(y_hr), 'valnum': y_hr, 'time': x_hr}, columns=['id', 'valnum', 'time'])
features_empty_timeseries = extract_features(timeseries, column_id="id", column_sort="time", disable_progressbar=True, default_fc_parameters=fc_parameters)
#Get patient events by event type
evs = dt_patient.chartevents
#List all types of chart events (Charts, Labs and signals)
for eventtype_idx, eventtype in enumerate(sorted((df_patientevents_categorylabels_dict.eventtype.unique()))):
if verbose >= 3: print('* ' + eventtype)
event_list = df_patientevents_categorylabels_dict[df_patientevents_categorylabels_dict['eventtype']==eventtype]
for category_idx, category in enumerate(sorted((df_patientevents_categorylabels_dict.category.unique()))):
if verbose >= 3: print('-> ' + category)
category_list = df_patientevents_categorylabels_dict[df_patientevents_categorylabels_dict['category']==category]
for item_idx, item in enumerate(sorted(category_list.label.unique())):
if verbose >= 3: print('---> ' + item)
# POPULATE FEATURE SPACE FOR PATIENT
item_chart = evs[evs['label']==item]
empty_timeseries = False
# Set x equal to the times
x_hr = item_chart.deltacharttime[item_chart.label==item]
if len(x_hr)==0:
x_hr =[0]
empty_timeseries = True
y_hr = item_chart.valuenum[item_chart.label==item]
y_hr = y_hr[~(np.isnan(y_hr))]
x_hr = x_hr[0:len(y_hr)]
if y_hr.empty:
y_hr = np.arange(len(x_hr))
extracted_features = features_empty_timeseries
else:
# Extract Features with TSFresh
timeseries = pd.DataFrame({'id': np.zeros_like(y_hr), 'valnum': y_hr, 'time': x_hr}, columns=['id', 'valnum', 'time'])
extracted_features = impute(extract_features(timeseries, column_id="id", column_sort="time", disable_progressbar=disable_progressbar, default_fc_parameters = fc_parameters))
if (eventtype_idx ==0) & (category_idx ==0) & (item_idx == 0):
evs_features = extracted_features
else:
evs_features = evs_features.append(extracted_features)
# Transform extracted features from 0-1
transformer = QuantileTransformer().fit(evs_features)
norm_evs_features = transformer.transform(evs_features)
norm_evs_features = np.asarray(norm_evs_features)
if verbose >= 1:
# Plot feature representation
plt.figure(figsize = (20,5))
plt.imshow(X, cmap='hot', interpolation='nearest', aspect='auto')
plt.colorbar(label="Patient Timeseries Features", orientation="vertical")
plt.show()
return norm_evs_features, evs_features
def pivot_chartevent(df, event_list):
# create a new table with additional columns with label list
df1 = df[['subject_id', 'hadm_id', 'stay_id', 'charttime']]
for event in event_list:
df1[event] = np.nan
#search in the abbreviations column
df1.loc[(df['label']==event), event] = df['valuenum'].astype(float)
df_out = df1.dropna(axis=0, how='all', subset=event_list)
return df_out
def pivot_labevent(df, event_list):
# create a new table with additional columns with label list
df1 = df[['subject_id', 'hadm_id', 'charttime']]
for event in event_list:
df1[event] = np.nan
#search in the label column
df1.loc[(df['label']==event), event] = df['valuenum'].astype(float)
df_out = df1.dropna(axis=0, how='all', subset=event_list)
return df_out
def pivot_procedureevent(df, event_list):
# create a new table with additional columns with label list
df1 = df[['subject_id', 'hadm_id', 'storetime']]
for event in event_list:
df1[event] = np.nan
#search in the label column
df1.loc[(df['label']==event), event] = df['value'].astype(float) #Yu: maybe if not label use abbreviation
df_out = df1.dropna(axis=0, how='all', subset=event_list)
return df_out
#FUNCTION TO COMPUTE A LIST OF TIME SERIES FEATURES
def get_ts_emb(df_pivot, event_list):
# Inputs:
# df_pivot -> Pivoted table
# event_list -> MIMIC IV Type of Event
#
# Outputs:
# df_out -> Embeddings
# %% EXAMPLE OF USE
# df_out = get_ts_emb(df_pivot, event_list)
# Initialize table
try:
df_out = df_pivot[['subject_id', 'hadm_id']].iloc[0]
except:
# print(df_pivot)
df_out = pd.DataFrame(columns = ['subject_id', 'hadm_id'])
# df_out = df_pivot[['subject_id', 'hadm_id']]
#Adding a row of zeros to df_pivot in case there is no value
df_pivot = df_pivot.append(pd.Series(0, index=df_pivot.columns), ignore_index=True)
#Compute the following features
for event in event_list:
series = df_pivot[event].dropna() #dropna rows
if len(series) >0: #if there is any event
df_out[event+'_max'] = series.max()
df_out[event+'_min'] = series.min()
df_out[event+'_mean'] = series.mean(skipna=True)
df_out[event+'_variance'] = series.var(skipna=True)
df_out[event+'_meandiff'] = series.diff().mean() #average change
df_out[event+'_meanabsdiff'] =series.diff().abs().mean()
df_out[event+'_maxdiff'] = series.diff().abs().max()
df_out[event+'_sumabsdiff'] =series.diff().abs().sum()
df_out[event+'_diff'] = series.iloc[-1]-series.iloc[0]
#Compute the n_peaks
peaks,_ = find_peaks(series) #, threshold=series.median()
df_out[event+'_npeaks'] = len(peaks)
#Compute the trend (linear slope)
if len(series)>1:
df_out[event+'_trend']= np.polyfit(np.arange(len(series)), series, 1)[0] #fit deg-1 poly
else:
df_out[event+'_trend'] = 0
return df_out
def get_ts_embeddings(dt_patient, event_type):
# Inputs:
# dt_patient -> Timebound Patient ICU stay structure
#
# Outputs:
# ts_emb -> TSfresh-like generated Lab event features for each timeseries
#
# %% EXAMPLE OF USE
# ts_emb = get_labevent_ts_embeddings(dt_patient)
#Get chartevents
if(event_type == 'procedure'):
df = dt_patient.procedureevents
#Define chart events of interest
event_list = ['Foley Catheter', 'PICC Line', 'Intubation', 'Peritoneal Dialysis',
'Bronchoscopy', 'EEG', 'Dialysis - CRRT', 'Dialysis Catheter',
'Chest Tube Removed', 'Hemodialysis']
df_pivot = pivot_procedureevent(df, event_list)
elif(event_type == 'lab'):
df = dt_patient.labevents
#Define chart events of interest
event_list = ['Glucose', 'Potassium', 'Sodium', 'Chloride', 'Creatinine',
'Urea Nitrogen', 'Bicarbonate', 'Anion Gap', 'Hemoglobin', 'Hematocrit',
'Magnesium', 'Platelet Count', 'Phosphate', 'White Blood Cells',
'Calcium, Total', 'MCH', 'Red Blood Cells', 'MCHC', 'MCV', 'RDW',
'Platelet Count', 'Neutrophils', 'Vancomycin']
df_pivot = pivot_labevent(df, event_list)
elif(event_type == 'chart'):
df = dt_patient.chartevents
#Define chart events of interest
event_list = ['Heart Rate','Non Invasive Blood Pressure systolic',
'Non Invasive Blood Pressure diastolic', 'Non Invasive Blood Pressure mean',
'Respiratory Rate','O2 saturation pulseoxymetry',
'GCS - Verbal Response', 'GCS - Eye Opening', 'GCS - Motor Response']
df_pivot = pivot_chartevent(df, event_list)
#Pivote df to record these values
ts_emb = get_ts_emb(df_pivot, event_list)
try:
ts_emb = ts_emb.drop(['subject_id', 'hadm_id']).fillna(value=0)
except:
ts_emb = pd.Series(0, index=ts_emb.columns).drop(['subject_id', 'hadm_id']).fillna(value=0)
return ts_emb
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# Biobert Chart Event embeddings for MIMIC-IV Deep Fusion |
#