Spaces:
Sleeping
Sleeping
File size: 10,128 Bytes
5d4afe2 d686612 643c0b7 5d4afe2 643c0b7 5d4afe2 d686612 5d4afe2 643c0b7 5d4afe2 643c0b7 012754b d686612 012754b e00f001 012754b e00f001 012754b 4bb4db8 d686612 5d4afe2 012754b d686612 012754b d686612 e00f001 d686612 5d4afe2 e00f001 012754b e00f001 012754b 5d4afe2 012754b d686612 012754b 5d4afe2 4bb4db8 012754b e00f001 012754b 5d4afe2 012754b 5d4afe2 d686612 012754b e00f001 012754b e00f001 012754b e00f001 012754b d686612 5d4afe2 e00f001 d686612 e00f001 012754b d686612 643c0b7 e00f001 012754b d686612 012754b 643c0b7 d686612 012754b d686612 e00f001 d686612 e00f001 d686612 e00f001 d686612 | 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 | from typing import Any
import numpy as np
import pandas as pd
import torch
from rdkit import Chem
from torch.utils.data import Dataset
from utils import smiles_to_graph
# ─────────────────────────────────────────────────────────────────
# Data Contract Exceptions & Loaders
# ─────────────────────────────────────────────────────────────────
class DataContractError(Exception):
"""Raised when dataset CSV files fail schema or integrity contracts."""
class GTExTissueLoader:
"""
Contract-conforming GTEx tissue profile loader.
Validates data/tissue_profiles.csv against contract specifications.
"""
def __init__(self, profiles: dict[str, torch.Tensor]):
self.profiles = profiles
@classmethod
def from_csv(cls, csv_path: str) -> "GTExTissueLoader":
df = pd.read_csv(csv_path)
expected_organs = {"Liver", "Heart", "Brain", "Kidney", "Lung"}
actual_organs = set(df["organ"].unique())
if not expected_organs.issubset(actual_organs):
raise DataContractError(
f"Missing required organs in {csv_path}. Expected at least {expected_organs}, got {actual_organs}"
)
feat_cols = [c for c in df.columns if c.startswith("feature_")]
if len(feat_cols) != 128:
raise DataContractError(
f"Expected 128 tissue feature columns in {csv_path}, found {len(feat_cols)}"
)
if df[feat_cols].isna().any().any():
raise DataContractError(f"NaN values found in tissue features of {csv_path}")
profiles = {}
for _, row in df.iterrows():
organ = str(row["organ"])
vec = torch.tensor(row[feat_cols].values.astype(np.float32))
profiles[organ] = vec
return cls(profiles)
def __contains__(self, organ: str) -> bool:
return organ in self.profiles
def __getitem__(self, organ: str) -> torch.Tensor:
if organ not in self.profiles:
raise DataContractError(f"Organ '{organ}' not found in loaded GTEx tissue profiles.")
return self.profiles[organ]
def load_labeled_records(csv_path: str, tissue: GTExTissueLoader) -> pd.DataFrame:
"""
Contract-conforming labeled ADR record loader.
Validates data/adr_records.csv against data contract constraints.
"""
df = pd.read_csv(csv_path)
expected_header = [
"smiles", "organ", "Hepatotoxicity", "Arrhythmia", "Seizure",
"Nephrotoxicity", "Pneumonitis", "Nausea", "Headache", "Dizziness",
"Fatigue", "Rash"
]
if list(df.columns) != expected_header:
raise DataContractError(
f"Header mismatch in {csv_path}.\nExpected: {expected_header}\nGot: {list(df.columns)}"
)
if df.isna().any().any():
raise DataContractError(f"Missing/NaN values detected in {csv_path}")
for idx, row in df.iterrows():
smiles = str(row["smiles"])
organ = str(row["organ"])
if organ not in tissue:
raise DataContractError(f"Row {idx}: Organ '{organ}' not in GTEx tissue loader.")
mol = Chem.MolFromSmiles(smiles)
if mol is None:
raise DataContractError(f"Row {idx}: Invalid SMILES string '{smiles}'")
for adr in expected_header[2:]:
val = row[adr]
if val not in (0, 1, 0.0, 1.0):
raise DataContractError(f"Row {idx}: Non-binary target label for {adr}: {val}")
return df
# ─────────────────────────────────────────────────────────────────
# Reproducibility seed
# ─────────────────────────────────────────────────────────────────
SEED = 42
np.random.seed(SEED)
# ─────────────────────────────────────────────────────────────────
# 10 Human Organs
# ─────────────────────────────────────────────────────────────────
ORGAN_NAMES = [
"Liver", "Heart", "Brain", "Kidney", "Lung",
"Pancreas", "Spleen", "Intestine", "Skin", "Bone_Marrow",
]
_TISSUE_ALPHA = {
"Liver": 1.80,
"Heart": 1.40,
"Brain": 0.70,
"Kidney": 1.20,
"Lung": 1.00,
"Pancreas": 0.90,
"Spleen": 1.10,
"Intestine": 1.50,
"Skin": 0.85,
"Bone_Marrow": 0.60,
}
TISSUE_DIM = 1024
GTEX_TISSUE_PROFILES: dict[str, torch.Tensor] = {
organ: torch.tensor(
np.random.dirichlet(np.ones(TISSUE_DIM) * alpha).astype(np.float32)
)
for organ, alpha in _TISSUE_ALPHA.items()
}
MEDDRA_ADR_CLASSES = [
"Hepatotoxicity", # 0
"Cardiotoxicity", # 1
"Nephrotoxicity", # 2
"Neurotoxicity", # 3
"Pulmotoxicity", # 4
"Gastrointestinal Toxicity", # 5
"Hematotoxicity", # 6
"Dermatological Reaction", # 7
"Immunotoxicity", # 8
"Metabolic Disruption", # 9
]
_RAW_DRUG_DEFS = [
("Acetaminophen", "CC(=O)NC1=CC=C(O)C=C1", ["Liver", "Kidney"]),
("Aspirin", "CC(=O)OC1=CC=CC=C1C(=O)O", ["Gastrointestinal Toxicity"]),
("Ibuprofen", "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", ["Kidney", "Gastrointestinal Toxicity"]),
("Diclofenac", "OC(=O)Cc1ccccc1Nc1c(Cl)cccc1Cl", ["Liver", "Kidney", "Gastrointestinal Toxicity"]),
("Naproxen", "COc1ccc2cc(C(C)C(=O)O)ccc2c1", ["Gastrointestinal Toxicity", "Kidney"]),
]
BENCHMARK_DRUGS: list[dict[str, Any]] = []
for idx, (name, smiles, tox) in enumerate(_RAW_DRUG_DEFS):
BENCHMARK_DRUGS.append({"name": name, "smiles": smiles, "toxic_organs": tox})
_ORGAN_TO_ADR_IDX = {
"Liver": 0,
"Heart": 1,
"Kidney": 2,
"Brain": 3,
"Lung": 4,
"Intestine": 5,
"Pancreas": 9,
"Spleen": 8,
"Skin": 7,
"Bone_Marrow": 6,
}
_SYSTEMIC_TO_ADR_IDX = {
"Hepatotoxicity": 0,
"Cardiotoxicity": 1,
"Nephrotoxicity": 2,
"Neurotoxicity": 3,
"Pulmotoxicity": 4,
"Gastrointestinal Toxicity": 5,
"Hematotoxicity": 6,
"Dermatological Reaction": 7,
"Immunotoxicity": 8,
"Metabolic Disruption": 9,
}
def _build_target_vector(organ_name: str, toxic_organs: list[str]) -> torch.Tensor:
target = torch.zeros(10, dtype=torch.float32)
organ_adr_idx = _ORGAN_TO_ADR_IDX.get(organ_name)
if organ_adr_idx is not None and organ_name in toxic_organs:
target[organ_adr_idx] = 1.0
for tox in toxic_organs:
if tox in _SYSTEMIC_TO_ADR_IDX:
target[_SYSTEMIC_TO_ADR_IDX[tox]] = 1.0
return target
class EpiADRDataset(Dataset):
def __init__(
self,
drugs: list[dict[str, Any]] | None = None,
repeat: int = 4,
):
self.drugs = drugs if drugs is not None else BENCHMARK_DRUGS
self.repeat = repeat
self.samples: list[dict[str, Any]] = []
self._build()
def _build(self):
graph_cache: dict[str, Any] = {}
for item in self.drugs:
smiles = item["smiles"]
if smiles not in graph_cache:
try:
node_feats, edge_index, _ = smiles_to_graph(smiles)
graph_cache[smiles] = (node_feats, edge_index)
except Exception:
graph_cache[smiles] = None
for _ in range(self.repeat):
for item in self.drugs:
smiles = item["smiles"]
drug_name = item.get("name", "Unknown")
toxic_list = item.get("toxic_organs", [])
cached = graph_cache.get(smiles)
if cached is None:
continue
node_feats, edge_index = cached
for organ_name in ORGAN_NAMES:
tissue_vec = GTEX_TISSUE_PROFILES[organ_name]
target = _build_target_vector(organ_name, toxic_list)
self.samples.append({
"smiles": smiles,
"drug_name": drug_name,
"node_feats": node_feats,
"edge_index": edge_index,
"organ_name": organ_name,
"tissue_vec": tissue_vec,
"target": target,
})
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
return self.samples[idx]
def custom_collate_fn(batch: list[dict[str, Any]]) -> dict[str, Any]:
node_feats_list = []
edge_index_list = []
batch_index_list = []
tissue_vec_list = []
target_list = []
smiles_list = []
node_offset = 0
for graph_idx, sample in enumerate(batch):
nf = sample["node_feats"]
ei = sample["edge_index"]
n = nf.shape[0]
node_feats_list.append(nf)
edge_index_list.append(ei + node_offset)
batch_index_list.append(torch.full((n,), graph_idx, dtype=torch.long))
tissue_vec_list.append(sample["tissue_vec"])
target_list.append(sample["target"])
smiles_list.append(sample["smiles"])
node_offset += n
return {
"x": torch.cat(node_feats_list, dim=0),
"edge_index": torch.cat(edge_index_list, dim=1),
"batch": torch.cat(batch_index_list, dim=0),
"tissue_vec": torch.stack(tissue_vec_list, dim=0),
"y": torch.stack(target_list, dim=0),
"smiles": smiles_list,
}
|