AcidGNet_HCT116 / src /run_identity_aware_validation.py
xuyun's picture
Upload folder using huggingface_hub
a521a25 verified
Raw History Blame Contribute Delete
34.5 kB
from __future__ import annotations
import gzip
import hashlib
import io
import itertools
import json
import random
import tarfile
from pathlib import Path
from typing import Optional
import networkx as nx
import numpy as np
import pandas as pd
import torch
from scipy.stats import wilcoxon
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score
from torch import nn
from torch_geometric.data import Batch, Data
from torch_geometric.nn import GATv2Conv, global_add_pool
ROOT = Path(__file__).resolve().parents[1]
SEED = 20260809
N_GENES = 300
EPOCHS = 180
NULL_EPOCHS = 100
NEURAL_SEEDS = [SEED, SEED + 1, SEED + 2]
N_REWIRES_PER_DOMAIN = 10
METHODS = ["ExprLogReg", "MLP", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"]
STRING_DIR = ROOT / "data/raw/string_v12"
STRING_INDEX_DIR = ROOT / "data/processed/string_v12"
_STRING_GENES: Optional[np.ndarray] = None
_STRING_SYMBOLS: Optional[np.ndarray] = None
_STRING_EDGE_A: Optional[np.ndarray] = None
_STRING_EDGE_B: Optional[np.ndarray] = None
def seed_all(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def strip_ensembl(value: str) -> str:
return str(value).split(".")[0]
def collapse_duplicate_genes(frame: pd.DataFrame) -> pd.DataFrame:
out = frame.copy()
out.index = [strip_ensembl(x) for x in out.index]
if out.index.has_duplicates:
out = out.groupby(level=0).mean()
return out
def load_gse253054() -> tuple[pd.DataFrame, pd.DataFrame]:
path = ROOT / "data/raw/GSE253054_Normalized_counts_Acidosis.csv.gz"
genes_by_samples = pd.read_csv(
path, sep=";", decimal=",", index_col=0, compression="gzip"
).astype(float)
genes_by_samples = collapse_duplicate_genes(genes_by_samples)
x = np.log2(genes_by_samples + 1).T
meta = pd.DataFrame(index=x.index)
prefix = pd.Series(meta.index.str.extract(r"^(Fadu|HCT|Siha)", expand=False), index=meta.index)
meta["cell_line"] = prefix.replace({"Fadu": "FaDu", "HCT": "HCT116", "Siha": "SiHa"})
meta["acid"] = meta.index.str.contains("65").astype(int)
meta["study"] = "GSE253054"
meta["pH_acid"] = "6.5"
meta["pH_control"] = "7.4"
return x, meta
def load_gse152345() -> tuple[pd.DataFrame, pd.DataFrame]:
path = ROOT / "data/raw/GSE152345_gene_level_quantification.txt.gz"
genes_by_samples = pd.read_csv(path, sep=r"\s+", index_col=0, compression="gzip")
genes_by_samples = collapse_duplicate_genes(genes_by_samples.astype(float))
x = np.log2(genes_by_samples + 1).T
meta = pd.DataFrame(index=x.index)
meta["cell_line"] = np.select(
[meta.index.str.startswith("MDA"), meta.index.str.startswith("Panc"), meta.index.str.startswith("MCF7")],
["MDA-MB-231", "PANC1", "MCF7"],
default="unknown",
)
meta["acid"] = meta.index.str.contains("6_5").astype(int)
meta["study"] = "GSE152345"
meta["pH_acid"] = "6.5"
meta["pH_control"] = "7.6"
return x, meta
def load_external() -> tuple[pd.DataFrame, pd.DataFrame]:
path = ROOT / "data/raw/GSE200546_RAW.tar"
columns: dict[str, pd.Series] = {}
with tarfile.open(path) as archive:
for member in archive.getmembers():
name = member.name
if ("pH6.6" not in name and "pH7.4" not in name) or "24H" in name:
continue
raw = gzip.decompress(archive.extractfile(member).read())
data = pd.read_csv(io.BytesIO(raw), sep="\t").set_index("gene_id")["expected_count"]
columns[name.replace(".txt.gz", "")] = data
x = np.log2(pd.DataFrame(columns).fillna(0).T + 1)
meta = pd.DataFrame(index=x.index)
meta["acid"] = meta.index.str.contains("pH6.6").astype(int)
meta["cell_line"] = "CLS1"
meta["study"] = "GSE200546"
return x, meta
def pooled_discovery() -> tuple[pd.DataFrame, pd.DataFrame]:
x1, m1 = load_gse253054()
x2, m2 = load_gse152345()
common = sorted(set(x1.columns) & set(x2.columns))
x = pd.concat([x1[common], x2[common]], axis=0)
meta = pd.concat([m1, m2], axis=0).loc[x.index]
if meta.cell_line.eq("unknown").any():
raise ValueError("Unparsed GSE152345 sample names")
return x, meta
def sample_rank(frame: pd.DataFrame) -> np.ndarray:
return frame.rank(axis=1, pct=True).sub(0.5).to_numpy(dtype=np.float32)
def prepare_string_index() -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Build/load a local gene-level STRING v12 index (combined score >=700).
The official files use ENSP identifiers for links. Only aliases explicitly marked
``Ensembl_gene`` are used to obtain ENSG identifiers. Multiple protein isoforms are
collapsed to one undirected gene pair; no online identifier inference is performed.
"""
global _STRING_GENES, _STRING_SYMBOLS, _STRING_EDGE_A, _STRING_EDGE_B
if _STRING_GENES is not None:
return _STRING_GENES, _STRING_SYMBOLS, _STRING_EDGE_A, _STRING_EDGE_B
aliases_path = STRING_DIR / "9606.protein.aliases.v12.0.txt.gz"
info_path = STRING_DIR / "9606.protein.info.v12.0.txt.gz"
links_path = STRING_DIR / "9606.protein.links.v12.0.txt.gz"
for path in (aliases_path, info_path, links_path):
if not path.exists():
raise FileNotFoundError(f"Required official STRING v12 file missing: {path}")
STRING_INDEX_DIR.mkdir(parents=True, exist_ok=True)
map_path = STRING_INDEX_DIR / "ensembl_gene_protein_map.csv.gz"
edge_path = STRING_INDEX_DIR / "gene_edges_score700.npz"
if not map_path.exists() or not edge_path.exists():
print("Preparing reproducible local STRING v12 gene index ...", flush=True)
protein_symbol: dict[str, str] = {}
with gzip.open(info_path, "rt", encoding="utf-8") as handle:
next(handle)
for line in handle:
fields = line.rstrip("\n").split("\t", 3)
if len(fields) >= 2:
protein_symbol[fields[0]] = fields[1]
rows: list[tuple[str, str, str]] = []
with gzip.open(aliases_path, "rt", encoding="utf-8") as handle:
next(handle)
for line in handle:
fields = line.rstrip("\n").split("\t")
if len(fields) == 3 and fields[2] == "Ensembl_gene" and fields[1].startswith("ENSG"):
rows.append((strip_ensembl(fields[1]), fields[0], protein_symbol.get(fields[0], "")))
mapping = pd.DataFrame(rows, columns=["gene_id", "protein_id", "symbol"]).drop_duplicates()
mapping = mapping.sort_values(["gene_id", "protein_id"]).reset_index(drop=True)
mapping.to_csv(map_path, index=False, compression="gzip")
gene_ids = np.array(sorted(mapping.gene_id.unique()), dtype=str)
gene_index = {gene: i for i, gene in enumerate(gene_ids)}
protein_to_gene = {
protein: gene_index[gene]
for gene, protein in mapping[["gene_id", "protein_id"]].itertuples(index=False, name=None)
}
edge_pairs: list[tuple[int, int]] = []
with gzip.open(links_path, "rt", encoding="utf-8") as handle:
next(handle)
for line in handle:
protein_a, protein_b, score_text = line.split()
if int(score_text) < 700:
continue
a = protein_to_gene.get(protein_a)
b = protein_to_gene.get(protein_b)
if a is not None and b is not None and a != b:
edge_pairs.append((min(a, b), max(a, b)))
pairs = np.unique(np.asarray(edge_pairs, dtype=np.int32), axis=0)
np.savez_compressed(edge_path, a=pairs[:, 0], b=pairs[:, 1])
print(
f"STRING local index: {len(gene_ids)} genes, {len(pairs)} unique high-confidence edges",
flush=True,
)
mapping = pd.read_csv(map_path, compression="gzip", dtype=str)
first = mapping.drop_duplicates("gene_id").sort_values("gene_id")
archive = np.load(edge_path)
_STRING_GENES = first.gene_id.to_numpy(dtype=str)
_STRING_SYMBOLS = first.symbol.fillna("").to_numpy(dtype=str)
_STRING_EDGE_A = archive["a"].astype(np.int32, copy=False)
_STRING_EDGE_B = archive["b"].astype(np.int32, copy=False)
return _STRING_GENES, _STRING_SYMBOLS, _STRING_EDGE_A, _STRING_EDGE_B
def string_graph(genes: list[str], tag: str) -> tuple[list[str], torch.Tensor, pd.DataFrame, pd.DataFrame]:
all_genes, all_symbols, all_a, all_b = prepare_string_index()
full_index = {gene: i for i, gene in enumerate(all_genes)}
mapped: list[str] = []
selected_full: list[int] = []
symbols: list[str] = []
seen_symbols: set[str] = set()
for gene in genes:
full = full_index.get(strip_ensembl(gene))
if full is None:
continue
symbol = str(all_symbols[full])
identity = symbol if symbol else gene
if identity in seen_symbols:
continue
mapped.append(strip_ensembl(gene))
selected_full.append(full)
symbols.append(symbol)
seen_symbols.add(identity)
if not mapped:
raise RuntimeError(f"No genes mapped to local STRING v12 for {tag}")
selected_mask = np.zeros(len(all_genes), dtype=bool)
selected_mask[np.asarray(selected_full, dtype=int)] = True
keep = selected_mask[all_a] & selected_mask[all_b]
remap = np.full(len(all_genes), -1, dtype=np.int32)
remap[np.asarray(selected_full, dtype=int)] = np.arange(len(mapped), dtype=np.int32)
undirected_a = remap[all_a[keep]]
undirected_b = remap[all_b[keep]]
directed_array = np.column_stack(
[np.concatenate([undirected_a, undirected_b]), np.concatenate([undirected_b, undirected_a])]
).astype(np.int64, copy=False)
edge_index = (
torch.from_numpy(directed_array.T.copy())
if len(directed_array)
else torch.empty((2, 0), dtype=torch.long)
)
nodes = pd.DataFrame({"node_id": np.arange(len(mapped)), "gene_id": mapped, "symbol": symbols})
edge_table = pd.DataFrame(
{
"source_gene_id": [mapped[i] for i in directed_array[:, 0]],
"target_gene_id": [mapped[i] for i in directed_array[:, 1]],
"source": "STRING_v12_combined_score_ge_700",
}
)
cache = ROOT / "data/processed/string_identity_v4_offline"
cache.mkdir(parents=True, exist_ok=True)
digest = hashlib.sha1("\n".join(genes).encode()).hexdigest()[:12]
nodes.to_csv(cache / f"{tag}_{digest}_nodes.csv", index=False)
edge_table.to_csv(cache / f"{tag}_{digest}_edges.csv", index=False)
return mapped, edge_index, nodes, edge_table
def graph_diagnostics(edge_index: torch.Tensor, n_nodes: int) -> dict[str, float]:
graph = nx.Graph()
graph.add_nodes_from(range(n_nodes))
graph.add_edges_from((int(a), int(b)) for a, b in edge_index.T.tolist() if a != b)
components = list(nx.connected_components(graph))
return {
"nodes": n_nodes,
"directed_edges": int(edge_index.shape[1]),
"undirected_edges": int(graph.number_of_edges()),
"isolated_nodes": int(len(list(nx.isolates(graph)))),
"isolated_fraction": float(len(list(nx.isolates(graph))) / max(n_nodes, 1)),
"components": int(nx.number_connected_components(graph)),
"largest_component": int(max((len(c) for c in components), default=0)),
"density": float(nx.density(graph)),
}
def degree_preserving_rewire(edge_index: torch.Tensor, n_nodes: int, seed: int) -> torch.Tensor:
graph = nx.Graph()
graph.add_nodes_from(range(n_nodes))
graph.add_edges_from((int(a), int(b)) for a, b in edge_index.T.tolist() if a < b)
rewired = graph.copy()
if rewired.number_of_edges() >= 4:
swaps = max(1, rewired.number_of_edges() * 3)
try:
nx.double_edge_swap(rewired, nswap=swaps, max_tries=swaps * 50, seed=seed)
except nx.NetworkXAlgorithmError:
nx.double_edge_swap(rewired, nswap=max(1, rewired.number_of_edges()), max_tries=swaps * 100, seed=seed)
if sorted(dict(graph.degree()).values()) != sorted(dict(rewired.degree()).values()):
raise RuntimeError("Degree sequence changed during rewiring")
directed = []
for a, b in sorted(rewired.edges()):
directed.extend([(a, b), (b, a)])
return torch.tensor(directed, dtype=torch.long).T.contiguous() if directed else torch.empty((2, 0), dtype=torch.long)
class ExpressionMLP(nn.Module):
def __init__(self, n_features: int):
super().__init__()
self.net = nn.Sequential(nn.Linear(n_features, 32), nn.ReLU(), nn.Dropout(0.2), nn.Linear(32, 1))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x).squeeze(1)
class GeneAwareDeepSet(nn.Module):
def __init__(self, n_nodes: int, id_dim: int = 8, hidden: int = 24):
super().__init__()
self.gene_embedding = nn.Embedding(n_nodes, id_dim)
self.node = nn.Sequential(nn.Linear(id_dim + 1, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU())
self.gate = nn.Linear(hidden, 1)
self.out = nn.Linear(hidden, 1)
def forward(self, batch: Batch) -> tuple[torch.Tensor, torch.Tensor]:
h = self.node(torch.cat([batch.x, self.gene_embedding(batch.node_id)], dim=1))
weight = torch.sigmoid(self.gate(h))
numerator = global_add_pool(h * weight, batch.batch)
denominator = global_add_pool(weight, batch.batch).clamp_min(1e-6)
z = numerator / denominator
return self.out(z).squeeze(1), z
class IdentityGAT(nn.Module):
def __init__(self, n_nodes: int, id_dim: int = 8, hidden: int = 24):
super().__init__()
self.gene_embedding = nn.Embedding(n_nodes, id_dim)
self.conv1 = GATv2Conv(id_dim + 1, hidden, heads=2, concat=False, dropout=0.2)
self.conv2 = GATv2Conv(hidden, hidden, heads=2, concat=False, dropout=0.2)
self.gate = nn.Linear(hidden, 1)
self.out = nn.Linear(hidden, 1)
def forward(self, batch: Batch) -> tuple[torch.Tensor, torch.Tensor]:
h = torch.cat([batch.x, self.gene_embedding(batch.node_id)], dim=1)
h = torch.relu(self.conv1(h, batch.edge_index))
h = torch.relu(self.conv2(h, batch.edge_index))
weight = torch.sigmoid(self.gate(h))
numerator = global_add_pool(h * weight, batch.batch)
denominator = global_add_pool(weight, batch.batch).clamp_min(1e-6)
z = numerator / denominator
return self.out(z).squeeze(1), z
def make_batch(values: np.ndarray, edge_index: torch.Tensor, device: torch.device) -> Batch:
n_nodes = values.shape[1]
node_ids = torch.arange(n_nodes, dtype=torch.long)
data = [
Data(x=torch.tensor(row[:, None], dtype=torch.float32), node_id=node_ids, edge_index=edge_index)
for row in values
]
return Batch.from_data_list(data).to(device)
def parameter_count(model: nn.Module) -> int:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def fit_predict_neural(
method: str,
x_train: np.ndarray,
y_train: np.ndarray,
x_test: np.ndarray,
edge_index: torch.Tensor,
seed: int,
device: torch.device,
epochs: int = EPOCHS,
) -> tuple[np.ndarray, float, int]:
seed_all(seed)
y = torch.tensor(y_train, dtype=torch.float32, device=device)
if method == "MLP":
model: nn.Module = ExpressionMLP(x_train.shape[1]).to(device)
train_obj = torch.tensor(x_train, dtype=torch.float32, device=device)
test_obj = torch.tensor(x_test, dtype=torch.float32, device=device)
forward = lambda obj: model(obj)
else:
use_edges = torch.empty((2, 0), dtype=torch.long) if method == "IDSelfLoopGAT" else edge_index
train_obj = make_batch(x_train, use_edges, device)
test_obj = make_batch(x_test, use_edges, device)
model = GeneAwareDeepSet(x_train.shape[1]).to(device) if method == "GeneAwareDeepSet" else IdentityGAT(x_train.shape[1]).to(device)
forward = lambda obj: model(obj)[0]
optimizer = torch.optim.AdamW(model.parameters(), lr=0.003, weight_decay=1e-4)
last_loss = float("nan")
for _ in range(epochs):
model.train()
optimizer.zero_grad()
logits = forward(train_obj)
loss = nn.functional.binary_cross_entropy_with_logits(logits, y)
loss.backward()
optimizer.step()
last_loss = float(loss.detach().cpu())
model.eval()
with torch.no_grad():
probabilities = torch.sigmoid(forward(test_obj)).cpu().numpy()
return probabilities, last_loss, parameter_count(model)
def metric_values(y: np.ndarray, probabilities: np.ndarray) -> dict[str, float]:
return {
"auroc": float(roc_auc_score(y, probabilities)),
"auprc": float(average_precision_score(y, probabilities)),
"brier": float(brier_score_loss(y, probabilities)),
}
def uncertainty(y: np.ndarray, probabilities: np.ndarray, seed: int) -> dict[str, float]:
rng = np.random.default_rng(seed)
positive = np.where(y == 1)[0]
negative = np.where(y == 0)[0]
aurocs: list[float] = []
auprcs: list[float] = []
for _ in range(5000):
index = np.r_[rng.choice(positive, len(positive), replace=True), rng.choice(negative, len(negative), replace=True)]
aurocs.append(roc_auc_score(y[index], probabilities[index]))
auprcs.append(average_precision_score(y[index], probabilities[index]))
observed_roc = roc_auc_score(y, probabilities)
observed_pr = average_precision_score(y, probabilities)
n_positive = int(y.sum())
perm_roc: list[float] = []
perm_pr: list[float] = []
for positives in itertools.combinations(range(len(y)), n_positive):
permuted = np.zeros(len(y), dtype=int)
permuted[list(positives)] = 1
perm_roc.append(roc_auc_score(permuted, probabilities))
perm_pr.append(average_precision_score(permuted, probabilities))
return {
"auroc_ci_low": float(np.quantile(aurocs, 0.025)),
"auroc_ci_high": float(np.quantile(aurocs, 0.975)),
"auprc_ci_low": float(np.quantile(auprcs, 0.025)),
"auprc_ci_high": float(np.quantile(auprcs, 0.975)),
"auroc_exact_p": float(np.mean(np.asarray(perm_roc) >= observed_roc - 1e-12)),
"auprc_exact_p": float(np.mean(np.asarray(perm_pr) >= observed_pr - 1e-12)),
"n_balanced_permutations": int(len(perm_roc)),
}
def evaluate_fold(
x: pd.DataFrame,
meta: pd.DataFrame,
held_out: str,
device: torch.device,
tag: str,
methods: Optional[list[str]] = None,
exclude_gene_ids: Optional[set[str]] = None,
run_nulls: bool = False,
) -> tuple[list[dict], list[dict], list[dict], dict, list[dict]]:
methods = methods or METHODS
exclude_gene_ids = exclude_gene_ids or set()
train_mask = meta.cell_line.ne(held_out)
test_mask = ~train_mask
candidate = x.loc[train_mask].drop(columns=list(exclude_gene_ids & set(x.columns)), errors="ignore")
top = candidate.var().nlargest(N_GENES).index.tolist()
nodes, edge_index, node_table, edge_table = string_graph(top, f"{tag}_{held_out}")
a = sample_rank(x.loc[train_mask, nodes])
b = sample_rank(x.loc[test_mask, nodes])
y_train = meta.loc[train_mask, "acid"].to_numpy(dtype=int)
y_test = meta.loc[test_mask, "acid"].to_numpy(dtype=int)
sample_ids = meta.index[test_mask].tolist()
predictions: list[dict] = []
metrics: list[dict] = []
seed_metrics: list[dict] = []
for method in methods:
if method == "ExprLogReg":
model = LogisticRegression(C=0.1, max_iter=2000, random_state=SEED).fit(a, y_train)
ensemble = model.predict_proba(b)[:, 1]
params = int(a.shape[1] + 1)
train_loss = float("nan")
for sample, label, probability in zip(sample_ids, y_test, ensemble):
predictions.append(
{"sample": sample, "held_out": held_out, "study": meta.loc[sample, "study"], "y": label, "prob": probability, "method": method, "seed": "ensemble"}
)
else:
per_seed = []
losses = []
params = 0
for seed in NEURAL_SEEDS:
probability, loss, params = fit_predict_neural(method, a, y_train, b, edge_index, seed, device)
per_seed.append(probability)
losses.append(loss)
current = metric_values(y_test, probability)
seed_metrics.append({"held_out": held_out, "method": method, "seed": seed, "n": len(y_test), **current})
for sample, label, value in zip(sample_ids, y_test, probability):
predictions.append(
{"sample": sample, "held_out": held_out, "study": meta.loc[sample, "study"], "y": label, "prob": value, "method": method, "seed": seed}
)
ensemble = np.mean(per_seed, axis=0)
train_loss = float(np.mean(losses))
for sample, label, probability in zip(sample_ids, y_test, ensemble):
predictions.append(
{"sample": sample, "held_out": held_out, "study": meta.loc[sample, "study"], "y": label, "prob": probability, "method": method, "seed": "ensemble"}
)
point = metric_values(y_test, ensemble)
interval = uncertainty(y_test, ensemble, SEED + sum(map(ord, held_out + method)))
metrics.append(
{
"held_out": held_out,
"study": meta.loc[test_mask, "study"].iloc[0],
"method": method,
"n": len(y_test),
"train_loss": train_loss,
"parameters": params,
**point,
**interval,
}
)
null_rows: list[dict] = []
if run_nulls and "AcidGNetID" in methods:
observed, _, _ = fit_predict_neural("AcidGNetID", a, y_train, b, edge_index, SEED, device, epochs=NULL_EPOCHS)
null_rows.append({"held_out": held_out, "rewire": -1, "kind": "observed_STRING", **metric_values(y_test, observed)})
seen_hashes: set[str] = set()
for rewire in range(N_REWIRES_PER_DOMAIN):
rewired = degree_preserving_rewire(edge_index, len(nodes), SEED + 1000 + rewire)
digest = hashlib.sha1(rewired.cpu().numpy().tobytes()).hexdigest()
seen_hashes.add(digest)
probability, _, _ = fit_predict_neural(
"AcidGNetID", a, y_train, b, rewired, SEED, device, epochs=NULL_EPOCHS
)
null_rows.append(
{"held_out": held_out, "rewire": rewire, "kind": "degree_preserving", "edge_hash": digest, **metric_values(y_test, probability)}
)
if len(seen_hashes) < N_REWIRES_PER_DOMAIN:
print(f"Warning: {held_out} produced {len(seen_hashes)} unique rewired graphs")
diagnostics = {
"held_out": held_out,
"study": meta.loc[test_mask, "study"].iloc[0],
"selected_candidates": len(top),
**graph_diagnostics(edge_index, len(nodes)),
}
node_table.assign(fold=held_out).to_csv(ROOT / f"data/processed/v4_nodes_{tag}_{held_out}.csv", index=False)
edge_table.assign(fold=held_out).to_csv(ROOT / f"data/processed/v4_edges_{tag}_{held_out}.csv", index=False)
return predictions, metrics, seed_metrics, diagnostics, null_rows
def run_loco(
x: pd.DataFrame,
meta: pd.DataFrame,
device: torch.device,
tag: str,
methods: Optional[list[str]] = None,
exclude_gene_ids: Optional[set[str]] = None,
run_nulls: bool = False,
) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
all_predictions: list[dict] = []
all_metrics: list[dict] = []
all_seed_metrics: list[dict] = []
diagnostics: list[dict] = []
nulls: list[dict] = []
for held_out in sorted(meta.cell_line.unique()):
print(f"[{tag}] held out: {held_out}", flush=True)
prediction, metric, seed_metric, diagnostic, null = evaluate_fold(
x, meta, held_out, device, tag, methods, exclude_gene_ids, run_nulls
)
all_predictions.extend(prediction)
all_metrics.extend(metric)
all_seed_metrics.extend(seed_metric)
diagnostics.append(diagnostic)
nulls.extend(null)
return (
pd.DataFrame(all_predictions),
pd.DataFrame(all_metrics),
pd.DataFrame(all_seed_metrics),
pd.DataFrame(diagnostics),
pd.DataFrame(nulls),
)
def fit_transfer(
x_train: pd.DataFrame,
y_train: np.ndarray,
x_test: pd.DataFrame,
y_test: np.ndarray,
test_meta: pd.DataFrame,
comparison: str,
device: torch.device,
tag: str,
) -> tuple[list[dict], list[dict]]:
top = x_train.var().nlargest(N_GENES).index.tolist()
nodes, edge_index, _, _ = string_graph(top, tag)
nodes = [g for g in nodes if g in x_test.columns]
if len(nodes) < 50:
raise RuntimeError(f"Insufficient common nodes for {comparison}: {len(nodes)}")
# Subset the original graph to nodes retained in the test set.
original_nodes, original_edge_index, _, _ = string_graph(top, tag)
keep = [original_nodes.index(g) for g in nodes]
remap = {old: new for new, old in enumerate(keep)}
edge_pairs = [(remap[a], remap[b]) for a, b in original_edge_index.T.tolist() if a in remap and b in remap]
use_edge_index = torch.tensor(edge_pairs, dtype=torch.long).T.contiguous() if edge_pairs else torch.empty((2, 0), dtype=torch.long)
a = sample_rank(x_train[nodes])
b = sample_rank(x_test[nodes])
predictions: list[dict] = []
metrics: list[dict] = []
for method in ["ExprLogReg", "GeneAwareDeepSet", "IDSelfLoopGAT", "AcidGNetID"]:
if method == "ExprLogReg":
model = LogisticRegression(C=0.1, max_iter=2000, random_state=SEED).fit(a, y_train)
probability = model.predict_proba(b)[:, 1]
else:
values = [fit_predict_neural(method, a, y_train, b, use_edge_index, seed, device)[0] for seed in NEURAL_SEEDS]
probability = np.mean(values, axis=0)
for sample, label, value in zip(x_test.index, y_test, probability):
predictions.append(
{"comparison": comparison, "sample": sample, "cell_line": test_meta.loc[sample, "cell_line"], "y": label, "prob": value, "method": method}
)
for domain in sorted(test_meta.cell_line.unique()):
mask = test_meta.cell_line.eq(domain).to_numpy()
point = metric_values(y_test[mask], probability[mask])
interval = uncertainty(y_test[mask], probability[mask], SEED + sum(map(ord, comparison + domain + method)))
metrics.append({"comparison": comparison, "test_domain": domain, "method": method, "n": int(mask.sum()), **point, **interval})
return predictions, metrics
def flagged_confounders() -> tuple[set[str], pd.DataFrame]:
mapping_file = ROOT / "metadata/ensembl_gene_mapping.csv"
mapping = pd.read_csv(mapping_file)
flagged_symbols = {
"IFI44L", "BST2", "APOL1", "IFITM1", "XAF1", "SAMD9L", "IFI44",
"RPS4Y1", "DDX3Y", "TXLNGY", "KDM5D", "USP9Y", "EIF1AY",
}
flagged = mapping[mapping.symbol.isin(flagged_symbols)].copy()
flagged["reason"] = np.where(flagged.symbol.str.contains("Y$|Y1$|DDX3Y|KDM5D|USP9Y|EIF1AY"), "Y-linked", "interferon-like top change")
return set(flagged.gene_id), flagged
def summarize(metrics: pd.DataFrame) -> pd.DataFrame:
rows = []
for method, group in metrics.groupby("method"):
rows.append(
{
"method": method,
"domains": group.held_out.nunique(),
"mean_auroc": group.auroc.mean(),
"median_auroc": group.auroc.median(),
"min_auroc": group.auroc.min(),
"max_auroc": group.auroc.max(),
"mean_auprc": group.auprc.mean(),
"mean_brier": group.brier.mean(),
"mean_parameters": group.parameters.mean(),
}
)
out = pd.DataFrame(rows)
pivot = metrics.pivot(index="held_out", columns="method", values="auroc")
if {"ExprLogReg", "AcidGNetID"}.issubset(pivot.columns):
diff = pivot["AcidGNetID"] - pivot["ExprLogReg"]
try:
test = wilcoxon(diff, alternative="two-sided", method="exact")
pvalue = float(test.pvalue)
except ValueError:
pvalue = float("nan")
out["acidgnet_minus_expr_median"] = float(diff.median())
out["paired_domain_wilcoxon_p"] = pvalue
return out
def main() -> None:
for folder in [ROOT / "results", ROOT / "data/processed", ROOT / "logs"]:
folder.mkdir(parents=True, exist_ok=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x, meta = pooled_discovery()
print(f"Pooled discovery: {x.shape[0]} samples, {x.shape[1]} common genes, {meta.cell_line.nunique()} domains", flush=True)
predictions, metrics, seed_metrics, graph_stats, nulls = run_loco(
x, meta, device, tag="primary", run_nulls=True
)
predictions.to_csv(ROOT / "results/v4_loco_predictions.csv", index=False)
metrics.to_csv(ROOT / "results/v4_loco_metrics.csv", index=False)
seed_metrics.to_csv(ROOT / "results/v4_loco_seed_metrics.csv", index=False)
graph_stats.to_csv(ROOT / "results/v4_graph_diagnostics.csv", index=False)
nulls.to_csv(ROOT / "results/v4_degree_preserving_nulls.csv", index=False)
summary = summarize(metrics)
summary.to_csv(ROOT / "results/v4_loco_summary.csv", index=False)
excluded_ids, flagged = flagged_confounders()
flagged.to_csv(ROOT / "results/v4_flagged_confounders.csv", index=False)
sens_pred, sens_metrics, _, sens_graphs, _ = run_loco(
x,
meta,
device,
tag="exclude_flagged",
methods=["ExprLogReg", "AcidGNetID"],
exclude_gene_ids=excluded_ids,
run_nulls=False,
)
sens_pred.to_csv(ROOT / "results/v4_confounder_sensitivity_predictions.csv", index=False)
sens_metrics.to_csv(ROOT / "results/v4_confounder_sensitivity_metrics.csv", index=False)
sens_graphs.to_csv(ROOT / "results/v4_confounder_sensitivity_graphs.csv", index=False)
x1, m1 = load_gse253054()
x2, m2 = load_gse152345()
common = sorted(set(x1.columns) & set(x2.columns))
transfer_predictions: list[dict] = []
transfer_metrics: list[dict] = []
for train_x, train_m, test_x, test_m, comparison, tag in [
(x1[common], m1, x2[common], m2, "GSE253054_to_GSE152345", "study_253_to_152"),
(x2[common], m2, x1[common], m1, "GSE152345_to_GSE253054", "study_152_to_253"),
]:
p, mm = fit_transfer(
train_x, train_m.acid.to_numpy(dtype=int), test_x, test_m.acid.to_numpy(dtype=int), test_m, comparison, device, tag
)
transfer_predictions.extend(p)
transfer_metrics.extend(mm)
pd.DataFrame(transfer_predictions).to_csv(ROOT / "results/v4_cross_study_predictions.csv", index=False)
pd.DataFrame(transfer_metrics).to_csv(ROOT / "results/v4_cross_study_metrics.csv", index=False)
external_x, external_meta = load_external()
top = x.var().nlargest(N_GENES).index.tolist()
nodes, edge_index, node_table, edge_table = string_graph(top, "external_pooled")
pairs = [(gene, symbol) for gene, symbol in zip(node_table.gene_id, node_table.symbol) if symbol in external_x.columns]
retained_genes = [gene for gene, _ in pairs]
retained_symbols = [symbol for _, symbol in pairs]
original_index = {gene: i for i, gene in enumerate(nodes)}
keep = [original_index[g] for g in retained_genes]
remap = {old: new for new, old in enumerate(keep)}
external_pairs = [(remap[a], remap[b]) for a, b in edge_index.T.tolist() if a in remap and b in remap]
external_edges = torch.tensor(external_pairs, dtype=torch.long).T.contiguous() if external_pairs else torch.empty((2, 0), dtype=torch.long)
a = sample_rank(x[retained_genes])
b = sample_rank(external_x[retained_symbols])
y_train = meta.acid.to_numpy(dtype=int)
y_test = external_meta.acid.to_numpy(dtype=int)
external_predictions: list[dict] = []
external_metrics: list[dict] = []
for method in METHODS:
if method == "ExprLogReg":
model = LogisticRegression(C=0.1, max_iter=2000, random_state=SEED).fit(a, y_train)
probability = model.predict_proba(b)[:, 1]
else:
values = [fit_predict_neural(method, a, y_train, b, external_edges, seed, device)[0] for seed in NEURAL_SEEDS]
probability = np.mean(values, axis=0)
for sample, label, value in zip(external_x.index, y_test, probability):
external_predictions.append({"sample": sample, "y": label, "prob": value, "method": method})
point = metric_values(y_test, probability)
interval = uncertainty(y_test, probability, SEED + sum(map(ord, method)))
external_metrics.append({"method": method, "n": len(y_test), "mapped_nodes": len(retained_genes), **point, **interval})
pd.DataFrame(external_predictions).to_csv(ROOT / "results/v4_external_predictions.csv", index=False)
pd.DataFrame(external_metrics).to_csv(ROOT / "results/v4_external_metrics.csv", index=False)
node_table.to_csv(ROOT / "data/processed/v4_external_nodes_all.csv", index=False)
edge_table.to_csv(ROOT / "data/processed/v4_external_edges_all.csv", index=False)
run_summary = {
"device": str(device),
"torch": torch.__version__,
"samples": int(len(meta)),
"domains": int(meta.cell_line.nunique()),
"studies": sorted(meta.study.unique().tolist()),
"common_genes": int(x.shape[1]),
"rewired_graph_models": int((nulls.kind == "degree_preserving").sum()),
"macro_metrics": summary.set_index("method")[["mean_auroc", "mean_auprc", "mean_brier"]].round(4).to_dict("index"),
"external_metrics": pd.DataFrame(external_metrics).set_index("method")[["auroc", "auprc", "brier"]].round(4).to_dict("index"),
}
(ROOT / "logs/v4_identity_aware_validation.json").write_text(json.dumps(run_summary, indent=2), encoding="utf-8")
print(json.dumps(run_summary, indent=2), flush=True)
if __name__ == "__main__":
main()