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
@@ -0,0 +1,7 @@
|
||||
from .model import GCNEncoder, GATEncoder, DeepGCNEncoder, build_encoder
|
||||
from .build_graph import build_graph, bin_bigwig
|
||||
|
||||
__all__ = [
|
||||
"GCNEncoder", "GATEncoder", "DeepGCNEncoder", "build_encoder",
|
||||
"build_graph", "bin_bigwig",
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import torch
|
||||
import cooler
|
||||
import pyBigWig
|
||||
from torch_geometric.data import Data
|
||||
|
||||
|
||||
def bin_bigwig(bw_path, chrom, bins):
|
||||
"""Average bigWig signal across each genomic bin"""
|
||||
bw = pyBigWig.open(bw_path)
|
||||
if chrom not in bw.chroms():
|
||||
raise ValueError(f"{chrom} not found in {bw_path}. Available: {list(bw.chroms().keys())[:5]}...")
|
||||
chrom_len = bw.chroms(chrom)
|
||||
vals = []
|
||||
for s, e in bins:
|
||||
s = max(0, s)
|
||||
e = min(chrom_len, 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 v)
|
||||
bw.close()
|
||||
return np.array(vals)
|
||||
|
||||
|
||||
def build_graph(mcool_path, chrom, res, bigwigs, out_path,
|
||||
max_dist=5_000_000, edge_top_pct=100):
|
||||
"""Convert .mcool + bigWigs to PyTorch Geometric Data object.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
edge_top_pct : int, 1–100
|
||||
Keep only the top N% of edges ranked by balanced contact weight.
|
||||
Default 100 = keep all. Use e.g. 50 to keep the strongest half,
|
||||
which removes low-weight noise from the ICE-balanced matrix.
|
||||
"""
|
||||
print(f"Processing {chrom} at {res} bp resolution...")
|
||||
|
||||
# Load pixels
|
||||
c = cooler.Cooler(f"{mcool_path}::resolutions/{res}")
|
||||
pixels = c.matrix(balance=True, as_pixels=True, join=True).fetch(chrom)
|
||||
pixels = pixels.query(f"chrom1 == chrom2 and abs(start2 - start1) <= {max_dist}")
|
||||
|
||||
# Map genomic coordinates to bin IDs
|
||||
bins_df = c.bins().fetch(chrom)
|
||||
bins_df["bin_id"] = np.arange(len(bins_df))
|
||||
start_to_bin = dict(zip(bins_df["start"].values, bins_df["bin_id"].values))
|
||||
|
||||
valid = pixels["start1"].isin(start_to_bin) & pixels["start2"].isin(start_to_bin)
|
||||
pixels = pixels.loc[valid]
|
||||
|
||||
bin1 = pixels["start1"].map(start_to_bin).values
|
||||
bin2 = pixels["start2"].map(start_to_bin).values
|
||||
|
||||
# Edge weights
|
||||
if "balanced" in pixels.columns and pixels["balanced"].notna().any():
|
||||
w = pixels["balanced"].fillna(0).values
|
||||
else:
|
||||
w = pixels["count"].values
|
||||
|
||||
# Optional edge thresholding: keep top edge_top_pct% by weight
|
||||
if edge_top_pct < 100:
|
||||
nonzero = w[w > 0]
|
||||
if len(nonzero):
|
||||
cutoff = np.percentile(nonzero, 100 - edge_top_pct)
|
||||
mask = w >= cutoff
|
||||
bin1, bin2, w = bin1[mask], bin2[mask], w[mask]
|
||||
print(f" Edge filter (top {edge_top_pct}%): "
|
||||
f"{mask.sum()} / {len(mask)} edges kept "
|
||||
f"(weight ≥ {cutoff:.4f})")
|
||||
|
||||
edge_index = torch.tensor(np.stack([bin1, bin2]), dtype=torch.long)
|
||||
edge_weight = torch.tensor(np.log1p(w), dtype=torch.float)
|
||||
|
||||
# Node features
|
||||
starts = bins_df["start"].values
|
||||
bins = [(int(s), int(s + res)) for s in starts]
|
||||
node_feats = []
|
||||
for bw in bigwigs:
|
||||
print(f" Adding feature from {bw}")
|
||||
node_feats.append(bin_bigwig(bw, chrom, bins))
|
||||
x = torch.tensor(np.stack(node_feats, axis=1), dtype=torch.float)
|
||||
|
||||
data = Data(x=x, edge_index=edge_index, edge_weight=edge_weight)
|
||||
torch.save(data, out_path)
|
||||
print(f"Saved {chrom}: {x.shape[0]} nodes, {edge_index.shape[1]} edges → {out_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = argparse.ArgumentParser(description="Build graph from Micro-C and bigWigs")
|
||||
p.add_argument("--mcool", required=True, help="Path to .mcool file")
|
||||
p.add_argument("--chrom", required=True, help="Chromosome name (e.g., chr21)")
|
||||
p.add_argument("--res", type=int, default=10000, help="Resolution (bp)")
|
||||
p.add_argument("--bigwigs", nargs="+", required=True, help="List of bigWig feature files")
|
||||
p.add_argument("--out", required=True, help="Output .pt file path")
|
||||
p.add_argument("--max_dist", type=int, default=5_000_000,
|
||||
help="Max genomic distance for edges (bp)")
|
||||
p.add_argument("--edge_top_pct", type=int, default=100,
|
||||
help="Keep only top N%% of edges by balanced weight (1-100, default 100=all)")
|
||||
args = p.parse_args()
|
||||
|
||||
build_graph(args.mcool, args.chrom, args.res, args.bigwigs, args.out,
|
||||
args.max_dist, args.edge_top_pct)
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
VGAE encoder architectures for chromatin contact graphs.
|
||||
|
||||
Exported symbols
|
||||
----------------
|
||||
GCNEncoder — original 2-layer GCN (kept for backward compatibility)
|
||||
GATEncoder — 2-layer GATv2 with multi-head attention
|
||||
DeepGCNEncoder — 3-layer GCN with residual BatchNorm between layers
|
||||
Encoder — alias for GCNEncoder (backward compat)
|
||||
build_encoder() — factory: returns the right class from a string name
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torch_geometric.nn import GCNConv, GATv2Conv
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GCN encoder (baseline)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class GCNEncoder(nn.Module):
|
||||
"""Two-layer GCN encoder with input BatchNorm.
|
||||
|
||||
Architecture: BatchNorm → GCNConv(hidden) → ReLU → Dropout
|
||||
→ GCNConv_mu / GCNConv_logstd
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: int, hidden: int, latent: int, dropout: float = 0.2, **_):
|
||||
super().__init__()
|
||||
self.norm = nn.BatchNorm1d(in_dim)
|
||||
self.gc1 = GCNConv(in_dim, hidden, add_self_loops=True, normalize=True)
|
||||
self.gc_mu = GCNConv(hidden, latent, add_self_loops=True, normalize=True)
|
||||
self.gc_log = GCNConv(hidden, latent, add_self_loops=True, normalize=True)
|
||||
self.dropout = dropout
|
||||
|
||||
def forward(self, x, edge_index, edge_weight=None):
|
||||
x = self.norm(x)
|
||||
h = F.relu(self.gc1(x, edge_index, edge_weight))
|
||||
h = F.dropout(h, p=self.dropout, training=self.training)
|
||||
return self.gc_mu(h, edge_index, edge_weight), self.gc_log(h, edge_index, edge_weight)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GAT encoder (preferred for Hi-C: handles degree heterogeneity via attention)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class GATEncoder(nn.Module):
|
||||
"""Two-layer GATv2 encoder.
|
||||
|
||||
Each GATv2 layer applies multi-head attention, which lets the model
|
||||
up-weight high-frequency contacts at TAD boundaries and CTCF anchors
|
||||
rather than averaging all neighbours uniformly (as GCN does).
|
||||
|
||||
Architecture: BatchNorm → GATv2(hidden, heads) → ELU → BN → Dropout
|
||||
→ GATv2(hidden, heads) → Dropout
|
||||
→ GCNConv_mu / GCNConv_logstd
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: int, hidden: int, latent: int,
|
||||
heads: int = 4, dropout: float = 0.2, **_):
|
||||
super().__init__()
|
||||
if hidden % heads != 0:
|
||||
raise ValueError(f"hidden ({hidden}) must be divisible by heads ({heads})")
|
||||
self.norm = nn.BatchNorm1d(in_dim)
|
||||
self.gat1 = GATv2Conv(in_dim, hidden // heads, heads=heads,
|
||||
dropout=dropout, add_self_loops=True, concat=True)
|
||||
self.bn1 = nn.BatchNorm1d(hidden)
|
||||
self.gat2 = GATv2Conv(hidden, hidden // heads, heads=heads,
|
||||
dropout=dropout, add_self_loops=True, concat=True)
|
||||
self.gc_mu = GCNConv(hidden, latent, add_self_loops=True, normalize=True)
|
||||
self.gc_log = GCNConv(hidden, latent, add_self_loops=True, normalize=True)
|
||||
self.dropout = dropout
|
||||
|
||||
def forward(self, x, edge_index, edge_weight=None):
|
||||
x = self.norm(x)
|
||||
h = F.elu(self.gat1(x, edge_index))
|
||||
h = self.bn1(h)
|
||||
h = F.dropout(h, p=self.dropout, training=self.training)
|
||||
h = F.elu(self.gat2(h, edge_index))
|
||||
h = F.dropout(h, p=self.dropout, training=self.training)
|
||||
# GATv2 learns its own attention weights; edge_weight is used only in the
|
||||
# final linear projection layers (mu/log) where GCNConv accepts it.
|
||||
return self.gc_mu(h, edge_index, edge_weight), self.gc_log(h, edge_index, edge_weight)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deep GCN encoder (3 message-passing layers)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class DeepGCNEncoder(nn.Module):
|
||||
"""Three-layer GCN encoder — wider receptive field than the baseline.
|
||||
|
||||
Architecture: BatchNorm → GCN1 → BN → ReLU → Dropout
|
||||
→ GCN2 → ReLU → Dropout
|
||||
→ GCNConv_mu / GCNConv_logstd
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: int, hidden: int, latent: int, dropout: float = 0.2, **_):
|
||||
super().__init__()
|
||||
self.norm = nn.BatchNorm1d(in_dim)
|
||||
self.gc1 = GCNConv(in_dim, hidden, add_self_loops=True, normalize=True)
|
||||
self.bn1 = nn.BatchNorm1d(hidden)
|
||||
self.gc2 = GCNConv(hidden, hidden, add_self_loops=True, normalize=True)
|
||||
self.gc_mu = GCNConv(hidden, latent, add_self_loops=True, normalize=True)
|
||||
self.gc_log = GCNConv(hidden, latent, add_self_loops=True, normalize=True)
|
||||
self.dropout = dropout
|
||||
|
||||
def forward(self, x, edge_index, edge_weight=None):
|
||||
x = self.norm(x)
|
||||
h = F.relu(self.gc1(x, edge_index, edge_weight))
|
||||
h = self.bn1(h)
|
||||
h = F.dropout(h, p=self.dropout, training=self.training)
|
||||
h = F.relu(self.gc2(h, edge_index, edge_weight))
|
||||
h = F.dropout(h, p=self.dropout, training=self.training)
|
||||
return self.gc_mu(h, edge_index, edge_weight), self.gc_log(h, edge_index, edge_weight)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backward compatibility alias
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Encoder = GCNEncoder
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_ENCODERS = {
|
||||
"gcn": GCNEncoder,
|
||||
"gat": GATEncoder,
|
||||
"deep_gcn": DeepGCNEncoder,
|
||||
}
|
||||
|
||||
|
||||
def build_encoder(name: str, in_dim: int, hidden: int, latent: int, **kwargs) -> nn.Module:
|
||||
"""Instantiate an encoder by name.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : {"gcn", "gat", "deep_gcn"}
|
||||
in_dim, hidden, latent : layer dimensions
|
||||
**kwargs : passed to the constructor (e.g. dropout=0.3, heads=8)
|
||||
"""
|
||||
name = name.lower()
|
||||
if name not in _ENCODERS:
|
||||
raise ValueError(f"Unknown encoder '{name}'. Choose from {list(_ENCODERS)}")
|
||||
return _ENCODERS[name](in_dim=in_dim, hidden=hidden, latent=latent, **kwargs)
|
||||
Reference in new issue
Block a user