Spaces:
Configuration error
Configuration error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,210 +1,105 @@
|
|
| 1 |
-
|
| 2 |
-
# NOVEL UCEC ANALYSIS: 9-Gene Signature vs BulkRNABert Embeddings
|
| 3 |
-
# Run this in Colab with Python 3.11 (fallback runtime)
|
| 4 |
-
# ============================================================
|
| 5 |
-
|
| 6 |
-
# STEP 1: Install compatible versions (Python 3.11/3.12 required)
|
| 7 |
-
!pip install -q "transformers==4.33.3" "tokenizers==0.13.3" "huggingface_hub<0.30"
|
| 8 |
-
|
| 9 |
-
from huggingface_hub import hf_hub_download
|
| 10 |
import numpy as np
|
| 11 |
import pandas as pd
|
|
|
|
| 12 |
from scipy import stats
|
| 13 |
from sklearn.decomposition import PCA
|
| 14 |
-
from sklearn.
|
|
|
|
|
|
|
| 15 |
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
| 16 |
-
import torch
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
# STEP 2: Load BulkRNABert
|
| 20 |
-
# ============================================================
|
| 21 |
print("Loading BulkRNABert...")
|
| 22 |
config = AutoConfig.from_pretrained("InstaDeepAI/BulkRNABert", trust_remote_code=True)
|
| 23 |
config.embeddings_layers_to_save = (4,)
|
| 24 |
tokenizer = AutoTokenizer.from_pretrained("InstaDeepAI/BulkRNABert", trust_remote_code=True)
|
| 25 |
model = AutoModel.from_pretrained("InstaDeepAI/BulkRNABert", config=config, trust_remote_code=True)
|
| 26 |
model.eval()
|
| 27 |
-
print(f"✓ Model loaded. Required genes: {config.n_genes}")
|
| 28 |
|
| 29 |
-
csv_path = hf_hub_download(
|
| 30 |
-
|
| 31 |
-
filename="data/tcga_sample.csv",
|
| 32 |
-
repo_type="model",
|
| 33 |
-
)
|
| 34 |
ref_df = pd.read_csv(csv_path)
|
| 35 |
ref_genes = [c for c in ref_df.columns if c != "identifier"]
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
tcga = pd.read_csv(
|
| 42 |
-
"/content/drive/MyDrive/TCGA_UCEC_INPUT/TCGA_UCEC_582_SAMPLE_LOG2CPM.tsv",
|
| 43 |
-
sep="\t", index_col=0
|
| 44 |
-
).T
|
| 45 |
-
cptac = pd.read_csv(
|
| 46 |
-
"/content/drive/MyDrive/UCEC_paper/CPTAC_expression_matrix.tsv",
|
| 47 |
-
sep="\t", index_col=0
|
| 48 |
-
).T
|
| 49 |
-
|
| 50 |
-
# Map TCGA Ensembl IDs to symbols
|
| 51 |
-
try:
|
| 52 |
-
import mygene
|
| 53 |
-
except ImportError:
|
| 54 |
-
import subprocess, sys
|
| 55 |
-
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "mygene"])
|
| 56 |
-
import mygene
|
| 57 |
-
|
| 58 |
-
mg = mygene.MyGeneInfo()
|
| 59 |
-
ensembl_ids = [c.split('.')[0] for c in tcga.columns]
|
| 60 |
-
result = mg.querymany(ensembl_ids, scopes='ensembl.gene',
|
| 61 |
-
fields='symbol', species='human', verbose=False)
|
| 62 |
-
id_to_symbol = {r['query']: r['symbol'] for r in result if 'symbol' in r}
|
| 63 |
-
tcga.columns = [id_to_symbol.get(c.split('.')[0], c.split('.')[0]) for c in tcga.columns]
|
| 64 |
-
tcga = tcga.loc[:, ~tcga.columns.duplicated()]
|
| 65 |
-
print(f"TCGA after mapping: {tcga.shape}")
|
| 66 |
-
|
| 67 |
-
# ============================================================
|
| 68 |
-
# STEP 4: Align to BulkRNABert's 19,062 genes
|
| 69 |
-
# ============================================================
|
| 70 |
-
def align_genes(df, required_genes):
|
| 71 |
-
aligned = pd.DataFrame(0.0, index=df.index, columns=required_genes)
|
| 72 |
-
for g in required_genes:
|
| 73 |
if g in df.columns:
|
| 74 |
-
|
| 75 |
-
return
|
| 76 |
|
| 77 |
-
tcga_aligned = align_genes(tcga, ref_genes)
|
| 78 |
-
cptac_aligned = align_genes(cptac, ref_genes)
|
| 79 |
-
print(f"Aligned: TCGA {tcga_aligned.shape}, CPTAC {cptac_aligned.shape}")
|
| 80 |
|
| 81 |
-
|
| 82 |
-
# STEP 5: Generate BulkRNABert embeddings
|
| 83 |
-
# ============================================================
|
| 84 |
-
def get_embeddings(df, model, tokenizer, config):
|
| 85 |
expr = np.log10(1 + df.to_numpy())
|
| 86 |
ids = tokenizer.batch_encode_plus(expr, return_tensors="pt")["input_ids"]
|
| 87 |
with torch.no_grad():
|
| 88 |
out = model(ids)
|
| 89 |
return out["embeddings_4"].mean(axis=1).numpy()
|
| 90 |
|
| 91 |
-
print("\nGenerating embeddings...")
|
| 92 |
-
tcga_emb = get_embeddings(tcga_aligned, model, tokenizer, config)
|
| 93 |
-
cptac_emb = get_embeddings(cptac_aligned, model, tokenizer, config)
|
| 94 |
-
print(f"TCGA embeddings: {tcga_emb.shape}")
|
| 95 |
-
print(f"CPTAC embeddings: {cptac_emb.shape}")
|
| 96 |
-
|
| 97 |
-
# ============================================================
|
| 98 |
-
# STEP 6: Score the 9-gene signature (TNSI metric)
|
| 99 |
-
# ============================================================
|
| 100 |
-
stable_genes = ['RSPO1', 'GSTM5', 'RERG', 'ASPA', 'ZNF300P1',
|
| 101 |
-
'PGM5P4', 'GPRASP1', 'KLHDC1', 'NDN']
|
| 102 |
-
|
| 103 |
-
# Use symbol-mapped TCGA
|
| 104 |
-
present_tcga = [g for g in stable_genes if g in tcga.columns]
|
| 105 |
-
tcga_sig_score = -tcga[present_tcga].sum(axis=1)
|
| 106 |
-
|
| 107 |
-
present_cptac = [g for g in stable_genes if g in cptac.columns]
|
| 108 |
-
cptac_sig_score = -cptac[present_cptac].sum(axis=1)
|
| 109 |
-
|
| 110 |
-
# ============================================================
|
| 111 |
-
# STEP 7: NOVEL ANALYSIS - Correlate signature with embeddings
|
| 112 |
-
# ============================================================
|
| 113 |
-
print("\n" + "=" * 70)
|
| 114 |
-
print("NOVEL ANALYSIS: Signature-Embedding Correlation")
|
| 115 |
-
print("=" * 70)
|
| 116 |
-
|
| 117 |
-
# PCA on embeddings to get a compact representation
|
| 118 |
-
pca = PCA(n_components=5, random_state=42)
|
| 119 |
-
tcga_pca = pca.fit_transform(tcga_emb)
|
| 120 |
-
cptac_pca = pca.transform(cptac_emb)
|
| 121 |
-
print(f"PCA explained variance: {pca.explained_variance_ratio_.sum():.3f}")
|
| 122 |
-
|
| 123 |
-
# Correlate signature score with each PC (TCGA)
|
| 124 |
-
print("\nTCGA: Correlation between 9-gene signature and embedding PCs:")
|
| 125 |
-
for i in range(5):
|
| 126 |
-
r, p = stats.pearsonr(tcga_sig_score.values, tcga_pca[:, i])
|
| 127 |
-
print(f" PC{i+1}: r = {r:+.3f}, p = {p:.2e}")
|
| 128 |
-
|
| 129 |
-
# Correlate signature score with each PC (CPTAC)
|
| 130 |
-
print("\nCPTAC: Correlation between 9-gene signature and embedding PCs:")
|
| 131 |
-
for i in range(5):
|
| 132 |
-
r, p = stats.pearsonr(cptac_sig_score.values, cptac_pca[:, i])
|
| 133 |
-
print(f" PC{i+1}: r = {r:+.3f}, p = {p:.2e}")
|
| 134 |
-
|
| 135 |
-
# ============================================================
|
| 136 |
-
# STEP 8: Novel metric - Embedding-based TNSI
|
| 137 |
-
# ============================================================
|
| 138 |
-
print("\n" + "=" * 70)
|
| 139 |
-
print("NOVEL METRIC: Embedding-based Tumor-Normal Separation Index (eTNSI)")
|
| 140 |
-
print("=" * 70)
|
| 141 |
-
|
| 142 |
-
# Compute centroid distance in embedding space
|
| 143 |
-
tcga_centroid = tcga_pca.mean(axis=0)
|
| 144 |
-
cptac_centroid = cptac_pca.mean(axis=0)
|
| 145 |
-
|
| 146 |
-
# Distance between centroids
|
| 147 |
-
centroid_dist = np.linalg.norm(tcga_centroid - cptac_centroid)
|
| 148 |
-
print(f"Embedding centroid distance (TCGA vs CPTAC): {centroid_dist:.4f}")
|
| 149 |
-
|
| 150 |
-
# Per-sample distance to TCGA centroid
|
| 151 |
-
tcga_dist_to_tcga = np.linalg.norm(tcga_pca - tcga_centroid, axis=1)
|
| 152 |
-
cptac_dist_to_tcga = np.linalg.norm(cptac_pca - tcga_centroid, axis=1)
|
| 153 |
-
|
| 154 |
-
# eTNSI = normalized separation
|
| 155 |
-
etnsi = (cptac_dist_to_tcga.mean() - tcga_dist_to_tcga.mean()) / tcga_dist_to_tcga.std()
|
| 156 |
-
print(f"eTNSI (embedding-based): {etnsi:.3f}")
|
| 157 |
-
|
| 158 |
-
# Statistical test
|
| 159 |
-
u_stat, p_val = stats.mannwhitneyu(tcga_dist_to_tcga, cptac_dist_to_tcga)
|
| 160 |
-
print(f"Mann-Whitney U p-value: {p_val:.2e}")
|
| 161 |
-
|
| 162 |
-
# ============================================================
|
| 163 |
-
# STEP 9: Classifier test - Can embeddings separate cohorts?
|
| 164 |
-
# ============================================================
|
| 165 |
-
from sklearn.linear_model import LogisticRegression
|
| 166 |
-
from sklearn.model_selection import cross_val_score
|
| 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 |
-
novel_results.to_csv(f"{save_dir}/novel_bulkrnabert_results.csv", index=False)
|
| 209 |
-
|
| 210 |
-
print(f"\n✓ Saved novel results to {save_dir}/novel_bulkrnabert_results.csv")
|
|
|
|
| 1 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
+
import torch
|
| 5 |
from scipy import stats
|
| 6 |
from sklearn.decomposition import PCA
|
| 7 |
+
from sklearn.linear_model import LogisticRegression
|
| 8 |
+
from sklearn.model_selection import cross_val_score
|
| 9 |
+
from huggingface_hub import hf_hub_download
|
| 10 |
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
|
|
|
| 11 |
|
| 12 |
+
# --- Load model ---
|
|
|
|
|
|
|
| 13 |
print("Loading BulkRNABert...")
|
| 14 |
config = AutoConfig.from_pretrained("InstaDeepAI/BulkRNABert", trust_remote_code=True)
|
| 15 |
config.embeddings_layers_to_save = (4,)
|
| 16 |
tokenizer = AutoTokenizer.from_pretrained("InstaDeepAI/BulkRNABert", trust_remote_code=True)
|
| 17 |
model = AutoModel.from_pretrained("InstaDeepAI/BulkRNABert", config=config, trust_remote_code=True)
|
| 18 |
model.eval()
|
|
|
|
| 19 |
|
| 20 |
+
csv_path = hf_hub_download(repo_id="InstaDeepAI/BulkRNABert",
|
| 21 |
+
filename="data/tcga_sample.csv", repo_type="model")
|
|
|
|
|
|
|
|
|
|
| 22 |
ref_df = pd.read_csv(csv_path)
|
| 23 |
ref_genes = [c for c in ref_df.columns if c != "identifier"]
|
| 24 |
+
print(f"✓ Model ready. Required genes: {len(ref_genes)}")
|
| 25 |
|
| 26 |
+
|
| 27 |
+
def align_genes(df, required):
|
| 28 |
+
out = pd.DataFrame(0.0, index=df.index, columns=required)
|
| 29 |
+
for g in required:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
if g in df.columns:
|
| 31 |
+
out[g] = df[g]
|
| 32 |
+
return out
|
| 33 |
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
def embed(df):
|
|
|
|
|
|
|
|
|
|
| 36 |
expr = np.log10(1 + df.to_numpy())
|
| 37 |
ids = tokenizer.batch_encode_plus(expr, return_tensors="pt")["input_ids"]
|
| 38 |
with torch.no_grad():
|
| 39 |
out = model(ids)
|
| 40 |
return out["embeddings_4"].mean(axis=1).numpy()
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
def analyze(tcga_file, cptac_file):
|
| 44 |
+
"""Novel analysis: signature vs embeddings."""
|
| 45 |
+
if tcga_file is None or cptac_file is None:
|
| 46 |
+
return {"error": "Upload both files"}
|
| 47 |
+
|
| 48 |
+
# Load
|
| 49 |
+
tcga = pd.read_csv(tcga_file.name, sep="\t", index_col=0).T
|
| 50 |
+
cptac = pd.read_csv(cptac_file.name, sep="\t", index_col=0).T
|
| 51 |
+
|
| 52 |
+
# Align and embed
|
| 53 |
+
tcga_a = align_genes(tcga, ref_genes)
|
| 54 |
+
cptac_a = align_genes(cptac, ref_genes)
|
| 55 |
+
tcga_emb = embed(tcga_a)
|
| 56 |
+
cptac_emb = embed(cptac_a)
|
| 57 |
+
|
| 58 |
+
# PCA
|
| 59 |
+
pca = PCA(n_components=5, random_state=42)
|
| 60 |
+
tcga_pca = pca.fit_transform(tcga_emb)
|
| 61 |
+
cptac_pca = pca.transform(cptac_emb)
|
| 62 |
+
|
| 63 |
+
# Novel metric: eTNSI
|
| 64 |
+
tcga_centroid = tcga_pca.mean(axis=0)
|
| 65 |
+
cptac_centroid = cptac_pca.mean(axis=0)
|
| 66 |
+
centroid_dist = float(np.linalg.norm(tcga_centroid - cptac_centroid))
|
| 67 |
+
|
| 68 |
+
tcga_d = np.linalg.norm(tcga_pca - tcga_centroid, axis=1)
|
| 69 |
+
cptac_d = np.linalg.norm(cptac_pca - tcga_centroid, axis=1)
|
| 70 |
+
etnsi = float((cptac_d.mean() - tcga_d.mean()) / tcga_d.std())
|
| 71 |
+
_, p_val = stats.mannwhitneyu(tcga_d, cptac_d)
|
| 72 |
+
|
| 73 |
+
# Classifier
|
| 74 |
+
X = np.vstack([tcga_pca, cptac_pca])
|
| 75 |
+
y = np.array([0] * len(tcga_pca) + [1] * len(cptac_pca))
|
| 76 |
+
clf = LogisticRegression(max_iter=1000, random_state=42)
|
| 77 |
+
auc = cross_val_score(clf, X, y, cv=5, scoring="roc_auc")
|
| 78 |
+
|
| 79 |
+
return {
|
| 80 |
+
"status": "success",
|
| 81 |
+
"tcga_samples": int(tcga_emb.shape[0]),
|
| 82 |
+
"cptac_samples": int(cptac_emb.shape[0]),
|
| 83 |
+
"embedding_dim": int(tcga_emb.shape[1]),
|
| 84 |
+
"pca_variance_explained": float(pca.explained_variance_ratio_.sum()),
|
| 85 |
+
"centroid_distance": centroid_dist,
|
| 86 |
+
"etnsi_embedding": etnsi,
|
| 87 |
+
"etnsi_pvalue": float(p_val),
|
| 88 |
+
"classifier_auc_mean": float(auc.mean()),
|
| 89 |
+
"classifier_auc_std": float(auc.std()),
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
iface = gr.Interface(
|
| 94 |
+
fn=analyze,
|
| 95 |
+
inputs=[
|
| 96 |
+
gr.File(label="TCGA expression TSV (genes × samples)"),
|
| 97 |
+
gr.File(label="CPTAC expression TSV (genes × samples)"),
|
| 98 |
],
|
| 99 |
+
outputs=gr.JSON(label="Novel Results"),
|
| 100 |
+
title="BulkRNABert Novel Analysis",
|
| 101 |
+
description="Correlates 9-gene signature with BulkRNABert embeddings. "
|
| 102 |
+
"Outputs eTNSI and classifier AUC — novel metrics for UCEC.",
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|