Download bbflow_base/scripts/centroid_shrinkage_check.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 21.8 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/centroid_shrinkage_check.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/centroid_shrinkage_check.py
-
curl -L -o centroid_shrinkage_check.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/centroid_shrinkage_check.py
21.8 kB
| """Follow-up to centroid_reliability.py: is negative transfer real drift, or overcorrection? | |
| `centroid_reliability.py` found that a full-strength centroid correction, estimated on one | |
| whole MD segment and applied to a different segment, made the score *worse* than doing | |
| nothing, on all 82 test proteins and all 7 checkpoints tried. That result stands: raw, | |
| full-strength segment-centroid correction is unusable. It does not by itself distinguish | |
| two explanations, which imply opposite next steps: | |
| overcorrection each 1001-frame segment carries only a handful of effective | |
| independent samples (measured separately per protein), so a | |
| segment's own centroid is a noisy estimate of a real, stable target. | |
| Applying it at full strength imports that noise; a shrunk correction | |
| could still help, and a denoised/learned centroid could be worth a | |
| separate learnability experiment. | |
| genuine instability there is no stable target at this timescale -- segments differ | |
| because the underlying occupancy itself drifts or the trajectory | |
| visits different metastable states in different windows. No amount | |
| of shrinkage rescues a moving target, and the line should stop. | |
| Two checks, both closed-form and CPU-only, reusing the exact production-style primary | |
| construction (all frames of segment A, reference drawn with replacement from all of | |
| segment B, at the production cloud size): | |
| directed pairs the six ordered segment pairs, reported separately rather than | |
| pooled. Segments are indexed by discovery order (`_R1`, `_R2`, | |
| `_R3`), which is deterministic but is *not* independently verified | |
| here to be simulation chronology -- see the caveat below. If only | |
| pairs touching the first-discovered segment fail, that is | |
| *consistent with* an equilibration transient or a protocol | |
| difference specific to that segment, not proof of one; if the other | |
| two segments fail just as badly against each other, instability is | |
| the more credible reading regardless of what segment order means. | |
| shrinkage, cross-validated, held-out, at the production gate three curves per | |
| directed pair and alpha, mirroring `centroid_reliability.py`'s | |
| primary/held-out/paired-contrast design exactly, because the same | |
| size mismatch that design was built to handle shows up here too: | |
| production full 250-sample cloud, anchor = its own mean. This is the only curve | |
| evaluated against the project's 0.10 Angstrom threshold, because that | |
| threshold was set at the production cloud size and the mean term sits | |
| inside a square root -- a correction that clears 0.10 at n=125 is not | |
| shown to clear it at n=250, and one that fails at n=125 is not shown to | |
| fail at n=250 either. | |
| held-out half the cloud (125), anchor = a disjoint half's mean, so the anchor | |
| cannot cancel the realized sampling noise of the half being scored. This | |
| is the *only* curve alpha selection uses: choosing among alphas is a | |
| relative comparison and does not need the production cloud size, but it | |
| does need to be leak-free, or every alpha would look better than it is | |
| by a similar amount and the ranking would not be trustworthy. | |
| held-out, in-sample anchor the same scored half and reference draw as held-out, | |
| anchored to its own mean instead. Paired with held-out at the same size, | |
| this reproduces the primary script's leak/attenuation contrast: how much | |
| of the held-out gain would collapse if the anchor were allowed to see | |
| the batch it corrects. | |
| For each protein, the fraction is chosen by *median* gain on the held-out curve of the | |
| other 81 proteins (leave-one-protein-out), then that fraction is applied to this | |
| protein's own *production* curve for the 0.10 Angstrom gate, and separately checked | |
| against the paired attenuation contrast at matched size. A pass requires both: the | |
| production gain clears 0.10, and the held-out gain is not mostly attributable to the | |
| in-sample anchor's leak. | |
| Both reuse `md_context` / `load_generated` from `centroid_reliability.py` unchanged, so | |
| the MD projection, segment definitions and CA/topology handling are exactly what the | |
| reviewed primary result used -- this is not a new measurement of the reference, only a | |
| different way of slicing and aggregating the same closed-form quantity. | |
| Cohort and shape preconditions mirror the primary script: the verdict is suppressed, | |
| not merely annotated, if the analysed cohort, generated-sample count, or segment length | |
| don't match what was expected, so a run that silently lost proteins or ran on truncated | |
| segments can't produce a headline number. | |
| A pass here is not proof a sequence-based model can learn the equilibrium centroid -- | |
| only that a segment's own centroid carries transferable information worth a *separate* | |
| learnability experiment. And because the checkpoints compared are trained on the same 82 | |
| proteins, MD and segmentation, seven of them agreeing is not seven independent | |
| confirmations; the summary at the end reports how many give the same read rather than | |
| treating one pass among several as a rescue. | |
| """ | |
| import argparse | |
| import os | |
| from collections import Counter | |
| import numpy as np | |
| from centroid_reliability import (load_generated, md_context, stable_seed, w2_sq) | |
| ALPHA_GRID = tuple(sorted(set( | |
| [round(x, 3) for x in np.arange(0.0, 0.1001, 0.01)] + # dense near zero | |
| [0.125, 0.15, 0.175, 0.20] + | |
| [round(x, 3) for x in np.arange(0.25, 1.0001, 0.05)]))) | |
| MIN_ATTENUATION = 0.5 | |
| def _curve(gen_score, mu_apply, mu_a, ref, scale, alphas): | |
| """Closed-form distance at every alpha for one already-drawn (cloud, reference) pair. | |
| `mu_apply` is subtracted as the correction anchor; `mu_a` is the segment-A centroid | |
| being partially applied. Passing `mu_apply = gen_score.mean(0)` gives the in-sample | |
| (leaky) curve; passing a disjoint half's mean gives the held-out curve. One transport | |
| call gives every alpha, via the same mean-separation identity the primary script uses. | |
| """ | |
| mu_gs = gen_score.mean(0) | |
| mu_b = ref.mean(0) | |
| c = w2_sq(gen_score - mu_gs, ref - mu_b, scale) | |
| d = mu_gs - mu_b | |
| step = mu_a - mu_apply | |
| s2 = scale ** 2 | |
| return {a: float(np.square(d + a * step).sum() * s2 + c) ** 0.5 for a in alphas} | |
| def pair_gains(gen_p, mu_a, seg_b, n_prod, scale, rng, n_ref_draws, alphas): | |
| """Three curves per directed pair: production, held-out, and held-out's in-sample twin. | |
| All three share `mu_a` and are averaged over `n_ref_draws` draws each, but only `ho` | |
| and `hoalt` share their *specific* scored half and reference draw within every | |
| iteration -- they are the paired pair the attenuation contrast needs. `prod` draws its | |
| own reference independently and scores the full cloud, so it is not paired against the | |
| other two frame-for-frame; only the selected alpha (chosen from `ho` alone, on other | |
| proteins) carries over to it. | |
| """ | |
| n_gen = gen_p.shape[0] | |
| acc_prod = {a: 0.0 for a in alphas} | |
| acc_ho = {a: 0.0 for a in alphas} | |
| acc_hoalt = {a: 0.0 for a in alphas} | |
| for _ in range(n_ref_draws): | |
| ref_prod = seg_b[rng.integers(0, len(seg_b), n_prod)] | |
| c_prod = _curve(gen_p, gen_p.mean(0), mu_a, ref_prod, scale, alphas) | |
| for a in alphas: | |
| acc_prod[a] += c_prod[a] | |
| g_idx = rng.permutation(n_gen) | |
| cut = n_gen // 2 | |
| scored_half, apply_half = gen_p[g_idx[:cut]], gen_p[g_idx[cut:]] | |
| ref_ho = seg_b[rng.integers(0, len(seg_b), cut)] | |
| c_ho = _curve(scored_half, apply_half.mean(0), mu_a, ref_ho, scale, alphas) | |
| c_hoalt = _curve(scored_half, scored_half.mean(0), mu_a, ref_ho, scale, alphas) | |
| for a in alphas: | |
| acc_ho[a] += c_ho[a] | |
| acc_hoalt[a] += c_hoalt[a] | |
| return ({a: v / n_ref_draws for a, v in acc_prod.items()}, | |
| {a: v / n_ref_draws for a, v in acc_ho.items()}, | |
| {a: v / n_ref_draws for a, v in acc_hoalt.items()}) | |
| def audit_one(name, ctx, gen_flat, k_dim, rng, n_ref_draws, alphas): | |
| segs = ctx["segs"] | |
| scale = 10.0 / ctx["n_atoms"] ** 0.5 | |
| gen_p = (gen_flat - ctx["centre"]) @ ctx["basis"].T | |
| n_prod = gen_p.shape[0] | |
| rows = [] | |
| for i in range(len(segs)): | |
| for j in range(len(segs)): | |
| if i == j: | |
| continue | |
| prod, ho, hoalt = pair_gains(gen_p, segs[i].mean(0), segs[j], n_prod, scale, | |
| rng, n_ref_draws, alphas) | |
| rows.append({"name": name, "src": i, "dst": j, | |
| "touches_seg0": (i == 0 or j == 0), | |
| **{f"prod_a{a}": prod[a] for a in alphas}, | |
| **{f"ho_a{a}": ho[a] for a in alphas}, | |
| **{f"hoalt_a{a}": hoalt[a] for a in alphas}}) | |
| return rows | |
| def boot_ci(v, reps=4000): | |
| v = np.asarray(v, float) | |
| s = np.random.default_rng(0).choice(v, (reps, v.size), replace=True) | |
| return tuple(np.percentile(np.median(s, axis=1), [2.5, 97.5])) | |
| def select_alpha_lopo(df, alphas, mask=None): | |
| """Leave-one-protein-out fraction, chosen by median held-out gain on every other | |
| protein. Held-out (not production, not its in-sample twin) is the only curve this | |
| reads, because comparing alphas needs to be leak-free but does not need the | |
| production cloud size -- that size only matters once, for the gate itself. | |
| Returns, per protein: the chosen alpha, and that protein's own production and | |
| held-out-pair gains *at* that alpha, so the gate and the attenuation check are | |
| evaluated at the fraction genuinely selected without seeing this protein. | |
| """ | |
| d = df[mask] if mask is not None else df | |
| ho_cols = [f"ho_a{a}" for a in alphas] | |
| per_protein = d.groupby("name")[[*ho_cols, | |
| *[f"prod_a{a}" for a in alphas], | |
| *[f"hoalt_a{a}" for a in alphas]]].mean() | |
| names = per_protein.index.to_numpy() | |
| ho_unc = per_protein[ho_cols].to_numpy() | |
| ho_gain = ho_unc[:, alphas.index(0.0)][:, None] - ho_unc | |
| n = len(names) | |
| chosen_idx = np.empty(n, dtype=int) | |
| for i in range(n): | |
| med_others = np.median(np.delete(ho_gain, i, axis=0), axis=0) | |
| chosen_idx[i] = int(np.argmax(med_others)) | |
| prod_unc = per_protein[[f"prod_a{a}" for a in alphas]].to_numpy() | |
| hoalt_unc = per_protein[[f"hoalt_a{a}" for a in alphas]].to_numpy() | |
| prod_base, hoalt_base = prod_unc[:, alphas.index(0.0)], hoalt_unc[:, alphas.index(0.0)] | |
| out = [] | |
| for i in range(n): | |
| a_idx = chosen_idx[i] | |
| out.append({"name": names[i], "alpha": alphas[a_idx], | |
| "prod_gain": prod_base[i] - prod_unc[i, a_idx], | |
| "ho_gain": ho_gain[i, a_idx], | |
| "hoalt_gain": hoalt_base[i] - hoalt_unc[i, a_idx]}) | |
| import pandas as pd | |
| return pd.DataFrame(out) | |
| def report_shrinkage(df, alphas, min_useful_gain, subset_label, mask=None): | |
| sel = select_alpha_lopo(df, alphas, mask) | |
| chosen = sel["alpha"].to_numpy() | |
| top, top_n = Counter(np.round(chosen, 3)).most_common(1)[0] | |
| print(f"\n [{subset_label}] leave-one-protein-out shrinkage, {len(sel)} proteins") | |
| print(f" fraction selected on the held-out curve: median {np.median(chosen):.3f}, " | |
| f"most common {top:.3f} ({top_n}/{len(sel)}), " | |
| f"range [{chosen.min():.3f}, {chosen.max():.3f}]") | |
| g = sel["prod_gain"].to_numpy() | |
| g_lo, g_hi = boot_ci(g) | |
| gate = ("DEAD" if g_hi < min_useful_gain else | |
| "clears the gate" if g_lo > min_useful_gain else "UNRESOLVED") | |
| print(f" gate: production-size (n=250) gain at the selected fraction, applied to " | |
| f"this protein only\n {np.median(g):+.4f} [{g_lo:+.4f}, {g_hi:+.4f}] " | |
| f"against {min_useful_gain:.2f} -> {gate}") | |
| ho, hoalt = sel["ho_gain"].to_numpy(), sel["hoalt_gain"].to_numpy() | |
| contrast = ho - MIN_ATTENUATION * hoalt | |
| c_lo, c_hi = boot_ci(contrast) | |
| holds_up = bool(np.median(ho) > 0 and c_lo > 0) | |
| print(f" qualification: held-out gain {np.median(ho):+.4f} vs its in-sample twin " | |
| f"{np.median(hoalt):+.4f} at the same n=125") | |
| print(f" held-out minus {MIN_ATTENUATION:.2f} of the twin: " | |
| f"{np.median(contrast):+.4f} [{c_lo:+.4f}, {c_hi:+.4f}] -> " | |
| f"{'holds up' if holds_up else 'does not clear the margin'}") | |
| if gate == "DEAD": | |
| verdict = "DEAD" | |
| elif gate == "clears the gate" and holds_up: | |
| verdict = "warrants a separate learnability experiment" | |
| else: | |
| verdict = "UNRESOLVED" | |
| print(f" -> {verdict}") | |
| # Sensitivity only, not a second chance at a verdict: alpha ranking can differ at | |
| # n=125 (where it was chosen) from n=250 (where the gate is applied), since the shape | |
| # term changes with cloud size. If a DEAD verdict is going to be reported as "no | |
| # shrinkage helps," this shows whether any alpha's production gain clears 0.10 even | |
| # though it wasn't the one the leak-free procedure selected. A large value here is a | |
| # reason to look closer, via the held-out qualification at that specific alpha, not a | |
| # license to report it as if it had been selected honestly. | |
| all_prod = df[mask] if mask is not None else df | |
| prod_curve = all_prod.groupby("name")[[f"prod_a{a}" for a in alphas]].mean() | |
| prod_gain_by_alpha = prod_curve.iloc[:, alphas.index(0.0)].to_numpy()[:, None] \ | |
| - prod_curve.to_numpy() | |
| best_unselected = int(np.argmax(np.median(prod_gain_by_alpha, axis=0))) | |
| print(f" sensitivity only, not selected: best production-gain alpha in hindsight " | |
| f"is {alphas[best_unselected]:.3f}, median gain " | |
| f"{np.median(prod_gain_by_alpha[:, best_unselected]):+.4f} -- report this only " | |
| f"alongside the held-out check at that alpha, never as a standalone pass") | |
| return verdict | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--md_dir", required=True) | |
| ap.add_argument("--ensemble_dirs", nargs="+", required=True) | |
| ap.add_argument("--names", nargs="*", default=[]) | |
| ap.add_argument("--k", type=int, default=2) | |
| ap.add_argument("--n_ref_draws", type=int, default=5) | |
| ap.add_argument("--min_useful_gain", type=float, default=0.10) | |
| ap.add_argument("--require_segments", type=int, default=3) | |
| ap.add_argument("--expect_cohort", type=int, default=82) | |
| ap.add_argument("--expect_n_gen", type=int, default=250) | |
| ap.add_argument("--expect_seg_len", type=int, default=1001) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--out_csv", default="") | |
| args = ap.parse_args() | |
| labels = args.names or [os.path.basename(d.rstrip("/")) for d in args.ensemble_dirs] | |
| if len(labels) != len(args.ensemble_dirs) or len(set(labels)) != len(labels): | |
| raise SystemExit("--names must match --ensemble_dirs, uniquely") | |
| import pandas as pd | |
| cohort = sorted(set.intersection(*[ | |
| {d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))} | |
| for e in args.ensemble_dirs])) | |
| print(f"cohort common to all runs: {len(cohort)} proteins", flush=True) | |
| rows, failures, n_gen_seen, seg_lens = [], {}, set(), set() | |
| for i, nm in enumerate(cohort): | |
| try: | |
| ctx = md_context(nm, args.md_dir, args.k, args.require_segments) | |
| except Exception as exc: # noqa: BLE001 | |
| for label in labels: | |
| failures.setdefault(label, []).append(f"{nm}: {exc}") | |
| continue | |
| seg_lens.update(len(s) for s in ctx["segs"]) | |
| for label, ens in zip(labels, args.ensemble_dirs): | |
| try: | |
| gen_flat = load_generated(nm, ens, ctx["ref"]) | |
| n_gen_seen.add(gen_flat.shape[0]) | |
| r = audit_one(nm, ctx, gen_flat, args.k, | |
| np.random.default_rng(stable_seed(nm, args.seed)), | |
| args.n_ref_draws, ALPHA_GRID) | |
| for row in r: | |
| row["run"] = label | |
| rows.extend(r) | |
| except Exception as exc: # noqa: BLE001 | |
| failures.setdefault(label, []).append(f"{nm}: {exc}") | |
| if (i + 1) % 10 == 0: | |
| print(f" {i+1}/{len(cohort)} proteins", flush=True) | |
| if failures: | |
| print("\nfailures:") | |
| for label, msgs in failures.items(): | |
| print(f" [{label}] {len(msgs)}") | |
| for m in msgs[:5]: | |
| print(f" {m}") | |
| df = pd.DataFrame(rows) | |
| if df.empty: | |
| raise SystemExit("no protein produced a measurement") | |
| counts = df.groupby("name")["run"].nunique() | |
| shared = set(counts[counts == len(labels)].index) | |
| df = df[df.name.isin(shared)] | |
| guards = [] | |
| if args.expect_cohort and len(shared) != args.expect_cohort: | |
| guards.append(f"analysed {len(shared)} proteins, expected {args.expect_cohort}") | |
| if args.expect_n_gen and n_gen_seen != {args.expect_n_gen}: | |
| guards.append(f"generated sample counts seen {sorted(n_gen_seen)}, " | |
| f"expected {args.expect_n_gen}") | |
| if args.expect_seg_len and seg_lens != {args.expect_seg_len}: | |
| guards.append(f"segment lengths seen {sorted(seg_lens)}, " | |
| f"expected {args.expect_seg_len} in every segment") | |
| if args.out_csv: | |
| df.to_csv(args.out_csv, index=False) | |
| print(f"\nper-directed-pair values -> {args.out_csv}") | |
| for label in labels: | |
| d = df[df.run == label] | |
| if d.empty: | |
| continue | |
| print(f"\n{'='*78}\n{label}\n{'='*78}") | |
| print("\n directed segment pairs (1-indexed to match R1/R2/R3), held-out " | |
| "full-strength gain (Angstrom),\n median over proteins, n=125") | |
| d = d.copy() | |
| d["gain_ho_full"] = d["ho_a0.0"] - d[f"ho_a{ALPHA_GRID[-1]}"] | |
| piv = d.groupby(["src", "dst"])["gain_ho_full"].median().unstack() | |
| print(" src\\dst " + "".join(f"{j+1:>10}" for j in range(3))) | |
| for i in range(3): | |
| cells = "".join(f"{piv.loc[i, j]:>10.4f}" if j in piv.columns and i in piv.index | |
| and not np.isnan(piv.loc[i, j]) else f"{'':>10}" | |
| for j in range(3)) | |
| print(f" {i+1} {cells}") | |
| seg0 = d[d.touches_seg0].groupby("name")["gain_ho_full"].mean() | |
| seg23 = d[~d.touches_seg0].groupby("name")["gain_ho_full"].mean() | |
| def summarize(v, tag): | |
| lo, hi = boot_ci(v) | |
| print(f" {tag:<28} median {np.median(v):+.4f} [{lo:+.4f}, {hi:+.4f}] " | |
| f"n={len(v)}") | |
| print("\n held-out full-strength gain: pairs touching R1 vs R2<->R3 only") | |
| summarize(seg0.to_numpy(), "touches R1") | |
| if len(seg23): | |
| summarize(seg23.to_numpy(), "R2 <-> R3 only") | |
| else: | |
| print(" R2 <-> R3 only no data (need >=3 segments)") | |
| print(" only touching-R1 failing is CONSISTENT WITH an equilibration") | |
| print(" transient or a protocol difference specific to R1 -- it does not by") | |
| print(" itself prove one, and R1/R2/R3 file order is not independently") | |
| print(" verified here as simulation chronology") | |
| if guards: | |
| print("\n VERDICT SUPPRESSED for this run's shrinkage analysis:") | |
| for g in guards: | |
| print(f" {g}") | |
| continue | |
| report_shrinkage(d, ALPHA_GRID, args.min_useful_gain, "all six directed pairs") | |
| if len(seg23): | |
| report_shrinkage(d, ALPHA_GRID, args.min_useful_gain, | |
| "R2<->R3 only, excludes any R1-specific artefact", | |
| mask=~d.touches_seg0) | |
| print(f"\n{'='*78}\n across-checkpoint summary\n{'='*78}") | |
| print(" These checkpoints share the same 82 proteins, MD and segmentation, so") | |
| print(" agreement across them is not independent confirmation the way agreement") | |
| print(" across different held-out data would be. A pass on one checkpoint alone") | |
| print(" is not a rescue; only a consistent pattern across the group is meaningful.") | |
| if guards: | |
| print(f"\n guard tripped, no per-checkpoint verdicts to summarise: " | |
| f"{'; '.join(guards)}") | |
| return | |
| verdicts = {} | |
| for label in labels: | |
| d = df[df.run == label] | |
| if d.empty: | |
| continue | |
| sel = select_alpha_lopo(d, ALPHA_GRID, mask=~d.touches_seg0) | |
| g_lo, g_hi = boot_ci(sel["prod_gain"].to_numpy()) | |
| c_lo, _ = boot_ci(sel["ho_gain"].to_numpy() | |
| - MIN_ATTENUATION * sel["hoalt_gain"].to_numpy()) | |
| if g_hi < args.min_useful_gain: | |
| verdicts[label] = "DEAD" | |
| elif g_lo > args.min_useful_gain and sel["ho_gain"].median() > 0 and c_lo > 0: | |
| verdicts[label] = "PASS" | |
| else: | |
| verdicts[label] = "UNRESOLVED" | |
| for label, v in verdicts.items(): | |
| print(f" {label:<16} R2<->R3-only, LOPO-selected, held-out-qualified " | |
| f"verdict: {v}") | |
| n_dead = sum(v == "DEAD" for v in verdicts.values()) | |
| print(f"\n {n_dead}/{len(verdicts)} checkpoints DEAD on the qualified, " | |
| f"R1-excluded view") | |
| if __name__ == "__main__": | |
| main() | |