|
|
| import argparse
|
| import json
|
| from pathlib import Path
|
|
|
| import mdtraj as md
|
| import numpy as np
|
| import pandas as pd
|
| import matplotlib.pyplot as plt
|
|
|
| from tqdm import tqdm
|
| from sklearn.decomposition import PCA
|
| from sklearn.neighbors import NearestNeighbors
|
| from sklearn.metrics import pairwise_distances
|
| from scipy.linalg import eigh
|
|
|
|
|
| def load_replicates(entry_dir: Path):
|
| entry = entry_dir.name
|
| top = entry_dir / f"{entry}.pdb"
|
| xtcs = sorted(entry_dir.glob(f"{entry}_R*.xtc"))
|
|
|
| if not top.exists():
|
| raise FileNotFoundError(f"Missing pdb: {top}")
|
| if len(xtcs) == 0:
|
| raise FileNotFoundError(f"Missing xtc files in {entry_dir}")
|
|
|
| trajs = []
|
| for xtc in xtcs:
|
| traj = md.load(str(xtc), top=str(top))
|
| trajs.append(traj)
|
|
|
| return entry, top, trajs
|
|
|
|
|
| def select_ca_pairs(traj, cutoff_nm=1.2, min_seq_sep=4, max_pairs=4000, seed=0):
|
| ca_idx = traj.topology.select("name CA")
|
| if len(ca_idx) < 10:
|
| raise ValueError("Too few CA atoms")
|
|
|
| xyz = traj.xyz[0, ca_idx]
|
| n = len(ca_idx)
|
|
|
| pairs = []
|
| for i in range(n):
|
| for j in range(i + min_seq_sep, n):
|
| d = np.linalg.norm(xyz[i] - xyz[j])
|
| if d <= cutoff_nm:
|
| pairs.append((ca_idx[i], ca_idx[j]))
|
|
|
| pairs = np.asarray(pairs, dtype=np.int32)
|
|
|
| if len(pairs) == 0:
|
| raise ValueError("No CA pairs selected")
|
|
|
| if len(pairs) > max_pairs:
|
| rng = np.random.default_rng(seed)
|
| idx = rng.choice(len(pairs), size=max_pairs, replace=False)
|
| pairs = pairs[idx]
|
|
|
| return ca_idx, pairs
|
|
|
|
|
| def compute_features(trajs, pairs):
|
| feats = []
|
| for traj in trajs:
|
| x = md.compute_distances(traj, pairs).astype(np.float32)
|
| feats.append(x)
|
| return feats
|
|
|
|
|
| def standardize(feats, eps=1e-6):
|
| all_x = np.concatenate(feats, axis=0)
|
| mean = all_x.mean(axis=0, keepdims=True)
|
| std = all_x.std(axis=0, keepdims=True)
|
| std = np.maximum(std, eps)
|
| return [(x - mean) / std for x in feats]
|
|
|
|
|
| def fit_pca(feats, pca_dim=50, seed=0):
|
| all_x = np.concatenate(feats, axis=0)
|
| pca_dim = min(pca_dim, all_x.shape[0] - 1, all_x.shape[1])
|
|
|
| pca = PCA(n_components=pca_dim, random_state=seed)
|
| all_y = pca.fit_transform(all_x).astype(np.float32)
|
|
|
| outs = []
|
| start = 0
|
| for x in feats:
|
| n = x.shape[0]
|
| outs.append(all_y[start:start + n])
|
| start += n
|
|
|
| return outs
|
|
|
|
|
| def fit_tica(feats, lag=10, tica_dim=3, reg=1e-6):
|
| d = feats[0].shape[1]
|
|
|
| C00 = np.zeros((d, d), dtype=np.float64)
|
| C0t = np.zeros((d, d), dtype=np.float64)
|
| count = 0
|
|
|
| for x in feats:
|
| if x.shape[0] <= lag:
|
| continue
|
|
|
| x0 = x[:-lag].astype(np.float64)
|
| xt = x[lag:].astype(np.float64)
|
|
|
| C00 += x0.T @ x0
|
| C00 += xt.T @ xt
|
| C0t += x0.T @ xt
|
| count += x0.shape[0]
|
|
|
| if count == 0:
|
| raise ValueError("lag too large")
|
|
|
| C00 = C00 / (2.0 * count)
|
| C0t = C0t / count
|
|
|
| C00 = 0.5 * (C00 + C00.T)
|
| C0t = 0.5 * (C0t + C0t.T)
|
|
|
| C00 += reg * np.eye(d)
|
|
|
| vals, vecs = eigh(C0t, C00)
|
| order = np.argsort(np.abs(vals))[::-1]
|
| vals = vals[order]
|
| vecs = vecs[:, order]
|
|
|
| tica_dim = min(tica_dim, vecs.shape[1])
|
| W = vecs[:, :tica_dim]
|
|
|
| qs = [(x @ W).astype(np.float32) for x in feats]
|
| return qs, vals[:tica_dim]
|
|
|
|
|
| def build_affinity(q_all, k_scale=30, eps=1e-8):
|
| D = pairwise_distances(q_all, metric="euclidean").astype(np.float32)
|
|
|
| k_scale = min(k_scale, len(q_all) - 1)
|
| nn = NearestNeighbors(n_neighbors=k_scale + 1)
|
| nn.fit(q_all)
|
| dist, _ = nn.kneighbors(q_all)
|
|
|
| sigma = dist[:, -1].astype(np.float32)
|
| sigma = np.maximum(sigma, eps)
|
|
|
| A = np.exp(-(D ** 2) / (sigma[:, None] * sigma[None, :])).astype(np.float32)
|
| np.fill_diagonal(A, 1.0)
|
|
|
| return A, sigma
|
|
|
|
|
| def make_metadata(trajs):
|
| rep_ids = []
|
| local_ids = []
|
|
|
| for r, traj in enumerate(trajs):
|
| n = traj.n_frames
|
| rep_ids.extend([r] * n)
|
| local_ids.extend(list(range(n)))
|
|
|
| return np.asarray(rep_ids), np.asarray(local_ids)
|
|
|
|
|
| def kabsch_rmsd(P, Q):
|
| P = P - P.mean(axis=0, keepdims=True)
|
| Q = Q - Q.mean(axis=0, keepdims=True)
|
|
|
| H = P.T @ Q
|
| U, S, Vt = np.linalg.svd(H)
|
| R = Vt.T @ U.T
|
|
|
| if np.linalg.det(R) < 0:
|
| Vt[-1] *= -1
|
| R = Vt.T @ U.T
|
|
|
| P_rot = P @ R
|
| return np.sqrt(np.mean(np.sum((P_rot - Q) ** 2, axis=1)))
|
|
|
|
|
| def sample_groups(A, rep_ids, mode="all", n_pairs=3000, n_candidates=500000, seed=0):
|
| rng = np.random.default_rng(seed)
|
| n = A.shape[0]
|
|
|
| i = rng.integers(0, n, size=n_candidates)
|
| j = rng.integers(0, n, size=n_candidates)
|
|
|
| mask = i != j
|
|
|
| if mode == "cross":
|
| mask &= rep_ids[i] != rep_ids[j]
|
| elif mode == "same":
|
| mask &= rep_ids[i] == rep_ids[j]
|
|
|
| i = i[mask]
|
| j = j[mask]
|
|
|
| vals = A[i, j]
|
|
|
| q10 = np.quantile(vals, 0.10)
|
| q45 = np.quantile(vals, 0.45)
|
| q55 = np.quantile(vals, 0.55)
|
| q90 = np.quantile(vals, 0.90)
|
|
|
| idx_high = np.where(vals >= q90)[0]
|
| idx_mid = np.where((vals >= q45) & (vals <= q55))[0]
|
| idx_low = np.where(vals <= q10)[0]
|
|
|
| groups = {}
|
| for name, idx in [
|
| (f"{mode}_high", idx_high),
|
| (f"{mode}_mid", idx_mid),
|
| (f"{mode}_low", idx_low),
|
| ]:
|
| if len(idx) == 0:
|
| groups[name] = (np.array([], dtype=int), np.array([], dtype=int))
|
| continue
|
|
|
| take = rng.choice(idx, size=min(n_pairs, len(idx)), replace=False)
|
| groups[name] = (i[take], j[take])
|
|
|
| return groups, {
|
| f"{mode}_q10": float(q10),
|
| f"{mode}_q45": float(q45),
|
| f"{mode}_q55": float(q55),
|
| f"{mode}_q90": float(q90),
|
| }
|
|
|
|
|
| def evaluate_groups(groups, ca_xyz_all, dist_feat_all, rep_ids, local_ids):
|
| rows = []
|
|
|
| for group, (ii, jj) in groups.items():
|
| rmsds = []
|
| contact_diffs = []
|
| same_rep = []
|
| time_gaps = []
|
|
|
| for a, b in tqdm(list(zip(ii, jj)), desc=f"eval {group}", leave=False):
|
| rmsd = kabsch_rmsd(ca_xyz_all[a], ca_xyz_all[b]) * 10.0
|
| cdiff = np.mean(np.abs(dist_feat_all[a] - dist_feat_all[b])) * 10.0
|
|
|
| sr = rep_ids[a] == rep_ids[b]
|
| gap = abs(int(local_ids[a]) - int(local_ids[b])) if sr else np.nan
|
|
|
| rmsds.append(rmsd)
|
| contact_diffs.append(cdiff)
|
| same_rep.append(sr)
|
| time_gaps.append(gap)
|
|
|
| rmsds = np.asarray(rmsds, dtype=np.float32)
|
| contact_diffs = np.asarray(contact_diffs, dtype=np.float32)
|
| same_rep = np.asarray(same_rep, dtype=bool)
|
| time_gaps = np.asarray(time_gaps, dtype=np.float32)
|
|
|
| rows.append({
|
| "group": group,
|
| "n_pairs": len(rmsds),
|
| "rmsd_A_mean": float(np.nanmean(rmsds)),
|
| "rmsd_A_std": float(np.nanstd(rmsds)),
|
| "contact_diff_A_mean": float(np.nanmean(contact_diffs)),
|
| "contact_diff_A_std": float(np.nanstd(contact_diffs)),
|
| "same_rep_frac": float(np.mean(same_rep)) if len(same_rep) else np.nan,
|
| "time_gap_mean_same_rep": float(np.nanmean(time_gaps)),
|
| "near_time_frac_gap_le_5": float(np.nanmean(time_gaps <= 5)),
|
| "near_time_frac_gap_le_20": float(np.nanmean(time_gaps <= 20)),
|
| })
|
|
|
| return pd.DataFrame(rows)
|
|
|
|
|
| def plot_full_heatmap(A, frames_per_rep, out_file):
|
| plt.figure(figsize=(6, 5))
|
| plt.imshow(A, aspect="auto", vmin=0, vmax=1)
|
| plt.colorbar(label="Affinity")
|
|
|
| boundaries = np.cumsum(frames_per_rep)[:-1]
|
| for b in boundaries:
|
| plt.axhline(b, color="white", linewidth=1)
|
| plt.axvline(b, color="white", linewidth=1)
|
|
|
| plt.title("Full affinity heatmap with replicate boundaries")
|
| plt.xlabel("Frame index")
|
| plt.ylabel("Frame index")
|
| plt.tight_layout()
|
| plt.savefig(out_file, dpi=200)
|
| plt.close()
|
|
|
|
|
| def plot_q(q_all, rep_ids, out_file):
|
| plt.figure(figsize=(5, 4))
|
|
|
| if q_all.shape[1] >= 2:
|
| plt.scatter(q_all[:, 0], q_all[:, 1], c=rep_ids, s=4, alpha=0.75)
|
| plt.xlabel("TIC 1")
|
| plt.ylabel("TIC 2")
|
| else:
|
| plt.scatter(np.arange(len(q_all)), q_all[:, 0], c=rep_ids, s=4, alpha=0.75)
|
| plt.xlabel("Frame")
|
| plt.ylabel("TIC 1")
|
|
|
| plt.title("Slow coordinates colored by replicate")
|
| plt.tight_layout()
|
| plt.savefig(out_file, dpi=200)
|
| plt.close()
|
|
|
|
|
| def process_entry(entry_dir: Path, out_root: Path, args):
|
| entry, top, trajs = load_replicates(entry_dir)
|
| out_dir = out_root / entry
|
| out_dir.mkdir(parents=True, exist_ok=True)
|
|
|
| ca_idx, pairs = select_ca_pairs(
|
| trajs[0],
|
| cutoff_nm=args.contact_cutoff_nm,
|
| min_seq_sep=args.min_seq_sep,
|
| max_pairs=args.max_ca_pairs,
|
| seed=args.seed,
|
| )
|
|
|
| raw_feats = compute_features(trajs, pairs)
|
| feats = standardize(raw_feats)
|
|
|
| pca_feats = fit_pca(feats, pca_dim=args.pca_dim, seed=args.seed)
|
| qs, tica_vals = fit_tica(pca_feats, lag=args.lag, tica_dim=args.tica_dim)
|
|
|
| q_all = np.concatenate(qs, axis=0)
|
| A, sigma = build_affinity(q_all, k_scale=args.k_scale)
|
|
|
| rep_ids, local_ids = make_metadata(trajs)
|
|
|
| ca_xyz_all = np.concatenate([t.xyz[:, ca_idx, :] for t in trajs], axis=0)
|
| dist_feat_all = np.concatenate(raw_feats, axis=0)
|
|
|
| all_groups, all_thr = sample_groups(
|
| A, rep_ids, mode="all",
|
| n_pairs=args.sample_pairs,
|
| n_candidates=args.candidate_pairs,
|
| seed=args.seed,
|
| )
|
|
|
| cross_groups, cross_thr = sample_groups(
|
| A, rep_ids, mode="cross",
|
| n_pairs=args.sample_pairs,
|
| n_candidates=args.candidate_pairs,
|
| seed=args.seed,
|
| )
|
|
|
| same_groups, same_thr = sample_groups(
|
| A, rep_ids, mode="same",
|
| n_pairs=args.sample_pairs,
|
| n_candidates=args.candidate_pairs,
|
| seed=args.seed,
|
| )
|
|
|
| summary_all = evaluate_groups(all_groups, ca_xyz_all, dist_feat_all, rep_ids, local_ids)
|
| summary_cross = evaluate_groups(cross_groups, ca_xyz_all, dist_feat_all, rep_ids, local_ids)
|
| summary_same = evaluate_groups(same_groups, ca_xyz_all, dist_feat_all, rep_ids, local_ids)
|
|
|
| summary = pd.concat([summary_all, summary_cross, summary_same], axis=0)
|
| summary.insert(0, "entry", entry)
|
|
|
| summary.to_csv(out_dir / "affinity_sanity_all_cross_same.tsv", sep="\t", index=False)
|
|
|
| frames_per_rep = [int(t.n_frames) for t in trajs]
|
|
|
| np.save(out_dir / "q.npy", q_all)
|
| np.save(out_dir / "affinity.float16.npy", A.astype(np.float16))
|
|
|
| plot_q(q_all, rep_ids, out_dir / "q_by_replicate.png")
|
| plot_full_heatmap(A, frames_per_rep, out_dir / "full_affinity_heatmap.png")
|
|
|
| meta = {
|
| "entry": entry,
|
| "topology": str(top),
|
| "frames_per_replicate": frames_per_rep,
|
| "total_frames": int(sum(frames_per_rep)),
|
| "n_CA": int(len(ca_idx)),
|
| "n_CA_pairs": int(len(pairs)),
|
| "lag": args.lag,
|
| "pca_dim": args.pca_dim,
|
| "tica_dim": args.tica_dim,
|
| "tica_eigenvalues": [float(x) for x in tica_vals],
|
| "sigma_mean": float(np.mean(sigma)),
|
| "sigma_std": float(np.std(sigma)),
|
| "thresholds": {**all_thr, **cross_thr, **same_thr},
|
| }
|
|
|
| with open(out_dir / "meta.json", "w") as f:
|
| json.dump(meta, f, indent=2)
|
|
|
| return summary
|
|
|
|
|
| def main():
|
| parser = argparse.ArgumentParser()
|
|
|
| parser.add_argument("--atlas_root", default="/raid_zoe/home/lr/wangyi/p/atlas_1000_analysis")
|
| parser.add_argument("--out_root", default="/raid_zoe/home/lr/wangyi/p/affinity_crossrep_check")
|
| parser.add_argument("--entry", default="16pk_A")
|
| parser.add_argument("--max_proteins", type=int, default=None)
|
|
|
| parser.add_argument("--lag", type=int, default=10)
|
| parser.add_argument("--pca_dim", type=int, default=50)
|
| parser.add_argument("--tica_dim", type=int, default=3)
|
|
|
| parser.add_argument("--contact_cutoff_nm", type=float, default=1.2)
|
| parser.add_argument("--min_seq_sep", type=int, default=4)
|
| parser.add_argument("--max_ca_pairs", type=int, default=4000)
|
|
|
| parser.add_argument("--k_scale", type=int, default=30)
|
| parser.add_argument("--sample_pairs", type=int, default=3000)
|
| parser.add_argument("--candidate_pairs", type=int, default=500000)
|
|
|
| parser.add_argument("--seed", type=int, default=0)
|
|
|
| args = parser.parse_args()
|
|
|
| atlas_root = Path(args.atlas_root)
|
| out_root = Path(args.out_root)
|
| out_root.mkdir(parents=True, exist_ok=True)
|
|
|
| if args.entry.lower() == "all":
|
| entry_dirs = sorted([
|
| p for p in atlas_root.iterdir()
|
| if p.is_dir() and not p.name.startswith("_")
|
| ])
|
| if args.max_proteins is not None:
|
| entry_dirs = entry_dirs[:args.max_proteins]
|
| else:
|
| entry_dirs = [atlas_root / args.entry]
|
|
|
| all_summaries = []
|
|
|
| for entry_dir in tqdm(entry_dirs, desc="proteins"):
|
| try:
|
| summary = process_entry(entry_dir, out_root, args)
|
| all_summaries.append(summary)
|
| print(summary)
|
| except Exception as e:
|
| print(f"[FAILED] {entry_dir.name}: {e}")
|
| with open(out_root / "failed.txt", "a") as f:
|
| f.write(f"{entry_dir.name}\t{e}\n")
|
|
|
| if all_summaries:
|
| df = pd.concat(all_summaries, axis=0)
|
| df.to_csv(out_root / "all_affinity_sanity_all_cross_same.tsv", sep="\t", index=False)
|
|
|
| print(f"Saved to: {out_root}")
|
|
|
|
|
| if __name__ == "__main__":
|
| main() |