File size: 27,955 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
#!/usr/bin/env python
"""Diagnose the interface between projected MD coefficients and sampled q.

This is a diagnostic script only. It does not train, select checkpoints, or use
MD-derived quantities as an inference-time method. The MD frames are used here
only as held-out measurement labels to answer three questions:

1. controllability: if we feed clean frame-projected c*, does the generator move
   toward the matching MD frame?
2. robustness: if clean c* is perturbed toward q-like noise, how quickly does
   the generator lose the target?
3. qdist: does q(c|x_eq) match the empirical distribution of frame-projected c*?
"""
import argparse
import json
from pathlib import Path
import sys

import mdtraj
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.interpolant_bbflow import InterpolantBBFlow
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow
from bbflow.models.bbflow_module import BBFlowModule


def load_module(ckpt_path, device, num_timesteps):
    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.inference.interpolant.use_tqdm = False
    cfg.inference.interpolant.rots.sample_schedule = ckpt_cfg.interpolant.rots.sample_schedule
    cfg.inference.interpolant.trans.sample_schedule = ckpt_cfg.interpolant.trans.sample_schedule
    cfg.model.embed = ckpt_cfg.model.embed
    if num_timesteps is not None:
        cfg.inference.interpolant.rots.num_timesteps = int(num_timesteps)
        cfg.inference.interpolant.trans.num_timesteps = int(num_timesteps)

    module = BBFlowModule(cfg)
    checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    current = module.state_dict()
    compatible = {
        key: value
        for key, value in checkpoint["state_dict"].items()
        if key in current and current[key].shape == value.shape
    }
    missing, unexpected = module.load_state_dict(compatible, strict=False)
    module.to(device)
    module.eval()

    interpolant = InterpolantBBFlow(cfg.inference.interpolant)
    interpolant.set_device(device)
    return module, interpolant, {
        "loaded": len(compatible),
        "missing": len(missing),
        "unexpected": len(unexpected),
    }


def move_item_to_device(item, device):
    out = {}
    for key, value in item.items():
        if torch.is_tensor(value):
            out[key] = value[None].to(device)
        else:
            out[key] = value
    return out


def select_protein_indices(df, dataset, pdb_names, num_proteins, max_len):
    if pdb_names:
        wanted = [name.strip() for name in pdb_names.split(",") if name.strip()]
        by_name = {str(name): idx for idx, name in enumerate(dataset.pdb_names)}
        missing = [name for name in wanted if name not in by_name]
        if missing:
            raise ValueError(f"pdb_names not found in csv: {missing}")
        return [by_name[name] for name in wanted]

    candidates = list(range(len(df)))
    if "modeled_seq_len" in df.columns:
        candidates = [
            idx for idx in candidates
            if int(df.iloc[idx]["modeled_seq_len"]) <= int(max_len)
        ]
        candidates = sorted(candidates, key=lambda idx: int(df.iloc[idx]["modeled_seq_len"]))
    return candidates[: int(num_proteins)]


def infer_num_conformations(row):
    for key in [
        "num_conformations",
        "n_conformations",
        "num_frames",
        "n_frames",
        "traj_num_frames",
    ]:
        if key in row and pd.notna(row[key]):
            return int(row[key])

    if "folder" in row and pd.notna(row["folder"]):
        folder = Path(str(row["folder"]))
    elif "pdb_path" in row and pd.notna(row["pdb_path"]):
        folder = Path(str(row["pdb_path"])).parent
    else:
        folder = None
    name = str(row["name"]) if "name" in row else str(row.get("pdb_name", ""))
    if folder is not None and name:
        traj_path = folder / f"{name}_R1.xtc"
        if traj_path.exists():
            try:
                with mdtraj.open(str(traj_path)) as handle:
                    if hasattr(handle, "n_frames"):
                        return int(handle.n_frames)
                    return int(len(handle))
            except Exception:
                pass
    return None


def frame_indices_for_row(row, num_frames):
    total = infer_num_conformations(row)
    if total is None:
        name = str(row["name"]) if "name" in row else str(row.get("pdb_name", ""))
        if "folder" in row and pd.notna(row["folder"]):
            folder = str(row["folder"])
        elif "pdb_path" in row and pd.notna(row["pdb_path"]):
            folder = str(Path(str(row["pdb_path"])).parent)
        else:
            folder = "<missing folder and pdb_path columns>"
        raise RuntimeError(
            "Cannot determine the number of MD frames for "
            f"{name}. CSV has no frame-count column and {folder}/{name}_R1.xtc "
            "could not be opened. Refusing to use guessed frame indices."
        )
    if total <= 1:
        return [0]
    # Avoid frame 0 only; spread across the trajectory.
    return sorted(set(np.linspace(0, total - 1, int(num_frames), dtype=int).tolist()))


def ca_from_trans(trans):
    return trans.detach().float()


def rmsd_to_target(ca, target):
    target = target.to(device=ca.device, dtype=ca.dtype)
    diff = ca.float() - target.float()[None]
    return torch.sqrt(diff.square().mean(dim=(1, 2)).clamp_min(0.0))


def pairwise_target_rmsd(a, b):
    b = b.to(device=a.device, dtype=a.dtype)
    return float(torch.sqrt((a.float() - b.float()).square().mean()).detach().cpu().item())


def flattened_cosine(a, b):
    a = a.detach().float().reshape(-1)
    b = b.detach().float().reshape(-1).to(device=a.device)
    denom = a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8)
    return float((a * b).sum().div(denom).detach().cpu().item())


def norm_ratio(a, b):
    a = a.detach().float().reshape(-1)
    b = b.detach().float().reshape(-1).to(device=a.device)
    return float((a.norm() / b.norm().clamp_min(1e-8)).detach().cpu().item())


def repeat_condition(module, condition, batch_size):
    return module.latent_encoder.repeat_condition(condition, batch_size)


def clone_condition(condition):
    return {
        key: value.clone() if torch.is_tensor(value) else value
        for key, value in condition.items()
    }


def q_marginal_stats(module, prior_condition):
    second = module.latent_encoder.mixture_second_moment(prior_condition).float()
    logits = prior_condition["mixture_logits"].float()
    probs = torch.softmax(logits, dim=-1)
    mu = prior_condition["mixture_mu"].float()
    mean = torch.einsum("bm,bmk->bk", probs, mu)
    var = torch.diagonal(second, dim1=-2, dim2=-1) - mean.square()
    return mean, var.clamp_min(1e-8), second


def build_cstar_condition(module, item, prior_condition, mean_disp=None):
    return module.latent_encoder.frame_condition_from_projection(
        item["trans_1"],
        item["trans_equilibrium"],
        item["rotmats_equilibrium"],
        torch.ones_like(item["trans_equilibrium"][..., 0]),
        prior_condition,
        mean_disp=mean_disp,
    )


def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device):
    disps = []
    for frame_id in frame_ids:
        row = dataset.csv.iloc[protein_idx]
        item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device)
        disp = module.latent_encoder.relative_displacement(
            item["trans_1"].float(),
            item["trans_equilibrium"].float(),
            torch.ones_like(item["trans_equilibrium"][..., 0]),
        )
        disps.append(disp)
    return torch.cat(disps, dim=0).mean(dim=0, keepdim=True)


def sample_final_ca(module, interpolant, item, condition, num_samples, seed, final_only=True):
    device = item["trans_equilibrium"].device
    _, num_res = item["trans_equilibrium"].shape[:2]
    torch.manual_seed(int(seed))
    np.random.seed(int(seed) % (2**32 - 1))
    z = repeat_condition(module, condition, int(num_samples))
    with torch.no_grad():
        atom37_traj, _, _ = interpolant.sample(
            int(num_samples),
            int(num_res),
            module.model,
            item["trans_equilibrium"].repeat(int(num_samples), 1, 1),
            item["rotmats_equilibrium"].repeat(int(num_samples), 1, 1, 1),
            item["seq"].repeat(int(num_samples), 1, 1),
            z=z,
            return_trajectory=not final_only,
            cache_static_features=True,
        )
    final_atom37 = torch.stack(atom37_traj, dim=1)[:, -1]
    return final_atom37[:, :, 1, :].detach().float()


def run_qdist(args, module, dataset, indices, device):
    rows = []
    for protein_idx in indices:
        row = dataset.csv.iloc[protein_idx]
        frame_ids = frame_indices_for_row(row, args.num_frames)
        eq_item = move_item_to_device(dataset[(protein_idx, 0, frame_ids[0])], device)
        res_mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0])
        with torch.no_grad():
            prior, _ = module.latent_encoder.forward_prior(
                eq_item["trans_equilibrium"],
                eq_item["rotmats_equilibrium"],
                eq_item["seq"],
                res_mask,
            )
            mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device)
            cstars = []
            for frame_id in frame_ids:
                item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device)
                _, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp)
                cstars.append(coeff.detach().float())
            cstar = torch.cat(cstars, dim=0)
            q_mean, q_var, _ = q_marginal_stats(module, prior)
            q_condition = repeat_condition(module, prior, max(args.num_q_samples, 2))
            q_coeff, _ = module.latent_encoder.sample_coefficients_from_q(q_condition)
            q_coeff = q_coeff.detach().float()

        cstar_mean = cstar.mean(dim=0)
        cstar_var = cstar.var(dim=0, unbiased=False).clamp_min(1e-8)
        rows.append({
            "pdb_name": str(row["name"]),
            "num_res": int(eq_item["trans_equilibrium"].shape[1]),
            "num_frames": int(cstar.shape[0]),
            "cstar_norm_mean": float(cstar.norm(dim=-1).mean().cpu()),
            "q_norm_mean": float(q_coeff.norm(dim=-1).mean().cpu()),
            "q_over_cstar_norm_mean": float((q_coeff.norm(dim=-1).mean() / cstar.norm(dim=-1).mean().clamp_min(1e-8)).cpu()),
            "diag_var_rel_l1": float(((q_var[0] - cstar_var).abs().mean() / cstar_var.abs().mean().clamp_min(1e-8)).cpu()),
            "mean_rel_l2": float(((q_mean[0] - cstar_mean).norm() / cstar_mean.norm().clamp_min(1e-8)).cpu()),
            "q_nll_on_cstar": float(module.latent_encoder.mixture_nll(repeat_condition(module, prior, cstar.shape[0]), cstar).detach().cpu()),
        })
    return pd.DataFrame(rows)


def run_controllability(args, module, interpolant, dataset, indices, device):
    rows = []
    for protein_idx in indices:
        row = dataset.csv.iloc[protein_idx]
        frame_ids = frame_indices_for_row(row, max(args.num_frames, 2))
        if len(frame_ids) < 2:
            continue
        a_id, b_id = int(frame_ids[0]), int(frame_ids[-1])
        a_item = move_item_to_device(dataset[(protein_idx, 0, a_id)], device)
        b_item = move_item_to_device(dataset[(protein_idx, 0, b_id)], device)
        res_mask = torch.ones_like(a_item["trans_equilibrium"][..., 0])
        with torch.no_grad():
            prior, _ = module.latent_encoder.forward_prior(
                a_item["trans_equilibrium"],
                a_item["rotmats_equilibrium"],
                a_item["seq"],
                res_mask,
            )
            mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device)
            cond_a, coeff_a = build_cstar_condition(module, a_item, prior, mean_disp=mean_disp)
            cond_b, coeff_b = build_cstar_condition(module, b_item, prior, mean_disp=mean_disp)
        ca_a = ca_from_trans(a_item["trans_1"][0])
        ca_b = ca_from_trans(b_item["trans_1"][0])
        gen_a = sample_final_ca(module, interpolant, a_item, cond_a, args.samples_per_condition, args.seed, args.final_only)
        gen_b = sample_final_ca(module, interpolant, a_item, cond_b, args.samples_per_condition, args.seed, args.final_only)
        a_to_a = rmsd_to_target(gen_a, ca_a)
        a_to_b = rmsd_to_target(gen_a, ca_b)
        b_to_a = rmsd_to_target(gen_b, ca_a)
        b_to_b = rmsd_to_target(gen_b, ca_b)
        rows.append({
            "pdb_name": str(row["name"]),
            "num_res": int(a_item["trans_equilibrium"].shape[1]),
            "frame_a": a_id,
            "frame_b": b_id,
            "target_pair_rmsd": pairwise_target_rmsd(ca_a, ca_b),
            "coeff_pair_l2": float((coeff_a - coeff_b).norm().detach().cpu()),
            "a_condition_correct_fraction": float((a_to_a < a_to_b).float().mean().cpu()),
            "b_condition_correct_fraction": float((b_to_b < b_to_a).float().mean().cpu()),
            "mean_correct_fraction": float(torch.cat([(a_to_a < a_to_b).float(), (b_to_b < b_to_a).float()]).mean().cpu()),
            "a_margin_rmsd_b_minus_a": float((a_to_b - a_to_a).mean().cpu()),
            "b_margin_rmsd_a_minus_b": float((b_to_a - b_to_b).mean().cpu()),
            "gen_centroid_pair_rmsd": pairwise_target_rmsd(gen_a.mean(dim=0), gen_b.mean(dim=0)),
        })
    return pd.DataFrame(rows)


def project_generated_coefficients(module, trans_gen, item, prior, mean_disp):
    device = trans_gen.device
    trans_eq = item["trans_equilibrium"].to(device=device, dtype=trans_gen.dtype)
    res_mask = torch.ones_like(trans_eq[..., 0], device=device)
    u_global = prior["u_global"].to(device=device, dtype=trans_gen.dtype)
    disp = module.latent_encoder.relative_displacement(
        trans_gen.float(),
        trans_eq.float(),
        res_mask,
    )
    disp = (disp - mean_disp.to(device=disp.device, dtype=disp.dtype)) * res_mask.float()[:, :, None]
    return module.latent_encoder.project_displacement_lstsq(
        disp,
        u_global,
        res_mask,
        ridge=module.latent_encoder.q_lstsq_ridge,
        detach_modes=True,
    )


def choose_matched_distance_pair(candidates):
    """Pick frames with similar ||x-x_eq|| but large c*/target separation."""
    best = None
    for i in range(len(candidates)):
        for j in range(i + 1, len(candidates)):
            a, b = candidates[i], candidates[j]
            dist_gap = abs(a["eq_rmsd"] - b["eq_rmsd"])
            dist_scale = max(a["eq_rmsd"], b["eq_rmsd"], 1e-8)
            dist_rel_gap = dist_gap / dist_scale
            if dist_rel_gap > 0.15:
                continue
            coeff_gap = float((a["coeff"] - b["coeff"]).norm().detach().cpu().item())
            target_gap = pairwise_target_rmsd(a["trans_1"], b["trans_1"])
            score = coeff_gap * target_gap / (1.0 + 10.0 * dist_rel_gap)
            row = {
                "i": i,
                "j": j,
                "score": score,
                "eq_rmsd_gap": dist_gap,
                "eq_rmsd_rel_gap": dist_rel_gap,
                "coeff_pair_l2": coeff_gap,
                "target_pair_rmsd": target_gap,
            }
            if best is None or score > best["score"]:
                best = row
    if best is not None:
        return best

    # If no pair passes the strict 15% distance match, still return the least
    # biased high-separation pair and record the larger rel gap in the output.
    for i in range(len(candidates)):
        for j in range(i + 1, len(candidates)):
            a, b = candidates[i], candidates[j]
            dist_gap = abs(a["eq_rmsd"] - b["eq_rmsd"])
            dist_scale = max(a["eq_rmsd"], b["eq_rmsd"], 1e-8)
            dist_rel_gap = dist_gap / dist_scale
            coeff_gap = float((a["coeff"] - b["coeff"]).norm().detach().cpu().item())
            target_gap = pairwise_target_rmsd(a["trans_1"], b["trans_1"])
            score = coeff_gap * target_gap / (1.0 + 10.0 * dist_rel_gap)
            row = {
                "i": i,
                "j": j,
                "score": score,
                "eq_rmsd_gap": dist_gap,
                "eq_rmsd_rel_gap": dist_rel_gap,
                "coeff_pair_l2": coeff_gap,
                "target_pair_rmsd": target_gap,
            }
            if best is None or score > best["score"]:
                best = row
    return best


def run_matched_controllability(args, module, interpolant, dataset, indices, device):
    rows = []
    for protein_idx in indices:
        row = dataset.csv.iloc[protein_idx]
        frame_ids = frame_indices_for_row(row, args.num_frames)
        if len(frame_ids) < 2:
            continue
        eq_item = move_item_to_device(dataset[(protein_idx, 0, int(frame_ids[0]))], device)
        res_mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0])
        with torch.no_grad():
            prior, _ = module.latent_encoder.forward_prior(
                eq_item["trans_equilibrium"],
                eq_item["rotmats_equilibrium"],
                eq_item["seq"],
                res_mask,
            )
            mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device)
            candidates = []
            for frame_id in frame_ids:
                item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device)
                cond, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp)
                trans_1 = item["trans_1"][0].detach().float()
                trans_eq = item["trans_equilibrium"][0].detach().float()
                candidates.append({
                    "frame_id": int(frame_id),
                    "item": item,
                    "condition": cond,
                    "coeff": coeff.detach().float(),
                    "trans_1": trans_1,
                    "eq_rmsd": pairwise_target_rmsd(trans_1, trans_eq),
                })
        pair = choose_matched_distance_pair(candidates)
        if pair is None:
            continue
        a = candidates[pair["i"]]
        b = candidates[pair["j"]]
        gen_a = sample_final_ca(
            module, interpolant, a["item"], a["condition"],
            args.samples_per_condition, args.seed, args.final_only,
        )
        gen_b = sample_final_ca(
            module, interpolant, b["item"], b["condition"],
            args.samples_per_condition, args.seed, args.final_only,
        )
        mean_gen_a = gen_a.mean(dim=0, keepdim=True)
        mean_gen_b = gen_b.mean(dim=0, keepdim=True)
        generated_delta = mean_gen_b[0] - mean_gen_a[0]
        target_delta = b["trans_1"].to(generated_delta.device) - a["trans_1"].to(generated_delta.device)

        coeff_gen_a = project_generated_coefficients(
            module, mean_gen_a, a["item"], prior, mean_disp
        )
        coeff_gen_b = project_generated_coefficients(
            module, mean_gen_b, b["item"], prior, mean_disp
        )
        a_coeff = a["coeff"].to(device=coeff_gen_a.device, dtype=coeff_gen_a.dtype)
        b_coeff = b["coeff"].to(device=coeff_gen_b.device, dtype=coeff_gen_b.dtype)
        coeff_gen_delta = coeff_gen_b - coeff_gen_a
        coeff_delta = b_coeff - a_coeff

        cycle_a = float(((coeff_gen_a - a_coeff).norm() / a_coeff.norm().clamp_min(1e-8)).detach().cpu().item())
        cycle_b = float(((coeff_gen_b - b_coeff).norm() / b_coeff.norm().clamp_min(1e-8)).detach().cpu().item())
        rows.append({
            "pdb_name": str(row["name"]),
            "num_res": int(eq_item["trans_equilibrium"].shape[1]),
            "frame_a": int(a["frame_id"]),
            "frame_b": int(b["frame_id"]),
            "eq_rmsd_a": float(a["eq_rmsd"]),
            "eq_rmsd_b": float(b["eq_rmsd"]),
            "eq_rmsd_rel_gap": float(pair["eq_rmsd_rel_gap"]),
            "target_pair_rmsd": float(pair["target_pair_rmsd"]),
            "coeff_pair_l2": float(pair["coeff_pair_l2"]),
            "generated_pair_rmsd": pairwise_target_rmsd(mean_gen_a[0], mean_gen_b[0]),
            "direction_score": flattened_cosine(generated_delta, target_delta),
            "gain_score": norm_ratio(generated_delta, target_delta),
            "coeff_direction_score": flattened_cosine(coeff_gen_delta, coeff_delta),
            "coeff_gain_score": norm_ratio(coeff_gen_delta, coeff_delta),
            "cycle_error_a": cycle_a,
            "cycle_error_b": cycle_b,
            "cycle_error_mean": 0.5 * (cycle_a + cycle_b),
        })
    return pd.DataFrame(rows)


def perturb_condition_coefficients(module, prior, base_coeff, q_var, rotmats_eq, res_mask, sigma, seed):
    gen = torch.Generator(device=base_coeff.device)
    gen.manual_seed(int(seed))
    noise = torch.randn(base_coeff.shape, generator=gen, device=base_coeff.device)
    coeff = base_coeff.float() + float(sigma) * torch.sqrt(q_var).to(base_coeff.device) * noise
    return module.latent_encoder.condition_from_mode_coefficients(
        prior["u_global"],
        coeff,
        rotmats_eq,
        res_mask,
        extra={
            key: prior[key]
            for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
            if key in prior
        },
    )


def run_robustness(args, module, interpolant, dataset, indices, device):
    rows = []
    sigmas = [float(x) for x in args.sigmas.split(",") if x.strip()]
    for protein_idx in indices:
        row = dataset.csv.iloc[protein_idx]
        frame_ids = frame_indices_for_row(row, args.num_frames)
        target_id = int(frame_ids[len(frame_ids) // 2])
        item = move_item_to_device(dataset[(protein_idx, 0, target_id)], device)
        res_mask = torch.ones_like(item["trans_equilibrium"][..., 0])
        with torch.no_grad():
            prior, _ = module.latent_encoder.forward_prior(
                item["trans_equilibrium"],
                item["rotmats_equilibrium"],
                item["seq"],
                res_mask,
            )
            mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device)
            clean_cond, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp)
            _, q_var, _ = q_marginal_stats(module, prior)
        target = ca_from_trans(item["trans_1"][0])
        clean_gen = sample_final_ca(module, interpolant, item, clean_cond, args.samples_per_condition, args.seed, args.final_only)
        clean_rmsd = rmsd_to_target(clean_gen, target).mean()
        for sigma in sigmas:
            if sigma == 0.0:
                cond = clean_cond
            else:
                cond = perturb_condition_coefficients(
                    module,
                    prior,
                    coeff,
                    q_var,
                    item["rotmats_equilibrium"],
                    res_mask,
                    sigma,
                    args.seed + int(1000 * sigma) + protein_idx,
                )
            gen = sample_final_ca(module, interpolant, item, cond, args.samples_per_condition, args.seed, args.final_only)
            rows.append({
                "pdb_name": str(row["name"]),
                "num_res": int(item["trans_equilibrium"].shape[1]),
                "frame": target_id,
                "sigma": sigma,
                "target_rmsd": float(rmsd_to_target(gen, target).mean().cpu()),
                "target_rmsd_delta_vs_clean": float((rmsd_to_target(gen, target).mean() - clean_rmsd).cpu()),
                "centroid_drift_from_clean": pairwise_target_rmsd(gen.mean(dim=0), clean_gen.mean(dim=0)),
            })
    return pd.DataFrame(rows)


def summarize(df, task):
    numeric = df.select_dtypes(include=[np.number])
    out = {"task": task, "n_rows": int(len(df))}
    for col in numeric.columns:
        out[f"{col}_mean"] = float(numeric[col].mean())
        out[f"{col}_median"] = float(numeric[col].median())
    return out


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--task",
        choices=["controllability", "matched_controllability", "robustness", "qdist"],
        required=True,
    )
    parser.add_argument("--ckpt_path", required=True)
    parser.add_argument("--csv_path", required=True)
    parser.add_argument("--out_dir", required=True)
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--pdb_names", default="")
    parser.add_argument("--num_proteins", type=int, default=12)
    parser.add_argument("--max_len", type=int, default=450)
    parser.add_argument("--num_frames", type=int, default=6)
    parser.add_argument("--num_q_samples", type=int, default=256)
    parser.add_argument("--samples_per_condition", type=int, default=4)
    parser.add_argument("--num_timesteps", type=int, default=20)
    parser.add_argument("--sigmas", default="0,0.25,0.5,1.0")
    parser.add_argument("--seed", type=int, default=20260710)
    parser.add_argument("--final_only", action="store_true", default=True)
    args = parser.parse_args()

    torch.manual_seed(args.seed)
    np.random.seed(args.seed % (2**32 - 1))
    device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu")
    module, interpolant, load_info = load_module(args.ckpt_path, device, args.num_timesteps)

    df = pd.read_csv(args.csv_path)
    if "folder" not in df.columns:
        if "pdb_path" not in df.columns:
            raise RuntimeError(
                "CSV must contain either a folder column or a pdb_path column "
                "so MD trajectory paths can be resolved scientifically."
            )
        df = df.copy()
        df["folder"] = df["pdb_path"].map(lambda path: str(Path(str(path)).parent))
    dataset = PDBDatasetBBFlow(df)
    indices = select_protein_indices(df, dataset, args.pdb_names, args.num_proteins, args.max_len)
    if not indices:
        raise RuntimeError("No proteins selected")

    if args.task == "controllability":
        result = run_controllability(args, module, interpolant, dataset, indices, device)
    elif args.task == "matched_controllability":
        result = run_matched_controllability(args, module, interpolant, dataset, indices, device)
    elif args.task == "robustness":
        result = run_robustness(args, module, interpolant, dataset, indices, device)
    else:
        result = run_qdist(args, module, dataset, indices, device)

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    csv_path = out_dir / f"{args.task}.csv"
    json_path = out_dir / f"{args.task}_summary.json"
    result.to_csv(csv_path, index=False)
    summary = {
        "ckpt_path": str(args.ckpt_path),
        "csv_path": str(args.csv_path),
        "load_info": load_info,
        "selected_pdb_names": [str(dataset.pdb_names[idx]) for idx in indices],
        "summary": summarize(result, args.task),
    }
    json_path.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
    print(json.dumps(summary, indent=2, sort_keys=True))
    print(f"[saved] {csv_path}")
    print(f"[saved] {json_path}")


if __name__ == "__main__":
    main()