File size: 11,727 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 | """Could a per-protein conditioning scale beat one global scale? Upper bound, existing files.
Every one of the conditioned configurations buys PCA-W2 at the cost of dispersion, and
lowering `condition_scale` shrinks the gain and the cost together. One reading is that a
single global scale must compromise between proteins that are badly over-dispersed and
proteins that are nearly right, so a per-protein scale could do better. Before spending a
generation run on any rule for choosing it, this measures the **ceiling**: give every
protein its own best scale, chosen with full knowledge of the answer, and see whether that
oracle even beats the best global scale. If the oracle gain is small, no rule for
predicting the scale can do better, and the idea is dead without generating anything.
Three questions, in order:
1. heterogeneity do different proteins actually want different scales, or does almost
everyone want the same one? If the optimum is homogeneous, a global
scale is already doing the job and there is nothing to recover.
2. ceiling median PCA-W2 under the per-protein oracle versus under the single
best global scale. This is the most any per-protein rule can buy.
3. compatibility does the scale that minimises PCA-W2 for a protein also move its
dispersion toward the MD target, or are they minimised at opposite
ends? If they fight, a scalar cannot fix both no matter how it is
chosen, and the trade is structural rather than a compromise.
The scorer's noise is handled without departing from its definition. The official
implementation draws its reference subsample unseeded, and repeated runs on identical
files gave 1.18 / 1.24 / 1.27 -- SD about 0.046, which swamps every difference in the
sweep. Here the **same reference indices are used for every configuration** within a
protein and draw, so configurations are compared on identical references and that noise
cancels in the comparison instead of being averaged down at 1/sqrt(n). The metric itself
is the project's own `_pca_w2` on the project's own `_get_pca`, unmodified.
RMSF and pairwise summaries here are this script's own definitions, used only to answer
question 3 in relative terms. They are not the official columns and must not be compared
with the published table.
"""
import argparse
import os
import numpy as np
def fit_reference_pca(ref_xyz):
from bbflow.analysis.analyse_bbflow import _get_pca
return _get_pca(ref_xyz)
def pca_w2_shared(ref_coords, model_coords, n_atoms, idx):
"""The project's metric on a caller-supplied reference draw, so arms are paired."""
from bbflow.analysis.analyse_bbflow import _pca_w2
return float(_pca_w2(ref_coords[idx], model_coords, n_atoms, K=2)["pca_w2"])
def _kabsch_rmsd_batch(a, b):
ac, bc = a - a.mean(1, keepdims=True), b - b.mean(1, keepdims=True)
h = np.einsum("fij,fik->fjk", ac, bc)
u, s, vt = np.linalg.svd(h)
sign = np.sign(np.linalg.det(np.einsum("fij,fjk->fik", u, vt)))
s = s.copy()
s[:, -1] *= sign
n = a.shape[1]
return np.sqrt(np.maximum(
(np.square(ac).sum((1, 2)) + np.square(bc).sum((1, 2)) - 2 * s.sum(1)) / n, 0.0))
def dispersion(xyz, rng, n_pairs=800):
"""Internal dispersion summaries, in Angstrom. Not the official definitions."""
x = xyz * 10.0
rmsf = np.sqrt(np.square(x - x.mean(0)).sum(-1).mean(0))
i, j = rng.integers(0, len(x), n_pairs), rng.integers(0, len(x), n_pairs)
ok = i != j
return float(np.median(rmsf)), float(np.median(_kabsch_rmsd_batch(x[i[ok]], x[j[ok]])))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--md_dir", required=True)
ap.add_argument("--ensemble_dirs", nargs="+", required=True)
ap.add_argument("--scales", nargs="+", type=float, required=True,
help="the condition_scale each ensemble dir was generated at")
ap.add_argument("--baseline_dir", default="",
help="optional unconditioned run, scored on the same references")
ap.add_argument("--n_draws", type=int, default=15)
ap.add_argument("--require_segments", type=int, default=3)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--out_csv", default="")
args = ap.parse_args()
if len(args.scales) != len(args.ensemble_dirs):
raise SystemExit("--scales must match --ensemble_dirs in length")
order = np.argsort(args.scales)
scales = [args.scales[i] for i in order]
dirs = [args.ensemble_dirs[i] for i in order]
print("scales: " + " ".join(f"{s:g}" for s in scales), flush=True)
from centroid_reliability import load_generated, load_reference, stable_seed
import pandas as pd
pools = [dirs] + ([[args.baseline_dir]] if args.baseline_dir else [])
cohort = sorted(set.intersection(*[
{d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))}
for grp in pools for e in grp]))
print(f"cohort: {len(cohort)} proteins", flush=True)
rows, failures = [], []
for pi, prot in enumerate(cohort):
try:
ref, md_flat, n_atoms, _ = load_reference(prot, args.md_dir,
args.require_segments)
ref_pca, ref_coords = fit_reference_pca(md_flat.reshape(len(md_flat), n_atoms, 3))
except Exception as exc: # noqa: BLE001
failures.append(f"{prot}: {exc}")
continue
try:
gens = [load_generated(prot, d, ref) for d in dirs]
base = load_generated(prot, args.baseline_dir, ref) if args.baseline_dir else None
except Exception as exc: # noqa: BLE001
failures.append(f"{prot}: {exc}")
continue
n_gen = len(gens[0])
rng = np.random.default_rng(stable_seed(prot, args.seed))
# One set of reference draws, shared by every configuration for this protein.
draws = [rng.integers(0, ref_coords.shape[0], n_gen) for _ in range(args.n_draws)]
projected = [ref_pca.transform(g.reshape(len(g), -1)) for g in gens]
base_proj = ref_pca.transform(base.reshape(len(base), -1)) if base is not None else None
drng = np.random.default_rng(stable_seed(prot, args.seed + 1))
for k, (s, g, mp) in enumerate(zip(scales, gens, projected)):
w2 = float(np.mean([pca_w2_shared(ref_coords, mp, n_atoms, d) for d in draws]))
rm, pw = dispersion(g.reshape(len(g), n_atoms, 3),
np.random.default_rng(stable_seed(prot, 99)))
rows.append({"name": prot, "arm": f"s{s:g}", "scale": s, "pca_w2": w2,
"rmsf_med": rm, "pw_med": pw})
if base_proj is not None:
w2 = float(np.mean([pca_w2_shared(ref_coords, base_proj, n_atoms, d)
for d in draws]))
rm, pw = dispersion(base.reshape(len(base), n_atoms, 3),
np.random.default_rng(stable_seed(prot, 99)))
rows.append({"name": prot, "arm": "baseline", "scale": np.nan, "pca_w2": w2,
"rmsf_med": rm, "pw_med": pw})
# MD's own dispersion, for question 3's target
rm, pw = dispersion(md_flat.reshape(len(md_flat), n_atoms, 3)[
np.random.default_rng(stable_seed(prot, 5)).integers(0, len(md_flat), n_gen)],
np.random.default_rng(stable_seed(prot, 99)))
rows.append({"name": prot, "arm": "MD", "scale": np.nan, "pca_w2": np.nan,
"rmsf_med": rm, "pw_med": pw})
if (pi + 1) % 10 == 0:
print(f" {pi+1}/{len(cohort)}", flush=True)
if failures:
print(f"\n{len(failures)} failures; first: {failures[0]}")
df = pd.DataFrame(rows)
if df.empty:
raise SystemExit("nothing measured")
if args.out_csv:
df.to_csv(args.out_csv, index=False)
print(f"per-protein values -> {args.out_csv}")
cond = df[df.arm.str.startswith("s")]
piv = cond.pivot(index="name", columns="scale", values="pca_w2").dropna()
md = df[df.arm == "MD"].set_index("name")
n = len(piv)
print(f"\n{'='*74}\n per-scale medians, paired references ({args.n_draws} shared "
f"draws)\n{'='*74}")
print(f" {'scale':>8}{'PCA-W2':>10}{'rmsf_med':>11}{'pw_med':>10}")
for s in piv.columns:
c = cond[cond.scale == s]
print(f" {s:>8g}{piv[s].median():>10.4f}{c.rmsf_med.median():>11.4f}"
f"{c.pw_med.median():>10.4f}")
if args.baseline_dir:
b = df[df.arm == "baseline"]
print(f" {'baseline':>8}{b.pca_w2.median():>10.4f}{b.rmsf_med.median():>11.4f}"
f"{b.pw_med.median():>10.4f}")
print(f" {'MD':>8}{'-':>10}{md.rmsf_med.median():>11.4f}{md.pw_med.median():>10.4f}")
print(f"\n{'='*74}\n 1. heterogeneity: does each protein want a different scale?"
f"\n{'='*74}")
best = piv.idxmin(axis=1)
counts = best.value_counts().sort_index()
for s, c in counts.items():
print(f" scale {s:<6g} is best for {c:>3}/{n} proteins ({c/n:.2f})")
print(f"\n If one scale is best for nearly everyone there is no heterogeneity to")
print(f" exploit and a per-protein rule has nothing to recover.")
print(f"\n{'='*74}\n 2. CEILING: per-protein oracle versus the best global scale"
f"\n{'='*74}")
global_best_s = piv.median().idxmin()
glob = piv[global_best_s]
oracle = piv.min(axis=1)
gap = float(glob.median() - oracle.median())
rng = np.random.default_rng(0)
idx = rng.integers(0, n, (4000, n))
g_arr, o_arr = glob.to_numpy(), oracle.to_numpy()
boot = np.median(g_arr[idx], axis=1) - np.median(o_arr[idx], axis=1)
lo, hi = np.percentile(boot, [2.5, 97.5])
print(f" best global scale {global_best_s:g}")
print(f" its median PCA-W2 {glob.median():.4f}")
print(f" per-protein oracle median {oracle.median():.4f}")
print(f" CEILING (what any rule could buy) {gap:+.4f} [{lo:+.4f}, {hi:+.4f}]")
print(f"\n This oracle is chosen with the answer in hand, so it is an upper bound no")
print(f" predictor can exceed. Against the scorer's ~0.046 single-run SD and the")
print(f" project's 0.06-0.08 selection band, a ceiling below roughly 0.05 means a")
print(f" per-protein rule cannot matter even if it worked perfectly.")
print(f"\n{'='*74}\n 3. compatibility: does the PCA-W2 optimum also fix dispersion?"
f"\n{'='*74}")
rm_piv = cond.pivot(index="name", columns="scale", values="rmsf_med").loc[piv.index]
pw_piv = cond.pivot(index="name", columns="scale", values="pw_med").loc[piv.index]
rm_best = (rm_piv - md.rmsf_med.loc[piv.index].to_numpy()[:, None]).abs().idxmin(axis=1)
pw_best = (pw_piv - md.pw_med.loc[piv.index].to_numpy()[:, None]).abs().idxmin(axis=1)
agree_rm = float((best == rm_best).mean())
agree_pw = float((best == pw_best).mean())
print(f" scale minimising PCA-W2 also closest on rmsf_med: {agree_rm:.2f} of proteins")
print(f" scale minimising PCA-W2 also closest on pw_med: {agree_pw:.2f} of proteins")
print(f" median scale wanted by PCA-W2 {best.median():g}, "
f"by rmsf_med {rm_best.median():g}, by pw_med {pw_best.median():g}")
print(f"\n If PCA-W2 and dispersion want opposite ends of the range, no scalar fixes")
print(f" both, however it is chosen, and the trade is structural rather than a")
print(f" compromise a per-protein rule could resolve.")
if __name__ == "__main__":
main()
|