File size: 9,527 Bytes
71ae2f0
 
 
 
 
 
 
 
6bd4e42
 
 
 
 
 
 
52f8cb9
751062d
6bd4e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de40714
 
 
e1efb8d
 
 
de40714
 
 
4780d8d
de40714
 
4780d8d
85adf5f
 
de40714
 
 
 
a2b6947
751062d
 
85adf5f
 
 
 
 
 
 
4780d8d
de40714
 
4780d8d
 
de40714
 
 
 
 
4780d8d
de40714
 
 
 
 
 
 
a2b6947
 
 
 
 
 
 
 
4780d8d
85adf5f
 
a2b6947
 
 
 
 
751062d
 
85adf5f
 
 
 
 
 
 
a2b6947
 
 
4780d8d
a2b6947
 
 
 
de40714
 
a2b6947
de40714
466e964
a2b6947
de40714
466e964
 
 
 
de40714
a2b6947
466e964
 
 
de40714
 
 
 
4780d8d
de40714
 
4780d8d
de40714
e1efb8d
de40714
 
e1efb8d
de40714
 
 
 
4780d8d
de40714
 
 
4780d8d
de40714
 
 
 
 
 
 
 
 
6bd4e42
 
 
 
 
 
 
 
 
 
49fbf68
 
6bd4e42
 
 
 
 
 
 
49fbf68
 
6bd4e42
 
 
 
 
 
49fbf68
 
6bd4e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4780d8d
 
49fbf68
 
 
4780d8d
49fbf68
4780d8d
49fbf68
 
 
4780d8d
49fbf68
4780d8d
49fbf68
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
"""Data structures and utilities for inference modules.

This module provides:
- Cancer type to integer mappings for model inputs/outputs
- SiteType enum for primary vs metastatic classification
- TileFeatureTensorDataset for feeding features to PyTorch models
"""

from enum import Enum
from typing import List

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

from mosaic.data_directory import get_data_directory

CANCER_TYPE_TO_INT_MAP = {
    "AASTR": 0,
    "ACC": 1,
    "ACRM": 2,
    "ACYC": 3,
    "ADNOS": 4,
    "ALUCA": 5,
    "AMPCA": 6,
    "ANGS": 7,
    "ANSC": 8,
    "AODG": 9,
    "APAD": 10,
    "ARMM": 11,
    "ARMS": 12,
    "ASTR": 13,
    "ATM": 14,
    "BA": 15,
    "BCC": 16,
    "BLAD": 17,
    "BLCA": 18,
    "BMGCT": 19,
    "BRCA": 20,
    "BRCANOS": 21,
    "BRCNOS": 22,
    "CCOV": 23,
    "CCRCC": 24,
    "CESC": 25,
    "CHDM": 26,
    "CHOL": 27,
    "CHRCC": 28,
    "CHS": 29,
    "COAD": 30,
    "COADREAD": 31,
    "CSCC": 32,
    "CSCLC": 33,
    "CUP": 34,
    "CUPNOS": 35,
    "DA": 36,
    "DASTR": 37,
    "DDLS": 38,
    "DES": 39,
    "DIFG": 40,
    "DSRCT": 41,
    "DSTAD": 42,
    "ECAD": 43,
    "EGC": 44,
    "EHAE": 45,
    "EHCH": 46,
    "EMPD": 47,
    "EOV": 48,
    "EPDCA": 49,
    "EPIS": 50,
    "EPM": 51,
    "ERMS": 52,
    "ES": 53,
    "ESCA": 54,
    "ESCC": 55,
    "GB": 56,
    "GBAD": 57,
    "GBC": 58,
    "GBM": 59,
    "GCCAP": 60,
    "GEJ": 61,
    "GINET": 62,
    "GIST": 63,
    "GNOS": 64,
    "GRCT": 65,
    "HCC": 66,
    "HGGNOS": 67,
    "HGNEC": 68,
    "HGSFT": 69,
    "HGSOC": 70,
    "HNMUCM": 71,
    "HNSC": 72,
    "IDC": 73,
    "IHCH": 74,
    "ILC": 75,
    "LGGNOS": 76,
    "LGSOC": 77,
    "LMS": 78,
    "LNET": 79,
    "LUAD": 80,
    "LUAS": 81,
    "LUCA": 82,
    "LUNE": 83,
    "LUPC": 84,
    "LUSC": 85,
    "LXSC": 86,
    "MAAP": 87,
    "MACR": 88,
    "MBC": 89,
    "MCC": 90,
    "MDLC": 91,
    "MEL": 92,
    "MFH": 93,
    "MFS": 94,
    "MGCT": 95,
    "MNG": 96,
    "MOV": 97,
    "MPNST": 98,
    "MRLS": 99,
    "MUP": 100,
    "MXOV": 101,
    "NBL": 102,
    "NECNOS": 103,
    "NETNOS": 104,
    "NOT": 105,
    "NPC": 106,
    "NSCLC": 107,
    "NSCLCPD": 108,
    "NSGCT": 109,
    "OCS": 110,
    "OCSC": 111,
    "ODG": 112,
    "OOVC": 113,
    "OPHSC": 114,
    "OS": 115,
    "PAAC": 116,
    "PAAD": 117,
    "PAASC": 118,
    "PAMPCA": 119,
    "PANET": 120,
    "PAST": 121,
    "PDC": 122,
    "PECOMA": 123,
    "PEMESO": 124,
    "PHC": 125,
    "PLBMESO": 126,
    "PLEMESO": 127,
    "PLMESO": 128,
    "PRAD": 129,
    "PRCC": 130,
    "PSEC": 131,
    "PTAD": 132,
    "RBL": 133,
    "RCC": 134,
    "RCSNOS": 135,
    "READ": 136,
    "RMS": 137,
    "SARCNOS": 138,
    "SBC": 139,
    "SBOV": 140,
    "SBWDNET": 141,
    "SCBC": 142,
    "SCCNOS": 143,
    "SCHW": 144,
    "SCLC": 145,
    "SCUP": 146,
    "SDCA": 147,
    "SEM": 148,
    "SFT": 149,
    "SKCM": 150,
    "SOC": 151,
    "SPDAC": 152,
    "SSRCC": 153,
    "STAD": 154,
    "SYNS": 155,
    "TAC": 156,
    "THAP": 157,
    "THHC": 158,
    "THME": 159,
    "THPA": 160,
    "THPD": 161,
    "THYC": 162,
    "THYM": 163,
    "TYST": 164,
    "UCCC": 165,
    "UCEC": 166,
    "UCP": 167,
    "UCS": 168,
    "UCU": 169,
    "UDMN": 170,
    "UEC": 171,
    "ULMS": 172,
    "UM": 173,
    "UMEC": 174,
    "URCC": 175,
    "USARC": 176,
    "USC": 177,
    "UTUC": 178,
    "VMM": 179,
    "VSC": 180,
    "WDLS": 181,
    "WT": 182,
}
INT_TO_CANCER_TYPE_MAP = {v: k for k, v in CANCER_TYPE_TO_INT_MAP.items()}


# Tissue site mapping (module-level cache)
_TISSUE_SITE_MAP = None

# Default tissue site index for "Not Applicable"
DEFAULT_TISSUE_SITE_IDX = 8


def get_tissue_site_map():
    """Load tissue site name → index mapping from CSV.

    Returns:
        dict: Mapping of tissue site names to indices (0-56)

    Raises:
        FileNotFoundError: If the tissue site CSV file is not found
    """
    global _TISSUE_SITE_MAP
    if _TISSUE_SITE_MAP is None:
        import pandas as pd

        data_dir = get_data_directory()
        csv_path = data_dir / "tissue_site_original_to_idx.csv"
        try:
            df = pd.read_csv(csv_path)
        except FileNotFoundError as e:
            raise FileNotFoundError(
                f"Tissue site mapping file not found at {csv_path}. "
                f"Please ensure the data directory contains 'tissue_site_original_to_idx.csv'."
            ) from e

        _TISSUE_SITE_MAP = {}
        for _, row in df.iterrows():
            _TISSUE_SITE_MAP[row["TISSUE_SITE"]] = int(row["idx"])

    return _TISSUE_SITE_MAP


def get_tissue_site_options():
    """Get sorted unique tissue site names for UI dropdowns.

    Returns:
        list: Sorted list of unique tissue site names
    """
    site_map = get_tissue_site_map()
    return sorted(set(site_map.keys()))


_SEX_MAP = None


def get_sex_map():
    """Get the sex to index mapping from CSV file.

    Returns:
        dict: Mapping of sex values to indices (0-2)

    Raises:
        FileNotFoundError: If the sex mapping CSV file is not found
    """
    global _SEX_MAP
    if _SEX_MAP is None:
        import pandas as pd

        data_dir = get_data_directory()
        csv_path = data_dir / "sex_original_to_idx.csv"
        try:
            df = pd.read_csv(csv_path)
        except FileNotFoundError as e:
            raise FileNotFoundError(
                f"Sex mapping file not found at {csv_path}. "
                f"Please ensure the data directory contains 'sex_original_to_idx.csv'."
            ) from e

        _SEX_MAP = {}
        for _, row in df.iterrows():
            _SEX_MAP[row["SEX"]] = int(row["idx"])

    return _SEX_MAP


def encode_sex(sex):
    """Convert sex to numeric encoding.

    Args:
        sex: "Male" or "Female" (required, case insensitive)

    Returns:
        int: 0 for Male, 1 for Female

    Raises:
        ValueError: If sex is not "Male" or "Female"
    """
    sex_map = get_sex_map()
    if sex not in sex_map:
        raise ValueError(f"Sex must be 'Male' or 'Female', got: {sex}")
    return sex_map[sex]


def encode_tissue_site(site_name):
    """Convert tissue site name to index (0-56).

    Args:
        site_name: Tissue site name from CSV

    Returns:
        int: Tissue site index, defaults to DEFAULT_TISSUE_SITE_IDX ("Not Applicable")
    """
    site_map = get_tissue_site_map()
    return site_map.get(site_name, DEFAULT_TISSUE_SITE_IDX)


def tissue_site_to_one_hot(site_idx, num_classes=57):
    """Convert tissue site index to one-hot vector.

    Args:
        site_idx: Index value (0-56 for tissue site, 0-2 for sex)
        num_classes: Number of classes (57 for tissue site, 3 for sex)

    Returns:
        list: One-hot encoded vector
    """
    one_hot = [0] * num_classes
    if 0 <= site_idx < num_classes:
        one_hot[site_idx] = 1
    return one_hot


class SiteType(Enum):
    PRIMARY = "Primary"
    METASTASIS = "Metastasis"


class TileFeatureTensorDataset(Dataset):
    def __init__(
        self,
        site_type: SiteType,
        tile_features: np.ndarray,
        sex: int = None,
        tissue_site_idx: int = None,
        n_max_tiles: int = 20000,
    ) -> None:
        """Initialize the dataset.

        Args:
            site_type: the site type as str, either "Primary" or "Metastasis"
            tile_features: the tile feature array
            sex: patient sex (0=Male, 1=Female), optional for Aeon
            tissue_site_idx: tissue site index (0-56), optional for Aeon
            n_max_tiles: the maximum number of tiles to use as int

        Returns:
            None
        """
        self.site_type = site_type
        self.sex = sex
        self.tissue_site_idx = tissue_site_idx
        self.n_max_tiles = n_max_tiles
        self.features = self._get_features(tile_features)

    def __len__(self) -> int:
        """Return the length of the dataset.

        Returns:
            int: the length of the dataset
        """
        return 1

    def _get_features(self, features) -> torch.Tensor:
        """Get the tile features

        Args:
            features: the tile features as a numpy array

        Returns:
            torch.Tensor: the tile tensor
        """
        features = torch.tensor(features, dtype=torch.float32)
        if features.shape[0] > self.n_max_tiles:
            indices = torch.randperm(features.shape[0])[: self.n_max_tiles]
            features = features[indices]
        if features.shape[0] < self.n_max_tiles:
            padding = torch.zeros(
                self.n_max_tiles - features.shape[0], features.shape[1]
            )
            features = torch.cat([features, padding], dim=0)
        return features

    def __getitem__(self, idx: int) -> dict:
        """Return an item from the dataset.

        Args:
            idx: the index of the item to return

        Returns:
            dict: the item
        """
        result = {"site": self.site_type.value, "tile_tensor": self.features}

        # Add sex and tissue_site if provided (for Aeon)
        if self.sex is not None:
            result["SEX"] = torch.tensor(
                tissue_site_to_one_hot(self.sex, num_classes=3), dtype=torch.float32
            )

        if self.tissue_site_idx is not None:
            result["TISSUE_SITE"] = torch.tensor(
                tissue_site_to_one_hot(self.tissue_site_idx, num_classes=57),
                dtype=torch.float32,
            )

        return result