File size: 6,009 Bytes
70f7ab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""PyTorch datasets for the three modalities.

All datasets return a uniform batch dict so the trainer is modality-agnostic:
  {"slices": (T,3,H,W) | "vol": (1,D,H,W), "tab": (F,), "y": int, "subject_id": str}

Tabular features are standardized with statistics FIT ON THE TRAINING FOLD ONLY
(passed in as `tab_stats`) — never on the full dataset — to prevent leakage.
Missing tabular values are median/mode-imputed from training-fold stats too.
"""
from __future__ import annotations

from pathlib import Path

import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset

ROOT = Path(__file__).resolve().parents[3]
PROC2D = ROOT / "data" / "processed_2d"
PROC3D = ROOT / "data" / "processed_3d"

# imagenet stats for pretrained backbones (applied after per-volume z-score,
# so slices are re-scaled into the pretrained input regime)
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)


def fit_tab_stats(df: pd.DataFrame, features) -> dict:
    """Compute train-fold imputation + standardization stats for tab features."""
    stats = {}
    for f in features:
        col = df[f].astype(float)
        med = float(col.median())
        vals = col.fillna(med)
        mu, sd = float(vals.mean()), float(vals.std())
        stats[f] = {"median": med, "mean": mu, "std": sd if sd > 1e-6 else 1.0}
    return stats


def _encode_tab(row, features, stats) -> np.ndarray:
    out = np.zeros(len(features), dtype=np.float32)
    for i, f in enumerate(features):
        v = row[f]
        s = stats[f]
        if pd.isna(v):
            v = s["median"]
        out[i] = (float(v) - s["mean"]) / s["std"]
    return out


class SliceDataset(Dataset):
    """2D / 2.5D tri-planar slices. planes/n_slices select which of the 27 to load.

    modality:
      slice2d  -> single center axial slice returned as (1,3,H,W)
      slice25d -> the requested planes x n_slices as (T,3,H,W)
    """

    def __init__(self, df, features, tab_stats, planes=("axial",), n_slices=9,
                 modality="slice25d", augment=False):
        self.df = df.reset_index(drop=True)
        self.features = features
        self.stats = tab_stats
        self.planes = planes
        self.n_slices = n_slices
        self.modality = modality
        self.augment = augment

    def __len__(self):
        return len(self.df)

    def _load_plane(self, sid, plane):
        arr = np.load(PROC2D / sid / plane / "slices.npy").astype(np.float32)  # (9,H,W)
        # select n_slices centered subset if fewer requested
        if self.n_slices < arr.shape[0]:
            start = (arr.shape[0] - self.n_slices) // 2
            arr = arr[start:start + self.n_slices]
        return arr

    def _to_rgb(self, sl):  # (H,W) -> (3,H,W) imagenet-normalized
        x = np.stack([sl, sl, sl], axis=0)
        x = (x - IMAGENET_MEAN[:, None, None]) / IMAGENET_STD[:, None, None]
        return x.astype(np.float32)

    def _augment(self, arr):  # light aug on a (n,H,W) stack
        if not self.augment:
            return arr
        if np.random.rand() < 0.5:
            arr = arr + np.random.normal(0, 0.02, arr.shape).astype(np.float32)
        if np.random.rand() < 0.5:
            arr = arr * np.random.uniform(0.95, 1.05)
        return arr

    def __getitem__(self, idx):
        row = self.df.iloc[idx]
        sid = row["subject_id"]
        if self.modality == "slice2d":
            axial = self._load_plane(sid, "axial")
            center = axial[len(axial) // 2]
            slices = self._to_rgb(self._augment(center[None]))[0][None]  # (1,3,H,W)
        else:
            planes = []
            for p in self.planes:
                stack = self._augment(self._load_plane(sid, p))
                planes.append(np.stack([self._to_rgb(s) for s in stack]))  # (n,3,H,W)
            slices = np.concatenate(planes, axis=0)  # (T,3,H,W)
        return {
            "slices": torch.from_numpy(slices),
            "tab": torch.from_numpy(_encode_tab(row, self.features, self.stats)),
            "y": int(row["class_id"]),
            "subject_id": sid,
        }


class VolumeDataset(Dataset):
    """Whole-brain 3D volumes for CNN3D / transformer / hybrid models."""

    def __init__(self, df, features, tab_stats, target="cnn3d", augment=False):
        self.df = df.reset_index(drop=True)
        self.features = features
        self.stats = tab_stats
        self.target = target  # cnn3d (128^3) or tf3d (96x112x112)
        self.augment = augment

    def __len__(self):
        return len(self.df)

    def __getitem__(self, idx):
        row = self.df.iloc[idx]
        sid = row["subject_id"]
        vol = np.load(PROC3D / self.target / f"{sid}.npy").astype(np.float32)
        if self.augment and np.random.rand() < 0.5:
            vol = vol + np.random.normal(0, 0.02, vol.shape).astype(np.float32)
        return {
            "vol": torch.from_numpy(vol[None]),  # (1,D,H,W)
            "tab": torch.from_numpy(_encode_tab(row, self.features, self.stats)),
            "y": int(row["class_id"]),
            "subject_id": sid,
        }


class TabularDataset(Dataset):
    def __init__(self, df, features, tab_stats):
        self.df = df.reset_index(drop=True)
        self.features = features
        self.stats = tab_stats

    def __len__(self):
        return len(self.df)

    def __getitem__(self, idx):
        row = self.df.iloc[idx]
        return {
            "tab": torch.from_numpy(_encode_tab(row, self.features, self.stats)),
            "y": int(row["class_id"]),
            "subject_id": row["subject_id"],
        }


def collate(items):
    """Uniform collate that stacks whichever tensors are present."""
    out = {"y": torch.tensor([it["y"] for it in items]),
           "subject_id": [it["subject_id"] for it in items]}
    for key in ("slices", "vol", "tab"):
        if key in items[0]:
            out[key] = torch.stack([it[key] for it in items])
    return out