Download code/survivalstandalone/dataset.py from unknownBrain/survivalanalysis_checkpointing: direct link, hf CLI and curl.
- Browser
- Download file 4.63 kB
-
https://huggingface.co/datasets/unknownBrain/survivalanalysis_checkpointing/resolve/main/code/survivalstandalone/dataset.py
- Command line
-
hf download hf://datasets/unknownBrain/survivalanalysis_checkpointing/code/survivalstandalone/dataset.py
-
curl -L -o dataset.py https://huggingface.co/datasets/unknownBrain/survivalanalysis_checkpointing/resolve/main/code/survivalstandalone/dataset.py
4.63 kB
| """ | |
| 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"]) |