-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmimic3Q.py
More file actions
2250 lines (1851 loc) · 74.7 KB
/
mimic3Q.py
File metadata and controls
2250 lines (1851 loc) · 74.7 KB
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
import csv
import gzip
import re
import os
import sys
import math
import random
from pathlib import Path
from datetime import datetime, timedelta
from typing import Any, Dict, Iterable, List, Optional, Tuple
from collections import defaultdict, Counter
try:
import matplotlib.pyplot as plt
except Exception:
plt = None
# ===============================
# FIXED CLASS ORDER (CAPITALS)
# ===============================
CLASSES = [
"B:PSEUDOMONAS AERUGINOSA",
"B:STAPH AUREUS COAG +",
"B:SERRATIA MARCESCENS",
"B:MORGANELLA MORGANII",
"B:ESCHERICHIA COLI",
"B:PROTEUS MIRABILIS",
"B:PROVIDENCIA STUARTII",
"B:POSITIVE FOR METHICILLIN RESISTANT STAPH AUREUS",
"B:YEAST",
"B:GRAM POSITIVE COCCUS(COCCI)",
"B:OTHER",
"V:OTHER",
]
CLASS_TO_INDEX = {c: i for i, c in enumerate(CLASSES)}
INDEX_TO_CLASS = {i: c for c, i in CLASS_TO_INDEX.items()}
MRSA_LABEL = "B:POSITIVE FOR METHICILLIN RESISTANT STAPH AUREUS"
MSSA_LABEL = "B:STAPH AUREUS COAG +"
# ===============================
# PATHS (resolved per dataset run)
# ===============================
MICRO_PATH: Path
PRESC_PATH: Path
ADMISSIONS_PATH: Path
PATIENTS_PATH: Path
D_ITEMS_PATH: Path
CHARTEVENTS_PATH: Path
D_LABITEMS_PATH: Path
LABEVENTS_PATH: Path
# ===============================
# SETTINGS
# ===============================
SEED = int(os.environ.get("SEED", "42"))
random.seed(SEED)
HOURS_WINDOW = int(os.environ.get("HOURS_WINDOW", "24"))
ANTIBIOTICS = ["VANCOMYCIN", "CIPROFLOXACIN", "MEROPENEM", "PIPERACILLIN", "CEFTRIAXONE"]
ABX_ORDER = [a.lower() for a in ANTIBIOTICS]
VITAL_ORDER = ["temperature_c", "wbc", "spo2", "age"]
NUMERIC_ORDER = VITAL_ORDER + ABX_ORDER
USE_CLASS_WEIGHTS = os.environ.get("USE_CLASS_WEIGHTS", "1").strip() == "1"
MAX_CLASS_WEIGHT = float(os.environ.get("MAX_CLASS_WEIGHT", "15.0"))
BOTHER_EXTRA_DOWNWEIGHT = float(os.environ.get("BOTHER_EXTRA_DOWNWEIGHT", "0.5"))
MAX_EPOCHS = int(os.environ.get("MAX_EPOCHS", "80"))
EARLY_PATIENCE = int(os.environ.get("EARLY_PATIENCE", "10"))
MIN_DELTA = float(os.environ.get("MIN_DELTA", "1e-6"))
MAX_TEXT_TOKENS = int(os.environ.get("MAX_TEXT_TOKENS", "5000"))
TEXT_BINARY = os.environ.get("TEXT_BINARY", "0").strip() == "1"
LR = float(os.environ.get("LR", "0.03"))
WEIGHT_DECAY = float(os.environ.get("WEIGHT_DECAY", "1e-5"))
CALIB_BINS = int(os.environ.get("CALIB_BINS", "10"))
BIAS_MIN_GROUP_N = int(os.environ.get("BIAS_MIN_GROUP_N", "25"))
WBC_SAMPLE_MAX = 200_000
MIN_TEST_UNIQUE_HADM = int(os.environ.get("MIN_TEST_UNIQUE_HADM", "2"))
TARGET_STOP_METRIC = os.environ.get("TARGET_STOP_METRIC", "acc").strip().lower()
TARGET_ACC = float(os.environ.get("TARGET_ACC", "0.95"))
TARGET_ACC_KIND = os.environ.get("TARGET_ACC_KIND", "overall").strip().lower()
TARGET_F1 = float(os.environ.get("TARGET_F1", "0.925"))
TARGET_F1_KIND = os.environ.get("TARGET_F1_KIND", "macro").strip().lower()
MAX_TRAIN_RESTARTS = int(os.environ.get("MAX_TRAIN_RESTARTS", "3"))
RETRAIN_ON_FULL_TRAIN = os.environ.get("RETRAIN_ON_FULL_TRAIN", "1").strip() == "1"
# ---- Pure Python MLP ----
MLP_HIDDEN_DIM = int(os.environ.get("MLP_HIDDEN_DIM", "48"))
MLP_INIT_SCALE = float(os.environ.get("MLP_INIT_SCALE", "0.05"))
ACTIVATION_NAME = os.environ.get("ACTIVATION_NAME", "pade_tanh").strip().lower() # "tanh" | "pade_tanh"
# ===============================
# Pure Python numeric helpers
# ===============================
def isfinite(x: float) -> bool:
return math.isfinite(float(x))
def clip(x: float, lo: float, hi: float) -> float:
if x < lo:
return lo
if x > hi:
return hi
return x
def mean(xs: List[float]) -> float:
if not xs:
return 0.0
return sum(xs) / float(len(xs))
def variance(xs: List[float], ddof: int = 0) -> float:
n = len(xs)
if n == 0 or n - ddof <= 0:
return 0.0
m = mean(xs)
return sum((x - m) * (x - m) for x in xs) / float(n - ddof)
def std(xs: List[float], ddof: int = 0) -> float:
return math.sqrt(max(variance(xs, ddof=ddof), 0.0))
def median(xs: List[float]) -> float:
if not xs:
return 0.0
ys = sorted(float(x) for x in xs)
n = len(ys)
mid = n // 2
if n % 2 == 1:
return ys[mid]
return 0.5 * (ys[mid - 1] + ys[mid])
def argmax(values: List[float]) -> int:
if not values:
raise ValueError("argmax() received empty list")
best_i = 0
best_v = values[0]
for i in range(1, len(values)):
if values[i] > best_v:
best_v = values[i]
best_i = i
return best_i
def bincount(values: List[int], minlength: int) -> List[int]:
out = [0] * int(minlength)
for v in values:
iv = int(v)
if 0 <= iv < minlength:
out[iv] += 1
return out
def softmax_row(logits_row: List[float]) -> List[float]:
if not logits_row:
return []
m = max(logits_row)
exps = [math.exp(x - m) for x in logits_row]
s = sum(exps)
if s == 0.0:
return [0.0 for _ in logits_row]
return [x / s for x in exps]
def probs_from_logits(logits: List[List[float]]) -> List[List[float]]:
return [softmax_row(row) for row in logits]
def unique(values: List[Any]) -> List[Any]:
return sorted(set(values))
# ===============================
# Activations: tanh / pade_tanh
# ===============================
def tanh_act(x: float) -> float:
return math.tanh(x)
def tanh_deriv_from_pre(x: float) -> float:
t = math.tanh(x)
return 1.0 - t * t
def pade_tanh_act(x: float) -> float:
"""
Padé approximation of tanh(x):
tanh(x) ~= x * (27 + x^2) / (27 + 9x^2)
"""
x = clip(float(x), -3.0, 3.0)
x2 = x * x
return x * (27.0 + x2) / (27.0 + 9.0 * x2)
def pade_tanh_deriv_from_pre(x: float) -> float:
"""
Derivative of the clipped Padé tanh approximation.
"""
x = clip(float(x), -3.0, 3.0)
x2 = x * x
num = (x2 - 9.0) * (x2 - 9.0)
den = 9.0 * (x2 + 3.0) * (x2 + 3.0)
return num / den
def get_activation_pair(name: str):
n = str(name).strip().lower()
if n == "tanh":
return tanh_act, tanh_deriv_from_pre
return pade_tanh_act, pade_tanh_deriv_from_pre
# ===============================
# CSV helpers (no pandas) + .csv.gz support
# ===============================
def _canon(s: str) -> str:
return "".join(ch for ch in str(s).strip().lower() if ch.isalnum())
def _norm_text(x: Any) -> str:
s = str(x).strip().lower()
s = re.sub(r"\s+", " ", s)
return s
def _open_text(path: Path, encoding: str):
if str(path).endswith(".gz"):
return gzip.open(path, "rt", newline="", encoding=encoding)
return open(path, "r", newline="", encoding=encoding)
def _read_header(path: Path) -> List[str]:
for enc in ("utf-8", "utf-8-sig", "latin-1"):
try:
with _open_text(path, enc) as f:
r = csv.reader(f)
header = next(r)
return [h.strip() for h in header]
except Exception:
continue
raise RuntimeError(f"Could not read header for {path}")
def _find_col_index(actual_cols: List[str], candidates: List[str]) -> int:
canon_map = {_canon(c): i for i, c in enumerate(actual_cols)}
for cand in candidates:
key = _canon(cand)
if key in canon_map:
return canon_map[key]
raise ValueError(f"Missing columns {candidates}. Found sample: {actual_cols[:50]} ...")
def _resolve_usecols_idx(path: Path, wanted: Dict[str, List[str]]) -> Dict[str, int]:
header = _read_header(path)
resolved: Dict[str, int] = {}
for std_name, cands in wanted.items():
resolved[std_name] = _find_col_index(header, cands)
return resolved
def _iter_csv_std(path: Path, wanted: Dict[str, List[str]]) -> Iterable[Dict[str, str]]:
idx = _resolve_usecols_idx(path, wanted)
for enc in ("utf-8", "utf-8-sig", "latin-1"):
try:
with _open_text(path, enc) as f:
r = csv.reader(f)
_ = next(r)
for row in r:
if not row:
continue
out = {}
for k, j in idx.items():
out[k] = row[j].strip() if j < len(row) else ""
yield out
return
except Exception:
continue
raise RuntimeError(f"Could not read CSV {path}")
def _resolve_usecols_idx_optional(path: Path, wanted: Dict[str, List[str]]) -> Dict[str, int]:
header = _read_header(path)
canon_map = {_canon(c): i for i, c in enumerate(header)}
resolved: Dict[str, int] = {}
for std_name, cands in wanted.items():
found = None
for cand in cands:
key = _canon(cand)
if key in canon_map:
found = canon_map[key]
break
if found is not None:
resolved[std_name] = int(found)
return resolved
def _iter_csv_optional(path: Path, wanted: Dict[str, List[str]]) -> Iterable[Dict[str, str]]:
idx = _resolve_usecols_idx_optional(path, wanted)
if not idx:
return
yield
for enc in ("utf-8", "utf-8-sig", "latin-1"):
try:
with _open_text(path, enc) as f:
r = csv.reader(f)
_ = next(r)
for row in r:
if not row:
continue
out = {}
for k, j in idx.items():
out[k] = row[j].strip() if j < len(row) else ""
yield out
return
except Exception:
continue
raise RuntimeError(f"Could not read CSV {path}")
def _parse_int(x: Any) -> Optional[int]:
if x is None:
return None
s = str(x).strip()
if s == "" or s.lower() in {"nan", "none", "nat"}:
return None
try:
return int(float(s))
except Exception:
return None
def _parse_float(x: Any) -> Optional[float]:
if x is None:
return None
s = str(x).strip()
if s == "" or s.lower() in {"nan", "none", "nat"}:
return None
try:
return float(s)
except Exception:
return None
_DT_FORMATS = (
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y-%m-%d %H:%M:%S.%f",
)
def _safe_parse_datetime_str(x: Any) -> Optional[datetime]:
if x is None:
return None
s = str(x).strip()
if s == "" or s.lower() in {"nan", "none", "nat"}:
return None
m = re.match(r"^\s*(\d{4})", s)
if m:
try:
year = int(m.group(1))
if year >= 3000:
return None
except Exception:
pass
for fmt in _DT_FORMATS:
try:
return datetime.strptime(s, fmt)
except Exception:
continue
try:
return datetime.fromisoformat(s.replace("Z", ""))
except Exception:
return None
# ===============================
# Dataset discovery / path resolution
# ===============================
def _first_existing(paths: List[Path]) -> Path:
for p in paths:
if p.exists():
return p
raise FileNotFoundError(f"None of these files exist: {[str(x) for x in paths]}")
def _looks_like_mimic4_root(root: Path) -> bool:
return (root / "hosp").exists() and (root / "icu").exists()
def _looks_like_mimic3_root(root: Path) -> bool:
candidates = [
root / "ADMISSIONS.csv",
root / "ADMISSIONS.csv.gz",
root / "admissions.csv",
root / "admissions.csv.gz",
]
return any(p.exists() for p in candidates)
def _sanitize_tag(s: str) -> str:
s = s.strip().lower()
s = re.sub(r"[^a-z0-9]+", "_", s)
s = re.sub(r"_+", "_", s).strip("_")
return s or "dataset"
def resolve_paths(data_root: Path) -> Tuple[Dict[str, Path], str]:
if _looks_like_mimic4_root(data_root):
hosp = data_root / "hosp"
icu = data_root / "icu"
def pick(dirp: Path, base: str) -> Path:
return _first_existing(
[
dirp / f"{base}.csv",
dirp / f"{base}.csv.gz",
dirp / f"{base.upper()}.csv",
dirp / f"{base.upper()}.csv.gz",
]
)
return (
{
"micro": pick(hosp, "microbiologyevents"),
"presc": pick(hosp, "prescriptions"),
"admissions": pick(hosp, "admissions"),
"patients": pick(hosp, "patients"),
"d_items": pick(icu, "d_items"),
"chartevents": pick(icu, "chartevents"),
"d_labitems": pick(hosp, "d_labitems"),
"labevents": pick(hosp, "labevents"),
},
"mimic4",
)
def pick(base: str) -> Path:
return _first_existing(
[
data_root / f"{base}.csv",
data_root / f"{base}.csv.gz",
data_root / f"{base.upper()}.csv",
data_root / f"{base.upper()}.csv.gz",
]
)
return (
{
"micro": pick("microbiologyevents"),
"presc": pick("prescriptions"),
"admissions": pick("admissions"),
"patients": pick("patients"),
"d_items": pick("d_items"),
"chartevents": pick("chartevents"),
"d_labitems": pick("d_labitems"),
"labevents": pick("labevents"),
},
"mimic3",
)
def discover_dataset_roots() -> List[Path]:
roots: List[Path] = []
env = os.environ.get("MIMIC_AUTOROOTS", "").strip()
if env:
for part in env.split(","):
p = Path(part.strip())
if p.exists() and p.is_dir():
roots.append(p)
p_m4 = Path(
"datasets/datasets/montassarba/mimic-iv-clinical-database-demo-2-2/versions/1/mimic-iv-clinical-database-demo-2.2"
)
if p_m4.exists() and p_m4.is_dir():
roots.append(p_m4)
p_base = Path("dataset/mimic")
if p_base.exists() and p_base.is_dir():
roots.append(p_base)
for cand in list(p_base.glob("*")) + list(p_base.glob("*/*")):
if cand.is_dir():
if _looks_like_mimic4_root(cand) or _looks_like_mimic3_root(cand):
roots.append(cand)
seen = set()
out: List[Path] = []
for r in roots:
rp = r.resolve()
if rp not in seen:
seen.add(rp)
out.append(r)
return out
# ===============================
# MAP ORGANISM -> CLASS
# ===============================
def map_org(org: str) -> str:
o = str(org).upper()
viral_keys = ["VIRUS", "INFLUENZA", "RSV", "ADENOVIRUS", "PARAINFLUENZA", "CORONAVIRUS", "SARS", "COV"]
if any(k in o for k in viral_keys):
return "V:OTHER"
if "PSEUDOMONAS AERUGINOSA" in o:
return "B:PSEUDOMONAS AERUGINOSA"
if "STAPH AUREUS" in o and "METHICILLIN" not in o and "MRSA" not in o:
return "B:STAPH AUREUS COAG +"
if "SERRATIA MARCESCENS" in o:
return "B:SERRATIA MARCESCENS"
if "MORGANELLA MORGANII" in o:
return "B:MORGANELLA MORGANII"
if "ESCHERICHIA COLI" in o or "E. COLI" in o:
return "B:ESCHERICHIA COLI"
if "PROTEUS MIRABILIS" in o:
return "B:PROTEUS MIRABILIS"
if "PROVIDENCIA STUARTII" in o:
return "B:PROVIDENCIA STUARTII"
if "MRSA" in o or "METHICILLIN" in o:
return "B:POSITIVE FOR METHICILLIN RESISTANT STAPH AUREUS"
if "YEAST" in o or "CANDIDA" in o:
return "B:YEAST"
if "COCCUS" in o or "COCCI" in o:
return "B:GRAM POSITIVE COCCUS(COCCI)"
return "B:OTHER"
# ===============================
# ITEMID SETS: Temperature(C/F), SpO2, WBC
# ===============================
def build_itemid_sets() -> Tuple[set[int], set[int], set[int], set[int]]:
d_items_wanted = {"ITEMID": ["ITEMID", "ITEM_ID"], "LABEL": ["LABEL", "NAME"]}
temp_c_ids: set[int] = set()
temp_f_ids: set[int] = set()
spo2_ids: set[int] = set()
for row in _iter_csv_std(D_ITEMS_PATH, d_items_wanted):
itemid = _parse_int(row["ITEMID"])
label = row["LABEL"]
if itemid is None:
continue
ll = str(label).lower()
if "temperature" in ll and "c" in ll:
temp_c_ids.add(itemid)
if "temperature" in ll and "f" in ll:
temp_f_ids.add(itemid)
if "spo2" in ll:
spo2_ids.add(itemid)
if len(spo2_ids) == 0:
for row in _iter_csv_std(D_ITEMS_PATH, d_items_wanted):
itemid = _parse_int(row["ITEMID"])
label = row["LABEL"]
if itemid is None:
continue
ll = str(label).lower()
if ("o2" in ll) and ("saturation" in ll):
spo2_ids.add(itemid)
d_lab_wanted = {"ITEMID": ["ITEMID", "ITEM_ID"], "LABEL": ["LABEL", "NAME"]}
wbc_ids: set[int] = set()
wbc_re = re.compile(r"\bwbc\b", re.IGNORECASE)
for row in _iter_csv_std(D_LABITEMS_PATH, d_lab_wanted):
itemid = _parse_int(row["ITEMID"])
label = row["LABEL"]
if itemid is None:
continue
ll = str(label).lower()
if wbc_re.search(ll) or ("white blood" in ll):
wbc_ids.add(itemid)
return temp_c_ids, temp_f_ids, spo2_ids, wbc_ids
# ===============================
# Build admission windows + age
# ===============================
def build_adm_windows_for_hadm_set(hadm_set: set[int]) -> Tuple[Dict[int, Tuple[datetime, datetime]], Dict[int, float]]:
adm_wanted = {
"HADM_ID": ["HADM_ID", "HADMID"],
"SUBJECT_ID": ["SUBJECT_ID", "SUBJECTID"],
"ADMITTIME": ["ADMITTIME", "ADMIT_TIME", "ADMIT TIME"],
}
admissions: Dict[int, Tuple[int, datetime]] = {}
for row in _iter_csv_std(ADMISSIONS_PATH, adm_wanted):
hadm = _parse_int(row["HADM_ID"])
sid = _parse_int(row["SUBJECT_ID"])
adt = _safe_parse_datetime_str(row["ADMITTIME"])
if hadm is None or sid is None or adt is None:
continue
if hadm in hadm_set:
admissions[hadm] = (sid, adt)
patients_header = [h.lower() for h in _read_header(PATIENTS_PATH)]
has_dob = any(_canon(h) == _canon("dob") for h in patients_header)
has_anchor = any(_canon(h) == _canon("anchor_age") for h in patients_header) and any(
_canon(h) == _canon("anchor_year") for h in patients_header
)
dob_by_subject: Dict[int, datetime] = {}
anchor_by_subject: Dict[int, Tuple[float, int]] = {}
if has_dob:
pat_wanted = {"SUBJECT_ID": ["SUBJECT_ID", "SUBJECTID"], "DOB": ["DOB", "DATE_OF_BIRTH", "DATE OF BIRTH"]}
for row in _iter_csv_std(PATIENTS_PATH, pat_wanted):
sid = _parse_int(row["SUBJECT_ID"])
dob = _safe_parse_datetime_str(row["DOB"])
if sid is None or dob is None:
continue
dob_by_subject[sid] = dob
elif has_anchor:
pat_wanted = {
"SUBJECT_ID": ["SUBJECT_ID", "SUBJECTID"],
"ANCHOR_AGE": ["ANCHOR_AGE", "ANCHORAGE"],
"ANCHOR_YEAR": ["ANCHOR_YEAR", "ANCHORYEAR"],
}
for row in _iter_csv_std(PATIENTS_PATH, pat_wanted):
sid = _parse_int(row["SUBJECT_ID"])
aa = _parse_float(row["ANCHOR_AGE"])
ay = _parse_int(row["ANCHOR_YEAR"])
if sid is None or aa is None or ay is None:
continue
anchor_by_subject[sid] = (float(aa), int(ay))
else:
raise RuntimeError("PATIENTS schema not recognized (no DOB and no anchor_age/anchor_year).")
windows: Dict[int, Tuple[datetime, datetime]] = {}
ages: Dict[int, float] = {}
for hadm, (sid, adt) in admissions.items():
if has_dob:
dob = dob_by_subject.get(sid)
if dob is None:
continue
age = float((adt - dob).days) / 365.2425
else:
anc = anchor_by_subject.get(sid)
if anc is None:
continue
anchor_age, anchor_year = anc
age = float(anchor_age) + float(adt.year - int(anchor_year))
if not isfinite(age):
continue
if age > 120.0:
age = 90.0
age = clip(age, 0.0, 110.0)
windows[hadm] = (adt, adt + timedelta(hours=int(HOURS_WINDOW)))
ages[hadm] = age
return windows, ages
# ===============================
# Compute vitals/labs per HADM_ID
# ===============================
def compute_vitals_features(hadm_set: set[int]) -> Dict[int, Dict[str, float]]:
windows, ages = build_adm_windows_for_hadm_set(hadm_set)
if len(windows) == 0:
raise RuntimeError("No admission windows found for hadm_set.")
temp_c_ids, temp_f_ids, spo2_ids, wbc_ids = build_itemid_sets()
want_chart_itemids = temp_c_ids | temp_f_ids | spo2_ids
ce_wanted = {
"HADM_ID": ["HADM_ID", "HADMID"],
"ITEMID": ["ITEMID", "ITEM_ID"],
"CHARTTIME": ["CHARTTIME", "CHART_TIME", "CHART TIME"],
"VALUENUM": ["VALUENUM", "VALUE", "VALUE_NUM", "VALUE NUM"],
}
temp_sum: Dict[int, float] = {}
temp_n: Dict[int, int] = {}
spo2_min: Dict[int, float] = {}
for row in _iter_csv_std(CHARTEVENTS_PATH, ce_wanted):
hadm = _parse_int(row["HADM_ID"])
itemid = _parse_int(row["ITEMID"])
if hadm is None or itemid is None or hadm not in windows or itemid not in want_chart_itemids:
continue
ct = _safe_parse_datetime_str(row["CHARTTIME"])
if ct is None:
continue
t0, t1 = windows[hadm]
if ct < t0 or ct > t1:
continue
v = _parse_float(row["VALUENUM"])
if v is None:
continue
if itemid in temp_c_ids or itemid in temp_f_ids:
temp_c = float(v) if itemid in temp_c_ids else (float(v) - 32.0) / 1.8
if temp_c < 30.0 or temp_c > 45.0:
continue
temp_sum[hadm] = temp_sum.get(hadm, 0.0) + temp_c
temp_n[hadm] = temp_n.get(hadm, 0) + 1
elif itemid in spo2_ids:
spo2 = float(v)
if spo2 < 50.0 or spo2 > 100.0:
continue
prev = spo2_min.get(hadm)
spo2_min[hadm] = spo2 if (prev is None or spo2 < prev) else prev
temp_mean: Dict[int, float] = {}
for hadm, s in temp_sum.items():
n = temp_n.get(hadm, 0)
if n > 0:
temp_mean[hadm] = s / float(n)
le_wanted = {
"HADM_ID": ["HADM_ID", "HADMID"],
"ITEMID": ["ITEMID", "ITEM_ID"],
"CHARTTIME": ["CHARTTIME", "CHART_TIME", "CHART TIME"],
"VALUENUM": ["VALUENUM", "VALUE", "VALUE_NUM", "VALUE NUM"],
}
sample: List[float] = []
rng = random.Random(SEED)
seen = 0
for row in _iter_csv_std(LABEVENTS_PATH, le_wanted):
hadm = _parse_int(row["HADM_ID"])
itemid = _parse_int(row["ITEMID"])
if hadm is None or itemid is None or hadm not in windows or itemid not in wbc_ids:
continue
ct = _safe_parse_datetime_str(row["CHARTTIME"])
if ct is None:
continue
t0, t1 = windows[hadm]
if ct < t0 or ct > t1:
continue
v = _parse_float(row["VALUENUM"])
if v is None:
continue
seen += 1
if len(sample) < WBC_SAMPLE_MAX:
sample.append(float(v))
else:
j = rng.randrange(seen)
if j < WBC_SAMPLE_MAX:
sample[j] = float(v)
scale_by_1000 = False
if len(sample) > 0:
med = median(sample)
if med < 200.0:
scale_by_1000 = True
wbc_max: Dict[int, float] = {}
for row in _iter_csv_std(LABEVENTS_PATH, le_wanted):
hadm = _parse_int(row["HADM_ID"])
itemid = _parse_int(row["ITEMID"])
if hadm is None or itemid is None or hadm not in windows or itemid not in wbc_ids:
continue
ct = _safe_parse_datetime_str(row["CHARTTIME"])
if ct is None:
continue
t0, t1 = windows[hadm]
if ct < t0 or ct > t1:
continue
v = _parse_float(row["VALUENUM"])
if v is None:
continue
w = float(v) * (1000.0 if scale_by_1000 else 1.0)
if w < 2000.0 or w > 40000.0:
continue
prev = wbc_max.get(hadm)
wbc_max[hadm] = w if (prev is None or w > prev) else prev
out: Dict[int, Dict[str, float]] = {}
for hadm in hadm_set:
tm = temp_mean.get(hadm)
sp = spo2_min.get(hadm)
wb = wbc_max.get(hadm)
ag = ages.get(hadm)
if tm is None or sp is None or wb is None or ag is None:
continue
out[hadm] = {"temperature_c": float(tm), "wbc": float(wb), "spo2": float(sp), "age": float(ag)}
return out
# ===============================
# Load MICROBIOLOGYEVENTS -> rows
# ===============================
def load_micro_rows() -> List[Dict[str, Any]]:
micro_wanted = {
"HADM_ID": ["HADM_ID", "HADMID"],
"SPEC_TYPE_DESC": ["SPEC_TYPE_DESC", "SPECIMEN", "SPECIMEN_TYPE", "SPEC_TYPE"],
"ORG_NAME": ["ORG_NAME", "ORGANISM", "ORGNAME", "ORG NAME"],
"INTERPRETATION": ["INTERPRETATION", "RESULT", "COMMENTS", "COMMENT"],
}
rows: List[Dict[str, Any]] = []
for row in _iter_csv_std(MICRO_PATH, micro_wanted):
hadm = _parse_int(row["HADM_ID"])
org = row["ORG_NAME"]
if hadm is None or str(org).strip() == "":
continue
label = map_org(org)
if label not in CLASS_TO_INDEX:
continue
spec = _norm_text(row["SPEC_TYPE_DESC"])
interp = _norm_text(row["INTERPRETATION"])
if spec == "" or interp == "":
continue
rows.append({"hadm_id": int(hadm), "spec_type_desc": spec, "interpretation": interp, "label": label})
return rows
# ===============================
# Load PRESCRIPTIONS -> hadm_id -> antibiotics binary
# ===============================
def load_abx_features(hadm_set: set[int]) -> Dict[int, Dict[str, float]]:
presc_wanted = {"HADM_ID": ["HADM_ID", "HADMID"], "DRUG": ["DRUG", "DRUG_NAME", "MEDICATION"]}
wanted_upper = set(a.upper() for a in ANTIBIOTICS)
hadm_to_drugs: Dict[int, set[str]] = defaultdict(set)
for row in _iter_csv_std(PRESC_PATH, presc_wanted):
hadm = _parse_int(row["HADM_ID"])
if hadm is None or hadm not in hadm_set:
continue
drug = str(row["DRUG"]).strip()
if drug == "":
continue
if drug.upper() in wanted_upper:
hadm_to_drugs[int(hadm)].add(drug.upper())
out: Dict[int, Dict[str, float]] = {}
for hadm in hadm_set:
feats = {abx: 0.0 for abx in ABX_ORDER}
for abx_u in hadm_to_drugs.get(hadm, set()):
feats[abx_u.lower()] = 1.0
out[hadm] = feats
return out
# ===============================
# Tokenization and sparse features
# ===============================
def _tokenize(text: str) -> List[str]:
return [t for t in str(text).strip().lower().split() if t]
def build_vocab(texts: List[str], max_tokens: int) -> Dict[str, int]:
cnt = Counter()
for s in texts:
for t in _tokenize(str(s)):
cnt[t] += 1
keep = max(2, int(max_tokens))
vocab_items = cnt.most_common(max(0, keep))
vocab = {}
idx = 0
for tok, _ in vocab_items:
vocab[tok] = idx
idx += 1
return vocab
def fit_numeric_scaler(num_rows: List[List[float]], n_cont: int = 4) -> Tuple[List[float], List[float]]:
mu: List[float] = []
sd: List[float] = []
for j in range(n_cont):
col = [float(row[j]) for row in num_rows]
m = mean(col)
s = std(col) + 1e-6
mu.append(m)
sd.append(s)
return mu, sd
def apply_numeric_scaling(num_rows: List[List[float]], mu: List[float], sd: List[float], n_cont: int = 4) -> List[List[float]]:
out: List[List[float]] = []
for row in num_rows:
new_row = [float(x) for x in row]
for j in range(n_cont):
new_row[j] = (new_row[j] - mu[j]) / sd[j]
out.append(new_row)
return out
def make_sparse_feature(
num_row: List[float],
text: str,
vocab: Dict[str, int],
num_offset: int = 0,
text_offset: Optional[int] = None,
) -> Dict[int, float]:
if text_offset is None:
text_offset = len(num_row)
feat: Dict[int, float] = {}
for j, v in enumerate(num_row):
fv = float(v)
if abs(fv) > 1e-12:
feat[num_offset + j] = fv
tok_counts: Dict[int, float] = defaultdict(float)
toks = _tokenize(text)
if toks:
if TEXT_BINARY:
seen = set()
for tok in toks:
idx = vocab.get(tok)
if idx is not None:
seen.add(idx)
for idx in seen:
tok_counts[idx] = 1.0
else:
for tok in toks:
idx = vocab.get(tok)
if idx is not None:
tok_counts[idx] += 1.0
total = float(sum(tok_counts.values()))
if total > 0:
for idx in list(tok_counts.keys()):
tok_counts[idx] /= total
for idx, val in tok_counts.items():
feat[text_offset + idx] = val
return feat
def make_sparse_dataset(texts: List[str], num_rows: List[List[float]], vocab: Dict[str, int]) -> Tuple[List[Dict[int, float]], int]:
X: List[Dict[int, float]] = []
num_dim = len(num_rows[0]) if num_rows else len(NUMERIC_ORDER)
text_offset = num_dim
total_dim = num_dim + len(vocab)
for txt, num_row in zip(texts, num_rows):
X.append(make_sparse_feature(num_row, txt, vocab, num_offset=0, text_offset=text_offset))
return X, total_dim
# ===============================
# Pure Python split helpers
# ===============================
def stratified_split_indices(labels: List[int], test_size: float, seed: int) -> Tuple[List[int], List[int]]:
rng = random.Random(seed)
label_to_indices: Dict[int, List[int]] = defaultdict(list)
for i, y in enumerate(labels):
label_to_indices[int(y)].append(i)
train_idx: List[int] = []
test_idx: List[int] = []
for _label, idxs in label_to_indices.items():
idxs = list(idxs)
rng.shuffle(idxs)
if len(idxs) == 1:
train_part = idxs[:]
test_part = []
else:
n_test = int(round(len(idxs) * float(test_size)))
n_test = max(1, min(len(idxs) - 1, n_test))
test_part = idxs[:n_test]
train_part = idxs[n_test:]
train_idx.extend(train_part)
test_idx.extend(test_part)
rng.shuffle(train_idx)
rng.shuffle(test_idx)
return train_idx, test_idx
def take_by_indices(xs: List[Any], idxs: List[int]) -> List[Any]:
return [xs[i] for i in idxs]
def split_with_min_unique_hadm(
text_arr: List[str],
num_arr: List[List[float]],
y_arr: List[int],
hadm_arr: List[int],
test_size: float,
seed: int,
min_unique_test_hadm: int = MIN_TEST_UNIQUE_HADM,
):