#!/usr/bin/env python """Batch endpoint covariance transport for BBFlow ensembles. This script implements the low-cost test proposed in the handoff: 1. Start from an already sampled 20-step BBFlow endpoint ensemble. 2. Preserve that ensemble's per-coordinate variance scale. 3. Replace only part of its correlation structure with either: - oracle MD correlation, or - A30 learned mode-subspace correlation. 4. Write a standard ``/sampled_conformations.pdb`` directory that can be passed directly to ``reproduction/03_evaluate.sh``. The output is CA-only. The official RMSF / Pairwise / PCA-W2 path reduces both reference and model trajectories to CA coordinates, so this is sufficient for the core table metrics. Backbone geometry side effects must still be checked separately before making a paper claim. """ from __future__ import annotations import argparse import csv import json from pathlib import Path from typing import Iterable import mdtraj import numpy as np def read_test_names(csv_path: Path) -> list[str]: with csv_path.open(newline="") as handle: reader = csv.DictReader(handle) if reader.fieldnames is None: raise ValueError(f"Empty CSV: {csv_path}") name_key = "pdb_name" if "pdb_name" in reader.fieldnames else reader.fieldnames[0] names = [str(row[name_key]).strip() for row in reader if str(row[name_key]).strip()] if not names: raise ValueError(f"No protein names found in {csv_path}") return names def pdb_name_variants(name: str) -> Iterable[str]: yield name if "_" in name: yield name.replace("_", "") elif len(name) == 5: yield f"{name[:4]}_{name[4]}" def load_ca_pdb_models(pdb_path: Path) -> np.ndarray: """Load a multi-model PDB and return CA coordinates in Angstrom, [M,N,3].""" traj = mdtraj.load(str(pdb_path)) ca = traj.topology.select("name CA") if ca.size == 0: raise ValueError(f"No CA atoms in {pdb_path}") return np.asarray(traj.xyz[:, ca, :] * 10.0, dtype=np.float64) def load_md_ca_frames(atlas_root: Path, pdb_name: str, stride: int, max_frames: int, seed: int) -> np.ndarray: entry = atlas_root / pdb_name top_path = entry / f"{pdb_name}.pdb" if not top_path.exists(): raise FileNotFoundError(f"Missing MD topology PDB: {top_path}") top = mdtraj.load(str(top_path)) ca = top.topology.select("name CA") if ca.size == 0: raise ValueError(f"No CA atoms in {top_path}") frames = [] for replica in (1, 2, 3): xtc_path = entry / f"{pdb_name}_R{replica}.xtc" if not xtc_path.exists(): raise FileNotFoundError(f"Missing MD trajectory: {xtc_path}") traj = mdtraj.load(str(xtc_path), top=str(top_path), atom_indices=ca, stride=max(1, stride)) frames.append(np.asarray(traj.xyz * 10.0, dtype=np.float64)) out = np.concatenate(frames, axis=0) if max_frames and out.shape[0] > max_frames: rng = np.random.default_rng(seed) indices = np.sort(rng.choice(out.shape[0], size=max_frames, replace=False)) out = out[indices] return out def write_ca_pdb(path: Path, coords: np.ndarray) -> None: """Write [M,N,3] Angstrom CA coordinates as multi-model PDB.""" path.parent.mkdir(parents=True, exist_ok=True) with path.open("w") as handle: for model_idx, frame in enumerate(coords, start=1): handle.write(f"MODEL {model_idx:>4d}\n") for residue_idx, (x, y, z) in enumerate(frame, start=1): atom_serial = ((residue_idx - 1) % 99999) + 1 residue_serial = ((residue_idx - 1) % 9999) + 1 handle.write( f"ATOM {atom_serial:>5d} CA ALA A{residue_serial:>4d} " f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 C\n" ) handle.write("ENDMDL\n") handle.write("END\n") def kabsch(P: np.ndarray, Q: np.ndarray) -> np.ndarray: H = P.T @ Q U, _, Vt = np.linalg.svd(H, full_matrices=False) det = np.linalg.det(Vt.T @ U.T) sign = 1.0 if det >= 0.0 else -1.0 D = np.diag([1.0, 1.0, sign]) R = U @ D @ Vt if np.linalg.det(R) < 0.0: raise ValueError("Kabsch produced a reflection") return R def superpose_to_mean(X: np.ndarray, iterations: int = 3) -> tuple[np.ndarray, np.ndarray]: """Remove global translation/rotation and return centered frames and mean.""" Xc = X - X.mean(axis=1, keepdims=True) ref = Xc[0] - Xc[0].mean(axis=0, keepdims=True) aligned = Xc for _ in range(iterations): aligned = np.stack( [ (frame - frame.mean(axis=0, keepdims=True)) @ kabsch(frame - frame.mean(axis=0, keepdims=True), ref) for frame in aligned ], axis=0, ) ref = aligned.mean(axis=0) ref = ref - ref.mean(axis=0, keepdims=True) return aligned, ref def whiten_samples(X: np.ndarray, eps: float) -> np.ndarray: """Return sample coordinates with empirical covariance approximately I.""" sample_count = X.shape[0] U, S, _ = np.linalg.svd(X, full_matrices=False) rank = int(np.sum(S > eps * max(float(S.max()), 1.0))) if rank < 1: raise ValueError("Generated ensemble has zero covariance rank") return U[:, :rank] * np.sqrt(max(sample_count - 1, 1)) def color_from_factor(white: np.ndarray, target_factor: np.ndarray, eps: float) -> np.ndarray: """Color whitened samples with covariance encoded by factor L, C=L.T@L.""" _, S, Vt = np.linalg.svd(target_factor, full_matrices=False) rank = min(white.shape[1], int(np.sum(S > eps * max(float(S.max()), 1.0)))) if rank < 1: raise ValueError("Target covariance factor has zero rank") return (white[:, :rank] * S[:rank]) @ Vt[:rank, :] def match_marginal_variances(X: np.ndarray, target_diag: np.ndarray, eps: float) -> np.ndarray: """Rescale each coordinate so the finite-sample diagonal matches target_diag. The transport target can have rank above the available generated ensemble rank. After truncating back to at most M-1 sample directions, the diagonal is no longer guaranteed to match. This final coordinate-wise calibration restores the central promise of this diagnostic: preserve BBFlow endpoint marginals and trace, while only changing correlations as much as the finite ensemble allows. """ X = X - X.mean(axis=0, keepdims=True) current_diag = covariance_diag(X) scale = np.sqrt(np.clip(target_diag, eps, None) / np.clip(current_diag, eps, None)) return X * scale[None, :] def covariance_diag(X: np.ndarray) -> np.ndarray: return np.var(X, axis=0, ddof=1) def oracle_target_factor(Fg: np.ndarray, Fr: np.ndarray, lam: float, eps: float) -> np.ndarray: """Factor for Dg^1/2 [(1-lam)R_gen + lam R_MD] Dg^1/2.""" gen_factor = Fg / np.sqrt(max(Fg.shape[0] - 1, 1)) ref_factor = Fr / np.sqrt(max(Fr.shape[0] - 1, 1)) dg = np.clip(covariance_diag(Fg), eps, None) dr = np.clip(covariance_diag(Fr), eps, None) ref_scaled = ref_factor * np.sqrt(dg / dr)[None, :] return np.concatenate( [np.sqrt(max(1.0 - lam, 0.0)) * gen_factor, np.sqrt(max(lam, 0.0)) * ref_scaled], axis=0, ) def load_modes(modes_dir: Path, pdb_name: str, num_res: int) -> np.ndarray: for variant in pdb_name_variants(pdb_name): path = modes_dir / f"{variant}.npy" if path.exists(): modes = np.load(path) break else: raise FileNotFoundError(f"Missing A30 mode file for {pdb_name} in {modes_dir}") modes = np.asarray(modes, dtype=np.float64) if modes.shape[:2] == (num_res, 3): # [N,3,K] modes = np.transpose(modes, (0, 2, 1)) if modes.shape[0] != num_res or modes.ndim != 3: raise ValueError(f"Expected modes [N,K,3] or [N,3,K] for {pdb_name}, got {modes.shape}") return np.transpose(modes, (0, 2, 1)).reshape(num_res * 3, modes.shape[1]) def a30_target_factor(Fg: np.ndarray, modes: np.ndarray, lam: float, eps: float) -> np.ndarray: """Factor for Dg^1/2 [(1-lam)R_gen + lam R_A30] Dg^1/2.""" gen_factor = Fg / np.sqrt(max(Fg.shape[0] - 1, 1)) mode_cols = modes / np.linalg.norm(modes, axis=0, keepdims=True).clip(min=eps) mode_diag = np.sum(mode_cols * mode_cols, axis=1).clip(min=eps) dg = np.clip(covariance_diag(Fg), eps, None) mode_factor = (mode_cols * np.sqrt(dg / mode_diag)[:, None]).T return np.concatenate( [np.sqrt(max(1.0 - lam, 0.0)) * gen_factor, np.sqrt(max(lam, 0.0)) * mode_factor], axis=0, ) def transport_one( pdb_name: str, ensemble_dir: Path, atlas_root: Path, out_dir: Path, mode: str, lam: float, stride: int, max_md_frames: int, seed: int, modes_dir: Path | None, eps: float, overwrite: bool, ) -> dict[str, float | str | int]: gen_pdb = ensemble_dir / pdb_name / "sampled_conformations.pdb" out_pdb = out_dir / pdb_name / "sampled_conformations.pdb" if out_pdb.exists() and not overwrite: return {"pdb_name": pdb_name, "status": "skipped_exists"} if not gen_pdb.exists(): return {"pdb_name": pdb_name, "status": "missing_gen_pdb", "path": str(gen_pdb)} Xg = load_ca_pdb_models(gen_pdb) Xr = load_md_ca_frames(atlas_root, pdb_name, stride=stride, max_frames=max_md_frames, seed=seed) if Xg.shape[1] != Xr.shape[1]: raise ValueError(f"{pdb_name}: residue mismatch gen={Xg.shape[1]} md={Xr.shape[1]}") Xg_aligned, mean_g = superpose_to_mean(Xg) Xr_aligned, mean_r = superpose_to_mean(Xr) Rg2r = kabsch(mean_g, mean_r) Xg_aligned = Xg_aligned @ Rg2r mean_g = mean_g @ Rg2r num_res = Xg.shape[1] Fg = Xg_aligned.reshape(Xg_aligned.shape[0], num_res * 3) Fr = Xr_aligned.reshape(Xr_aligned.shape[0], num_res * 3) white = whiten_samples(Fg, eps=eps) if mode == "oracle": target_factor = oracle_target_factor(Fg, Fr, lam=lam, eps=eps) elif mode == "a30": if modes_dir is None: raise ValueError("--modes_dir is required for --mode a30") modes = load_modes(modes_dir, pdb_name, num_res=num_res) target_factor = a30_target_factor(Fg, modes, lam=lam, eps=eps) else: raise ValueError(mode) Ft = color_from_factor(white, target_factor, eps=eps) Ft = match_marginal_variances(Ft, covariance_diag(Fg), eps=eps) Xt = Ft.reshape(Fg.shape[0], num_res, 3) + mean_g[None, :, :] write_ca_pdb(out_pdb, Xt) diag_gen = covariance_diag(Fg) diag_out = covariance_diag(Ft) return { "pdb_name": pdb_name, "status": "ok", "num_res": int(num_res), "num_gen_frames": int(Xg.shape[0]), "num_md_frames": int(Xr.shape[0]), "trace_gen": float(np.sum(diag_gen)), "trace_out": float(np.sum(diag_out)), "diag_l1_gen_out": float(np.mean(np.abs(diag_gen - diag_out))), "diag_rel_l1_gen_out": float(np.mean(np.abs(diag_gen - diag_out)) / max(np.mean(diag_gen), eps)), } def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--ensemble_dir", required=True, type=Path) parser.add_argument("--atlas_root", required=True, type=Path) parser.add_argument("--test_csv", required=True, type=Path) parser.add_argument("--out_dir", required=True, type=Path) parser.add_argument("--mode", choices=["oracle", "a30"], default="oracle") parser.add_argument("--lam", type=float, default=0.5) parser.add_argument("--modes_dir", type=Path, default=None) parser.add_argument("--md_stride", type=int, default=1) parser.add_argument("--max_md_frames", type=int, default=0, help="0 means all MD frames after stride") parser.add_argument("--seed", type=int, default=123) parser.add_argument("--eps", type=float, default=1e-8) parser.add_argument("--overwrite", action="store_true") parser.add_argument("--limit", type=int, default=0, help="0 means all proteins") return parser.parse_args() def main() -> None: args = parse_args() if not args.ensemble_dir.exists(): raise FileNotFoundError(args.ensemble_dir) if not args.atlas_root.exists(): raise FileNotFoundError(args.atlas_root) if not args.test_csv.exists(): raise FileNotFoundError(args.test_csv) if args.mode == "a30" and (args.modes_dir is None or not args.modes_dir.exists()): raise FileNotFoundError(f"--mode a30 requires existing --modes_dir, got {args.modes_dir}") names = read_test_names(args.test_csv) if args.limit > 0: names = names[: args.limit] args.out_dir.mkdir(parents=True, exist_ok=True) rows = [] for idx, name in enumerate(names, start=1): print(f"[{idx}/{len(names)}] {name} mode={args.mode} lambda={args.lam}") row = transport_one( pdb_name=name, ensemble_dir=args.ensemble_dir, atlas_root=args.atlas_root, out_dir=args.out_dir, mode=args.mode, lam=args.lam, stride=args.md_stride, max_md_frames=args.max_md_frames, seed=args.seed + idx, modes_dir=args.modes_dir, eps=args.eps, overwrite=args.overwrite, ) rows.append(row) print(json.dumps(row, sort_keys=True)) summary_path = args.out_dir / "transport_summary.json" with summary_path.open("w") as handle: json.dump( { "mode": args.mode, "lambda": args.lam, "ensemble_dir": str(args.ensemble_dir), "atlas_root": str(args.atlas_root), "test_csv": str(args.test_csv), "rows": rows, }, handle, indent=2, sort_keys=True, ) print(f"Saved: {summary_path}") if __name__ == "__main__": main()