Download bbflow_base/scripts/diagnose_z.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/diagnose_z.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/diagnose_z.py
-
curl -L -o diagnose_z.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/diagnose_z.py
12.3 kB
| import argparse | |
| import os | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from omegaconf import OmegaConf | |
| from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb | |
| from bbflow.models.bbflow_module import BBFlowModule | |
| from bbflow.data.interpolant_bbflow import InterpolantBBFlow | |
| def load_module(ckpt_path, device): | |
| ckpt_path = Path(ckpt_path) | |
| cfg_path = ckpt_path.parent / "config.yaml" | |
| if not cfg_path.exists(): | |
| raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") | |
| repo_root = Path(__file__).resolve().parents[1] | |
| 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.inference.interpolant.use_tqdm = False | |
| cfg.model.embed = ckpt_cfg.model.embed | |
| module = BBFlowModule(cfg) | |
| ckpt = torch.load(ckpt_path, map_location="cpu") | |
| 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 | |
| } | |
| module.load_state_dict(compatible_state, strict=False) | |
| module.to(device) | |
| module.eval() | |
| return module, cfg | |
| def pairwise_ca_rmsd(ca_coords): | |
| flat = ca_coords.reshape(ca_coords.shape[0], -1) | |
| diff = flat[:, None, :] - flat[None, :, :] | |
| return np.sqrt(np.mean(diff ** 2, axis=-1)) | |
| def summarize_rmsd(ca_coords, num_z, samples_per_z): | |
| rmsd = pairwise_ca_rmsd(ca_coords) | |
| msd = rmsd ** 2 | |
| within, between, within_msd, between_msd = [], [], [], [] | |
| for i in range(num_z * samples_per_z): | |
| zi = i // samples_per_z | |
| for j in range(i + 1, num_z * samples_per_z): | |
| zj = j // samples_per_z | |
| if zi == zj: | |
| within.append(float(rmsd[i, j])) | |
| within_msd.append(float(msd[i, j])) | |
| else: | |
| between.append(float(rmsd[i, j])) | |
| between_msd.append(float(msd[i, j])) | |
| within_mean = float(np.mean(within)) if within else 0.0 | |
| between_mean = float(np.mean(between)) if between else 0.0 | |
| grouped = ca_coords.reshape(num_z, samples_per_z, *ca_coords.shape[1:]) | |
| centroids = grouped.mean(axis=1) | |
| centroid_rmsd = pairwise_ca_rmsd(centroids) | |
| centroid_between = [ | |
| float(centroid_rmsd[i, j]) | |
| for i in range(num_z) | |
| for j in range(i + 1, num_z) | |
| ] | |
| centroid_between_mean = float(np.mean(centroid_between)) if centroid_between else 0.0 | |
| within_msd_mean = float(np.mean(within_msd)) if within_msd else 0.0 | |
| between_msd_mean = float(np.mean(between_msd)) if between_msd else 0.0 | |
| z_signal_msd = max(0.0, between_msd_mean - within_msd_mean) | |
| z_signal_rmsd = float(np.sqrt(z_signal_msd)) | |
| return { | |
| "within_z_mean": within_mean, | |
| "between_z_mean": between_mean, | |
| "between_over_within": between_mean / max(within_mean, 1e-8), | |
| "within_z_msd_mean": within_msd_mean, | |
| "between_z_msd_mean": between_msd_mean, | |
| "z_signal_msd": z_signal_msd, | |
| "z_signal_rmsd": z_signal_rmsd, | |
| "z_signal_over_within": z_signal_rmsd / max(within_mean, 1e-8), | |
| "centroid_between_z_mean": centroid_between_mean, | |
| "centroid_between_over_within": centroid_between_mean / max(within_mean, 1e-8), | |
| } | |
| def select_indices(dataset, pdb_name, num_proteins): | |
| if pdb_name is not None: | |
| names = [name.strip() for name in pdb_name.split(",") if name.strip()] | |
| indices = [] | |
| for name in names: | |
| matches = [i for i, 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 | |
| return list(range(min(num_proteins, len(dataset)))) | |
| def clone_condition(condition): | |
| return { | |
| key: value.clone() if torch.is_tensor(value) else value | |
| for key, value in condition.items() | |
| } | |
| def scale_condition(condition, factor): | |
| out = clone_condition(condition) | |
| for key in ["node_cond", "edge_cond"]: | |
| if key in out: | |
| out[key] = out[key] * factor | |
| return out | |
| def perturb_mode_channel(condition, mode_idx, factor): | |
| out = clone_condition(condition) | |
| if "node_cond" in out: | |
| out["node_cond"][..., mode_idx] = out["node_cond"][..., mode_idx] * factor | |
| if "edge_cond" in out: | |
| out["edge_cond"][..., mode_idx] = out["edge_cond"][..., mode_idx] * factor | |
| return out | |
| def repeat_condition(module, condition, batch_size): | |
| return module.latent_encoder.repeat_condition(condition, batch_size) | |
| def condition_abs_std(condition): | |
| values = [] | |
| for key in ["node_cond", "edge_cond"]: | |
| if key in condition: | |
| values.append(condition[key].detach().float().reshape(-1)) | |
| merged = torch.cat(values) if values else torch.zeros(1) | |
| return float(merged.abs().mean().cpu().item()), float(merged.std().cpu().item()) | |
| def make_z_variants(module, trans_eq, rotmats_eq, seq, res_mask, num_z, z_delta, mode): | |
| base_condition = module.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask) | |
| variants = [] | |
| with torch.no_grad(): | |
| center = (num_z - 1) / 2.0 | |
| if mode == "scale": | |
| for z_idx in range(num_z): | |
| factor = 1.0 + (z_idx - center) * z_delta | |
| variants.append(scale_condition(base_condition, factor)) | |
| else: | |
| num_modes = int(base_condition["node_cond"].shape[-1]) | |
| for z_idx in range(num_z): | |
| mode_idx = z_idx % num_modes | |
| factor = 1.0 + (z_idx - center) * z_delta | |
| variants.append(perturb_mode_channel(base_condition, mode_idx, factor)) | |
| return base_condition, variants | |
| def diagnose_one(module, cfg, interpolant, dataset, idx, args, device): | |
| item = dataset[idx] | |
| pdb_name = item["pdb_name"] | |
| 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) | |
| all_ca = [] | |
| labels = [] | |
| with torch.no_grad(): | |
| base_condition, z_variants = make_z_variants( | |
| module, trans_eq, rotmats_eq, seq, res_mask, | |
| args.num_z, args.z_delta, args.z_mode, | |
| ) | |
| for z_idx, z_one in enumerate(z_variants): | |
| z = repeat_condition(module, z_one, args.samples_per_z) | |
| atom37_traj, _, _ = interpolant.sample( | |
| args.samples_per_z, | |
| num_res, | |
| module.model, | |
| trans_eq.repeat(args.samples_per_z, 1, 1), | |
| rotmats_eq.repeat(args.samples_per_z, 1, 1, 1), | |
| seq.repeat(args.samples_per_z, 1, 1), | |
| z=z, | |
| ) | |
| final_atom37 = torch.stack(atom37_traj, dim=1)[:, -1] | |
| ca = final_atom37[:, :, 1, :].detach().cpu().numpy() | |
| all_ca.append(ca) | |
| labels.extend([f"z{z_idx}_sample{i}" for i in range(args.samples_per_z)]) | |
| all_ca = np.concatenate(all_ca, axis=0) | |
| rmsd = pairwise_ca_rmsd(all_ca) | |
| summary = summarize_rmsd(all_ca, args.num_z, args.samples_per_z) | |
| base_abs, base_std = condition_abs_std(base_condition) | |
| summary.update({ | |
| "pdb_name": pdb_name, | |
| "num_res": int(num_res), | |
| "num_z": args.num_z, | |
| "samples_per_z": args.samples_per_z, | |
| "z_delta": args.z_delta, | |
| "z_mode": args.z_mode, | |
| "base_condition_abs_mean": base_abs, | |
| "base_condition_std": base_std, | |
| "base_energy_mean": float(base_condition["energy"].detach().float().mean().cpu().item()), | |
| "base_effective_modes": float(module.latent_encoder.motion_metrics(base_condition, res_mask)["latent_effective_modes"].detach().cpu().item()), | |
| }) | |
| out_dir = Path(args.output_dir) / pdb_name | |
| os.makedirs(out_dir, exist_ok=True) | |
| np.save(out_dir / "ca_coords.npy", all_ca) | |
| np.save(out_dir / "ca_rmsd_matrix.npy", rmsd) | |
| pd.DataFrame(rmsd, index=labels, columns=labels).to_csv(out_dir / "ca_rmsd_matrix.csv") | |
| pd.Series(summary).to_json(out_dir / "summary.json", indent=2) | |
| return summary | |
| def aggregate(rows): | |
| df = pd.DataFrame(rows) | |
| ratio = df["between_over_within"] | |
| centroid_ratio = df["centroid_between_over_within"] | |
| signal_ratio = df["z_signal_over_within"] | |
| return { | |
| "num_proteins": int(len(df)), | |
| "within_z_mean_mean": float(df["within_z_mean"].mean()), | |
| "between_z_mean_mean": float(df["between_z_mean"].mean()), | |
| "between_over_within_mean": float(ratio.mean()), | |
| "between_over_within_std": float(ratio.std(ddof=0)), | |
| "between_over_within_min": float(ratio.min()), | |
| "between_over_within_max": float(ratio.max()), | |
| "fraction_gt_1.0": float((ratio > 1.0).mean()), | |
| "fraction_gt_1.2": float((ratio > 1.2).mean()), | |
| "centroid_between_z_mean_mean": float(df["centroid_between_z_mean"].mean()), | |
| "centroid_between_over_within_mean": float(centroid_ratio.mean()), | |
| "centroid_between_over_within_std": float(centroid_ratio.std(ddof=0)), | |
| "centroid_between_over_within_min": float(centroid_ratio.min()), | |
| "centroid_between_over_within_max": float(centroid_ratio.max()), | |
| "z_signal_rmsd_mean": float(df["z_signal_rmsd"].mean()), | |
| "z_signal_over_within_mean": float(signal_ratio.mean()), | |
| "z_signal_over_within_std": float(signal_ratio.std(ddof=0)), | |
| "z_signal_over_within_min": float(signal_ratio.min()), | |
| "z_signal_over_within_max": float(signal_ratio.max()), | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--ckpt_path", required=True) | |
| parser.add_argument("--csv_path", required=True) | |
| parser.add_argument("--pdb_name", default=None) | |
| parser.add_argument("--num_proteins", type=int, default=10) | |
| parser.add_argument("--output_dir", default="outputs/diagnose_z") | |
| parser.add_argument("--num_z", type=int, default=8) | |
| parser.add_argument("--samples_per_z", type=int, default=8) | |
| parser.add_argument("--z_delta", type=float, default=0.25) | |
| parser.add_argument("--z_mode", choices=["dimension", "scale"], default="dimension") | |
| parser.add_argument("--device", default="cuda") | |
| args = parser.parse_args() | |
| device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") | |
| module, cfg = load_module(args.ckpt_path, device) | |
| if not getattr(module, "latent_enabled", False): | |
| raise ValueError("Checkpoint/config has latent.enable=false; diagnose_z requires latent model.") | |
| csv = pd.read_csv(args.csv_path) | |
| dataset = PDBDatasetBBFlowFromPdb(csv, sort=False) | |
| indices = select_indices(dataset, args.pdb_name, args.num_proteins) | |
| interpolant = InterpolantBBFlow(cfg.inference.interpolant) | |
| interpolant.set_device(device) | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| rows = [] | |
| for n, idx in enumerate(indices, start=1): | |
| row = diagnose_one(module, cfg, interpolant, dataset, idx, args, device) | |
| rows.append(row) | |
| print( | |
| f"[{n}/{len(indices)}] {row['pdb_name']} " | |
| f"raw_between/within={row['between_over_within']:.4f} " | |
| f"centroid_between/within={row['centroid_between_over_within']:.4f} " | |
| f"z_signal_rmsd={row['z_signal_rmsd']:.4f} " | |
| f"within={row['within_z_mean']:.4f}" | |
| ) | |
| df = pd.DataFrame(rows) | |
| agg = aggregate(rows) | |
| out_dir = Path(args.output_dir) | |
| df.to_csv(out_dir / "summary_by_protein.csv", index=False) | |
| pd.Series(agg).to_json(out_dir / "summary_aggregate.json", indent=2) | |
| print("\nAggregate") | |
| print(pd.Series(agg).to_string()) | |
| print(f"Wrote z diagnostics to {out_dir}") | |
| if __name__ == "__main__": | |
| main() |