File size: 5,144 Bytes
5b2e6c5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | import argparse
from pathlib import Path
from types import SimpleNamespace
import mdtraj
import pandas as pd
import torch
from tqdm.auto import tqdm
from bbflow.data.alignment import ALIGNMENT_VERSION
from bbflow.data.utils import frames_from_pdb
from bbflow.models.latent import LatentEncoder
def pdb_name_from_row(row):
if "name" in row and pd.notna(row["name"]):
return str(row["name"])
if "pdb_name" in row and pd.notna(row["pdb_name"]):
return str(row["pdb_name"])
raise KeyError("CSV row has neither 'name' nor 'pdb_name'")
def entry_dir_from_row(row, atlas_root, name):
if "folder" in row and pd.notna(row["folder"]):
folder = Path(str(row["folder"]))
if folder.exists():
return folder
return atlas_root / name
def load_ca_md_frames(entry_dir, name):
eq_path = entry_dir / f"{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 = []
frame_counts = []
for traj_idx in range(1, 4):
xtc_path = entry_dir / f"{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)
ca = torch.tensor(traj.xyz, dtype=torch.float32) * 10.0
ca = ca - ca.mean(dim=1, keepdim=True)
frames.append(ca)
frame_counts.append(int(ca.shape[0]))
return torch.cat(frames, dim=0), frame_counts
def summarize_target(label):
rmsf = label["rmsf"]
local_cov = label["local_cov"]
cross_cov = label["cross_cov"]
offdiag = cross_cov[~torch.eye(cross_cov.shape[0], dtype=torch.bool)]
return {
"rmsf_mean": float(rmsf.mean().item()),
"rmsf_std": float(rmsf.std().item()),
"local_cov_abs_mean": float(local_cov.abs().mean().item()),
"cross_cov_offdiag_abs_mean": float(offdiag.abs().mean().item()) if offdiag.numel() else 0.0,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--atlas_root", required=True)
parser.add_argument("--csv", action="append", required=True)
parser.add_argument("--out_path", required=True)
parser.add_argument("--shape_k", type=int, default=5, help="Kept for old bash compatibility; unused by motion targets.")
parser.add_argument("--num_modes", type=int, default=8, help="Number of oracle PCA modes to store for oracle c* training.")
parser.add_argument("--max_entries", type=int, default=None)
args = parser.parse_args()
atlas_root = Path(args.atlas_root)
out_path = Path(args.out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
dfs = []
for csv_path in args.csv:
df = pd.read_csv(csv_path)
df["_source_csv"] = str(csv_path)
dfs.append(df)
table = pd.concat(dfs, ignore_index=True)
table["_name"] = table.apply(pdb_name_from_row, axis=1)
table = table.drop_duplicates("_name").reset_index(drop=True)
if args.max_entries is not None:
table = table.iloc[:args.max_entries].copy()
latent = LatentEncoder(SimpleNamespace(dim=16, num_modes=args.num_modes, z_stochastic=False))
motion_targets = {}
rows = []
for _, row in tqdm(table.iterrows(), total=len(table), desc="motion targets"):
name = row["_name"]
entry_dir = entry_dir_from_row(row, atlas_root, name)
trans_eq, _, _, _ = frames_from_pdb(entry_dir / f"{name}.pdb")
frames, frame_counts = load_ca_md_frames(entry_dir, name)
if frames.shape[1] != trans_eq.shape[0]:
raise ValueError(
f"Length mismatch for {name}: MD CA {frames.shape[1]} vs equilibrium {trans_eq.shape[0]}"
)
res_mask = torch.ones(trans_eq.shape[0], dtype=torch.float32)
label = latent.compute_motion_targets(frames, trans_eq, res_mask, num_modes=latent.num_modes)
motion_targets[name] = label
if len(name) == 5:
motion_targets[f"{name[:4]}_{name[4]}"] = label
rows.append({
"name": name,
"entry_dir": str(entry_dir),
"num_frames": int(frames.shape[0]),
"traj_frame_counts": ",".join(map(str, frame_counts)),
"num_res": int(trans_eq.shape[0]),
**summarize_target(label),
})
payload = {
"motion_targets": motion_targets,
"target_type": "centered_local_and_cross_covariance",
"alignment_version": ALIGNMENT_VERSION,
"num_entries": len(rows),
}
torch.save(payload, out_path)
pd.DataFrame(rows).to_csv(out_path.with_suffix(".tsv"), sep="\t", index=False)
print(f"Wrote {len(rows)} motion targets to {out_path}")
print(f"Wrote summary to {out_path.with_suffix('.tsv')}")
if __name__ == "__main__":
main() |