Download bbflow_base/scripts/diagnose_mode_pca_alignment.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/diagnose_mode_pca_alignment.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/diagnose_mode_pca_alignment.py
-
curl -L -o diagnose_mode_pca_alignment.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/diagnose_mode_pca_alignment.py
12.2 kB
| #!/usr/bin/env python | |
| """Compare learned latent modes with MD PCA/oracle modes. | |
| The goal is to test whether the model's highest-energy learned modes align | |
| with the MD top principal components that drive PCA-W2. | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import sys | |
| import numpy as np | |
| import pandas as pd | |
| import mdtraj | |
| import torch | |
| from omegaconf import OmegaConf | |
| REPO_ROOT = Path(__file__).resolve().parents[1] | |
| if str(REPO_ROOT) not in sys.path: | |
| sys.path.insert(0, str(REPO_ROOT)) | |
| from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb | |
| from bbflow.data.utils import frames_from_pdb | |
| from bbflow.models.latent import LatentEncoder | |
| from bbflow.models.bbflow_module import BBFlowModule | |
| from scripts.fit_motion_template_upper_bound import load_motion_targets, pdb_name_variants | |
| def load_module(ckpt_path, device): | |
| ckpt_path = Path(ckpt_path) | |
| cfg_path = ckpt_path.with_name("config.yaml") | |
| if not cfg_path.exists(): | |
| raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") | |
| infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") | |
| ckpt_cfg = OmegaConf.load(cfg_path) | |
| OmegaConf.set_struct(infer_cfg, False) | |
| OmegaConf.set_struct(ckpt_cfg, False) | |
| cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) | |
| cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior | |
| cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional | |
| cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot | |
| cfg.model.embed = ckpt_cfg.model.embed | |
| module = BBFlowModule(cfg) | |
| ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) | |
| current_state = module.state_dict() | |
| compatible_state = { | |
| key: value for key, value in ckpt["state_dict"].items() | |
| if key in current_state and current_state[key].shape == value.shape | |
| } | |
| missing, unexpected = module.load_state_dict(compatible_state, strict=False) | |
| module.to(device) | |
| module.eval() | |
| return module, {"loaded": len(compatible_state), "missing": len(missing), "unexpected": len(unexpected)} | |
| def target_for_pdb(targets, pdb_name): | |
| for name in pdb_name_variants(str(pdb_name)): | |
| if name in targets: | |
| return targets[name] | |
| raise KeyError(f"No motion target for {pdb_name}") | |
| def load_ca_md_frames(atlas_root, pdb_name): | |
| entry_dir = Path(atlas_root) / str(pdb_name) | |
| eq_path = entry_dir / f"{pdb_name}.pdb" | |
| if not eq_path.exists(): | |
| raise FileNotFoundError(f"Missing equilibrium PDB: {eq_path}") | |
| top = mdtraj.load(str(eq_path)) | |
| ca_indices = top.top.select("name CA") | |
| if ca_indices.size == 0: | |
| raise ValueError(f"No CA atoms found in {eq_path}") | |
| frames = [] | |
| for traj_idx in range(1, 4): | |
| xtc_path = entry_dir / f"{pdb_name}_R{traj_idx}.xtc" | |
| if not xtc_path.exists(): | |
| raise FileNotFoundError(f"Missing trajectory: {xtc_path}") | |
| traj = mdtraj.load(str(xtc_path), top=str(eq_path), atom_indices=ca_indices) | |
| frames.append(torch.as_tensor(traj.xyz, dtype=torch.float32) * 10.0) | |
| return torch.cat(frames, dim=0) | |
| def oracle_modes_from_target_or_md(target, atlas_root, pdb_name, num_md_pcs, device): | |
| if "oracle_modes" in target and "oracle_energy" in target: | |
| return ( | |
| torch.as_tensor(target["oracle_modes"], device=device, dtype=torch.float32), | |
| torch.as_tensor(target["oracle_energy"], device=device, dtype=torch.float32), | |
| "cache", | |
| ) | |
| if atlas_root is None: | |
| raise KeyError( | |
| f"{pdb_name} target lacks oracle_modes/oracle_energy; pass --atlas_root to compute them from MD" | |
| ) | |
| eq_path = Path(atlas_root) / str(pdb_name) / f"{pdb_name}.pdb" | |
| trans_eq, _, _, _ = frames_from_pdb(eq_path) | |
| frames = load_ca_md_frames(atlas_root, pdb_name) | |
| mask = torch.ones(trans_eq.shape[0], dtype=torch.float32) | |
| disp = LatentEncoder.relative_displacement(frames, trans_eq.float(), mask) | |
| disp_centered = disp - disp.mean(dim=0, keepdim=True) | |
| modes, energy = LatentEncoder.pca_modes_from_centered_displacement( | |
| disp_centered, | |
| mask, | |
| num_modes=num_md_pcs, | |
| ) | |
| return modes.to(device), energy.to(device), "md_xtc" | |
| def flatten_modes(modes, mask): | |
| """Return [K, 3N] masked, L2-normalized mode vectors.""" | |
| if modes.ndim == 4: | |
| modes = modes[0] | |
| # [N,K,3] -> [K,N,3] -> [K,3N] | |
| mask = mask.float() | |
| flat = (modes.float() * mask[:, None, None]).permute(1, 0, 2).reshape(modes.shape[1], -1) | |
| return flat / flat.norm(dim=-1, keepdim=True).clamp_min(1e-8) | |
| def cosine_matrix(learned_modes, md_modes, mask): | |
| learned = flatten_modes(learned_modes, mask) | |
| md = flatten_modes(md_modes, mask) | |
| return learned @ md.T | |
| def orthonormal_basis(mode_flat): | |
| # mode_flat: [K, D], row vectors. | |
| q, _ = torch.linalg.qr(mode_flat.T, mode="reduced") | |
| return q | |
| def subspace_overlap(learned_modes, md_modes, mask, learned_indices, md_indices): | |
| learned = flatten_modes(learned_modes, mask)[learned_indices] | |
| md = flatten_modes(md_modes, mask)[md_indices] | |
| q_l = orthonormal_basis(learned) | |
| q_m = orthonormal_basis(md) | |
| s = torch.linalg.svdvals(q_l.T @ q_m) | |
| return { | |
| "mean_sq_cos": float((s.square().mean()).detach().cpu().item()), | |
| "min_sq_cos": float((s.square().min()).detach().cpu().item()), | |
| "singular_values": [float(x) for x in s.detach().cpu().tolist()], | |
| } | |
| def numeric_mean(rows): | |
| out = {} | |
| if not rows: | |
| return out | |
| keys = sorted({key for row in rows for key in row}) | |
| for key in keys: | |
| vals = [row[key] for row in rows if isinstance(row.get(key), (int, float))] | |
| if vals: | |
| out[key] = float(np.mean(vals)) | |
| return out | |
| def parse_args(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--ckpt_path", required=True) | |
| parser.add_argument("--csv_path", required=True) | |
| parser.add_argument("--motion_target_cache_path", required=True) | |
| parser.add_argument("--output_dir", required=True) | |
| parser.add_argument("--atlas_root", default=None, help="ATLAS root with PDB/XTC files; used if cache lacks oracle_modes.") | |
| parser.add_argument("--num_md_pcs", type=int, default=5) | |
| parser.add_argument("--num_proteins", type=int, default=0, help="0 means all proteins") | |
| parser.add_argument("--pdb_name", default="") | |
| parser.add_argument("--device", default="cuda") | |
| return parser.parse_args() | |
| def select_indices(dataset, pdb_name, num_proteins): | |
| if pdb_name: | |
| wanted = [x.strip() for x in pdb_name.split(",") if x.strip()] | |
| indices = [] | |
| for name in wanted: | |
| matches = [idx for idx, pdb in enumerate(dataset.pdb_names) if pdb == name] | |
| if not matches: | |
| raise ValueError(f"pdb_name not found in csv: {name}") | |
| indices.append(matches[0]) | |
| return indices | |
| limit = len(dataset) if int(num_proteins) <= 0 else min(int(num_proteins), len(dataset)) | |
| return list(range(limit)) | |
| def main(): | |
| args = parse_args() | |
| device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") | |
| output_dir = Path(args.output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| module, load_info = load_module(args.ckpt_path, device) | |
| targets = load_motion_targets(args.motion_target_cache_path) | |
| df = pd.read_csv(args.csv_path) | |
| dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) | |
| indices = select_indices(dataset, args.pdb_name, args.num_proteins) | |
| rows = [] | |
| with torch.no_grad(): | |
| for idx in indices: | |
| pdb_name = dataset.pdb_names[idx] | |
| item = dataset[idx] | |
| trans_eq = item["trans_equilibrium"][None].to(device) | |
| rotmats_eq = item["rotmats_equilibrium"][None].to(device) | |
| seq = item["seq"][None].to(device) | |
| _, num_res = trans_eq.shape[:2] | |
| mask = torch.ones(num_res, device=device) | |
| res_mask = mask[None] | |
| condition, _ = module.latent_encoder.forward_prior(trans_eq, rotmats_eq, seq, res_mask) | |
| learned_modes = condition["u_global"].detach().float() | |
| learned_energy = condition["energy"][0].detach().float() | |
| target = target_for_pdb(targets, pdb_name) | |
| md_modes, md_energy, md_mode_source = oracle_modes_from_target_or_md( | |
| target, | |
| args.atlas_root, | |
| pdb_name, | |
| args.num_md_pcs, | |
| device, | |
| ) | |
| if md_modes.shape[1] < args.num_md_pcs: | |
| raise ValueError(f"{pdb_name} has only {md_modes.shape[1]} oracle modes") | |
| cos = cosine_matrix(learned_modes, md_modes[:, : args.num_md_pcs], mask) | |
| abs_cos = cos.abs() | |
| learned_order = torch.argsort(learned_energy, descending=True) | |
| md_order = torch.arange(args.num_md_pcs, device=device) | |
| row = { | |
| "pdb_name": pdb_name, | |
| "num_res": int(num_res), | |
| "md_mode_source": md_mode_source, | |
| "learned_energy_top0": float(learned_energy[learned_order[0]].cpu().item()), | |
| "learned_energy_top1": float(learned_energy[learned_order[1]].cpu().item()) if learned_order.numel() > 1 else float("nan"), | |
| "md_energy_pc1": float(md_energy[0].cpu().item()), | |
| "md_energy_pc2": float(md_energy[1].cpu().item()) if md_energy.numel() > 1 else float("nan"), | |
| } | |
| for pc_idx in range(min(args.num_md_pcs, abs_cos.shape[1])): | |
| best = torch.max(abs_cos[:, pc_idx]) | |
| best_idx = int(torch.argmax(abs_cos[:, pc_idx]).cpu().item()) | |
| top0 = int(learned_order[0].cpu().item()) | |
| row[f"best_abs_cos_to_md_pc{pc_idx + 1}"] = float(best.cpu().item()) | |
| row[f"best_learned_mode_for_md_pc{pc_idx + 1}"] = best_idx | |
| row[f"top_energy_abs_cos_to_md_pc{pc_idx + 1}"] = float(abs_cos[top0, pc_idx].cpu().item()) | |
| for rank in range(min(learned_order.numel(), 5)): | |
| learned_idx = int(learned_order[rank].cpu().item()) | |
| best_pc = torch.max(abs_cos[learned_idx, :]) | |
| best_pc_idx = int(torch.argmax(abs_cos[learned_idx, :]).cpu().item()) | |
| row[f"top{rank + 1}_energy_mode_index"] = learned_idx | |
| row[f"top{rank + 1}_energy_best_abs_cos_to_any_md_pc"] = float(best_pc.cpu().item()) | |
| row[f"top{rank + 1}_energy_best_md_pc"] = best_pc_idx + 1 | |
| top2_learned = learned_order[: min(2, learned_order.numel())] | |
| top2_md = md_order[: min(2, md_order.numel())] | |
| top2 = subspace_overlap(learned_modes, md_modes, mask, top2_learned, top2_md) | |
| row["top2_energy_vs_md_top2_subspace_mean_sq_cos"] = top2["mean_sq_cos"] | |
| row["top2_energy_vs_md_top2_subspace_min_sq_cos"] = top2["min_sq_cos"] | |
| all_learned = torch.arange(learned_modes.shape[2], device=device) | |
| best2 = subspace_overlap(learned_modes, md_modes, mask, all_learned, top2_md) | |
| row["all_learned_vs_md_top2_subspace_mean_sq_cos"] = best2["mean_sq_cos"] | |
| row["all_learned_vs_md_top2_subspace_min_sq_cos"] = best2["min_sq_cos"] | |
| rows.append(row) | |
| matrix_path = output_dir / f"{pdb_name}_abs_cosine.npy" | |
| np.save(matrix_path, abs_cos.detach().cpu().numpy()) | |
| out_csv = output_dir / "per_protein_mode_pca_alignment.csv" | |
| pd.DataFrame(rows).to_csv(out_csv, index=False) | |
| summary = { | |
| "ckpt_path": str(args.ckpt_path), | |
| "csv_path": str(args.csv_path), | |
| "motion_target_cache_path": str(args.motion_target_cache_path), | |
| "atlas_root": str(args.atlas_root) if args.atlas_root is not None else None, | |
| "load_info": load_info, | |
| "num_proteins": len(rows), | |
| "mean": numeric_mean(rows), | |
| } | |
| with (output_dir / "summary.json").open("w") as handle: | |
| json.dump(summary, handle, indent=2) | |
| print(json.dumps(summary, indent=2)) | |
| print(f"Wrote {out_csv}") | |
| if __name__ == "__main__": | |
| main() | |