Download bbflow_base/scripts/canonical_paired_eval.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/canonical_paired_eval.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/canonical_paired_eval.py
-
curl -L -o canonical_paired_eval.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/canonical_paired_eval.py
12.5 kB
| """Reconcile the metric, then test the headline estimand with the right statistic. | |
| Why this exists | |
| --------------- | |
| Two problems have to be settled before any claim is made. | |
| **The numbers do not agree.** Three values exist for quantities that should match: the | |
| published baseline 1.34, a paired script's baseline 1.2890, and 1.2236 versus 1.2396 for | |
| the same run measured two different ways. Until that is explained, the very small paired | |
| standard error is not known to describe the same thing the headline reports. | |
| A likely cause is visible in the canonical implementation: | |
| RAND1 = np.random.randint(0, ref_traj.n_frames, model_traj.n_frames) | |
| The reference cloud is drawn at random and **unseeded**, so two runs of the official | |
| scorer on identical files return different PCA-W2. This measures that noise floor | |
| directly, by repeating the draw, before attributing any difference to something real. | |
| **The wrong estimand was tested.** A paired comparison showed mean per-protein PCA-W2 | |
| lower by 0.132 at p = 0.0006. But the reported headline is the *median across proteins*, | |
| which moves only 1.2890 -> 1.2498, about 0.039. A handful of proteins with large gains can | |
| make the paired mean overwhelmingly significant while barely moving the median. The | |
| p-value for the mean cannot defend a median headline, and 0.039 still sits inside the | |
| 0.06-0.08 selection band established for this cohort. | |
| So the headline estimand is tested here on its own terms: a paired bootstrap that | |
| resamples proteins jointly, recomputes both medians, and takes their difference. The mean | |
| difference and the median paired difference are reported beside it, clearly separated, | |
| because they are different claims. | |
| What this does not fix | |
| ---------------------- | |
| Nothing here removes the selection objection. These 82 proteins have already informed | |
| 15-30 comparisons and the design of this analysis. A tighter interval on the same cohort | |
| quantifies uncertainty; it cannot undo cohort reuse. Only a genuinely untouched cohort can | |
| do that, and this script's `--emit_provenance` output is what a later frozen comparison | |
| would be built on. | |
| """ | |
| import argparse | |
| import hashlib | |
| import os | |
| import numpy as np | |
| def canonical_pca_w2(ref_xyz, model_xyz, n_atoms, rng, n_draws): | |
| """PCA-W2 exactly as `analyse_bbflow` computes it, repeated over reference draws. | |
| Uses the project's own `_get_pca` and `_pca_w2` rather than a reimplementation: the | |
| PCA is fitted on the full reference trajectory, the model is projected with it, and | |
| the reference is subsampled to the model's frame count with replacement. | |
| """ | |
| from bbflow.analysis.analyse_bbflow import _get_pca, _pca_w2 | |
| ref_pca, ref_coords = _get_pca(ref_xyz) | |
| model_coords = ref_pca.transform(model_xyz.reshape(model_xyz.shape[0], -1)) | |
| vals = [] | |
| for _ in range(n_draws): | |
| idx = rng.integers(0, ref_coords.shape[0], model_xyz.shape[0]) | |
| vals.append(float(_pca_w2(ref_coords[idx], model_coords, n_atoms, K=2)["pca_w2"])) | |
| return np.array(vals) | |
| def file_fingerprint(path): | |
| st = os.stat(path) | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| h.update(f.read(1 << 20)) # first MiB is enough to catch a different file | |
| return f"{st.st_size}:{h.hexdigest()[:12]}" | |
| 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="+", required=True) | |
| ap.add_argument("--reference", default="", | |
| help="name of the run every other run is compared against") | |
| ap.add_argument("--n_draws", type=int, default=20, | |
| help="reference draws per protein; their spread is the metric's own " | |
| "noise floor, which has to be known before any difference is " | |
| "called real") | |
| ap.add_argument("--require_segments", type=int, default=3) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--out_csv", default="") | |
| ap.add_argument("--compare_csv", default="", | |
| help="an existing per-protein CSV with columns name,run,pca_w2 to " | |
| "localise where previously reported numbers disagree") | |
| args = ap.parse_args() | |
| if len(args.names) != len(args.ensemble_dirs): | |
| raise SystemExit("--names must match --ensemble_dirs in length") | |
| ref_name = args.reference or args.names[0] | |
| if ref_name not in args.names: | |
| raise SystemExit(f"--reference {ref_name} is not one of --names") | |
| from centroid_reliability import load_generated, load_reference, stable_seed | |
| 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) | |
| for nm, e in zip(args.names, args.ensemble_dirs): | |
| own = len([d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))]) | |
| print(f" {nm:<16} {own:>4} protein directories" | |
| f"{'' if own == len(cohort) else ' <- NOT the common cohort'}") | |
| rows, failures = [], [] | |
| for i, prot in enumerate(cohort): | |
| try: | |
| ref, md_flat, n_atoms, _ = load_reference(prot, args.md_dir, | |
| args.require_segments) | |
| except Exception as exc: # noqa: BLE001 | |
| failures.append(f"{prot}: {exc}") | |
| continue | |
| ref_xyz = md_flat.reshape(len(md_flat), n_atoms, 3) | |
| for nm, ens in zip(args.names, args.ensemble_dirs): | |
| try: | |
| gen = load_generated(prot, ens, ref) | |
| path = os.path.join(ens, prot, "sampled_conformations.pdb") | |
| v = canonical_pca_w2(ref_xyz, gen.reshape(len(gen), n_atoms, 3), n_atoms, | |
| np.random.default_rng(stable_seed(prot, args.seed)), | |
| args.n_draws) | |
| rows.append({"name": prot, "run": nm, "pca_w2": float(v.mean()), | |
| "pca_w2_draw_sd": float(v.std(ddof=1)), | |
| "pca_w2_first_draw": float(v[0]), | |
| "n_gen": len(gen), "n_md": len(md_flat), "n_res": n_atoms, | |
| "file": file_fingerprint(path)}) | |
| except Exception as exc: # noqa: BLE001 | |
| failures.append(f"{prot}/{nm}: {exc}") | |
| if (i + 1) % 10 == 0: | |
| print(f" {i+1}/{len(cohort)}", flush=True) | |
| if failures: | |
| print(f"\n{len(failures)} failures; first 5:") | |
| for f in failures[:5]: | |
| print(f" {f}") | |
| df = pd.DataFrame(rows) | |
| if df.empty: | |
| raise SystemExit("nothing measured") | |
| counts = df.groupby("name")["run"].nunique() | |
| shared = set(counts[counts == len(args.names)].index) | |
| df = df[df.name.isin(shared)] | |
| if args.out_csv: | |
| df.to_csv(args.out_csv, index=False) | |
| print(f"\nper-protein values -> {args.out_csv}") | |
| piv = df.pivot(index="name", columns="run", values="pca_w2") | |
| print(f"\n{'='*76}\n 1. the metric's own noise floor\n{'='*76}") | |
| print(f" reference draws per protein: {args.n_draws}. The canonical scorer draws the") | |
| print(f" reference once, unseeded, so a single official run lands somewhere in this") | |
| print(f" spread. Any difference smaller than it is not a real difference.") | |
| print(f"\n {'run':<16}{'median PCA-W2':>16}{'per-protein draw SD':>22}" | |
| f"{'SD of the median':>18}") | |
| for nm in args.names: | |
| s = df[df.run == nm] | |
| # spread of the aggregate median induced by redrawing the reference | |
| med_sd = float(s.pca_w2_draw_sd.median() / np.sqrt(len(s))) | |
| print(f" {nm:<16}{s.pca_w2.median():>16.4f}{s.pca_w2_draw_sd.median():>22.4f}" | |
| f"{med_sd:>18.4f}") | |
| print(f"\n a single unseeded run of one protein moves by about " | |
| f"{df.pca_w2_draw_sd.median():.4f};") | |
| print(f" the aggregate median moves far less, so draw noise explains per-protein") | |
| print(f" disagreements much more readily than headline disagreements") | |
| print(f"\n{'='*76}\n 2. the headline estimand: difference of aggregate medians\n{'='*76}") | |
| print(f" reference run: {ref_name}") | |
| rng = np.random.default_rng(0) | |
| n = len(piv) | |
| idx = rng.integers(0, n, (4000, n)) | |
| print(f"\n {'run':<16}{'median':>10}{'d(median)':>12}{'paired bootstrap 95%':>26}" | |
| f"{'wins':>8}") | |
| base_col = piv[ref_name].to_numpy() | |
| for nm in args.names: | |
| if nm == ref_name: | |
| print(f" {nm:<16}{piv[nm].median():>10.4f}{'-':>12}{'-':>26}{'-':>8}") | |
| continue | |
| col = piv[nm].to_numpy() | |
| d_med = float(np.median(col) - np.median(base_col)) | |
| # resample proteins jointly, recompute BOTH medians, difference them | |
| boot = np.median(col[idx], axis=1) - np.median(base_col[idx], axis=1) | |
| lo, hi = np.percentile(boot, [2.5, 97.5]) | |
| wins = int((col < base_col).sum()) | |
| print(f" {nm:<16}{piv[nm].median():>10.4f}{d_med:>12.4f}" | |
| f"{f'[{lo:+.4f}, {hi:+.4f}]':>26}{wins:>4}/{n}") | |
| print(f"\n{'='*76}\n 3. the paired estimands, which are DIFFERENT claims\n{'='*76}") | |
| print(f" {'run':<16}{'mean diff':>12}{'mean 95%':>24}{'median diff':>14}" | |
| f"{'median 95%':>24}") | |
| for nm in args.names: | |
| if nm == ref_name: | |
| continue | |
| d = piv[nm].to_numpy() - base_col | |
| bm = d[idx].mean(axis=1) | |
| bmd = np.median(d[idx], axis=1) | |
| lo_m, hi_m = np.percentile(bm, [2.5, 97.5]) | |
| lo_d, hi_d = np.percentile(bmd, [2.5, 97.5]) | |
| print(f" {nm:<16}{d.mean():>12.4f}{f'[{lo_m:+.4f}, {hi_m:+.4f}]':>24}" | |
| f"{np.median(d):>14.4f}{f'[{lo_d:+.4f}, {hi_d:+.4f}]':>24}") | |
| print("\n 'mean diff' is what the earlier paired test reported. It is NOT the") | |
| print(" headline: a few proteins improving a lot can make it large and highly") | |
| print(" significant while the aggregate median in section 2 barely moves. Quote") | |
| print(" section 2 against the published table, and section 3 only as the") | |
| print(" per-protein claim it actually is.") | |
| if args.compare_csv: | |
| print(f"\n{'='*76}\n 4. where the previously reported numbers disagree\n{'='*76}") | |
| old = pd.read_csv(args.compare_csv) | |
| need = {"name", "run", "pca_w2"} | |
| if not need <= set(old.columns): | |
| print(f" {args.compare_csv} lacks {need - set(old.columns)}; skipped") | |
| else: | |
| for nm in args.names: | |
| a = df[df.run == nm].set_index("name")["pca_w2"] | |
| b = old[old.run == nm].set_index("name")["pca_w2"] | |
| if b.empty: | |
| continue | |
| common = a.index.intersection(b.index) | |
| only_new, only_old = set(a.index) - set(b.index), set(b.index) - set(a.index) | |
| d = (a.loc[common] - b.loc[common]) | |
| print(f"\n {nm}: {len(common)} shared, {len(only_new)} only here, " | |
| f"{len(only_old)} only there") | |
| print(f" median difference {d.median():+.4f}, " | |
| f"largest |difference| {d.abs().max():.4f} on {d.abs().idxmax()}") | |
| print(f" aggregate medians: here {a.median():.4f}, " | |
| f"there {b.median():.4f}") | |
| if len(only_new) or len(only_old): | |
| print(f" protein sets differ -- that alone can move an aggregate " | |
| f"median and must be resolved first") | |
| print(f"\n{'='*76}\n what this does and does not settle\n{'='*76}") | |
| print(" Settles: whether the disagreeing numbers are draw noise, a different protein") | |
| print(" set, or different files (the fingerprints in the CSV identify the last), and") | |
| print(" what the headline median difference actually is with an interval built for") | |
| print(" that estimand rather than borrowed from the mean.") | |
| print() | |
| print(" Does not settle: selection. These 82 proteins have already informed 15-30") | |
| print(" comparisons and this analysis was designed while looking at them. An") | |
| print(" interval computed here is conditional on that history; a median gain inside") | |
| print(" the 0.06-0.08 band is not evidence no matter how tight the interval is.") | |
| print(" Only an untouched cohort settles that.") | |
| if __name__ == "__main__": | |
| main() | |