"""Phase A: how much PCA-W2 is recoverable by fixing the first two moments? The reported metric projects both ensembles onto the reference trajectory's leading two principal components and takes an empirical optimal-transport distance between the two 2-D clouds. Several objectives have been built to match second moments; none has improved the metric. Before designing another, this measures the ceiling: if the generated cloud's mean and covariance in that plane were corrected *exactly*, how much of the gap closes? A small answer means post-hoc calibration of the first two moments has little to offer on these ensembles, which is strong practical evidence against continuing down that line. It is not a proof that a covariance-based training objective is useless -- training can also move modality and tails -- but it removes the mechanism those objectives were meant to exploit. Method ------ The correction is the canonical Gaussian optimal-transport (Brenier) map, not an affine map fitted against the empirical distance: T(x) = m_ref + A (x - m_gen) A = C_gen^{-1/2} ( C_gen^{1/2} C_ref C_gen^{1/2} )^{1/2} C_gen^{-1/2} `A` is the unique symmetric positive-definite matrix carrying `C_gen` to `C_ref`, and is the minimum mean-squared affine displacement under a Gaussian approximation. An unrestricted affine map fitted against the empirical W2 is deliberately NOT implemented: it would let rotations and reflections chase higher-order structure, and fitted and scored on the same cloud it would absorb transport noise, answering a different question. Every corrected distance is reported twice: in-sample the map is estimated on the same cloud it is applied to. Removes that cloud's own sampling fluctuation as though it were model error, so it overstates what is recoverable. Optimistic bound. cross-fitted repeated K-fold. Each fold's points are transformed by a map estimated on the other folds, and the transformed folds are reassembled into a full out-of-fold cloud of the original size. That cloud is scored against the same fixed reference subset the uncorrected number uses, so the decision statistic stays at the sample size the metric is defined at. The reference moments used to build the map come from frames disjoint from the frames the distance is evaluated against, so the correction is never fitted to its own target sample. Reading the output ------------------ `floor` is the distance between two clouds of the same size resampled from the reference trajectory itself. It is what a perfect model would score; the gap worth discussing is measured against it, not against zero. A replica-versus-replica floor is reported alongside, which additionally absorbs slow drift between the three trajectory segments. The decision rule is in DECISION below, fixed before any association was examined, and stated in absolute Angstrom because the practical hurdle is an existing 1.27 against a 1.34 reference rather than a fraction of an arbitrary total. Caveats that belong with any use of these numbers: * Squared W2 separates the mean exactly: `W2^2(P,Q) = ||mu_P - mu_Q||^2 + W2^2(P - mu_P, Q - mu_Q)`. The exact mean component of the scored distance is `mean_err_eval`. The mean-only *column* corrects toward `m_ref` from the independent moment pool rather than toward the empirical mean of the scored cloud, so it is the honest cross-fitted version of that correction, not the identity term itself. The covariance term separates in no such way: Bures is a lower bound (Gelbrich), tight only for compatible elliptical families. The residual after correction is an operational remainder, not a formal "higher-order share". * CA atoms only, so absolute values sit a few percent from the all-atom pipeline. A paired within-protein difference is expected to be less sensitive to that than the absolute value is, but a preprocessing change can move paired gains too, not merely add a constant. Confirm against the official per-protein score on one checkpoint before relying on the magnitude. * When the eigenvalue floor activates, the map no longer carries the empirical `C_gen` exactly to `C_ref`. The transport residual is measured for every fitted map and surfaced; a run in which it is not negligible is a *regularized* correction, not an exact one. """ import argparse import hashlib import os import warnings import numpy as np from scipy.optimize import linear_sum_assignment # Fixed before any association was examined. See module docstring. DECISION = """ median cross-fitted paired improvement, in Angstrom: < 0.07 stop; less than the margin that would have to be beaten 0.07 - 0.10 probably stop, unless the effect is unusually consistent >= 0.10 - 0.15 enough upside to continue, if the lower bound sits near 0.07 and in every case: require improvement on a clear majority of proteins, not a median carried by a subset. """ INV_FLOOR_REL = 1e-6 # floor for the inverse square root, relative to the trace # An unfloored map in float64 should carry Cg to Cr to ~1e-13. A 1e-6 residual is a # failure, not an "exact" map; the legacy value would have passed the float32 pipeline # this run exists to replace. Floored maps are regularized by construction and are # tracked separately rather than judged against this. TRANSPORT_TOL = 1e-9 def emp_cov(x): """Empirical covariance, denominator n. `np.cov` defaults to n-1. The reference and generated sample sizes differ by an order of magnitude here, so those factors do not cancel between the two sides of the map, and the Gelbrich bound is defined for the empirical measure. """ xc = x - x.mean(0, keepdims=True) return (xc.T @ xc) / xc.shape[0] def _sym(a): return 0.5 * (a + a.T) def _psd_sqrt(c): """PSD square root. Only negative roundoff is clipped, so the Bures quantity is not perturbed by a positive floor.""" w, v = np.linalg.eigh(_sym(c)) w = np.clip(w, 0.0, None) return _sym((v * np.sqrt(w)) @ v.T) def _inv_sqrt(c): """Inverse square root with a positive relative floor. Returns whether it activated.""" w, v = np.linalg.eigh(_sym(c)) floor = max(INV_FLOOR_REL * max(w.sum(), 1e-30), 1e-30) activated = bool((w < floor).any()) w = np.clip(w, floor, None) return _sym((v * (1.0 / np.sqrt(w))) @ v.T), activated def bures_map(c_gen, c_ref): """Gaussian Brenier map from `c_gen` to `c_ref`, with transport diagnostics.""" g_half = _psd_sqrt(c_gen) g_inv_half, floored = _inv_sqrt(c_gen) middle = _psd_sqrt(_sym(g_half @ c_ref @ g_half)) a = _sym(g_inv_half @ middle @ g_inv_half) denom = max(np.linalg.norm(c_ref, "fro"), 1e-30) residual = float(np.linalg.norm(a @ c_gen @ a.T - c_ref, "fro") / denom) return a, floored, residual def w2(a, b, n_atoms): """Empirical 2-Wasserstein between equal-size clouds, in the reported units. Mirrors `analyse_bbflow._pca_w2` composed with `_get_wasserstein`. """ d = np.square(a[:, None] - b[None]).sum(-1) ** 0.5 / n_atoms ** 0.5 * 10.0 d = d ** 2 r, c = linear_sum_assignment(d) return float(d[r, c].mean() ** 0.5) def w2_sq_decomposition(a, b, n_atoms): """Split squared W2 into its mean and centred parts. For any two measures with finite second moments, writing `X = mu_P + X'`, E||X - Y||^2 = ||mu_P - mu_Q||^2 + E||X' - Y'||^2 because the cross term vanishes. The first term does not depend on the coupling, so the same coupling minimises both sides and W2^2(P, Q) = ||mu_P - mu_Q||^2 + W2^2(P_centred, Q_centred) holds exactly, empirical measures included. That makes it a hard invariant: any residual is a defect in the pipeline, not a property of the data. It is what the interaction between correction arms must satisfy, so a non-zero squared-scale interaction localises an inconsistency between how the arms are built. """ scale = 10.0 / n_atoms ** 0.5 dm = (a.mean(0) - b.mean(0)) * scale mean_term = float(dm @ dm) centred = w2(a - a.mean(0), b - b.mean(0), n_atoms) ** 2 total = w2(a, b, n_atoms) ** 2 return total, mean_term, centred def check_invariants(name, md_dir, ensemble_dir, k_dim, rng, n_folds, expect_gen): """Localise the squared-scale interaction between the correction arms. The mean/centred split of squared W2 is exact for every cloud on its own, but that alone does not force the interaction `G_affine - G_mean - G_cov` to vanish. Zero interaction additionally needs the arms to be a genuine factorial: mean-only must leave the centred cloud untouched, covariance-only must leave the mean untouched, and affine must be exactly covariance-only composed with the same mean shift. Two constructions here break that, and the diagnostic separates them: * the mean arm applies a *fold-specific* translation `m_ref - m_f`, so the reassembled cloud is not the raw cloud moved by one vector and its centred shape changes; * the covariance arm is globally recentred after reassembly while the affine arm is not. So the reported three arms are three separate interventions, not a factorial, and the interaction between them is not a distributional quantity. An explicit factorial is built alongside — raw, raw plus one global shift, the mean-preserving covariance cloud, and that cloud plus the same global shift — whose interaction must vanish to numerical error. It is a different estimator from the cross-fitted arms and is reported as such, never substituted for them. """ md_flat, gen_flat, n_atoms, _ = _load(name, md_dir, ensemble_dir) n_gen, n_md = gen_flat.shape[0], md_flat.shape[0] if expect_gen and n_gen != expect_gen: raise ValueError(f"{name}: {n_gen} generated samples, expected {expect_gen}") for arr, tag in ((md_flat, "reference"), (gen_flat, "generated")): if arr.dtype != np.float64: raise TypeError(f"{name}: {tag} coordinates are {arr.dtype}, expected float64") md_mean_all = md_flat.mean(0, keepdims=True) _, sing, vh = np.linalg.svd(md_flat - md_mean_all, full_matrices=False) basis = vh[:k_dim] md_p = (md_flat - md_mean_all) @ basis.T gen_p = (gen_flat - md_mean_all) @ basis.T perm = rng.permutation(n_md) md_eval = md_p[perm[:n_gen]] m_ref, c_ref = md_p[perm[n_gen:]].mean(0), emp_cov(md_p[perm[n_gen:]]) mean_arm = np.empty_like(gen_p) cov_pre = np.empty_like(gen_p) affine_arm = np.empty_like(gen_p) for fold in _fold_indices(n_gen, n_folds, rng): train = np.setdiff1d(np.arange(n_gen), fold) m_f, c_f = gen_p[train].mean(0), emp_cov(gen_p[train]) a, _, _ = bures_map(c_f, c_ref) held = gen_p[fold] mean_arm[fold] = held + (m_ref - m_f) cov_pre[fold] = (held - m_f) @ a.T + m_f affine_arm[fold] = (held - m_f) @ a.T + m_ref cov_arm = cov_pre + (gen_p.mean(0) - cov_pre.mean(0)) # Explicit factorial, defined after reassembly. Its interaction must vanish. shift = m_ref - gen_p.mean(0) fac = {"raw": gen_p, "mean": gen_p + shift, "cov": cov_arm, "affine": cov_arm + shift} scale = 10.0 / n_atoms ** 0.5 dec = {} for label, cloud in [("raw", gen_p), ("mean", mean_arm), ("cov_pre", cov_pre), ("cov", cov_arm), ("affine", affine_arm)]: dec[label] = w2_sq_decomposition(cloud, md_eval, n_atoms) def interaction(d): tot = {k: v[0] for k, v in d.items()} mt = {k: v[1] for k, v in d.items()} ct = {k: v[2] for k, v in d.items()} i_mean = mt["mean"] + mt["cov"] - mt["raw"] - mt["affine"] i_centred = ct["mean"] + ct["cov"] - ct["raw"] - ct["affine"] i_total = ((tot["raw"] - tot["affine"]) - (tot["raw"] - tot["mean"]) - (tot["raw"] - tot["cov"])) return i_total, i_mean, i_centred fac_dec = {k: w2_sq_decomposition(v, md_eval, n_atoms) for k, v in fac.items()} # Hard invariants: each must hold to numerical precision or the pipeline is wrong. hard = { "decomposition residual, max over clouds": max(abs(t - m - c) for t, m, c in list(dec.values()) + list(fac_dec.values())), # If these fail the defect is in the arm bookkeeping, not in the transport # solver; separating them tells you which layer to look at. "factorial mean arm != raw + shift": float(np.abs(fac["mean"] - (gen_p + shift)).max() * scale), "factorial affine arm != cov + shift": float(np.abs(fac["affine"] - (cov_arm + shift)).max() * scale), "covariance arm moves the mean": float(np.linalg.norm(cov_arm.mean(0) - gen_p.mean(0)) * scale), "recentring changes the centred cloud": float(np.abs((cov_arm - cov_arm.mean(0)) - (cov_pre - cov_pre.mean(0))).max() * scale), "explicit factorial interaction": abs(interaction(fac_dec)[0]), } # Soft diagnostics: expected to be non-zero, and the size is the finding. i_tot, i_mean, i_centred = interaction(dec) soft = { "mean arm alters the centred cloud (vs raw)": abs(dec["mean"][2] - dec["raw"][2]), "fold-specific mean arm vs one global shift, pointwise": float(np.abs(mean_arm - (gen_p + shift)).max() * scale), "affine arm vs cov_pre + global shift, pointwise": float(np.abs(affine_arm - (cov_pre + shift)).max() * scale), "affine arm mean minus m_ref": float(np.linalg.norm(affine_arm.mean(0) - m_ref) * scale), } means = { "raw -> reference": float(np.linalg.norm(gen_p.mean(0) - m_ref) * scale), "mean arm -> reference": float(np.linalg.norm(mean_arm.mean(0) - m_ref) * scale), "cov_pre -> raw": float(np.linalg.norm(cov_pre.mean(0) - gen_p.mean(0)) * scale), "cov -> raw": float(np.linalg.norm(cov_arm.mean(0) - gen_p.mean(0)) * scale), "affine -> reference": float(np.linalg.norm(affine_arm.mean(0) - m_ref) * scale), } c_g = emp_cov(gen_p) ev = np.linalg.eigvalsh(c_g) cond = float(ev.max() / max(ev.min(), 1e-300)) if len(sing) > k_dim: l2, l3 = sing[k_dim - 1] ** 2, sing[k_dim] ** 2 eigengap = float((l2 - l3) / max(l2, 1e-300)) else: eigengap = float("nan") return {"name": name, "dec": dec, "fac_dec": fac_dec, "hard": hard, "soft": soft, "means": means, "i_total": i_tot, "i_mean": i_mean, "i_centred": i_centred, "fac_i": interaction(fac_dec), "cov_eigs": ev, "cov_cond": cond, "pc_relgap": eigengap} def stable_seed(name, base): """Reproducible across processes; Python string hashing is randomised per run.""" h = hashlib.sha256(name.encode()).digest() return (base + int.from_bytes(h[:4], "big")) % (2 ** 32) def _ca_signature(traj): """Residue identity of the CA atoms, so a matching count with a different ordering cannot pass silently.""" return tuple(f"{a.residue.name}{a.residue.resSeq}{a.residue.chain.index}" for a in traj.top.atoms) def _load(name, md_dir, ensemble_dir): import mdtraj # imported here so the numeric path can be exercised without it top = os.path.join(md_dir, name, f"{name}.pdb") gen = os.path.join(ensemble_dir, name, "sampled_conformations.pdb") if not (os.path.exists(top) and os.path.exists(gen)): raise FileNotFoundError(f"{name}: missing reference or generated file") ref = mdtraj.load(top) ca = ref.top.select("name CA") if ca.size < 4: raise ValueError(f"{name}: {ca.size} CA atoms") ref = ref.atom_slice(ca) md, bounds = None, [] for i in (1, 2, 3): p = os.path.join(md_dir, name, f"{name}_R{i}.xtc") if not os.path.exists(p): continue part = mdtraj.load(p, top=top).atom_slice(ca) bounds.append((0 if md is None else md.n_frames, part.n_frames if md is None else md.n_frames + part.n_frames)) md = part if md is None else md + part if md is None: raise FileNotFoundError(f"{name}: no reference trajectory") g = mdtraj.load(gen) g = g.atom_slice(g.top.select("name CA")) if _ca_signature(g) != _ca_signature(ref): raise ValueError(f"{name}: CA residue identity differs between reference and generated") md.superpose(ref) g.superpose(ref) # mdtraj hands back float32. Casting here does not recover precision already lost in # the coordinates, but it keeps covariance estimation, the eigendecompositions, the # matrix square roots and the transport residual in float64 -- the residual was # sitting at 1e-6, which is float32 accumulation, not float64 machine precision. return (md.xyz.reshape(md.n_frames, -1).astype(np.float64), g.xyz.reshape(g.n_frames, -1).astype(np.float64), ca.size, bounds) def _fold_indices(n, k, rng): order = rng.permutation(n) return np.array_split(order, k) def audit_one(name, md_dir, ensemble_dir, k_dim, rng, n_folds, n_reps, expect_gen): md_flat, gen_flat, n_atoms, bounds = _load(name, md_dir, ensemble_dir) n_gen, n_md = gen_flat.shape[0], md_flat.shape[0] if expect_gen and n_gen != expect_gen: raise ValueError(f"{name}: {n_gen} generated samples, expected {expect_gen}") if n_folds > n_gen: raise ValueError(f"{name}: {n_folds} folds requested for {n_gen} samples") if n_md < 2 * n_gen: raise ValueError(f"{name}: {n_md} reference frames, need at least {2 * n_gen}") # Axes from the full trajectory, matching the metric's own definition. md_mean_all = md_flat.mean(0, keepdims=True) _, sing, vh = np.linalg.svd(md_flat - md_mean_all, full_matrices=False) basis = vh[:k_dim] def proj(x): return (x - md_mean_all) @ basis.T md_p, gen_p = proj(md_flat), proj(gen_flat) # Disjoint reference pools: one supplies the scored cloud, the other the target # moments. Fitting the correction to the frames it is scored against would # manufacture agreement. perm = rng.permutation(n_md) eval_idx, moment_idx = perm[:n_gen], perm[n_gen:] md_eval = md_p[eval_idx] m_ref, c_ref = md_p[moment_idx].mean(0), emp_cov(md_p[moment_idx]) row = {"name": name, "n_res": n_atoms, "n_gen": n_gen, "n_md": n_md} row["w2_raw"] = w2(md_eval, gen_p, n_atoms) # Finite-sample floor: two clouds resampled with replacement from the empirical # reference distribution. This is the OT sampling floor conditional on the observed # trajectory, which is the quantity the metric is subject to. row["floor"] = float(np.mean([ w2(md_p[rng.integers(0, n_md, n_gen)], md_p[rng.integers(0, n_md, n_gen)], n_atoms) for _ in range(n_reps) ])) # Sensitivity: distinct trajectory segments, which additionally absorb slow drift. seg = [w2(md_p[rng.choice(np.arange(*a), n_gen, replace=len(range(*a)) < n_gen)], md_p[rng.choice(np.arange(*b), n_gen, replace=len(range(*b)) < n_gen)], n_atoms) for i, a in enumerate(bounds) for b in bounds[i + 1:]] row["floor_replica"] = float(np.mean(seg)) if seg else float("nan") flooring_hits, transport_max, transport_max_unfloored = 0, 0.0, 0.0 # In-sample: map estimated on the very cloud it corrects. m_g, c_g = gen_p.mean(0), emp_cov(gen_p) a_in, fl, res = bures_map(c_g, c_ref) flooring_hits += int(fl) transport_max = max(transport_max, res) if not fl: transport_max_unfloored = max(transport_max_unfloored, res) row["w2_mean_insample"] = w2(md_eval, gen_p + (m_ref - m_g), n_atoms) row["w2_cov_insample"] = w2(md_eval, (gen_p - m_g) @ a_in.T + m_g, n_atoms) # In sample there is one global map, which already leaves `m_g` in place, so the # arm before recentring and the arm after it are the same cloud. Stated rather than # left to be inferred, since every mode in `per_rep` needs an in-sample counterpart. row["w2_cov_pre_insample"] = row["w2_cov_insample"] row["w2_affine_insample"] = w2(md_eval, (gen_p - m_g) @ a_in.T + m_ref, n_atoms) # Cross-fitted: reassemble a full out-of-fold cloud so the scored sample size matches # the metric's, then average over repeated partitions. Per-repetition values are kept # so split instability is visible rather than averaged away. # `cov_pre` is the covariance arm before its global recentring. It is carried as a # supplementary arm so the effect of the recentring is visible in the reported table, # not only under --invariants. per_rep = {m: [] for m in ("mean", "cov", "cov_pre", "affine")} fold_conds, fold_min_eigs = [], [] for _ in range(n_reps): out = {m: np.empty_like(gen_p) for m in per_rep} for fold in _fold_indices(n_gen, n_folds, rng): train = np.setdiff1d(np.arange(n_gen), fold, assume_unique=False) m_f, c_f = gen_p[train].mean(0), emp_cov(gen_p[train]) a, fl, res = bures_map(c_f, c_ref) flooring_hits += int(fl) transport_max = max(transport_max, res) if not fl: transport_max_unfloored = max(transport_max_unfloored, res) # The maps are fitted per fold, so the conditioning that matters is the # per-fold covariance's, not the whole cloud's. ev_f = np.linalg.eigvalsh(_sym(c_f)) fold_conds.append(float(ev_f.max() / max(ev_f.min(), 1e-300))) fold_min_eigs.append(float(ev_f.min())) held = gen_p[fold] out["mean"][fold] = held + (m_ref - m_f) # Every fold is centred on its *training* mean, so the reassembled cloud is # what applying the estimated maps to the population would give. Recentring # each fold on its own mean instead would leave between-fold mean variation # untransformed and make the result depend on the arbitrary partition. out["cov_pre"][fold] = (held - m_f) @ a.T + m_f out["cov"][fold] = out["cov_pre"][fold] out["affine"][fold] = (held - m_f) @ a.T + m_ref # One global translation restores the original mean exactly, which a rigid shift # does without touching the transformed covariance. Covariance-only therefore # contributes no mean correction at all. out["cov"] = out["cov_pre"] + (gen_p.mean(0) - out["cov_pre"].mean(0)) for m in per_rep: per_rep[m].append(w2(md_eval, out[m], n_atoms)) for m, vals in per_rep.items(): row[f"w2_{m}_cv"] = float(np.mean(vals)) row[f"w2_{m}_cv_sd"] = float(np.std(vals, ddof=1)) if len(vals) > 1 else 0.0 row[f"gain_{m}_cv"] = row["w2_raw"] - row[f"w2_{m}_cv"] row[f"gain_{m}_insample"] = row["w2_raw"] - row[f"w2_{m}_insample"] # Repetition-level values are retained, not averaged away: the Monte Carlo # uncertainty that matters is that of the across-protein median, which cannot be # reconstructed from per-protein summaries alone. for r, v in enumerate(vals): row[f"w2_{m}_rep{r}"] = float(v) row["floored_maps"] = flooring_hits row["transport_residual_max"] = transport_max # Judged separately: a floored map is regularized by construction and its residual # says nothing about arithmetic, whereas an unfloored map in float64 must be exact. row["transport_residual_max_unfloored"] = transport_max_unfloored row["fold_cond_max"] = float(np.max(fold_conds)) row["fold_min_eig"] = float(np.min(fold_min_eigs)) ev_ref = np.linalg.eigvalsh(_sym(c_ref)) row["ref_cond"] = float(ev_ref.max() / max(ev_ref.min(), 1e-300)) # Relative gap at the projection cut. An absolute singular-value difference scales # with trajectory length and coordinate units and is not comparable across proteins. if len(sing) > k_dim: l2, l3 = sing[k_dim - 1] ** 2, sing[k_dim] ** 2 row["pc_relgap"] = float((l2 - l3) / max(l2, 1e-300)) else: row["pc_relgap"] = float("nan") # Moment errors. `mean_err_eval` is the quantity that enters the exact squared-W2 # mean decomposition against the scored cloud; `mean_err_target` is the error against # the population target the map actually corrects toward. scale = 10.0 / n_atoms ** 0.5 row["mean_err_target"] = float(np.linalg.norm(gen_p.mean(0) - m_ref) * scale) row["mean_err_eval"] = float(np.linalg.norm(gen_p.mean(0) - md_eval.mean(0)) * scale) cross = _psd_sqrt(_psd_sqrt(c_ref) @ c_g @ _psd_sqrt(c_ref)) row["bures_err"] = float( np.sqrt(max(np.trace(c_g) + np.trace(c_ref) - 2 * np.trace(cross), 0.0)) * scale) row["trace_ratio"] = float(np.trace(c_g) / max(np.trace(c_ref), 1e-30)) return row 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, help="projected dimensions; the metric uses 2 and the decision run must") ap.add_argument("--n_folds", type=int, default=5) ap.add_argument("--n_reps", type=int, default=10) ap.add_argument("--expect_gen", type=int, default=250, help="required generated ensemble size; 0 disables the check") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out_csv", default="") ap.add_argument("--invariants", type=int, default=0, help="arm-consistency checks on this many proteins then exit; -1 = all") ap.add_argument("--compare_csv", default="", help="previous per-protein CSV; report the paired change against it") ap.add_argument("--equiv_tol", type=float, default=0.001, help="tolerance for calling --compare_csv equivalent, in Angstrom") ap.add_argument("--ratio_tol", type=float, default=0.002, help="separate tolerance for the dimensionless trace_ratio") args = ap.parse_args() if args.k != 2: warnings.warn(f"--k {args.k}: the decision thresholds are calibrated for k=2") if args.n_reps < 2: raise SystemExit("--n_reps must be at least 2; the Monte Carlo spread is the point") if args.n_folds < 2 or (args.expect_gen and args.n_folds > args.expect_gen): raise SystemExit(f"--n_folds must lie in [2, {args.expect_gen or 'n_gen'}]") labels = args.names or [os.path.basename(d.rstrip("/")) for d in args.ensemble_dirs] if len(labels) != len(args.ensemble_dirs): raise SystemExit("--names must match --ensemble_dirs in length") if len(set(labels)) != len(labels): raise SystemExit("run labels must be unique; otherwise the summary silently merges runs") import pandas as pd # One cohort for every checkpoint. Independent per-directory listings would let a # failure in one run silently shift its median relative to the others. per_dir = [set(d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))) for e in args.ensemble_dirs] cohort = sorted(set.intersection(*per_dir)) for label, s in zip(labels, per_dir): missing = sorted(set().union(*per_dir) - s) if missing: print(f" [{label}] absent: {len(missing)} -> {missing[:6]}") print(f"cohort common to all runs: {len(cohort)} proteins\n") if args.invariants: n_check = len(cohort) if args.invariants < 0 else min(args.invariants, len(cohort)) print(f"{'='*78}\n arm-consistency invariants, {n_check} proteins\n{'='*78}") print(" HARD invariants must hold to numerical precision; a violation is a defect.") print(" SOFT diagnostics are expected to be non-zero: the reported three arms are") print(" three separate interventions, not a factorial, because the mean arm uses") print(" fold-specific translations and the covariance arm is globally recentred.") print(" The explicit factorial built alongside must show zero interaction.\n") HARD_TOL = 1e-9 violations = [] agg = {} # Conditioning is data dependent, so every checkpoint is checked, not only the # first: a map can be well conditioned on one ensemble and not on another. for label, ens in zip(labels, args.ensemble_dirs): print(f" [{label}]") for nm in cohort[:n_check]: rng = np.random.default_rng(stable_seed(nm, args.seed)) r = check_invariants(nm, args.md_dir, ens, args.k, rng, args.n_folds, args.expect_gen) for k, v in r["hard"].items(): agg.setdefault(("HARD", k), []).append(v) if v > HARD_TOL: violations.append((f"{label}/{nm}", k, v)) for k, v in r["soft"].items(): agg.setdefault(("SOFT", k), []).append(v) for k, v in r["means"].items(): agg.setdefault(("mean distance", k), []).append(v) for k, v in (("I(W2^2) total", r["i_total"]), (" mean part", r["i_mean"]), (" centred part", r["i_centred"]), ("I(W2^2) explicit factorial", r["fac_i"][0]), ("covariance condition number", r["cov_cond"]), ("PC relative gap at the cut", r["pc_relgap"])): agg.setdefault(("interaction", k), []).append(v) if n_check <= 3: print(f" {r['name']}") print(f" {'cloud':<10}{'W2^2':>11}{'mean term':>12}{'centred':>11}{'resid':>11}") for label, (tot, mt, ct) in r["dec"].items(): print(f" {label:<10}{tot:>11.5f}{mt:>12.5f}{ct:>11.5f}{abs(tot-mt-ct):>11.2e}") print() for section in ("HARD", "SOFT", "mean distance", "interaction"): keys = [k for (sec, k) in agg if sec == section] if not keys: continue print(f" --- {section} (median over {n_check} proteins x {len(labels)} runs) ---") for k in keys: v = np.median(agg[(section, k)]) mx = np.max(np.abs(agg[(section, k)])) flag = "" if section == "HARD": flag = " <-- VIOLATED" if mx > HARD_TOL else " ok" print(f" {k:<52}{v:>12.3e} max {mx:>10.3e}{flag}") print() if violations: print(f" {len(violations)} hard-invariant violations, first five:") for nm, k, v in violations[:5]: print(f" {nm} {k} {v:.3e}") raise SystemExit(1) print(" all hard invariants hold") return rows, failures = [], {} for label, ens in zip(labels, args.ensemble_dirs): print(f"[{label}]", flush=True) for i, nm in enumerate(cohort): rng = np.random.default_rng(stable_seed(nm, args.seed)) try: r = audit_one(nm, args.md_dir, ens, args.k, rng, args.n_folds, args.n_reps, args.expect_gen) r["run"] = label # Matching on (run, name) does not prove like was compared with like. r.update({"cfg_seed": args.seed, "cfg_folds": args.n_folds, "cfg_reps": args.n_reps, "cfg_k": args.k, "cfg_expect_gen": args.expect_gen}) rows.append(r) except Exception as exc: # noqa: BLE001 failures.setdefault(label, []).append(f"{nm}: {type(exc).__name__}: {exc}") if (i + 1) % 20 == 0: print(f" {i+1}/{len(cohort)}", 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") # Summarise only proteins that succeeded everywhere, so the medians are paired. counts = df.groupby("name")["run"].nunique() shared = set(counts[counts == len(labels)].index) dropped = len(cohort) - len(shared) if dropped: print(f"\n{dropped} proteins failed in at least one run and are excluded") if not shared: raise SystemExit("no protein succeeded in every run; nothing is comparable") df = df[df.name.isin(shared)] if args.out_csv: df.to_csv(args.out_csv, index=False) print(f"per-protein values -> {args.out_csv}") if args.compare_csv: old = pd.read_csv(args.compare_csv) key = ["run", "name"] for tag, frame in (("new", df), ("previous", old)): if frame.duplicated(key).any(): raise SystemExit(f"{tag} table has duplicate (run, name) keys") # Required columns are validated up front. A conditionally built column list can # otherwise report "equivalent" while silently having compared nothing. # The schema splits three ways. Imposing the new columns on the previous table # would reject the very pre-change CSV this comparison exists to check against. REQUIRED_BOTH = ["w2_raw", "w2_mean_cv", "w2_cov_cv", "w2_affine_cv", "bures_err", "mean_err_eval", "trace_ratio"] REQUIRED_NEW = ["transport_residual_max_unfloored", "floored_maps", "fold_cond_max", "fold_min_eig", "ref_cond", "pc_relgap"] NEW_ONLY = ["w2_cov_pre_cv"] # no counterpart to compare against missing = [c for c in REQUIRED_BOTH if c not in df.columns] missing += [c for c in REQUIRED_NEW + NEW_ONLY if c not in df.columns] if missing: raise SystemExit(f"new table is missing required columns: {missing}") missing_old = [c for c in REQUIRED_BOTH if c not in old.columns] if missing_old: raise SystemExit(f"previous table is missing required columns: {missing_old}") absent_old = [c for c in REQUIRED_NEW + NEW_ONLY if c not in old.columns] if absent_old: print(f" new outputs with no counterpart in the previous table, judged" f" absolutely rather than paired: {absent_old}") # A provenance comparison run under a different configuration cannot conclude # equivalence, so a mismatch is fatal rather than a warning. for c in ("cfg_seed", "cfg_folds", "cfg_reps", "cfg_k", "cfg_expect_gen"): if c not in df.columns or c not in old.columns: warnings.warn(f"{c} absent from one table; provenance unverified " "(expected when comparing against a pre-change CSV)") continue a, b = sorted(df[c].unique().tolist()), sorted(old[c].unique().tolist()) if a != b: raise SystemExit(f"{c} differs between tables: {a} vs {b}; " "the two runs are not comparable") j = df.merge(old, on=key, suffixes=("_new", "_old")) if len(j) != len(df) or len(j) != len(old): raise SystemExit( f"row counts disagree: new {len(df)}, previous {len(old)}, " f"matched {len(j)}. A dropped row would make this meaningless.") contrasts = {"gain_affine": ("w2_raw", "w2_affine_cv"), "gain_mean": ("w2_raw", "w2_mean_cv"), "gain_cov": ("w2_raw", "w2_cov_cv"), "cov_after_mean": ("w2_mean_cv", "w2_affine_cv")} print(f"\n{'='*78}\n equivalence against {args.compare_csv}\n{'='*78}") print(f" Paired within (run, protein). {len(j)} rows, all matched.\n") worst, worst_ratio = 0.0, 0.0 print(f" {'quantity':<26}{'median |d|':>14}{'max |d|':>12}{'at':>14}{'verdict':>10}") def line(label, d_, tol, bucket="angstrom"): nonlocal worst, worst_ratio if not np.isfinite(d_).all(): raise SystemExit(f"non-finite change in {label}") if tol is not None: if bucket == "angstrom": worst = max(worst, float(d_.max())) else: worst_ratio = max(worst_ratio, float(d_.max())) at = j.loc[d_.idxmax(), "name"] v = "-" if tol is None else ("ok" if d_.max() < tol else "EXCEEDS") print(f" {label:<26}{d_.median():>14.6f}{d_.max():>12.6f}{at:>14}{v:>10}") for c in [c for c in df.columns if c in old.columns and c.startswith(("w2_", "mean_err", "bures", "floor")) and not c.endswith("_sd") and "_rep" not in c and c not in NEW_ONLY]: line(c, (j[f"{c}_new"] - j[f"{c}_old"]).abs(), args.equiv_tol) print() # The contrasts are what the decision reads. Each column can move under # tolerance while their difference moves over it. for label, (a, b) in contrasts.items(): d_ = ((j[f"{a}_new"] - j[f"{b}_new"]) - (j[f"{a}_old"] - j[f"{b}_old"])).abs() line(label, d_, args.equiv_tol) print() # Dimensionless but scientifically meaningful, so it gets its own bound rather # than being waved through as a numerical diagnostic. line("trace_ratio", (j["trace_ratio_new"] - j["trace_ratio_old"]).abs(), args.ratio_tol, bucket="ratio") # The transport residual is judged against an absolute float64 correctness bound, # not against the previous run -- the previous run is what is being replaced. rescol = ("transport_residual_max_unfloored_new" if "transport_residual_max_unfloored_new" in j else "transport_residual_max_unfloored") floorcol = "floored_maps_new" if "floored_maps_new" in j else "floored_maps" res_new = j[rescol] if not np.isfinite(res_new).all(): raise SystemExit("non-finite transport residual in the new table") bad = int((res_new > TRANSPORT_TOL).sum()) floored_rows = int((j[floorcol] > 0).sum()) print(f"\n unfloored transport residual: median {res_new.median():.3e}" f" max {res_new.max():.3e} " + ("ok" if bad == 0 else f"{bad} rows above {TRANSPORT_TOL:.0e}")) print(f" rows with at least one floored map: {floored_rows}" + ("" if floored_rows == 0 else " <-- those are regularized estimators")) # Column equivalence is not the claim; the reported table is. print(f"\n {'run':<16}" + "".join(f"{c + ' (change)':>26}" for c in contrasts)) for r in sorted(j.run.unique()): g = j[j.run == r] cells = "" for a, b in contrasts.values(): gn = float((g[f"{a}_new"] - g[f"{b}_new"]).median()) go = float((g[f"{a}_old"] - g[f"{b}_old"]).median()) cells += f"{gn:>17.4f}{gn - go:>+9.4f}" print(f" {r:<16}{cells}") ok = worst < args.equiv_tol and worst_ratio < args.ratio_tol and bad == 0 verdict = ("equivalent; the previous table may be replaced" if ok else "NOT equivalent -- investigate before replacing anything") print(f"\n worst Angstrom change {worst:.6f} vs {args.equiv_tol}" f" worst ratio change {worst_ratio:.6f} vs {args.ratio_tol}" f" residual violations {bad}\n {verdict}") def boot(v, n=4000): v = np.asarray(v, float) s = np.random.default_rng(0).choice(v, (n, v.size), replace=True) return np.percentile(np.median(s, axis=1), [2.5, 97.5]) print(f"\n{'='*78}\n Phase A: recoverable by exact first- and second-moment correction\n{'='*78}") print(f" cohort {len(shared)} proteins {args.n_folds}-fold x {args.n_reps} repetitions") for label in labels: d = df[df.run == label] if d.empty: continue print(f"\n--- {label} ---") print(f" uncorrected {d['w2_raw'].median():.4f}") print(f" resampled reference floor {d['floor'].median():.4f}" f" (distinct segments: {d['floor_replica'].median():.4f})") print(f" projected mean error vs target {d['mean_err_target'].median():.4f}" f" (vs scored cloud: {d['mean_err_eval'].median():.4f})") print(f" projected Bures covariance error {d['bures_err'].median():.4f}") print(f" covariance trace ratio {d['trace_ratio'].median():.4f}") fl = int(d['floored_maps'].sum()) print(f" eigenvalue floor activations {fl}" f" max transport residual {d['transport_residual_max'].max():.2e}" f"{' <-- REGULARIZED, not exact' if fl or d['transport_residual_max'].max() > TRANSPORT_TOL else ''}") print(f"\n {'correction':<10}{'in-sample':>20}{'cross-fitted':>30}") print(f" {'':10}{'W2':>10}{'gain':>10}{'W2':>10}{'gain':>10}" f"{'95% CI of gain':>22}{'win':>7}{'~MC SE':>9}{'p90 prot':>10}") for m in ("mean", "cov", "cov_pre", "affine"): g = d[f"gain_{m}_cv"] lo, hi = boot(g) # Monte Carlo uncertainty of the *reported median gain*: recompute the # across-protein median separately for each repetition, then take the spread # of those. The median of the per-protein SDs answers a different question. per_rep_median = [ float((d["w2_raw"] - d[f"w2_{m}_rep{r}"]).median()) for r in range(args.n_reps) ] mc = float(np.std(per_rep_median, ddof=1) / np.sqrt(args.n_reps)) p90 = float((d[f"w2_{m}_cv_sd"] / np.sqrt(args.n_reps)).quantile(0.90)) print(f" {m:<10}{d[f'w2_{m}_insample'].median():>10.4f}" f"{d[f'gain_{m}_insample'].median():>10.4f}" f"{d[f'w2_{m}_cv'].median():>10.4f}{g.median():>10.4f}" f" [{lo:+.4f}, {hi:+.4f}]{(g > 0).mean():>7.2f}{mc:>9.4f}{p90:>10.4f}") # The contrast being adjudicated for the covariance line needs its own interval, # not only the standalone arms. inc = d["w2_mean_cv"] - d["w2_affine_cv"] lo, hi = boot(inc) # Not a factorial conditional: the mean and affine arms can have different # reassembled means, so this is the contrast between those two arms, no more. print(f"\n affine arm minus mean arm (covariance contrast)" f" {inc.median():>+8.4f} [{lo:+.4f}, {hi:+.4f}]" f" win {(inc > 0).mean():.2f}") print(f"\n{'='*78}\n prespecified decision rule\n{'='*78}{DECISION}") print(" Decide on the cross-fitted `affine` gain; in-sample is the optimistic bound.") print(" ~MC SE is an approximation (the median is nonlinear) and should sit well") print(" below 0.005; if not, raise --n_reps. A rerun under a different --seed is the") print(" decisive stability check when the gain lands near a threshold.") print(" A small gain says post-hoc moment calibration has little to offer on these") print(" ensembles -- strong practical evidence against another covariance objective,") print(" though not a proof, since training can also move modality and tails. The") print(" residual after correction is an operational remainder, not a formal") print(" higher-order share: only the mean term separates exactly in squared W2.") if __name__ == "__main__": main()