File size: 44,731 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
"""Is the reference centroid a stable target, or an artefact of a finite trajectory window?

An oracle experiment showed that correcting the generated ensemble's mean in the scored
2-D plane recovers 0.34-0.53 Angstrom of PCA-W2, two to five times what correcting the
covariance recovers. That correction used the test protein's own MD. Before anything is
built on it, the target has to be shown to be a property of the protein rather than of the
window it was estimated in.

Why almost no transport is computed
-----------------------------------
The metric is a true empirical W2: `analyse_bbflow._get_wasserstein` squares the distance
matrix, assigns, means, takes the root, and asserts the matrix is square. So the mean
separates exactly. For a fixed pairing the squared cost splits into a mean term plus a
centred term, the mean term does not depend on the pairing, so the optimal pairing is the
same for the centred clouds and

    W2^2(G, R) = ||mu_G - mu_R||^2 + C,      C = W2^2(G - mu_G, R - mu_R)

Translating `G` moves only the first term. One transport per block pair gives `C`, and
every arm, every correction strength, and the random-direction control are then closed
form. `--verify` checks this against transport actually computed on a shifted cloud.

The two results
---------------
**Primary**, at the production cloud size: a centroid estimated on one whole trajectory
segment, applied, and scored against a draw from a different segment. This is the estimand
the question is about and the only row a threshold is applied to.

**Diagnostic ladder**, every row at one common cloud size, one common number of
centroid-estimation frames, and one common reference support, so the rows differ in
temporal separation and nothing else. The support matters as much as the rest: a 100-frame
sub-block and a 1001-frame segment drawn to the same cloud size have very different
duplicate rates, and `C` sits inside every square root.

    no separation   a random disjoint subset of the scored block itself
    within L        a contiguous gap-separated sub-block, short lag
    adjacent        the other half of the same segment, both directions, medium lag
    between         a different segment, long lag

`retention` is the fraction of the no-separation gain that survives at each lag. It is
explanatory only. **The gate is the absolute transferred gain**, because retention of 0.30
against a 0.40 Angstrom achievable gain is still 0.12 Angstrom, and because a ratio is
unstable when its denominator is small.

Estimand hazards this script tries not to fall into
---------------------------------------------------
  The oracle never uses the frames being scored. Taking its centroid in sample lets it
  chase the particular draw, which inflates the denominator and depresses retention.

  Transferred and oracle centroids are estimated from the *same number* of frames. The
  distant block is longer than the scored block's disjoint remainder, and leaving that
  unequal hands the transferred arm an advantage that has nothing to do with lag.

  The scored draw is taken with replacement from a disjoint pool, matching what
  `analyse_bbflow` does (`np.random.randint`), while keeping the estimation frames out.

  The no-separation control draws its transferred estimate from a *third* disjoint pool.
  Taking it from the whole scored block would let it overlap the frames being scored
  while the oracle cannot, which handicaps the oracle instead of controlling anything.

  The random-direction control is the expectation of the W2, `E[sqrt(C + m)]`, by 64-point
  angular quadrature. Using `sqrt(C + E[m])` instead is an RMS over directions, is larger
  by Jensen, and makes "beats random" too easy.

  The primary arm is the one place estimation sizes are deliberately *not* matched: its
  estimand is the best correction the whole of segment A affords, and cutting A to the
  oracle's precision would discard half the segment and could manufacture a false
  negative. Retention for the primary is therefore not reported; the ladder's
  "different segment" row is the matched-size version.

Both between-segment arms are always computed. In one, the model-side centroid the
correction subtracts is the scored cloud's own mean, so the correction sets the shifted
centroid exactly and cancels the realized Monte Carlo error of that draw. That is fine for
an inference-time procedure that recentres every cloud, and it is not evidence about a
learned objective, which can move a population mean but cannot know one draw's error. In
the other the model-side centroid comes from a disjoint half of the generated frames,
which necessarily halves the scored cloud, so **it gets no verdict**: its Angstroms are
not the metric the threshold was set on. It does gate the verdict qualitatively -- a
primary pass whose held-out counterpart collapses is reported as unresolved, because the
ceiling would then be partly the leak.

What a pass would and would not mean
------------------------------------
The transferred gain is a ceiling. It says a centroid estimated somewhere else is worth
that much, not that anything can predict one. A pass justifies running the MD-free
prediction test and nothing more. The fractional-strength rows exist to make the
predictor-efficiency assumption explicit before that test rather than after it.

Stability is also not enough on its own: these PCA coordinates carry an arbitrary sign and
an arbitrary rotation inside a near-degenerate leading pair, so the shift is not itself a
cross-protein prediction target. A deployable predictor would emit a structural correction
in a deterministic frame, projected only for evaluation.

Note also that the pooled PCA axes here come from the held-out protein's full MD. That is
correct for evaluating the published metric and impossible for a deployable method.
"""

import argparse
import hashlib
import os

import numpy as np
from scipy.optimize import linear_sum_assignment

VERIFY_TOL = 1e-9
# Two effective observations is enough to say "almost no information", not enough to
# clear a stability result. Cells below this are masked out of every median.
MIN_ESS_CELL = 5.0
FRACTIONS = (0.25, 0.5, 0.75)


def stable_seed(name, base):
    h = hashlib.sha256(name.encode()).digest()
    return (base + int.from_bytes(h[:4], "big")) % (2 ** 32)


def _ca_signature(traj):
    return tuple(f"{a.residue.name}{a.residue.resSeq}{a.residue.chain.index}"
                 for a in traj.top.atoms)


def load_reference(name, md_dir, require_segments):
    """The MD side. Everything here depends on the protein alone, never on a checkpoint."""
    import mdtraj
    top = os.path.join(md_dir, name, f"{name}.pdb")
    if not os.path.exists(top):
        raise FileNotFoundError(f"{name}: no reference topology at {top}")

    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)
        lo = 0 if md is None else md.n_frames
        md = part if md is None else md + part
        bounds.append((lo, md.n_frames))
    if md is None or len(bounds) < require_segments:
        raise FileNotFoundError(f"{name}: {len(bounds)} trajectory segments, "
                                f"{require_segments} required")
    md.superpose(ref)
    return ref, md.xyz.reshape(md.n_frames, -1).astype(np.float64), ca.size, bounds


def load_generated(name, ensemble_dir, ref):
    gen = os.path.join(ensemble_dir, name, "sampled_conformations.pdb")
    if not os.path.exists(gen):
        raise FileNotFoundError(f"{name}: no generated ensemble at {gen}")
    import mdtraj
    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 ensemble")
    g.superpose(ref)
    return g.xyz.reshape(g.n_frames, -1).astype(np.float64)


def md_context(name, md_dir, k_dim, require_segments):
    """Projection basis, segments and autocorrelations, computed once per protein.

    The pooled SVD of a 3003 x 3N trajectory dominates the runtime and depends only on
    the MD, so recomputing it per checkpoint would multiply the cost of comparing runs by
    the number of runs for no new information.
    """
    ref, md_flat, n_atoms, bounds = load_reference(name, md_dir, require_segments)
    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
    segs = [md_p[a:b] for a, b in bounds]
    return {"ref": ref, "n_atoms": n_atoms, "n_md": md_flat.shape[0], "bounds": bounds,
            "centre": md_mean_all, "basis": basis, "md_p": md_p, "segs": segs,
            "acs": [ac for s in segs for ac in autocorr_set(s)], "sing": sing}


def w2_sq(a, b, scale):
    """Empirical squared W2 in the metric's units. Both clouds must have equal size."""
    if a.shape[0] != b.shape[0]:
        raise ValueError(f"unequal cloud sizes {a.shape[0]} vs {b.shape[0]}")
    d = np.square(a[:, None] - b[None]).sum(-1) * scale ** 2
    r, c = linear_sum_assignment(d)
    return float(d[r, c].mean())


def autocorr_set(x, max_lag_frac=0.5):
    """`(tau, rho)` for every projected coordinate, `rho` cut at the Geyer truncation.

    Geyer's initial monotone positive sequence: sum the paired autocovariances
    `Gamma_m = rho_2m + rho_2m+1`, stop at the first non-positive pair, then enforce
    monotonicity. Truncating on individual `rho_k` stops far too early on noisy MD and
    overstates independence, which would let a null be cleared that the data cannot
    support.

    Every coordinate is returned rather than only the one with the largest asymptotic
    tau, because the slowest coordinate at infinite lag is not necessarily the one with
    the least independent content in a 100-frame block, and the block mask wants the
    worst of those. Only the projected coordinates are examined, so a slow direction that
    is a mixture of PC1 and PC2 can still be understated: these are upper bounds.
    """
    n = x.shape[0]
    max_lag = max(2, int(n * max_lag_frac))
    out = []
    for j in range(x.shape[1]):
        v = x[:, j] - x[:, j].mean()
        denom = float(v @ v)
        if denom <= 0:
            continue
        rho = np.array([1.0] + [float(v[:-k] @ v[k:]) / denom for k in range(1, max_lag)])
        gammas, m = [], 0
        while 2 * m + 1 < len(rho):
            g = rho[2 * m] + rho[2 * m + 1]
            if g <= 0:
                break
            gammas.append(g)
            m += 1
        for i in range(1, len(gammas)):
            gammas[i] = min(gammas[i], gammas[i - 1])
        tau = max(2.0 * sum(gammas) - 1.0, 1.0) if gammas else 1.0
        # Cut at the Geyer truncation. Past it the sample autocorrelations are noise
        # each carrying a -1/n bias, and summing hundreds of them cancels the signal
        # outright: on AR(1) at phi 0.5 the untruncated sum called all 4000 frames
        # independent instead of 1333.
        out.append((tau, rho[:max(2 * len(gammas), 1)]))
    return out or [(1.0, np.array([1.0]))]


def ess_block(rho, length):
    """Effective sample size of a mean over `length` contiguous frames.

    Uses the finite-length form with the triangular weight, `1 + 2 sum (1 - k/L) rho_k`.
    Scaling a whole-segment ESS by `L / segment_length` instead assumes independent
    content grows linearly in block length, which is optimistic exactly where it matters,
    when the block is near or below the correlation time.
    """
    k = np.arange(1, min(length, len(rho)))
    if k.size == 0:
        return float(length)
    tau = 1.0 + 2.0 * float(((1.0 - k / length) * rho[k]).sum())
    return float(length / max(tau, 1.0))


def moving_block_se(x, block, rng, n_boot):
    """Centroid standard error under a moving-block bootstrap, correlation preserved."""
    n = x.shape[0]
    block = max(1, min(int(block), n))
    n_blocks = int(np.ceil(n / block))
    means = np.empty((n_boot, x.shape[1]))
    for b in range(n_boot):
        starts = rng.integers(0, n - block + 1, n_blocks)
        means[b] = x[np.concatenate([np.arange(s, s + block) for s in starts])[:n]].mean(0)
    return float(np.linalg.norm(means.std(0, ddof=1)))


def quadrature_directions(k, n_quad, seed=0):
    """Deterministic unit directions for the random-shift expectation."""
    if k == 2:
        th = np.arange(n_quad) * (2 * np.pi / n_quad)
        return np.stack([np.cos(th), np.sin(th)], axis=1)
    d = np.random.default_rng(seed).normal(size=(n_quad, k))
    return d / np.linalg.norm(d, axis=1, keepdims=True)


def score_pair(gen_score, mu_apply, mu_trn, mu_oracle, ref_score, scale, quad, n_est,
               group=0):
    """All arms for one block pair, sharing the single transport that gives `C`.

    Sharing `C` is exact, not an approximation, and it is what makes the arms paired.

    When `mu_apply` is a held-out generated centroid, `transferred_alt` repeats the
    transferred arm using the scored cloud's own mean instead, on the identical cloud,
    reference draw and A centroid. The difference between the two isolates exactly what
    sample recentring buys, at matched `n` and perfectly paired -- comparing a 250-sample
    in-sample arm with a 125-sample held-out one confounds the leak with the cloud size.
    """
    mu_b, mu_gs, s2 = ref_score.mean(0), gen_score.mean(0), scale ** 2
    c = w2_sq(gen_score - mu_gs, ref_score - mu_b, scale)
    d = mu_gs - mu_b

    def w2_of(shift):
        return float(np.square(d + shift).sum() * s2 + c) ** 0.5

    step = mu_trn - mu_apply
    out = {"uncorrected": w2_of(0.0), "oracle": w2_of(mu_oracle - mu_apply),
           "transferred": w2_of(step), "transferred_alt": w2_of(mu_trn - mu_gs), "C": c,
           "m_trn": float(np.square(d + step).sum()) * s2,
           "n_used": gen_score.shape[0], "n_est": n_est, "group": group}
    for a in FRACTIONS:
        out[f"frac{int(a*100)}"] = w2_of(a * step)
    # The expected W2 under a random direction of the same length as the correct
    # correction: E[sqrt(C + m)], by quadrature. sqrt(C + E[m]) is an RMS over
    # directions, is larger by Jensen, and would make "beats random" too easy.
    r = quad * float(np.linalg.norm(step))
    out["random"] = float(np.mean(np.sqrt(np.square(d + r).sum(1) * s2 + c)))
    return out


def block_pair(gen_p, est_block, score_block, n_score, scale, rng, gen_holdout, quad,
               n_est_cap=None, equalize=True, support_cap=None, full_support=False,
               group=0):
    """Score one (estimation block, scored block) pair.

    The scored block is split into two disjoint pools: the scored draw is taken with
    replacement from one, matching production, and the oracle centroid from the other.
    The transferred centroid is subsampled to the same frame count as the oracle's, so
    the two arms differ in temporal separation and not in how much MD they saw.

    `n_est_cap` holds that count equal across the *rows* of the ladder as well. Without
    it a long-lag row estimates from 501 frames while a short sub-block row estimates
    from 50, and the rows differ in estimation precision on top of lag. `equalize`
    switches it off for the primary arm, whose estimand is the best correction available
    from the whole of `est_block`: matching the oracle's precision there would throw away
    half the segment and could manufacture a false negative.

    `est_block=None` is the no-separation control, where the transferred estimate comes
    from a third disjoint pool of the scored block. Drawing it from the whole block
    instead lets it overlap the scored frames while the oracle cannot, which is not a
    control but a handicap on the oracle.

    `full_support` reproduces production's reference sampling: `analyse_bbflow` draws the
    reference cloud with replacement from *all* of the segment, so drawing instead from a
    disjoint half nearly doubles the duplicate rate, correlates the draws through a
    randomly chosen support, and shifts `C` -- which sits inside every square root and so
    moves the absolute gain being tested. Under `full_support` the reference is drawn from
    the whole block first and the oracle pool is whatever frames the draw did not touch.
    `support_cap` does the opposite job for the ladder, holding the support size equal
    across rows whose blocks differ in length.
    """
    # The generated side first, because it fixes the cloud size the reference must match.
    if gen_holdout:
        g = rng.permutation(len(gen_p))
        cut = len(gen_p) // 2
        if cut < 2:
            return None
        pool_gen, mu_apply = gen_p[g[:cut]], gen_p[g[cut:]].mean(0)
    else:
        pool_gen, mu_apply = gen_p, None
    n_use = min(n_score, len(pool_gen))
    gen_score = (pool_gen if n_use == len(pool_gen)
                 else pool_gen[rng.permutation(len(pool_gen))[:n_use]])
    if mu_apply is None:
        mu_apply = gen_score.mean(0)

    if full_support:
        ref_idx = rng.integers(0, len(score_block), n_use)
        keep = np.ones(len(score_block), bool)
        keep[ref_idx] = False
        ref_score, pool_oracle, pool_est = score_block[ref_idx], score_block[keep], est_block
    else:
        idx = rng.permutation(len(score_block))
        if est_block is None:
            t = len(score_block) // 3
            if t < 2:
                return None
            pool_score, pool_oracle, pool_est = (score_block[idx[:t]],
                                                 score_block[idx[t:2 * t]],
                                                 score_block[idx[2 * t:]])
        else:
            half = len(score_block) // 2
            if half < 2:
                return None
            pool_score, pool_oracle, pool_est = (score_block[idx[:half]],
                                                 score_block[idx[half:]], est_block)
        if support_cap:
            pool_score = pool_score[:support_cap]
        ref_score = pool_score[rng.integers(0, len(pool_score), n_use)]

    n_est = (min(len(pool_oracle), len(pool_est), n_est_cap or len(pool_est))
             if equalize else len(pool_est))
    if n_est < 2 or len(pool_oracle) < 2:
        return None
    mu_oracle = pool_oracle[rng.permutation(len(pool_oracle))[:n_est]].mean(0)
    mu_trn = (pool_est.mean(0) if n_est >= len(pool_est)
              else pool_est[rng.permutation(len(pool_est))[:n_est]].mean(0))
    return score_pair(gen_score, mu_apply, mu_trn, mu_oracle, ref_score, scale, quad,
                      n_est, group)


def sub_blocks(seg, length, gap):
    return [seg[s:s + length] for s in range(0, len(seg) - length + 1, length + gap)]


def sampled_pairs(n_blocks, budget, rng):
    """All directed pairs, then a uniform sample of `budget` of them.

    Walking the pairs in nested order and stopping at the budget selects only
    `block 0 -> everything`, which is one early estimate extrapolated over every lag with
    no reverse directions, so a temporal trend reads as a lag effect.
    """
    all_pairs = [(p, q) for p in range(n_blocks) for q in range(n_blocks) if p != q]
    if len(all_pairs) <= budget:
        return all_pairs
    sel = rng.permutation(len(all_pairs))[:budget]
    return [all_pairs[i] for i in sorted(sel)]


ARM_KEYS = ("uncorrected", "oracle", "transferred", "random",
            *[f"frac{int(a*100)}" for a in FRACTIONS])


def summarise(row, pairs, tag):
    """Average each arm over block pairs, then form gains.

    Averaging then differencing equals differencing then averaging, since every square
    root is already taken inside each pair. Retention is a ratio of averaged gains rather
    than an average of ratios, so a pair with a near-zero denominator cannot take over.
    """
    cols = ("unc", "oracle", "trn", "rnd", "gain_oracle", "gain_trn", "gain_rnd",
            "retention", "rms_est_to_ref", "n_pairs", "n_used", "n_est", "gain_trn_mcse",
            "gain_trn_alt", "leak",
            *[f"gain_frac{int(a*100)}" for a in FRACTIONS])
    if not pairs:
        for c in cols:
            row[f"{tag}_{c}"] = float("nan")
        return
    a = {k: float(np.mean([p[k] for p in pairs]))
         for k in (*ARM_KEYS, "transferred_alt", "m_trn", "n_used", "n_est")}
    row[f"{tag}_unc"] = a["uncorrected"]
    row[f"{tag}_oracle"] = a["oracle"]
    row[f"{tag}_trn"] = a["transferred"]
    row[f"{tag}_rnd"] = a["random"]
    row[f"{tag}_gain_oracle"] = a["uncorrected"] - a["oracle"]
    row[f"{tag}_gain_trn"] = a["uncorrected"] - a["transferred"]
    row[f"{tag}_gain_rnd"] = a["uncorrected"] - a["random"]
    for f in FRACTIONS:
        row[f"{tag}_gain_frac{int(f*100)}"] = a["uncorrected"] - a[f"frac{int(f*100)}"]
    g_o = row[f"{tag}_gain_oracle"]
    row[f"{tag}_retention"] = (row[f"{tag}_gain_trn"] / g_o) if g_o > 1e-12 else float("nan")
    # Root mean square, not mean: it is the average of the squared terms the identity uses.
    row[f"{tag}_rms_est_to_ref"] = a["m_trn"] ** 0.5
    # Paired leak: the same cloud, reference draw and A centroid, corrected once with a
    # held-out generated centroid and once with the scored cloud's own mean. Zero unless
    # this tag ran with a holdout.
    row[f"{tag}_gain_trn_alt"] = a["uncorrected"] - a["transferred_alt"]
    row[f"{tag}_leak"] = row[f"{tag}_gain_trn_alt"] - row[f"{tag}_gain_trn"]
    # Monte Carlo error of the reference draws only. Pooling the spread over all directed
    # pairs instead would fold in real heterogeneity between those pairs, which is signal,
    # and would not describe how much a different set of random partitions could move the
    # result.
    by_group = {}
    for p in pairs:
        by_group.setdefault(p["group"], []).append(p["uncorrected"] - p["transferred"])
    reps = [np.var(v, ddof=1) for v in by_group.values() if len(v) > 1]
    row[f"{tag}_gain_trn_mcse"] = (float(np.mean(reps) / len(pairs)) ** 0.5
                                   if reps else float("nan"))
    row[f"{tag}_n_pairs"] = len(pairs)
    row[f"{tag}_n_used"] = a["n_used"]
    row[f"{tag}_n_est"] = a["n_est"]


def audit_one(name, ctx, gen_flat, k_dim, rng, sub_lens, gap, n_ref_draws,
              max_pairs_per_segment, n_boot, n_quad):
    n_atoms, bounds, segs = ctx["n_atoms"], ctx["bounds"], ctx["segs"]
    md_p, sing, acs = ctx["md_p"], ctx["sing"], ctx["acs"]
    n_md, n_gen = ctx["n_md"], gen_flat.shape[0]
    scale = 10.0 / n_atoms ** 0.5                      # the metric's own units
    quad = quadrature_directions(k_dim, n_quad)
    gen_p = (gen_flat - ctx["centre"]) @ ctx["basis"].T
    seg_len = min(len(s) for s in segs)

    row = {"name": name, "n_res": n_atoms, "n_gen": n_gen, "n_md": n_md,
           "n_segments": len(bounds), "seg_len_min": seg_len,
           "seg_len_max": max(len(s) for s in segs)}
    row["d_gen_to_pool"] = float(np.linalg.norm(gen_p.mean(0) - md_p.mean(0)) * scale)

    # A typical conditional standard error of a 250-sample centroid. Not the realized
    # error of this draw, which is unobservable; it gives the typical sampling scale of
    # the measured centroid gap, so a gap of the same order is not safely model bias.
    boot = np.array([gen_p[rng.integers(0, n_gen, n_gen)].mean(0) for _ in range(n_boot)])
    row["mc_gen_centroid"] = float(np.linalg.norm(boot.std(0, ddof=1)) * scale)

    # Every segment and every projected coordinate, because the mask wants the worst
    # finite-length independent content, not the slowest asymptotic one.
    tau = max(t for t, _ in acs)
    row["tau_segment"] = float(tau)
    row["ess_min_segment"] = min(ess_block(r, seg_len) for _, r in acs)
    blk = max(1, int(round(tau)))
    row["block_len_used"] = blk
    row["se_segment_centroid"] = max(moving_block_se(s, blk, rng, n_boot)
                                     for s in segs) * scale

    # The ladder runs at one cloud size and one estimation size, so its rows differ in
    # temporal separation and nothing else. The shortest sub-block sets both: it can
    # spare only half its frames for the oracle estimate.
    ladder_n = max(2, min(n_gen, min(sub_lens) // 2)) if sub_lens else n_gen
    ladder_est = max(2, min(sub_lens) // 2) if sub_lens else None
    row["ladder_n"], row["ladder_n_est"] = ladder_n, ladder_est or 0

    def between_pairs(n_score, holdout, cap, equalize=True, full=False, support=None):
        out, grp = [], 0
        for i, a in enumerate(segs):
            for j, b in enumerate(segs):
                if i == j:
                    continue
                grp += 1
                for _ in range(n_ref_draws):
                    p = block_pair(gen_p, a, b, n_score, scale, rng, holdout, quad, cap,
                                   equalize, support, full, grp)
                    if p is not None:
                        out.append(p)
        return out

    # Primary: production cloud size drawn production-style from the whole of segment B,
    # and the centroid taken from all of segment A, since the estimand is the best
    # correction the whole segment affords. Then the same with the generated centroid
    # held out, which necessarily halves the cloud.
    summarise(row, between_pairs(n_gen, False, None, False, True), "primary")
    summarise(row, between_pairs(n_gen, True, None, False, True), "primaryH")

    # Ladder: common cloud size, estimation size, and reference support, so duplicate
    # rates and C do not vary with block length alongside the lag.
    summarise(row, between_pairs(ladder_n, False, ladder_est, support=ladder_est),
              "L_between")

    no_sep = []
    for gi, s in enumerate(segs):
        for _ in range(n_ref_draws):
            p = block_pair(gen_p, None, s, ladder_n, scale, rng, False, quad, ladder_est,
                           True, ladder_est, False, gi)
            if p is not None:
                no_sep.append(p)
    summarise(row, no_sep, "L_nosep")

    adj, grp = [], 0
    for s in segs:
        h = len(s) // 2
        for est, sc in ((s[:h], s[h:]), (s[h:], s[:h])):     # both directions
            grp += 1
            for _ in range(n_ref_draws):
                p = block_pair(gen_p, est, sc, ladder_n, scale, rng, False, quad,
                               ladder_est, True, ladder_est, False, grp)
                if p is not None:
                    adj.append(p)
    summarise(row, adj, "L_adjacent")

    for L in sub_lens:
        pairs = []
        for si, seg in enumerate(segs):
            blocks = sub_blocks(seg, L, gap)
            sel = sampled_pairs(len(blocks), max_pairs_per_segment,
                                np.random.default_rng(stable_seed(f"{name}:{L}:{si}", 0)))
            for gi, (p_i, q_i) in enumerate(sel):
                for _ in range(n_ref_draws):
                    r = block_pair(gen_p, blocks[p_i], blocks[q_i], ladder_n,
                                   scale, rng, False, quad, ladder_est, True,
                                   ladder_est, False, si * 1000 + gi)
                    if r is not None:
                        pairs.append(r)
        tag = f"L_within{L}"
        summarise(row, pairs, tag)
        e = min(ess_block(r, L) for _, r in acs)
        row[f"{tag}_ess"] = e
        if e < MIN_ESS_CELL:      # masked, so it is genuinely not counted anywhere
            for c in [c for c in row if c.startswith(f"{tag}_") and not c.endswith("_ess")]:
                row[c] = float("nan")

    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")
    return row


def verify_identity(name, ctx, gen_flat, rng):
    """Check the closed form against transport actually computed on the shifted cloud."""
    scale = 10.0 / ctx["n_atoms"] ** 0.5
    md_p, bounds = ctx["md_p"], ctx["bounds"]
    gen_p = (gen_flat - ctx["centre"]) @ ctx["basis"].T

    a_seg = md_p[bounds[0][0]:bounds[0][1]]
    b_seg = md_p[bounds[1][0]:bounds[1][1]]
    b = b_seg[rng.integers(0, len(b_seg), gen_p.shape[0])]
    mu_a, mu_g, mu_b = a_seg.mean(0), gen_p.mean(0), b.mean(0)

    measured = w2_sq(gen_p + (mu_a - mu_g), b, scale) ** 0.5
    predicted = (float(np.square(mu_a - mu_b).sum()) * scale ** 2
                 + w2_sq(gen_p - mu_g, b - mu_b, scale)) ** 0.5
    return {"name": name, "measured": measured, "predicted": predicted}


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("--sub_lens", type=int, nargs="*", default=[100, 250, 400])
    ap.add_argument("--gap", type=int, default=50,
                    help="frames skipped between contiguous sub-blocks")
    ap.add_argument("--n_ref_draws", type=int, default=5,
                    help="scored draws per block pair, so nothing rests on one subset")
    ap.add_argument("--max_pairs_per_segment", type=int, default=6)
    ap.add_argument("--n_boot", type=int, default=400)
    ap.add_argument("--n_quad", type=int, default=64,
                    help="directions in the random-shift expectation")
    ap.add_argument("--verify", type=int, default=3,
                    help="proteins on which to check the closed form against transport")
    ap.add_argument("--min_useful_gain", type=float, default=0.10,
                    help="Angstrom. 0.10 is the project's prespecified continuation "
                         "threshold and treats the ceiling as the thing being gated; "
                         "0.20 corresponds to assuming a predictor captures half of it")
    ap.add_argument("--min_attenuation", type=float, default=0.5,
                    help="fraction of the paired in-sample gain the held-out correction "
                         "must retain before a pass is allowed to stand")
    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("--require_segments", type=int, default=3)
    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):
        raise SystemExit("--names must match --ensemble_dirs in length")
    if len(set(labels)) != len(labels):
        raise SystemExit("run labels must be unique")

    import pandas as pd
    guards = []          # any entry suppresses the verdict rather than annotating it
    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)

    # Protein-outer, so the pooled SVD and the autocorrelations are paid for once no
    # matter how many checkpoints are being compared.
    rows, failures, verified = [], {}, 0
    print(f"\ncomparing {len(labels)} runs; the MD projection is computed once per "
          f"protein\n", flush=True)
    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}: {type(exc).__name__}: {exc}")
            continue
        for label, ens in zip(labels, args.ensemble_dirs):
            try:
                gen_flat = load_generated(nm, ens, ctx["ref"])
                if verified < args.verify and label == labels[0]:
                    v = verify_identity(nm, ctx, gen_flat,
                                        np.random.default_rng(stable_seed(nm, args.seed)))
                    rel = abs(v["measured"] - v["predicted"]) / max(abs(v["measured"]), 1e-30)
                    print(f"  identity check {nm}: measured {v['measured']:.6f} "
                          f"predicted {v['predicted']:.6f}  rel {rel:.2e}", flush=True)
                    if rel > VERIFY_TOL:
                        raise SystemExit("the closed form does not reproduce transport; "
                                         "the whole design rests on it, so stop here")
                    verified += 1
                r = audit_one(nm, ctx, gen_flat, args.k,
                              np.random.default_rng(stable_seed(nm, args.seed)),
                              args.sub_lens, args.gap, args.n_ref_draws,
                              args.max_pairs_per_segment, args.n_boot, args.n_quad)
                r["run"] = label
                r.update({"cfg_seed": args.seed, "cfg_k": args.k, "cfg_gap": args.gap,
                          "cfg_ref_draws": args.n_ref_draws, "cfg_boot": args.n_boot})
                rows.append(r)
            except SystemExit:
                raise
            except Exception as exc:                                  # noqa: BLE001
                failures.setdefault(label, []).append(f"{nm}: {type(exc).__name__}: {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)
    if not shared:
        raise SystemExit("no protein succeeded in every run")
    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}")

    # Checked after the failures are known, so a cohort that shrank during the run cannot
    # slip a verdict through on a selected subset.
    if args.expect_cohort and len(shared) != args.expect_cohort:
        guards.append(f"analysed {len(shared)} proteins, expected {args.expect_cohort}")
    # Both ends, since a minimum of 1001 is also satisfied by [1001, 1002, 1002].
    for field, expect, what in (("n_gen", args.expect_n_gen, "generated samples"),
                                ("seg_len_min", args.expect_seg_len, "frames in every segment"),
                                ("seg_len_max", args.expect_seg_len, "frames in every segment")):
        if not expect:
            continue
        bad = int((df[field] != expect).sum())
        if bad:
            # A truncated segment changes both the A estimate and B's support, so the
            # design is not the one the threshold was set for.
            guards.append(f"{bad} rows do not have {expect} {what}")

    def boot_ci(v, n=4000):
        v = np.asarray(v, float)
        v = v[np.isfinite(v)]
        if v.size < 2:
            return float("nan"), float("nan")
        s = np.random.default_rng(0).choice(v, (n, v.size), replace=True)
        return tuple(np.percentile(np.median(s, axis=1), [2.5, 97.5]))

    print(f"\n{'='*78}\n median over {len(shared)} proteins, Angstrom\n{'='*78}")
    for label in labels:
        d = df[df.run == label]
        if d.empty:
            continue
        print(f"\n--- {label} ---")

        print(f"\n  diagnostic ladder, all rows at one cloud size and one estimation size")
        print(f"  {'lag':<26}{'uncorr':>9}{'oracle':>9}{'transf':>9}{'random':>9}"
              f"{'gain_o':>9}{'gain_t':>9}{'keep':>8}{'n':>6}{'n_est':>7}{'prots':>7}")
        ladder = [("no separation", "L_nosep"),
                  *[(f"within segment, {L} fr", f"L_within{L}") for L in args.sub_lens],
                  ("half segment apart", "L_adjacent"),
                  ("different segment", "L_between")]
        for title, tag in ladder:
            if f"{tag}_unc" not in d.columns or d[f"{tag}_unc"].isna().all():
                e = d.get(f"{tag}_ess")
                note = (f"UNRESOLVED, {e.median():.1f} effective samples"
                        if e is not None else "no data")
                print(f"  {title:<26}{note:>74}")
                continue
            # Proteins masked out by the ESS floor leave the row, so say how many are
            # left: a row over 23 high-autocorrelation proteins must not be compared
            # with one over all 82 as though the lag were the only difference.
            valid = int(d[f"{tag}_unc"].notna().sum())
            print(f"  {title:<26}{d[f'{tag}_unc'].median():>9.4f}"
                  f"{d[f'{tag}_oracle'].median():>9.4f}{d[f'{tag}_trn'].median():>9.4f}"
                  f"{d[f'{tag}_rnd'].median():>9.4f}{d[f'{tag}_gain_oracle'].median():>9.4f}"
                  f"{d[f'{tag}_gain_trn'].median():>9.4f}"
                  f"{d[f'{tag}_retention'].median():>8.3f}"
                  f"{int(d[f'{tag}_n_used'].median()):>6}"
                  f"{int(d[f'{tag}_n_est'].median()):>7}"
                  f"{valid:>7}")

        g_lo, g_hi = boot_ci(d["primary_gain_trn"])
        g = d["primary_gain_trn"].median()
        # A pass on the production arm alone is not enough: that arm subtracts the scored
        # cloud's own centroid and so cancels a realized Monte Carlo error a learned
        # objective could never know. The check is the paired one inside the held-out run
        # -- same cloud, same reference draw, same A centroid, corrected once each way --
        # so it isolates the leak instead of confounding it with the halved cloud size.
        #
        # A non-inferiority contrast, not a ratio. Two negative gains divide to about one,
        # so a ratio can read as perfect retention of an effect that is not there; and
        # requiring only the ratio's *upper* end to clear the margin would approve a CI
        # like [0.10, 0.60] that mostly indicates collapse.
        held = d["primaryH_gain_trn"]
        contrast = held - args.min_attenuation * d["primaryH_gain_trn_alt"]
        c_lo, c_hi = boot_ci(contrast)
        holdout_agrees = bool(held.median() > 0 and c_lo > 0)
        if guards:
            verdict = "SUPPRESSED"
        elif g_hi < args.min_useful_gain:
            verdict = "DEAD"
        elif g_lo > args.min_useful_gain:
            verdict = ("worth the MD-free prediction gate" if holdout_agrees
                       else "UNRESOLVED: does not clear the held-out margin")
        else:
            verdict = "UNRESOLVED"
        print(f"\n  primary: a centroid from all of one segment, applied and scored "
              f"against a different\n  segment, n={int(d['primary_n_used'].median())} "
              f"(the production cloud size), estimated from "
              f"{int(d['primary_n_est'].median())} frames")
        print(f"    transferred gain {g:+.4f} [{g_lo:+.4f}, {g_hi:+.4f}] "
              f"against {args.min_useful_gain:.2f}  ->  {verdict}")
        print(f"    positive on {(d['primary_gain_trn'] > 0).mean():.2f} of proteins, "
              f"beats a matched random shift on "
              f"{(d['primary_gain_trn'] > d['primary_gain_rnd']).mean():.2f}"
              f"   (draw-to-draw SE {d['primary_gain_trn_mcse'].median():.4f})")
        print(f"    retention is not reported here: this arm deliberately gives the "
              f"transferred estimate\n    the whole segment while the oracle gets half, "
              f"so read 'different segment' in the ladder")
        frac = "  ".join(f"{int(f*100)}%: {d[f'primary_gain_frac{int(f*100)}'].median():+.4f}"
                         for f in FRACTIONS)
        print(f"    gain at a fraction of the shift   {frac}   100%: {g:+.4f}")
        print(f"      (a predictor captures a fraction of the shift, not of the gain; "
              f"read the row above\n       before choosing a threshold, not after)")

        hg_lo, hg_hi = boot_ci(d["primaryH_gain_trn"])
        print(f"\n  same, generated centroid held out, n={int(d['primaryH_n_used'].median())}"
              f" -- no verdict, this is not the metric the threshold was set on")
        print(f"    transferred gain {d['primaryH_gain_trn'].median():+.4f} "
              f"[{hg_lo:+.4f}, {hg_hi:+.4f}]   "
              f"retention {d['primaryH_retention'].median():+.3f}")
        print(f"    paired against the same cloud corrected with its own mean "
              f"({d['primaryH_gain_trn_alt'].median():+.4f}): the leak is worth "
              f"{d['primaryH_leak'].median():+.4f}")
        print(f"    held-out minus {args.min_attenuation:.2f} of in-sample: "
              f"{contrast.median():+.4f} [{c_lo:+.4f}, {c_hi:+.4f}]  ->  "
              f"{'holds up' if holdout_agrees else 'does not clear the margin'}")

        print(f"\n  generated centroid vs pooled reference  {d['d_gen_to_pool'].median():.4f}"
              f"   typical Monte Carlo SE {d['mc_gen_centroid'].median():.4f}")
        print(f"  correlation time {d['tau_segment'].median():.1f} frames, so a "
              f"{int(d['seg_len_min'].median())}-frame segment holds "
              f"{d['ess_min_segment'].median():.1f} effective samples")
        print(f"  worst-segment centroid SE {d['se_segment_centroid'].median():.4f}, "
              f"top-2 eigenvalue gap {d['pc_relgap'].median():.3f}")

    if guards:
        print(f"\n{'='*78}\n VERDICT SUPPRESSED\n{'='*78}")
        for g in guards:
            print(f"  {g}")
        print("  The numbers above are still printed, but this was set up as a "
              "prespecified\n  decision experiment and the preconditions did not hold.")

    print(f"\n{'='*78}\n reading\n{'='*78}")
    print("  The gate is the absolute transferred gain on the primary row. Retention says")
    print("  how much of the achievable correction survives the lag; the gain says whether")
    print("  what survives is worth anything. A pass means only that the target is stable")
    print("  enough to justify the MD-free prediction test -- the transferred gain is a")
    print("  ceiling reached by knowing another segment's centroid, not a prediction.")
    print()
    print("  The ladder's 'no separation' row is the sensitivity control for the ladder,")
    print("  not for the primary row, which has its own denominator at its own cloud size.")
    print("  A healthy control there does not by itself establish power at long lag: three")
    print("  temporal replicates estimate between-segment variability imprecisely, and a")
    print("  randomised draw from a segment averages its whole occupancy while a")
    print("  contiguous estimation block does not.")
    print()
    print("  The ladder is not monotone. Retention high at short lag and collapsing")
    print("  between segments is compatible with drift or with differing metastable")
    print("  occupancy -- and trapping in distinct basins can equally mean the trajectory")
    print("  is too short for the equilibrium quantity being aimed at. The reverse shape,")
    print("  short lag poor while whole segments hold up, is compatible with strong")
    print("  within-segment autocorrelation or other short-window heterogeneity. Neither")
    print("  shape identifies its cause; check the correlation time before reading either.")
    print()
    print("  A null is attributable to the measurement rather than the target when the")
    print("  control row's gain is small, when the Monte Carlo centroid SE is a large part")
    print("  of the generated centroid error, when the correlation time leaves few")
    print("  effective samples, when the top-2 eigenvalue gap is narrow enough that the")
    print("  plane itself is unstable, or when a segment is an equilibration transient")
    print("  rather than equilibrium occupancy. Those are not automated: the verdict is")
    print("  suppressed only for the cohort and sample-size preconditions.")
    print()
    print("  Stability is necessary, not sufficient. The shift also has to be predictable")
    print("  without the test protein's MD, and these PCA coordinates carry an arbitrary")
    print("  sign and rotation, so they are not themselves a cross-protein target.")


if __name__ == "__main__":
    main()