File size: 4,633 Bytes
232c308 | 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 | """
survivalstandalone/dataset.py
Reads clinicaldata.csv (UCSF-PDGM format: ID, OS, '1-dead 0-alive', ...)
and loads the corresponding T1c volume for Cox survival training.
CSV columns used:
ID -> e.g. 'UCSF-PDGM-004' -> folder/file naming
OS -> survival time in DAYS (confirm this against the
UCSF-PDGM data dictionary before trusting units)
'1-dead 0-alive' -> event indicator (1 = death observed, 0 = censored)
"""
import os
import csv
import numpy as np
import nibabel as nib
import torch
from torch.utils.data import Dataset
import re
TARGET_SHAPE = (160, 192, 160) # same as CMTLNet preprocessing
def crop_or_pad(vol: np.ndarray, target_shape=TARGET_SHAPE) -> np.ndarray:
out = np.zeros(target_shape, dtype=vol.dtype)
src_slices, dst_slices = [], []
for s, t in zip(vol.shape, target_shape):
if s >= t:
start = (s - t) // 2
src_slices.append(slice(start, start + t))
dst_slices.append(slice(0, t))
else:
pad_start = (t - s) // 2
src_slices.append(slice(0, s))
dst_slices.append(slice(pad_start, pad_start + s))
out[tuple(dst_slices)] = vol[tuple(src_slices)]
return out
def load_volume(path: str) -> np.ndarray:
img = nib.load(path).get_fdata().astype(np.float32)
img = crop_or_pad(img)
mean, std = img.mean(), img.std() + 1e-8
img = (img - mean) / std
return img
def normalize_id(csv_id: str) -> str:
"""
clinicaldata.csv uses IDs like 'UCSF-PDGM-004' or 'UCSF-PDGM-0429_FU003d'.
The HuggingFace upload uses 4-digit zero-padded IDs like 'UCSF-PDGM-0004'.
This handles non-standard characters safely.
"""
prefix, num_part = csv_id.rsplit("-", 1)
# Extract only the leading digits from the numeric block
match = re.match(r"^(\d+)", num_part)
if match:
num = int(match.group(1))
suffix = num_part[match.end():]
return f"{prefix}-{num:04d}{suffix}"
else:
# Fallback if no digits match at all
return csv_id
def build_records(csv_path: str, data_root: str, modality: str = "T1c", preprocessed: bool = False):
"""
preprocessed=False -> reads raw HF download layout:
<data_root>/UCSF-PDGM-0004_nifti/UCSF-PDGM-0004_T1c.nii.gz
preprocessed=True -> reads output of preprocess_ucsf.py:
<data_root>/UCSF-PDGM-0004/T1C.nii.gz (always T1C.nii.gz regardless of `modality`)
"""
records = []
skipped_no_os = 0
skipped_missing_file = 0
with open(csv_path, newline="") as f:
for row in csv.DictReader(f):
raw_id = row["ID"].strip()
os_val = row["OS"].strip()
event_val = row["1-dead 0-alive"].strip()
if not os_val or not event_val:
skipped_no_os += 1
continue
sid = normalize_id(raw_id) # e.g. 'UCSF-PDGM-0004'
if preprocessed:
img_path = os.path.join(data_root, sid, "T1C.nii.gz")
else:
folder = f"{sid}_nifti"
img_path = os.path.join(data_root, folder, f"{sid}_{modality}.nii.gz")
if not os.path.exists(img_path):
skipped_missing_file += 1
continue
records.append({
"id": raw_id,
"path": img_path,
"time": float(os_val),
"event": int(event_val),
})
print(f"[build_records] usable={len(records)} "
f"skipped_no_survival_label={skipped_no_os} "
f"skipped_missing_file={skipped_missing_file}")
return records
class SurvivalDataset(Dataset):
def __init__(self, records):
self.records = records
def __len__(self):
return len(self.records)
def __getitem__(self, idx):
r = self.records[idx]
vol = load_volume(r["path"])
vol = torch.from_numpy(vol).unsqueeze(0) # (1, D, H, W)
return {
"id": r["id"],
"image": vol,
"time": torch.tensor(r["time"], dtype=torch.float32),
"event": torch.tensor(r["event"], dtype=torch.float32),
}
if __name__ == "__main__":
# quick manual test — adjust paths to your machine
CSV_PATH = "clinicaldata.csv"
DATA_ROOT = r"D:\jainam\UCSF-PDGM-v5" # <-- change to your actual root
records = build_records(CSV_PATH, DATA_ROOT)
if records:
ds = SurvivalDataset(records)
sample = ds[0]
print(sample["id"], sample["image"].shape, sample["time"], sample["event"]) |