File size: 4,580 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
#!/usr/bin/env python
"""Report the centered MD-PCA projection ceiling stored in a motion-target cache."""

import argparse
import csv
import json
import math
import statistics
from pathlib import Path

import torch

from bbflow.data.alignment import require_alignment_version


def target_pca_metrics(target, num_modes):
    mask = torch.as_tensor(target["res_mask"], dtype=torch.float64)
    local_cov = torch.as_tensor(target["local_cov"], dtype=torch.float64)
    energy = torch.as_tensor(target["oracle_energy"], dtype=torch.float64)
    mean_disp = torch.as_tensor(target["oracle_mean_disp"], dtype=torch.float64)
    if int(num_modes) > int(energy.numel()):
        raise ValueError(
            f"Requested K={num_modes}, but cache contains only {energy.numel()} PCA modes"
        )

    fluctuation_energy = (
        torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1) * mask
    ).sum()
    pca_energy = energy[: int(num_modes)].clamp_min(0.0).sum()
    explained = (pca_energy / fluctuation_energy.clamp_min(1e-12)).clamp(0.0, 1.0)
    mean_offset_energy = (mean_disp.square().sum(dim=-1) * mask).sum()
    total_energy = mean_offset_energy + fluctuation_energy

    return {
        "num_res": int(mask.sum().item()),
        "num_modes": int(num_modes),
        "pca_energy": float(pca_energy.item()),
        "fluctuation_energy": float(fluctuation_energy.item()),
        "pca_explained_fraction": float(explained.item()),
        "pca_optimal_relative_rmse": math.sqrt(max(0.0, 1.0 - float(explained.item()))),
        "mean_offset_energy": float(mean_offset_energy.item()),
        "mean_to_fluctuation_energy_ratio": float(
            (mean_offset_energy / fluctuation_energy.clamp_min(1e-12)).item()
        ),
        "mean_fraction_of_total_energy": float(
            (mean_offset_energy / total_energy.clamp_min(1e-12)).item()
        ),
    }


def canonical_targets(payload):
    if not isinstance(payload, dict) or "motion_targets" not in payload:
        raise ValueError("Expected a motion-target cache with a motion_targets mapping")
    targets = payload["motion_targets"]
    for name, target in targets.items():
        if "_" in name and name.replace("_", "") in targets:
            continue
        yield str(name), target


def aggregate(rows):
    metric_names = [
        "pca_explained_fraction",
        "pca_optimal_relative_rmse",
        "mean_to_fluctuation_energy_ratio",
        "mean_fraction_of_total_energy",
    ]
    result = {"num_proteins": len(rows)}
    for name in metric_names:
        values = [float(row[name]) for row in rows]
        result[f"{name}_mean"] = statistics.fmean(values)
        result[f"{name}_median"] = statistics.median(values)

    total_pca = sum(float(row["pca_energy"]) for row in rows)
    total_fluctuation = sum(float(row["fluctuation_energy"]) for row in rows)
    result["pca_explained_fraction_energy_weighted"] = total_pca / max(total_fluctuation, 1e-12)
    return result


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--motion_target_cache_path", required=True)
    parser.add_argument("--num_modes", type=int, nargs="+", default=[8, 16])
    parser.add_argument("--output_dir", required=True)
    return parser.parse_args()


def main():
    args = parse_args()
    cache_path = Path(args.motion_target_cache_path)
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    payload = torch.load(cache_path, map_location="cpu", weights_only=False)
    require_alignment_version(payload, source=str(cache_path))
    targets = list(canonical_targets(payload))

    all_results = {}
    for num_modes in args.num_modes:
        rows = []
        for name, target in targets:
            row = {"name": name, **target_pca_metrics(target, num_modes)}
            rows.append(row)

        summary = aggregate(rows)
        all_results[str(num_modes)] = summary
        csv_path = output_dir / f"pca_ceiling_k{num_modes}.csv"
        with csv_path.open("w", newline="") as handle:
            writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
            writer.writeheader()
            writer.writerows(rows)

        print(f"\n[PCA ceiling K={num_modes}]")
        for key, value in summary.items():
            print(f"{key}: {value:.6f}" if isinstance(value, float) else f"{key}: {value}")

    json_path = output_dir / "pca_ceiling_summary.json"
    json_path.write_text(json.dumps(all_results, indent=2, sort_keys=True) + "\n")
    print(f"\nWrote {json_path}")


if __name__ == "__main__":
    main()