added the complete work on the 3 hypotheses
This commit is contained in:
1 parent
cab92e67ae
commit
251254f5a9
519 files changed
+232924
-436
No files matched your search
Executable
+168
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
H1 genome-wide aggregation.
|
||||
|
||||
Reads per-chromosome H1 outputs and computes:
|
||||
• Link prediction test AUC/AP per chrom (from metrics.json)
|
||||
• Compartment recovery AUC per chrom (5-fold CV LogReg on GM12878 embeddings)
|
||||
• IMR90 zero-shot compartment AUC per chrom
|
||||
• Spearman r (PC1 vs best latent dim)
|
||||
• Mean ± SD across autosomes
|
||||
|
||||
Inputs (auto-discovered):
|
||||
results/h1_representation/chr*/metrics.json
|
||||
results/h1_representation/chr*/gm12878_emb.npy
|
||||
results/h1_representation/chr*/imr90_emb.npy
|
||||
results/h1_representation/compartments/{gm12878,imr90}_chr*.csv
|
||||
|
||||
Outputs:
|
||||
results/h1_representation/genome_summary.csv
|
||||
|
||||
Usage:
|
||||
python experiments/h1_representation/aggregate.py
|
||||
python experiments/h1_representation/aggregate.py --results_base results/h1_representation
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import spearmanr
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import roc_auc_score, average_precision_score
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
def cv_auc_ap(X, y, n_splits=5, seed=42):
|
||||
skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)
|
||||
aucs, aps = [], []
|
||||
for tr, te in skf.split(X, y):
|
||||
sc = StandardScaler().fit(X[tr])
|
||||
lr = LogisticRegression(max_iter=1000, random_state=seed)
|
||||
lr.fit(sc.transform(X[tr]), y[tr])
|
||||
prob = lr.predict_proba(sc.transform(X[te]))[:, 1]
|
||||
aucs.append(roc_auc_score(y[te], prob))
|
||||
aps.append(average_precision_score(y[te], prob))
|
||||
return float(np.mean(aucs)), float(np.mean(aps))
|
||||
|
||||
|
||||
def best_spearman(emb, pc1):
|
||||
rs = [abs(spearmanr(emb[:, d], pc1).statistic) for d in range(emb.shape[1])]
|
||||
return float(np.max(rs))
|
||||
|
||||
|
||||
def _load_compartments(path):
|
||||
df = pd.read_csv(path)
|
||||
valid = df["compartment"].isin(["A", "B"]) & df["pc1"].notna()
|
||||
if valid.sum() < 100:
|
||||
return None
|
||||
return {
|
||||
"mask": valid.values,
|
||||
"pc1": df.loc[valid, "pc1"].values,
|
||||
"y": (df.loc[valid, "compartment"] == "A").astype(int).values,
|
||||
}
|
||||
|
||||
|
||||
def evaluate_chrom(chrom, results_base, comp_dir):
|
||||
chr_dir = os.path.join(results_base, chrom)
|
||||
metrics_path = os.path.join(chr_dir, "metrics.json")
|
||||
if not os.path.exists(metrics_path):
|
||||
return None
|
||||
with open(metrics_path) as f:
|
||||
m = json.load(f)
|
||||
|
||||
row = {
|
||||
"chrom": chrom,
|
||||
"link_auc": m.get("test_auc"),
|
||||
"link_ap": m.get("test_ap"),
|
||||
"epochs_ran": m.get("epochs_ran"),
|
||||
}
|
||||
|
||||
# GM12878 in-domain compartment recovery.
|
||||
# Genome-wide runs save "emb.npy"; migrated chr1 has "gm12878_emb.npy".
|
||||
gm_emb_path = os.path.join(chr_dir, "emb.npy")
|
||||
if not os.path.exists(gm_emb_path):
|
||||
gm_emb_path = os.path.join(chr_dir, "gm12878_emb.npy")
|
||||
gm_comp = _load_compartments(os.path.join(comp_dir, f"gm12878_{chrom}.csv"))
|
||||
if os.path.exists(gm_emb_path) and gm_comp is not None:
|
||||
emb = np.load(gm_emb_path)[gm_comp["mask"]]
|
||||
auc, ap = cv_auc_ap(emb, gm_comp["y"])
|
||||
row["gm12878_n_bins"] = int(gm_comp["mask"].sum())
|
||||
row["gm12878_comp_auc"] = auc
|
||||
row["gm12878_comp_ap"] = ap
|
||||
row["gm12878_spearman"] = best_spearman(emb, gm_comp["pc1"])
|
||||
|
||||
# IMR90 zero-shot
|
||||
imr_emb_path = os.path.join(chr_dir, "imr90_emb.npy")
|
||||
imr_comp = _load_compartments(os.path.join(comp_dir, f"imr90_{chrom}.csv"))
|
||||
if os.path.exists(imr_emb_path) and imr_comp is not None:
|
||||
emb = np.load(imr_emb_path)[imr_comp["mask"]]
|
||||
auc, ap = cv_auc_ap(emb, imr_comp["y"])
|
||||
row["imr90_n_bins"] = int(imr_comp["mask"].sum())
|
||||
row["imr90_zs_comp_auc"] = auc
|
||||
row["imr90_zs_spearman"] = best_spearman(emb, imr_comp["pc1"])
|
||||
|
||||
return row
|
||||
|
||||
|
||||
def _natural_chrom_key(name):
|
||||
m = re.match(r"chr(\d+)$", name)
|
||||
return int(m.group(1)) if m else 99
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--results_base", default="results/h1_representation")
|
||||
ap.add_argument("--out", default=None,
|
||||
help="Output CSV. Default: <results_base>/genome_summary.csv")
|
||||
args = ap.parse_args()
|
||||
|
||||
out_path = args.out or os.path.join(args.results_base, "genome_summary.csv")
|
||||
comp_dir = os.path.join(args.results_base, "compartments")
|
||||
|
||||
chr_dirs = sorted(
|
||||
[os.path.basename(p) for p in glob.glob(os.path.join(args.results_base, "chr*"))
|
||||
if os.path.isdir(p)],
|
||||
key=_natural_chrom_key,
|
||||
)
|
||||
if not chr_dirs:
|
||||
print(f"No per-chrom dirs found in {args.results_base}. "
|
||||
"Run experiments/h1_representation/run_genome.sh first.")
|
||||
return
|
||||
|
||||
rows = []
|
||||
for chrom in chr_dirs:
|
||||
print(f"Evaluating {chrom}...")
|
||||
row = evaluate_chrom(chrom, args.results_base, comp_dir)
|
||||
if row:
|
||||
rows.append(row)
|
||||
|
||||
df = pd.DataFrame(rows)
|
||||
|
||||
# Mean ± SD summary row
|
||||
summary = {"chrom": "MEAN ± SD"}
|
||||
for col in df.columns:
|
||||
if col == "chrom":
|
||||
continue
|
||||
v = pd.to_numeric(df[col], errors="coerce").dropna()
|
||||
if col.endswith("_n_bins") or col == "epochs_ran":
|
||||
summary[col] = f"sum={int(v.sum())}" if len(v) else ""
|
||||
elif len(v):
|
||||
summary[col] = f"{v.mean():.3f} ± {v.std():.3f}"
|
||||
else:
|
||||
summary[col] = ""
|
||||
df_out = pd.concat([df, pd.DataFrame([summary])], ignore_index=True)
|
||||
|
||||
df_out.to_csv(out_path, index=False)
|
||||
print(f"\nSaved → {out_path}")
|
||||
print("\n" + df_out.to_string(index=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Compares two latent embedding matrices,
|
||||
computes similarity metrics (cosine, Euclidean, L1)
|
||||
|
||||
Usage:
|
||||
python scripts/compare_embeddings_general.py \
|
||||
--emb1 results/emb.npy \
|
||||
--emb2 results/emb_eedi.npy \
|
||||
--label1 CTRL --label2 EEDi \
|
||||
--prefix results/chr21
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
from scipy.spatial.distance import cosine, euclidean, cityblock
|
||||
import os
|
||||
|
||||
|
||||
def compute_metrics(emb1, emb2):
|
||||
"""Compute cosine similarity, cosine distance, L2, and L1 per row."""
|
||||
cos_sims, cos_dists, l2_dists, l1_dists = [], [], [], []
|
||||
for a, b in zip(emb1, emb2):
|
||||
cos_sim = 1 - cosine(a, b)
|
||||
cos_dist = 1 - cos_sim
|
||||
l2 = euclidean(a, b)
|
||||
l1 = cityblock(a, b)
|
||||
cos_sims.append(cos_sim)
|
||||
cos_dists.append(cos_dist)
|
||||
l2_dists.append(l2)
|
||||
l1_dists.append(l1)
|
||||
return np.array(cos_sims), np.array(cos_dists), np.array(l2_dists), np.array(l1_dists)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Compare two embedding matrices")
|
||||
p.add_argument("--emb1", required=True, help="Path to first embedding .npy")
|
||||
p.add_argument("--emb2", required=True, help="Path to second embedding .npy")
|
||||
p.add_argument("--label1", default="A", help="Label for first embedding")
|
||||
p.add_argument("--label2", default="B", help="Label for second embedding")
|
||||
p.add_argument("--prefix", default="results/compare", help="Prefix for output files")
|
||||
p.add_argument("--no-plot", action="store_true", help="Skip generating the plot")
|
||||
args = p.parse_args()
|
||||
|
||||
# Load
|
||||
emb1 = np.load(args.emb1)
|
||||
emb2 = np.load(args.emb2)
|
||||
if emb1.shape != emb2.shape:
|
||||
raise ValueError(f"Shape mismatch: {emb1.shape} vs {emb2.shape}")
|
||||
|
||||
prefix_dir = os.path.dirname(os.path.abspath(args.prefix))
|
||||
os.makedirs(prefix_dir, exist_ok=True)
|
||||
n_bins, n_dim = emb1.shape
|
||||
print(f"Loaded embeddings: {n_bins} bins × {n_dim} dims")
|
||||
|
||||
# Compute metrics
|
||||
cos_sims, cos_dists, l2_dists, l1_dists = compute_metrics(emb1, emb2)
|
||||
|
||||
df = pd.DataFrame({
|
||||
"bin_id": np.arange(n_bins),
|
||||
"cosine_similarity": cos_sims,
|
||||
"cosine_distance": cos_dists,
|
||||
"euclidean": l2_dists,
|
||||
"manhattan": l1_dists
|
||||
})
|
||||
csv_path = f"{args.prefix}_delta.csv"
|
||||
df.to_csv(csv_path, index=False)
|
||||
print(f"Saved metrics → {csv_path}")
|
||||
|
||||
# Plot
|
||||
if not args.no_plot:
|
||||
plt.figure(figsize=(12, 4))
|
||||
plt.plot(df["bin_id"], df["cosine_distance"], lw=0.8, color="steelblue")
|
||||
plt.title(f"Δ-Embedding ({args.label1} vs {args.label2})")
|
||||
plt.xlabel("Bin index")
|
||||
plt.ylabel("Cosine distance (1 – similarity)")
|
||||
plt.tight_layout()
|
||||
fig_path = f"{args.prefix}_delta.png"
|
||||
plt.savefig(fig_path, dpi=300)
|
||||
print(f"Saved plot → {fig_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Compute A/B chromatin compartments from a Hi-C .mcool file.
|
||||
|
||||
Algorithm
|
||||
---------
|
||||
1. Load ICE-balanced contact matrix for the target chromosome.
|
||||
2. Distance-normalise to O/E (divide each diagonal by its mean contact frequency).
|
||||
3. Compute Pearson correlation matrix of the O/E rows.
|
||||
4. PCA of the correlation matrix; PC1 distinguishes A from B compartments.
|
||||
5. Orient the PC1 sign using --bigwig_orient (e.g. CTCF):
|
||||
positive PC1 → high signal in that track.
|
||||
With CTCF: positive PC1 = CTCF-enriched = A compartment (active).
|
||||
With H3K27me3: pass --flip_orient so positive PC1 = B compartment (repressive).
|
||||
|
||||
Output
|
||||
------
|
||||
CSV with columns: chrom, start, end, pc1, compartment (A / B / N for masked bins).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
import cooler
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.decomposition import PCA
|
||||
|
||||
|
||||
|
||||
def _bin_bigwig(bw_path: str, chrom: str, bins) -> np.ndarray:
|
||||
"""Average bigWig signal over a list of (start, end) genomic bins."""
|
||||
import pyBigWig
|
||||
bw = pyBigWig.open(bw_path)
|
||||
chrom_len = bw.chroms().get(chrom, 0)
|
||||
vals = []
|
||||
for s, e in bins:
|
||||
s, e = max(0, int(s)), min(chrom_len, int(e))
|
||||
if s >= e:
|
||||
vals.append(0.0)
|
||||
continue
|
||||
v = bw.stats(chrom, s, e, type="mean")[0]
|
||||
vals.append(0.0 if v is None or np.isnan(v) else float(v))
|
||||
bw.close()
|
||||
return np.array(vals)
|
||||
|
||||
|
||||
def _observed_over_expected(matrix: np.ndarray) -> np.ndarray:
|
||||
"""Distance-normalise a symmetric contact matrix (O/E transform)."""
|
||||
n = matrix.shape[0]
|
||||
oe = np.zeros((n, n), dtype=float)
|
||||
for d in range(n):
|
||||
idx = np.arange(n - d)
|
||||
diag = matrix[idx, idx + d].astype(float)
|
||||
positive = diag[diag > 0]
|
||||
if positive.size == 0:
|
||||
continue
|
||||
mean_d = positive.mean()
|
||||
norm_diag = np.where((np.isnan(diag)) | (diag == 0), 0.0, diag / mean_d)
|
||||
oe[idx, idx + d] = norm_diag
|
||||
if d > 0:
|
||||
oe[idx + d, idx] = norm_diag
|
||||
return oe
|
||||
|
||||
|
||||
def compute_compartments(
|
||||
mcool_path: str,
|
||||
chrom: str,
|
||||
res: int,
|
||||
orient_signal=None,
|
||||
flip_orient: bool = False,
|
||||
) -> pd.DataFrame:
|
||||
"""
|
||||
Return a DataFrame (chrom, start, end, pc1, compartment).
|
||||
|
||||
Parameters
|
||||
----------
|
||||
orient_signal : array-like, optional
|
||||
Per-bin 1-D signal used to fix the sign of PC1.
|
||||
Pass CTCF signal for positive-PC1 = A convention.
|
||||
flip_orient : bool
|
||||
If True, high orient_signal maps to negative PC1 (use with H3K27me3).
|
||||
"""
|
||||
c = cooler.Cooler(f"{mcool_path}::resolutions/{res}")
|
||||
bins_df = c.bins().fetch(chrom).reset_index(drop=True)
|
||||
matrix = c.matrix(balance=True).fetch(chrom).astype(float)
|
||||
|
||||
bad_bins = np.isnan(matrix).all(axis=0) | (matrix.sum(axis=0) == 0)
|
||||
np.nan_to_num(matrix, nan=0.0, copy=False)
|
||||
|
||||
oe = _observed_over_expected(matrix)
|
||||
|
||||
good = ~bad_bins
|
||||
oe_good = oe[np.ix_(good, good)]
|
||||
|
||||
# Zero rows produce NaN in corrcoef; add tiny noise to avoid singularity
|
||||
row_norms = np.linalg.norm(oe_good, axis=1)
|
||||
oe_good[row_norms == 0] += 1e-9
|
||||
|
||||
corr = np.corrcoef(oe_good)
|
||||
np.nan_to_num(corr, nan=0.0, copy=False)
|
||||
|
||||
pca = PCA(n_components=3, random_state=42)
|
||||
pcs = pca.fit_transform(corr)
|
||||
pc1_good = pcs[:, 0]
|
||||
|
||||
pc1 = np.full(len(bins_df), np.nan)
|
||||
pc1[good] = pc1_good
|
||||
|
||||
if orient_signal is not None:
|
||||
sig = np.asarray(orient_signal, dtype=float)
|
||||
sig_good = sig[good]
|
||||
valid = ~np.isnan(sig_good) & ~np.isnan(pc1_good)
|
||||
if valid.sum() > 10:
|
||||
r = np.corrcoef(pc1_good[valid], sig_good[valid])[0, 1]
|
||||
# By default: positive orient_signal → positive PC1.
|
||||
# flip_orient reverses this (e.g. H3K27me3 → positive PC1 = B).
|
||||
if (r < 0 and not flip_orient) or (r > 0 and flip_orient):
|
||||
pc1 = -pc1
|
||||
|
||||
bins_df["pc1"] = pc1
|
||||
bins_df["compartment"] = np.where(
|
||||
np.isnan(bins_df["pc1"]), "N",
|
||||
np.where(bins_df["pc1"] > 0, "A", "B"),
|
||||
)
|
||||
return bins_df[["chrom", "start", "end", "pc1", "compartment"]]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
p.add_argument("--mcool", required=True, help="Path to .mcool file")
|
||||
p.add_argument("--chrom", required=True, help="Chromosome (e.g. chr21)")
|
||||
p.add_argument("--res", type=int, default=25000, help="Resolution in bp (default: 25000)")
|
||||
p.add_argument("--bigwig_orient",
|
||||
help="bigWig track for PC1 sign orientation (recommended: CTCF)")
|
||||
p.add_argument("--flip_orient", action="store_true",
|
||||
help="Flip orientation: high signal → negative PC1 (use with H3K27me3)")
|
||||
p.add_argument("--out", required=True, help="Output CSV path")
|
||||
args = p.parse_args()
|
||||
|
||||
orient_signal = None
|
||||
if args.bigwig_orient:
|
||||
c = cooler.Cooler(f"{args.mcool}::resolutions/{args.res}")
|
||||
bins_df = c.bins().fetch(args.chrom).reset_index(drop=True)
|
||||
coords = list(zip(bins_df["start"].values, bins_df["end"].values))
|
||||
orient_signal = _bin_bigwig(args.bigwig_orient, args.chrom, coords)
|
||||
print(f"Loaded orientation signal: {os.path.basename(args.bigwig_orient)}")
|
||||
|
||||
df = compute_compartments(
|
||||
args.mcool, args.chrom, args.res,
|
||||
orient_signal=orient_signal,
|
||||
flip_orient=args.flip_orient,
|
||||
)
|
||||
|
||||
os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
|
||||
df.to_csv(args.out, index=False)
|
||||
|
||||
n_a = (df["compartment"] == "A").sum()
|
||||
n_b = (df["compartment"] == "B").sum()
|
||||
n_nan = (df["compartment"] == "N").sum()
|
||||
print(f"Saved → {args.out}")
|
||||
print(f" A: {n_a} B: {n_b} N/masked: {n_nan} bins")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Encode a chromatin contact graph using a trained VGAE model.
|
||||
|
||||
Dimensions (in_dim, hidden, latent) and encoder type are read from the
|
||||
metrics.json saved alongside model.pt. Edge weights are passed to GCN-based
|
||||
encoders so the same weighted message-passing used during training is applied
|
||||
at inference time.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python scripts/encode_graph.py \\
|
||||
--model results/GM12878/model.pt \\
|
||||
--graph data/processed/IMR90_chr21.pt \\
|
||||
--out results/IMR90/emb.npy
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch_geometric.nn.models import VGAE
|
||||
from torch_geometric.utils import remove_self_loops, to_undirected
|
||||
|
||||
from chromatin_gnn.model import build_encoder, GCNEncoder
|
||||
|
||||
|
||||
def _load_metrics(model_path: str) -> dict:
|
||||
"""Read metrics.json from the same directory as model.pt."""
|
||||
metrics_path = os.path.join(os.path.dirname(os.path.abspath(model_path)), "metrics.json")
|
||||
if os.path.exists(metrics_path):
|
||||
with open(metrics_path) as f:
|
||||
return json.load(f)
|
||||
return {}
|
||||
|
||||
|
||||
def _infer_dims_gcn(state_dict: dict) -> tuple:
|
||||
"""Fallback: infer (in_dim, hidden, latent) from a GCN state_dict."""
|
||||
keys = list(state_dict.keys())
|
||||
|
||||
def _first_weight(substr):
|
||||
for k in keys:
|
||||
if (substr in k
|
||||
and "weight" in k
|
||||
and "running" not in k
|
||||
and "num_batches" not in k):
|
||||
return state_dict[k].shape
|
||||
raise KeyError(f"No weight key containing '{substr}'. Keys: {keys}")
|
||||
|
||||
gc1_shape = _first_weight("gc1")
|
||||
gc_mu_shape = _first_weight("gc_mu")
|
||||
hidden = gc1_shape[0]
|
||||
latent = gc_mu_shape[0]
|
||||
for k in keys:
|
||||
if "norm" in k and k.endswith("weight") and "running" not in k:
|
||||
in_dim = state_dict[k].shape[0]
|
||||
break
|
||||
else:
|
||||
in_dim = gc1_shape[1]
|
||||
return in_dim, hidden, latent
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
p.add_argument("--model", required=True,
|
||||
help="Path to model.pt saved by train_vgae.py")
|
||||
p.add_argument("--graph", required=True,
|
||||
help="Path to Data .pt file from build_graph.py")
|
||||
p.add_argument("--out", required=True,
|
||||
help="Output .npy path for node embeddings")
|
||||
p.add_argument("--device", default="auto",
|
||||
help="cuda | cpu | auto (default: auto-detect CUDA)")
|
||||
args = p.parse_args()
|
||||
|
||||
if args.device == "auto":
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
else:
|
||||
device = torch.device(args.device)
|
||||
print(f"Using device: {device}"
|
||||
+ (f" ({torch.cuda.get_device_name(0)})" if device.type == "cuda" else ""))
|
||||
|
||||
data = torch.load(args.graph, weights_only=False)
|
||||
state_dict = torch.load(args.model, map_location=device, weights_only=False)
|
||||
|
||||
# Build edge_index and edge_weight (undirected, consistent with training)
|
||||
ei, _ = remove_self_loops(data.edge_index)
|
||||
if hasattr(data, "edge_weight") and data.edge_weight is not None:
|
||||
ei, ew = to_undirected(ei, data.edge_weight, num_nodes=data.num_nodes)
|
||||
else:
|
||||
ei = to_undirected(ei, num_nodes=data.num_nodes)
|
||||
ew = None
|
||||
|
||||
# Read hyperparameters from metrics.json (preferred) or infer from state_dict
|
||||
metrics = _load_metrics(args.model)
|
||||
encoder_name = metrics.get("encoder", "gcn")
|
||||
hidden = metrics.get("hidden")
|
||||
latent = metrics.get("latent")
|
||||
heads = metrics.get("heads") or 4
|
||||
|
||||
if hidden is None or latent is None:
|
||||
print("metrics.json not found or incomplete — inferring dims from state_dict (GCN only)")
|
||||
_, hidden, latent = _infer_dims_gcn(state_dict)
|
||||
encoder_name = "gcn"
|
||||
|
||||
in_dim = data.x.shape[1]
|
||||
print(f"Encoder: {encoder_name} in_dim={in_dim} hidden={hidden} latent={latent}")
|
||||
|
||||
enc = build_encoder(encoder_name, in_dim=in_dim, hidden=hidden,
|
||||
latent=latent, dropout=0.0, heads=heads)
|
||||
model = VGAE(enc).to(device)
|
||||
model.load_state_dict(state_dict)
|
||||
model.eval()
|
||||
|
||||
x = data.x.float().to(device)
|
||||
ei = ei.to(device)
|
||||
if ew is not None: ew = ew.to(device)
|
||||
|
||||
with torch.no_grad():
|
||||
z = model.encode(x, ei, ew)
|
||||
|
||||
os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
|
||||
np.save(args.out, z.cpu().numpy())
|
||||
print(f"Saved embeddings → {args.out} shape={z.shape}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
H1 evaluation: quantify biological validity of VGAE embeddings.
|
||||
|
||||
Runs five comparisons against A/B compartment labels:
|
||||
1. VGAE embeddings (GM12878, in-domain, 5-fold CV logistic regression)
|
||||
2. PCA baseline (PC1 from O/E Pearson correlation matrix — classical method)
|
||||
3. Feature-only (PCA on raw ChIP-seq node features, no graph)
|
||||
4. Zero-shot IMR90 VGAE (train LR on GM12878 emb, test on IMR90 emb)
|
||||
5. Spearman r(PC1, VGAE latent dims) — alignment without supervision
|
||||
|
||||
Usage
|
||||
-----
|
||||
python experiments/h1_representation/evaluate.py \
|
||||
--gm12878_emb results/h1_representation/gm12878_emb.npy \
|
||||
--imr90_emb results/h1_representation/imr90_emb.npy \
|
||||
--gm12878_graph data/processed/gm12878/chr1.pt \
|
||||
--imr90_graph data/processed/imr90/chr1.pt \
|
||||
--comp_gm12878 results/h1_representation/compartments/gm12878_chr1.csv \
|
||||
--comp_imr90 results/h1_representation/compartments/imr90_chr1.csv \
|
||||
--out results/h1_representation/evaluation.json
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import torch
|
||||
from scipy.stats import spearmanr
|
||||
from sklearn.decomposition import PCA
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import roc_auc_score, average_precision_score
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def load_compartment_labels(csv_path):
|
||||
"""Return (pc1, binary_label, valid_mask) aligned to bin index."""
|
||||
df = pd.read_csv(csv_path)
|
||||
valid = (df["compartment"].isin(["A", "B"])) & (df["pc1"].notna())
|
||||
mask = valid.values
|
||||
pc1 = df.loc[valid, "pc1"].values
|
||||
y = (df.loc[valid, "compartment"] == "A").astype(int).values
|
||||
return pc1, y, mask
|
||||
|
||||
|
||||
def cv_auc(X, y, n_splits=5, seed=42):
|
||||
"""Stratified k-fold logistic regression AUC and AP."""
|
||||
skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)
|
||||
aucs, aps = [], []
|
||||
for tr, te in skf.split(X, y):
|
||||
sc = StandardScaler().fit(X[tr])
|
||||
lr = LogisticRegression(max_iter=1000, random_state=seed)
|
||||
lr.fit(sc.transform(X[tr]), y[tr])
|
||||
prob = lr.predict_proba(sc.transform(X[te]))[:, 1]
|
||||
aucs.append(roc_auc_score(y[te], prob))
|
||||
aps.append(average_precision_score(y[te], prob))
|
||||
return float(np.mean(aucs)), float(np.mean(aps))
|
||||
|
||||
|
||||
def zeroshot_auc(X_train, y_train, X_test, y_test, seed=42):
|
||||
"""Train on source, evaluate on target (zero-shot transfer)."""
|
||||
sc = StandardScaler().fit(X_train)
|
||||
lr = LogisticRegression(max_iter=1000, random_state=seed)
|
||||
lr.fit(sc.transform(X_train), y_train)
|
||||
prob = lr.predict_proba(sc.transform(X_test))[:, 1]
|
||||
return float(roc_auc_score(y_test, prob)), float(average_precision_score(y_test, prob))
|
||||
|
||||
|
||||
def pc1_auc(pc1, y):
|
||||
"""PC1 as a continuous score — AUC of signed PC1 (A = positive)."""
|
||||
# Sign convention: A compartment = positive PC1
|
||||
signed = pc1 if np.mean(pc1[y == 1]) > np.mean(pc1[y == 0]) else -pc1
|
||||
return float(roc_auc_score(y, signed)), float(average_precision_score(y, signed))
|
||||
|
||||
|
||||
def best_spearman(emb, pc1):
|
||||
"""Max |Spearman r| between PC1 and any single latent dimension."""
|
||||
rs = [abs(spearmanr(emb[:, d], pc1).statistic) for d in range(emb.shape[1])]
|
||||
best_dim = int(np.argmax(rs))
|
||||
return float(np.max(rs)), best_dim
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--gm12878_emb", required=True)
|
||||
ap.add_argument("--imr90_emb", required=True)
|
||||
ap.add_argument("--gm12878_graph", required=True)
|
||||
ap.add_argument("--imr90_graph", required=True)
|
||||
ap.add_argument("--comp_gm12878", required=True)
|
||||
ap.add_argument("--comp_imr90", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--n_splits", type=int, default=5)
|
||||
ap.add_argument("--seed", type=int, default=42)
|
||||
args = ap.parse_args()
|
||||
|
||||
# ── Load ─────────────────────────────────────────────────────────────────
|
||||
gm_emb = np.load(args.gm12878_emb)
|
||||
ir_emb = np.load(args.imr90_emb)
|
||||
|
||||
gm_graph = torch.load(args.gm12878_graph, weights_only=False)
|
||||
ir_graph = torch.load(args.imr90_graph, weights_only=False)
|
||||
|
||||
gm_pc1, gm_y, gm_mask = load_compartment_labels(args.comp_gm12878)
|
||||
ir_pc1, ir_y, ir_mask = load_compartment_labels(args.comp_imr90)
|
||||
|
||||
print(f"GM12878 — bins with A/B labels: {gm_mask.sum()} "
|
||||
f"(A={gm_y.sum()}, B={(~gm_y.astype(bool)).sum()})")
|
||||
print(f"IMR90 — bins with A/B labels: {ir_mask.sum()} "
|
||||
f"(A={ir_y.sum()}, B={(~ir_y.astype(bool)).sum()})")
|
||||
|
||||
# Masked embeddings (only labelled bins)
|
||||
gm_emb_m = gm_emb[gm_mask]
|
||||
ir_emb_m = ir_emb[ir_mask]
|
||||
|
||||
# ChIP-seq node features
|
||||
gm_feat = gm_graph.x.numpy()[gm_mask]
|
||||
ir_feat = ir_graph.x.numpy()[ir_mask]
|
||||
|
||||
results = {}
|
||||
|
||||
# ── 1. VGAE GM12878 in-domain ────────────────────────────────────────────
|
||||
print("\n[1] VGAE GM12878 in-domain (5-fold CV)...")
|
||||
auc, ap = cv_auc(gm_emb_m, gm_y, n_splits=args.n_splits, seed=args.seed)
|
||||
results["vgae_gm12878_auc"] = auc
|
||||
results["vgae_gm12878_ap"] = ap
|
||||
print(f" AUC={auc:.4f} AP={ap:.4f}")
|
||||
|
||||
# ── 2. PCA baseline (PC1 from O/E Pearson — classical method) ────────────
|
||||
print("\n[2] PCA baseline (Hi-C PC1 → A/B)...")
|
||||
auc_pca, ap_pca = pc1_auc(gm_pc1, gm_y)
|
||||
results["pca_baseline_auc"] = auc_pca
|
||||
results["pca_baseline_ap"] = ap_pca
|
||||
print(f" AUC={auc_pca:.4f} AP={ap_pca:.4f}")
|
||||
|
||||
# ── 3. Feature-only (ChIP-seq PCA, no graph) ─────────────────────────────
|
||||
print("\n[3] Feature-only (ChIP-seq PCA, no graph)...")
|
||||
n_components = min(gm_feat.shape[1], 8)
|
||||
feat_pca = PCA(n_components=n_components, random_state=args.seed).fit_transform(gm_feat)
|
||||
auc_feat, ap_feat = cv_auc(feat_pca, gm_y, n_splits=args.n_splits, seed=args.seed)
|
||||
results["feature_only_auc"] = auc_feat
|
||||
results["feature_only_ap"] = ap_feat
|
||||
print(f" AUC={auc_feat:.4f} AP={ap_feat:.4f}")
|
||||
|
||||
# ── 4. Zero-shot IMR90 ────────────────────────────────────────────────────
|
||||
print("\n[4] Zero-shot IMR90 (train on GM12878 emb, test on IMR90 emb)...")
|
||||
auc_zs, ap_zs = zeroshot_auc(gm_emb_m, gm_y, ir_emb_m, ir_y, seed=args.seed)
|
||||
results["vgae_imr90_zeroshot_auc"] = auc_zs
|
||||
results["vgae_imr90_zeroshot_ap"] = ap_zs
|
||||
print(f" AUC={auc_zs:.4f} AP={ap_zs:.4f}")
|
||||
|
||||
# IMR90 in-domain for reference
|
||||
auc_ir, ap_ir = cv_auc(ir_emb_m, ir_y, n_splits=args.n_splits, seed=args.seed)
|
||||
results["vgae_imr90_indomain_auc"] = auc_ir
|
||||
results["vgae_imr90_indomain_ap"] = ap_ir
|
||||
print(f" IMR90 in-domain (CV): AUC={auc_ir:.4f} AP={ap_ir:.4f}")
|
||||
|
||||
# ── 5. Spearman r(PC1, latent dims) ──────────────────────────────────────
|
||||
print("\n[5] Spearman r(PC1, VGAE latent dims)...")
|
||||
r_gm, dim_gm = best_spearman(gm_emb_m, gm_pc1)
|
||||
r_ir, dim_ir = best_spearman(ir_emb_m, ir_pc1)
|
||||
results["spearman_r_gm12878"] = r_gm
|
||||
results["spearman_best_dim_gm"] = dim_gm
|
||||
results["spearman_r_imr90"] = r_ir
|
||||
results["spearman_best_dim_imr90"]= dim_ir
|
||||
print(f" GM12878: |r|={r_gm:.4f} (dim {dim_gm})")
|
||||
print(f" IMR90: |r|={r_ir:.4f} (dim {dim_ir})")
|
||||
|
||||
# ── Summary ───────────────────────────────────────────────────────────────
|
||||
print("\n=== Summary ===")
|
||||
print(f" PCA baseline (Hi-C PC1): AUC {results['pca_baseline_auc']:.3f}")
|
||||
print(f" Feature-only (ChIP PCA): AUC {results['feature_only_auc']:.3f}")
|
||||
print(f" VGAE GM12878 (in-domain): AUC {results['vgae_gm12878_auc']:.3f}")
|
||||
print(f" VGAE IMR90 (zero-shot): AUC {results['vgae_imr90_zeroshot_auc']:.3f}")
|
||||
print(f" Spearman r GM12878: {results['spearman_r_gm12878']:.3f}")
|
||||
|
||||
with open(args.out, "w") as f:
|
||||
json.dump(results, f, indent=2)
|
||||
print(f"\nSaved → {args.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env bash
|
||||
# H1: Representation learning — GM12878 VGAE + IMR90 zero-shot transfer
|
||||
# Usage: bash experiments/h1_representation/run.sh [--chrom chr1] [--res 25000]
|
||||
set -euo pipefail
|
||||
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
export PYTHONPATH="$REPO:${PYTHONPATH:-}"
|
||||
|
||||
# Auto-activate conda env if its packages are not on the current Python
|
||||
if ! python -c "import torch_geometric" 2>/dev/null; then
|
||||
echo "Activating conda env chromatin_gnn..."
|
||||
eval "$(conda shell.bash hook)"
|
||||
conda activate chromatin_gnn
|
||||
fi
|
||||
|
||||
CHROM="${CHROM:-chr1}"
|
||||
RES="${RES:-25000}"
|
||||
EPOCHS="${EPOCHS:-300}"
|
||||
PATIENCE="${PATIENCE:-50}"
|
||||
HIDDEN="${HIDDEN:-256}"
|
||||
LATENT="${LATENT:-64}"
|
||||
SEED="${SEED:-42}"
|
||||
|
||||
DATA="$REPO/data"
|
||||
RESULTS_BASE="$REPO/results/h1_representation"
|
||||
RESULTS="$RESULTS_BASE/${CHROM}" # per-chromosome outputs
|
||||
COMPARTMENTS_DIR="$RESULTS_BASE/compartments" # shared (filenames include $CHROM)
|
||||
EXP="$REPO/experiments/h1_representation"
|
||||
|
||||
mkdir -p "$RESULTS/figures" "$COMPARTMENTS_DIR"
|
||||
|
||||
# ── Step 1: Build graphs ──────────────────────────────────────────────────────
|
||||
for CELL in gm12878 imr90; do
|
||||
CELL_UPPER=$(echo "$CELL" | tr '[:lower:]' '[:upper:]')
|
||||
OUT="$DATA/processed/$CELL/${CHROM}.pt"
|
||||
if [ -f "$OUT" ]; then
|
||||
echo "[$CELL] Graph already exists, skipping"
|
||||
else
|
||||
python -m chromatin_gnn.build_graph \
|
||||
--mcool "$DATA/raw/${CELL_UPPER}.mcool" \
|
||||
--chrom "$CHROM" --res "$RES" \
|
||||
--bigwigs \
|
||||
"$DATA/raw/${CELL_UPPER}_CTCF.bw" \
|
||||
"$DATA/raw/${CELL_UPPER}_H3K27me3.bw" \
|
||||
"$DATA/raw/${CELL_UPPER}_H3K4me3.bw" \
|
||||
--out "$OUT"
|
||||
fi
|
||||
done
|
||||
|
||||
# ── Step 2: Compute A/B compartments ─────────────────────────────────────────
|
||||
for CELL in gm12878 imr90; do
|
||||
CELL_UPPER=$(echo "$CELL" | tr '[:lower:]' '[:upper:]')
|
||||
OUT="$COMPARTMENTS_DIR/${CELL}_${CHROM}.csv"
|
||||
if [ -f "$OUT" ]; then
|
||||
echo "[$CELL] Compartments already exist, skipping"
|
||||
else
|
||||
python "$EXP/compute_compartments.py" \
|
||||
--mcool "$DATA/raw/${CELL_UPPER}.mcool" \
|
||||
--chrom "$CHROM" --res "$RES" \
|
||||
--bigwig_orient "$DATA/raw/${CELL_UPPER}_CTCF.bw" \
|
||||
--out "$OUT"
|
||||
fi
|
||||
done
|
||||
|
||||
# ── Step 3: Train VGAE on GM12878 ────────────────────────────────────────────
|
||||
if [ -f "$RESULTS/model.pt" ]; then
|
||||
echo "[GM12878] Model already exists, skipping training"
|
||||
else
|
||||
python "$EXP/train.py" \
|
||||
--graph "$DATA/processed/gm12878/${CHROM}.pt" \
|
||||
--encoder deep_gcn \
|
||||
--hidden "$HIDDEN" --latent "$LATENT" \
|
||||
--epochs "$EPOCHS" --patience "$PATIENCE" \
|
||||
--lr 3e-4 --dropout 0.3 --beta 0.5 --kl_anneal 100 \
|
||||
--seed "$SEED" \
|
||||
--outdir "$RESULTS"
|
||||
fi
|
||||
|
||||
# ── Step 4: Zero-shot encode IMR90 ───────────────────────────────────────────
|
||||
python "$EXP/encode.py" \
|
||||
--model "$RESULTS/model.pt" \
|
||||
--graph "$DATA/processed/imr90/${CHROM}.pt" \
|
||||
--out "$RESULTS/imr90_emb.npy"
|
||||
|
||||
# ── Step 5: Visualise (skip with SKIP_FIGURES=1 — useful in genome-wide loops) ─
|
||||
if [ -z "${SKIP_FIGURES:-}" ]; then
|
||||
python "$EXP/visualize.py" \
|
||||
--emb "$RESULTS/gm12878_emb.npy" "$RESULTS/imr90_emb.npy" \
|
||||
--labels GM12878 IMR90 \
|
||||
--compartments \
|
||||
"$COMPARTMENTS_DIR/gm12878_${CHROM}.csv" \
|
||||
"$COMPARTMENTS_DIR/imr90_${CHROM}.csv" \
|
||||
--prefix "$RESULTS/figures/umap" \
|
||||
--seed "$SEED"
|
||||
|
||||
# ── Step 6: Compare embeddings ────────────────────────────────────────────
|
||||
python "$EXP/compare.py" \
|
||||
--emb1 "$RESULTS/gm12878_emb.npy" \
|
||||
--emb2 "$RESULTS/imr90_emb.npy" \
|
||||
--label1 GM12878 --label2 IMR90 \
|
||||
--prefix "$RESULTS/figures/${CHROM}"
|
||||
else
|
||||
echo "[SKIP_FIGURES=1] Skipping visualization and comparison steps."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== H1 complete ($CHROM). Results: $RESULTS ==="
|
||||
cat "$RESULTS/metrics.json"
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
# H1 genome-wide: run the per-chromosome H1 pipeline for all autosomes (chr1..22).
|
||||
# Idempotent — skips chroms already trained. Disables per-chrom figures by default
|
||||
# (set SKIP_FIGURES= to enable).
|
||||
#
|
||||
# Usage:
|
||||
# bash experiments/h1_representation/run_genome.sh
|
||||
# bash experiments/h1_representation/run_genome.sh chr2 chr5 # only these
|
||||
# SKIP_FIGURES= bash experiments/h1_representation/run_genome.sh # render figures
|
||||
set -euo pipefail
|
||||
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
# Skip per-chrom UMAP/compare figures during genome loop (slow; render manually
|
||||
# for representative chroms after aggregation).
|
||||
export SKIP_FIGURES="${SKIP_FIGURES-1}"
|
||||
|
||||
if [ $# -gt 0 ]; then
|
||||
CHROMS=("$@")
|
||||
else
|
||||
CHROMS=()
|
||||
for i in $(seq 1 22); do CHROMS+=("chr$i"); done
|
||||
fi
|
||||
|
||||
START=$(date +%s)
|
||||
N=${#CHROMS[@]}
|
||||
i=0
|
||||
for CHROM in "${CHROMS[@]}"; do
|
||||
i=$((i + 1))
|
||||
echo ""
|
||||
echo "================================================================"
|
||||
echo "[H1] $CHROM ($i / $N)"
|
||||
echo "================================================================"
|
||||
CHROM="$CHROM" bash "$REPO/experiments/h1_representation/run.sh"
|
||||
done
|
||||
|
||||
ELAPSED=$(( $(date +%s) - START ))
|
||||
echo ""
|
||||
echo "=== H1 genome-wide complete in ${ELAPSED}s ==="
|
||||
echo "Next: python experiments/h1_representation/aggregate.py"
|
||||
@@ -0,0 +1,260 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Train a Variational Graph Autoencoder (VGAE) on a chromatin contact graph.
|
||||
|
||||
Key improvements over v1
|
||||
------------------------
|
||||
• GAT / DeepGCN encoders selectable via --encoder
|
||||
• β-VGAE with linear KL warm-up (--kl_anneal): lets the encoder learn
|
||||
structure before the prior regularises the latent space
|
||||
• Lower default LR (3e-4) and higher patience so the optimiser doesn't
|
||||
overshoot the minimum
|
||||
• --beta controls the final KL weight (default 1.0; try 0.5 to prevent
|
||||
posterior collapse on sparse graphs)
|
||||
|
||||
Inputs
|
||||
------
|
||||
PyTorch Geometric Data object from build_graph.py
|
||||
|
||||
Outputs (under --outdir)
|
||||
------------------------
|
||||
model.pt trained state_dict (+ encoder type stored in metrics.json)
|
||||
emb.npy node embeddings — mu vector, shape [num_nodes, latent_dim]
|
||||
metrics.json val/test AUC & AP, all hyperparameters
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch_geometric.nn.models import VGAE
|
||||
from torch_geometric.transforms import RandomLinkSplit
|
||||
from torch_geometric.utils import (
|
||||
negative_sampling,
|
||||
remove_self_loops,
|
||||
to_undirected,
|
||||
)
|
||||
from sklearn.metrics import average_precision_score, roc_auc_score
|
||||
|
||||
from chromatin_gnn.model import build_encoder
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def _eval_linkpred(z, pos_edges, neg_edges):
|
||||
def _score(edges):
|
||||
src, dst = edges
|
||||
return torch.sigmoid((z[src] * z[dst]).sum(dim=1)).cpu().numpy()
|
||||
y_true = np.concatenate([np.ones(pos_edges.size(1)),
|
||||
np.zeros(neg_edges.size(1))])
|
||||
y_pred = np.concatenate([_score(pos_edges), _score(neg_edges)])
|
||||
return roc_auc_score(y_true, y_pred), average_precision_score(y_true, y_pred)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
# Data
|
||||
ap.add_argument("--graph", required=True,
|
||||
help="Path to Data .pt file from build_graph.py")
|
||||
# Architecture
|
||||
ap.add_argument("--encoder", default="gat",
|
||||
choices=["gcn", "gat", "deep_gcn"],
|
||||
help="Encoder architecture (default: gat)")
|
||||
ap.add_argument("--hidden", type=int, default=128)
|
||||
ap.add_argument("--latent", type=int, default=64)
|
||||
ap.add_argument("--heads", type=int, default=4,
|
||||
help="Number of attention heads (GAT only)")
|
||||
ap.add_argument("--dropout", type=float, default=0.3)
|
||||
# Training
|
||||
ap.add_argument("--epochs", type=int, default=500)
|
||||
ap.add_argument("--patience", type=int, default=50,
|
||||
help="Early-stopping patience (val-AUC epochs)")
|
||||
ap.add_argument("--lr", type=float, default=3e-4)
|
||||
ap.add_argument("--beta", type=float, default=1.0,
|
||||
help="Final KL weight in the ELBO (β-VGAE). "
|
||||
"Values < 1 reduce regularisation on sparse graphs.")
|
||||
ap.add_argument("--kl_anneal",type=int, default=100,
|
||||
help="Linearly warm up KL weight from 0 → beta over "
|
||||
"this many epochs (0 = no annealing).")
|
||||
ap.add_argument("--seed", type=int, default=42)
|
||||
ap.add_argument("--outdir", default="results")
|
||||
ap.add_argument("--device", default="auto",
|
||||
help="cuda | cpu | auto (default: auto-detect CUDA)")
|
||||
ap.add_argument("--constant_features", action="store_true",
|
||||
help="Replace node features with a constant ones vector "
|
||||
"(topology-only ablation: removes feature signal so the "
|
||||
"encoder must rely on graph structure alone).")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.device == "auto":
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
else:
|
||||
device = torch.device(args.device)
|
||||
print(f"Using device: {device}"
|
||||
+ (f" ({torch.cuda.get_device_name(0)})" if device.type == "cuda" else ""))
|
||||
|
||||
torch.manual_seed(args.seed)
|
||||
np.random.seed(args.seed)
|
||||
if device.type == "cuda":
|
||||
torch.cuda.manual_seed_all(args.seed)
|
||||
os.makedirs(args.outdir, exist_ok=True)
|
||||
|
||||
# ---- Load and clean graph ----
|
||||
data = torch.load(args.graph, weights_only=False)
|
||||
ei, _ = remove_self_loops(data.edge_index)
|
||||
# Propagate edge_weight through to_undirected so split weights stay aligned
|
||||
if hasattr(data, "edge_weight") and data.edge_weight is not None:
|
||||
ei, ew = to_undirected(ei, data.edge_weight, num_nodes=data.num_nodes)
|
||||
data.edge_weight = ew
|
||||
else:
|
||||
ei = to_undirected(ei, num_nodes=data.num_nodes)
|
||||
data.edge_index = ei
|
||||
x = data.x.float()
|
||||
if args.constant_features:
|
||||
x = torch.ones(data.num_nodes, 1)
|
||||
print("[ablation] Replacing node features with constant ones "
|
||||
"(topology-only mode).")
|
||||
print(f"Graph: {data.num_nodes} nodes "
|
||||
f"{data.edge_index.shape[1]} edges "
|
||||
f"{x.shape[1]} node features")
|
||||
print(f"Encoder: {args.encoder} hidden={args.hidden} latent={args.latent}"
|
||||
+ (f" heads={args.heads}" if args.encoder == "gat" else ""))
|
||||
|
||||
# ---- Edge splits ----
|
||||
splitter = RandomLinkSplit(
|
||||
num_val=0.1, num_test=0.1,
|
||||
is_undirected=True,
|
||||
add_negative_train_samples=False,
|
||||
split_labels=False,
|
||||
)
|
||||
train_data, val_data, test_data = splitter(data)
|
||||
train_data.pos_edge_index = train_data.edge_index
|
||||
train_ew = getattr(train_data, "edge_weight", None)
|
||||
full_ew = getattr(data, "edge_weight", None)
|
||||
|
||||
for split in (val_data, test_data):
|
||||
split.pos_edge_index = split.edge_index
|
||||
split.neg_edge_index = negative_sampling(
|
||||
edge_index=split.edge_index,
|
||||
num_nodes=data.num_nodes,
|
||||
num_neg_samples=split.edge_index.size(1),
|
||||
method="sparse",
|
||||
)
|
||||
|
||||
# ---- Move tensors to device ----
|
||||
x = x.to(device)
|
||||
train_edge_index = train_data.edge_index.to(device)
|
||||
train_pos_edge = train_data.pos_edge_index.to(device)
|
||||
if train_ew is not None: train_ew = train_ew.to(device)
|
||||
full_edge_index = data.edge_index.to(device)
|
||||
if full_ew is not None: full_ew = full_ew.to(device)
|
||||
val_pos = val_data.pos_edge_index.to(device)
|
||||
val_neg = val_data.neg_edge_index.to(device)
|
||||
test_pos = test_data.pos_edge_index.to(device)
|
||||
test_neg = test_data.neg_edge_index.to(device)
|
||||
|
||||
# ---- Model ----
|
||||
enc = build_encoder(args.encoder, in_dim=x.size(1),
|
||||
hidden=args.hidden, latent=args.latent,
|
||||
dropout=args.dropout, heads=args.heads)
|
||||
model = VGAE(enc).to(device)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr,
|
||||
weight_decay=1e-5)
|
||||
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
|
||||
optimizer, mode="max", factor=0.5, patience=15, verbose=False
|
||||
)
|
||||
|
||||
# ---- Training loop with β-VGAE KL warm-up ----
|
||||
best_val_auc = -1.0
|
||||
best_state = None
|
||||
no_improve = 0
|
||||
epochs_ran = 0
|
||||
|
||||
for epoch in range(1, args.epochs + 1):
|
||||
# Linear KL warm-up: β rises from 0 to args.beta over kl_anneal epochs
|
||||
if args.kl_anneal > 0:
|
||||
kl_w = min(args.beta, args.beta * epoch / args.kl_anneal)
|
||||
else:
|
||||
kl_w = args.beta
|
||||
|
||||
model.train()
|
||||
optimizer.zero_grad()
|
||||
z = model.encode(x, train_edge_index, train_ew)
|
||||
loss = (model.recon_loss(z, train_pos_edge)
|
||||
+ (kl_w / data.num_nodes) * model.kl_loss())
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
||||
optimizer.step()
|
||||
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
z_full = model.encode(x, full_edge_index, full_ew)
|
||||
val_auc, val_ap = _eval_linkpred(z_full, val_pos, val_neg)
|
||||
|
||||
scheduler.step(val_auc)
|
||||
|
||||
if val_auc > best_val_auc:
|
||||
best_val_auc = val_auc
|
||||
best_state = {k: v.cpu().clone()
|
||||
for k, v in model.state_dict().items()}
|
||||
no_improve = 0
|
||||
else:
|
||||
no_improve += 1
|
||||
|
||||
epochs_ran = epoch
|
||||
if epoch % 20 == 0 or epoch == 1:
|
||||
lr_now = optimizer.param_groups[0]["lr"]
|
||||
print(f"[{epoch:03d}/{args.epochs}] "
|
||||
f"loss={loss.item():.4f} kl_w={kl_w:.3f} "
|
||||
f"val AUC={val_auc:.4f} AP={val_ap:.4f} lr={lr_now:.2e}")
|
||||
|
||||
if no_improve >= args.patience:
|
||||
print(f"Early stopping at epoch {epoch} "
|
||||
f"(no val-AUC improvement for {args.patience} epochs)")
|
||||
break
|
||||
|
||||
# ---- Restore best and test ----
|
||||
model.load_state_dict({k: v.to(device) for k, v in best_state.items()})
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
z_final = model.encode(x, full_edge_index, full_ew)
|
||||
test_auc, test_ap = _eval_linkpred(z_final, test_pos, test_neg)
|
||||
|
||||
# ---- Save outputs ----
|
||||
torch.save(best_state, os.path.join(args.outdir, "model.pt"))
|
||||
np.save(os.path.join(args.outdir, "emb.npy"), z_final.cpu().numpy())
|
||||
|
||||
metrics = {
|
||||
"encoder": args.encoder,
|
||||
"val_auc": float(best_val_auc),
|
||||
"test_auc": float(test_auc),
|
||||
"test_ap": float(test_ap),
|
||||
"epochs_ran": epochs_ran,
|
||||
"epochs_max": args.epochs,
|
||||
"patience": args.patience,
|
||||
"beta": args.beta,
|
||||
"kl_anneal": args.kl_anneal,
|
||||
"hidden": args.hidden,
|
||||
"latent": args.latent,
|
||||
"heads": args.heads if args.encoder == "gat" else None,
|
||||
"dropout": args.dropout,
|
||||
"lr": args.lr,
|
||||
"seed": args.seed,
|
||||
"constant_features": bool(args.constant_features),
|
||||
"in_features": int(x.size(1)),
|
||||
}
|
||||
with open(os.path.join(args.outdir, "metrics.json"), "w") as f:
|
||||
json.dump(metrics, f, indent=2)
|
||||
|
||||
print(f"\nSaved → {args.outdir}/")
|
||||
print(f"Embeddings shape: {z_final.shape}")
|
||||
print(f"Test AUC={test_auc:.4f} AP={test_ap:.4f} "
|
||||
f"(val best={best_val_auc:.4f})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Visualise VGAE node embeddings using UMAP.
|
||||
|
||||
Produces (under --prefix):
|
||||
{prefix}_{label}_position.png UMAP coloured by genomic position (bin index)
|
||||
{prefix}_{label}_compartment.png UMAP coloured by A/B compartment (needs --compartments)
|
||||
{prefix}_joint.png Joint UMAP of all supplied cell lines
|
||||
{prefix}_stats.csv Per-embedding summary statistics
|
||||
|
||||
Usage
|
||||
-----
|
||||
python scripts/visualize_embeddings.py \\
|
||||
--emb results/GM12878/emb.npy results/IMR90/emb.npy \\
|
||||
--labels GM12878 IMR90 \\
|
||||
--compartments results/GM12878/compartments_chr21.csv \\
|
||||
results/IMR90/compartments_chr21.csv \\
|
||||
--prefix results/figures/umap
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.metrics import silhouette_score
|
||||
import umap
|
||||
|
||||
|
||||
COMPARTMENT_COLORS = {"A": "#E41A1C", "B": "#377EB8", "N": "#AAAAAA"}
|
||||
CELL_LINE_PALETTE = ["#E41A1C", "#4DAF4A", "#984EA3", "#FF7F00", "#377EB8"]
|
||||
|
||||
plt.rcParams.update({
|
||||
"font.family": "sans-serif",
|
||||
"axes.spines.top": False,
|
||||
"axes.spines.right": False,
|
||||
})
|
||||
|
||||
|
||||
def _run_umap(emb: np.ndarray, seed: int = 42) -> np.ndarray:
|
||||
reducer = umap.UMAP(n_components=2, random_state=seed,
|
||||
min_dist=0.3, n_neighbors=15)
|
||||
return reducer.fit_transform(emb)
|
||||
|
||||
|
||||
def _plot_position(coords: np.ndarray, label: str, out_path: str):
|
||||
fig, ax = plt.subplots(figsize=(6.5, 5.5))
|
||||
sc = ax.scatter(coords[:, 0], coords[:, 1],
|
||||
c=np.arange(len(coords)), cmap="plasma",
|
||||
s=4, alpha=0.75, linewidths=0, rasterized=True)
|
||||
cbar = plt.colorbar(sc, ax=ax, shrink=0.8, pad=0.02)
|
||||
cbar.set_label("Bin index (5′ → 3′)", fontsize=9)
|
||||
ax.set_title(f"{label} — UMAP coloured by genomic position", fontsize=10)
|
||||
ax.set_xlabel("UMAP 1", fontsize=9)
|
||||
ax.set_ylabel("UMAP 2", fontsize=9)
|
||||
ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
|
||||
plt.tight_layout()
|
||||
plt.savefig(out_path, dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
def _plot_compartment(coords: np.ndarray, compartments: np.ndarray,
|
||||
label: str, out_path: str):
|
||||
fig, ax = plt.subplots(figsize=(6.5, 5.5))
|
||||
for comp in ("A", "B", "N"):
|
||||
mask = compartments == comp
|
||||
if mask.sum() == 0:
|
||||
continue
|
||||
ax.scatter(coords[mask, 0], coords[mask, 1],
|
||||
c=COMPARTMENT_COLORS[comp], s=4, alpha=0.75,
|
||||
label=f"{comp} ({mask.sum()} bins)", linewidths=0,
|
||||
rasterized=True)
|
||||
ax.legend(markerscale=3, title="Compartment", fontsize=9,
|
||||
title_fontsize=9, frameon=False)
|
||||
ax.set_title(f"{label} — UMAP coloured by A/B compartment", fontsize=10)
|
||||
ax.set_xlabel("UMAP 1", fontsize=9)
|
||||
ax.set_ylabel("UMAP 2", fontsize=9)
|
||||
ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
|
||||
plt.tight_layout()
|
||||
plt.savefig(out_path, dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
def _plot_joint(all_coords: np.ndarray, all_labels: list, out_path: str):
|
||||
fig, ax = plt.subplots(figsize=(7, 6))
|
||||
unique = list(dict.fromkeys(all_labels))
|
||||
arr = np.array(all_labels)
|
||||
for i, label in enumerate(unique):
|
||||
mask = arr == label
|
||||
ax.scatter(all_coords[mask, 0], all_coords[mask, 1],
|
||||
c=CELL_LINE_PALETTE[i % len(CELL_LINE_PALETTE)],
|
||||
s=3, alpha=0.6, label=label, linewidths=0, rasterized=True)
|
||||
ax.legend(markerscale=4, title="Cell line", fontsize=9,
|
||||
title_fontsize=9, frameon=False)
|
||||
ax.set_title("Joint UMAP — chromatin topology embeddings", fontsize=11)
|
||||
ax.set_xlabel("UMAP 1", fontsize=9)
|
||||
ax.set_ylabel("UMAP 2", fontsize=9)
|
||||
ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
|
||||
plt.tight_layout()
|
||||
plt.savefig(out_path, dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
def _silhouette(emb: np.ndarray, compartments: np.ndarray) -> float:
|
||||
mask = compartments != "N"
|
||||
if mask.sum() < 20 or len(set(compartments[mask])) < 2:
|
||||
return float("nan")
|
||||
try:
|
||||
return float(silhouette_score(emb[mask], compartments[mask], metric="cosine"))
|
||||
except Exception:
|
||||
return float("nan")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
p.add_argument("--emb", nargs="+", required=True,
|
||||
help="One or more .npy embedding files")
|
||||
p.add_argument("--labels", nargs="+", required=True,
|
||||
help="Label for each embedding (same order)")
|
||||
p.add_argument("--compartments", nargs="+",
|
||||
help="Compartment CSV files, one per embedding (optional)")
|
||||
p.add_argument("--prefix", default="results/figures/umap",
|
||||
help="Output file prefix")
|
||||
p.add_argument("--seed", type=int, default=42)
|
||||
args = p.parse_args()
|
||||
|
||||
if len(args.emb) != len(args.labels):
|
||||
raise ValueError("--emb and --labels must have the same length")
|
||||
|
||||
os.makedirs(os.path.dirname(os.path.abspath(args.prefix + "_x")), exist_ok=True)
|
||||
|
||||
embs = [np.load(f) for f in args.emb]
|
||||
comp_dfs = []
|
||||
if args.compartments:
|
||||
for f in args.compartments:
|
||||
comp_dfs.append(pd.read_csv(f) if (f and os.path.exists(f)) else None)
|
||||
|
||||
stats_rows = []
|
||||
|
||||
for i, (emb, label) in enumerate(zip(embs, args.labels)):
|
||||
print(f"\n[{label}] {emb.shape[0]} nodes × {emb.shape[1]} dims")
|
||||
coords = _run_umap(emb, seed=args.seed)
|
||||
|
||||
tag = label.replace(" ", "_")
|
||||
_plot_position(coords, label, f"{args.prefix}_{tag}_position.png")
|
||||
print(f" → {args.prefix}_{tag}_position.png")
|
||||
|
||||
comp_arr = None
|
||||
sil = float("nan")
|
||||
if comp_dfs and i < len(comp_dfs) and comp_dfs[i] is not None:
|
||||
comp_arr = comp_dfs[i]["compartment"].values[: len(emb)]
|
||||
_plot_compartment(coords, comp_arr, label,
|
||||
f"{args.prefix}_{tag}_compartment.png")
|
||||
print(f" → {args.prefix}_{tag}_compartment.png")
|
||||
sil = _silhouette(emb, comp_arr)
|
||||
print(f" Silhouette (A/B, cosine): {sil:.4f}")
|
||||
|
||||
stats_rows.append({
|
||||
"label": label,
|
||||
"n_bins": emb.shape[0],
|
||||
"latent_dim": emb.shape[1],
|
||||
"mean_embedding_norm": float(np.linalg.norm(emb, axis=1).mean()),
|
||||
"std_embedding_values": float(emb.std()),
|
||||
"silhouette_AB_cosine": sil,
|
||||
})
|
||||
|
||||
# Joint UMAP when multiple embeddings are supplied
|
||||
if len(embs) > 1:
|
||||
print("\nComputing joint UMAP…")
|
||||
all_emb = np.vstack(embs)
|
||||
all_labels = sum([[lab] * len(e) for lab, e in zip(args.labels, embs)], [])
|
||||
all_coords = _run_umap(all_emb, seed=args.seed)
|
||||
_plot_joint(all_coords, all_labels, f"{args.prefix}_joint.png")
|
||||
print(f" → {args.prefix}_joint.png")
|
||||
|
||||
stats_df = pd.DataFrame(stats_rows)
|
||||
stats_path = f"{args.prefix}_stats.csv"
|
||||
stats_df.to_csv(stats_path, index=False)
|
||||
print(f"\nStats → {stats_path}")
|
||||
print(stats_df.to_string(index=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user