data_transfer / bbflow_base /scripts /export_condition_modes.py
hanghang214's picture
Add files using upload-large-folder tool
5b2e6c5 verified
Raw History Blame Contribute Delete
5.52 kB
#!/usr/bin/env python
"""Export learned condition modes from a BBFlow/A30 checkpoint.
The covariance transport script consumes one ``<pdb_name>.npy`` file per
protein, with shape [N, K, 3]. This helper runs the latent prior on equilibrium
structures and writes those mode tensors.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import sys
import numpy as np
import pandas as pd
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.models.bbflow_module import BBFlowModule
def load_module(ckpt_path: Path, device: torch.device) -> tuple[BBFlowModule, dict[str, int]]:
cfg_path = ckpt_path.with_name("config.yaml")
if not cfg_path.exists():
raise FileNotFoundError(f"Missing checkpoint config next to checkpoint: {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 parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--ckpt_path", required=True, type=Path)
parser.add_argument("--csv_path", required=True, type=Path)
parser.add_argument("--output_dir", required=True, type=Path)
parser.add_argument("--device", default="cuda")
parser.add_argument("--limit", type=int, default=0, help="0 means all proteins")
parser.add_argument("--pdb_name", default="", help="Optional comma-separated protein names")
parser.add_argument("--overwrite", action="store_true")
return parser.parse_args()
def select_indices(dataset: PDBDatasetBBFlowFromPdb, pdb_name: str, limit: int) -> list[int]:
if pdb_name:
wanted = [item.strip() for item in pdb_name.split(",") if item.strip()]
indices = []
for name in wanted:
matches = [idx for idx, candidate in enumerate(dataset.pdb_names) if candidate == name]
if not matches:
raise ValueError(f"Protein not found in csv: {name}")
indices.append(matches[0])
return indices
count = len(dataset) if limit <= 0 else min(limit, len(dataset))
return list(range(count))
def main() -> None:
args = parse_args()
if not args.ckpt_path.exists():
raise FileNotFoundError(args.ckpt_path)
if not args.csv_path.exists():
raise FileNotFoundError(args.csv_path)
device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu")
args.output_dir.mkdir(parents=True, exist_ok=True)
module, load_info = load_module(args.ckpt_path, device)
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.limit)
rows = []
with torch.no_grad():
for idx in indices:
pdb_name = dataset.pdb_names[idx]
out_path = args.output_dir / f"{pdb_name}.npy"
if out_path.exists() and not args.overwrite:
rows.append({"pdb_name": pdb_name, "status": "skipped_exists", "path": str(out_path)})
continue
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]
res_mask = torch.ones(1, num_res, device=device)
condition, _ = module.latent_encoder.forward_prior(trans_eq, rotmats_eq, seq, res_mask)
modes = condition["u_global"][0].detach().float().cpu().numpy()
if modes.ndim != 3:
raise ValueError(f"{pdb_name}: expected u_global [N,K,3], got {modes.shape}")
np.save(out_path, modes)
row = {
"pdb_name": pdb_name,
"status": "ok",
"num_res": int(num_res),
"num_modes": int(modes.shape[1]),
"path": str(out_path),
}
rows.append(row)
print(json.dumps(row, sort_keys=True))
summary_path = args.output_dir / "export_condition_modes_summary.json"
with summary_path.open("w") as handle:
json.dump({"ckpt_path": str(args.ckpt_path), "load_info": load_info, "rows": rows}, handle, indent=2)
print(f"Saved: {summary_path}")
if __name__ == "__main__":
main()