Repository navigation
Expand file tree
/
Copy pathcross_study_finallydb.py
More file actions
1774 lines (1651 loc) · 77.4 KB
/
Copy pathcross_study_finallydb.py
File metadata and controls
1774 lines (1651 loc) · 77.4 KB
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Cross-study FinaleDB benchmark (publication-aware).
Honest open-data benchmark, NOT clinical validation. Open-data scope, no
external validation, no held-out clinical cohort. Per the cfdna-fragmentomics
skill:
- All FinaleDB studies are uniformly pre-processed cfDNA WGS, so pooling is
technically valid with mild per-study harmonization.
- The TRUE cross-study confound (cancer = 100% study A, healthy = 100%
study B) reaches AUC 0.999 without harmonization — that is the negative
control here.
- Per-study z-score harmonization inside each CV fold removes the batch
effect without leaking test-set statistics.
Publications (per cfdna-fragmentomics skill, FinaleDB publication id→study map):
1 = Snyder 2016 Cell
6 = Jiang 2015 PNAS (low-pass HCC)
7 = Sun 2019
8 = Cristiano 2019 (DELFI, pan-cancer + healthy)
9 = Adalsteinsson 2017
Sections:
1. Cell-line filter + cohort inventory (per-publication, per-cancer)
2. Per-publication AUC (one fit per requested publication)
3. Pooled cross-study with per-publication harmonization (5-seed x 5-fold CV)
4. Per-cancer sens@spec with bootstrap 95% CIs at spec in {0.95, 0.98, 0.99}
5. True-confound control: cancer = 100% pub A, healthy = 100% pub B,
per-publication z-score harmonization collapses to ~0.5 AUC
6. The reverse-confound for symmetry (also should collapse to ~0.5)
Outputs:
results/cross_study_finallydb.json
docs/CROSS_STUDY_BENCHMARK.md
FinaleDB API status: the public REST API and S3 bucket have been DOWN since
2026-09 (Postgres connection lost + S3 keys returned 403). Until they return,
adding publications 1 (Snyder) and 7 (Sun) requires re-fetching their
features, which is impossible. See docs/PUBLICATION_READINESS.md for the
honest current status. The default `--publications 6 8` uses the
already-cached local features for the open-data benchmark.
Usage:
env -u PYTHONPATH /Users/hermes/deepcatch/.venv/bin/python \\
scripts/cross_study_finallydb.py \\
--features-dir /Users/hermes/cfdna-fragmentomics-pipeline/data/features \\
--labels-multiclass /Users/hermes/cfdna-fragmentomics-pipeline/labels_multiclass.tsv \\
--publications 6 8 \\
--out-json results/cross_study_finallydb.json \\
--out-md docs/CROSS_STUDY_BENCHMARK.md
For the ULTRA-EARLY headline (screening-grade sens@99.5%/99.9% spec +
Stage I vs late-stage breakdown), pass `--include-screening` to extend
the per-cancer sens@spec grid. See ULTRA_EARLY_READINESS.md §1.2 for
the rationale and `docs/ULTRA_EARLY_READINESS_AUTO.md` for the
machine-generated readiness verdict.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
import warnings
from datetime import datetime, timezone
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
# Reuse the cfdna-fragmentomics-pipeline 5-channel loader + harmonize helper.
PIPELINE = "/Users/hermes/cfdna-fragmentomics-pipeline"
sys.path.insert(0, PIPELINE)
sys.path.insert(0, os.path.join(PIPELINE, "scripts"))
from honest_benchmark import load5 # noqa: E402
from train_classifier import _harmonize # noqa: E402
# Repo-local extended loader: load5 + 256-dim 4-mer end-motif counts.
# See scripts/load5_with_motifs.py for the loader contract and the
# graceful-missing-motif-file policy. Wired through `--include-motifs`
# (default OFF for backward-compat bit-identical behaviour).
_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, _REPO_ROOT)
sys.path.insert(0, os.path.join(_REPO_ROOT, "scripts"))
from load5_with_motifs import ( # noqa: E402
MOTIF_DIM,
load5_with_motifs as _load5_with_motifs,
load5_with_motifs_optional as _load5_with_motifs_optional,
load5_only as _load5_only_local,
)
from src.per_cancer_sens_at_spec import ( # noqa: E402
DEFAULT_PREVALENCES,
DEFAULT_SPECIFICITIES,
MIN_POSITIVES_FOR_CI,
PPV_AT_SPEC,
SCREENING_SPECIFICITIES,
build_per_cancer_table,
delong_auc_ci,
delong_sens_at_spec_ci,
ppv_at_prevalence,
)
# Cell-line filter regex per the cfdna-fragmentomics skill
CELL_LINE_RE = re.compile(
r"^(GM\d+|HeLa|HepG2|K562|HL60|Jurkat|Raji|MCF7|U937|THP1|HEK293|"
r"HCT116|SW480|A549|GM12878)",
re.I,
)
DEFAULT_SEEDS = [42, 13, 7, 99, 1234]
DEFAULT_PCA_N = 200
SPECS_FOR_PER_CANCER = [0.95, 0.98, 0.99]
# Default specificity grid for the per-cancer sens@spec breakdown.
# Backward-compatible: was [0.95, 0.98, 0.99] until the screening-grade
# (NHS-Galleri / CancerSEEK 99.5%/99.9% spec) grid was added.
DEFAULT_SPEC_GRID: tuple[float, ...] = tuple(DEFAULT_SPECIFICITIES)
SCREENING_SPEC_GRID: tuple[float, ...] = (
tuple(DEFAULT_SPECIFICITIES) + tuple(SCREENING_SPECIFICITIES),
)
N_BOOTSTRAP = 1000
BOOTSTRAP_SEED = 2026
# Shuffled-label null control threshold (literature: AUC < 0.55 on healthy
# controls is the expected null; >0.55 indicates batch leakage). The
# control is a sanity check, not a hard gate: a noisy seed can fluctuate
# just above this floor. We log a warning but do NOT fail the run.
SHUFFLED_AUC_NULL_FLOOR = 0.55
SHUFFLED_CONTROL_RUN_SEED = 20260924 # the global seed for the label perm
# ──────────────────────────────────────────────────────────────────────
# Publication registry (cfdna-fragmentomics skill: id→study map)
# ──────────────────────────────────────────────────────────────────────
#
# Each entry is (pub_id → short_label). The short_label is the value used
# for the harmonization grouping in `_harmonize(X, st, ...)` and as the
# display label in the inventory + markdown output.
#
# When FinaleDB API/S3 are reachable again, the new publications can be
# added simply by extending this dict + providing a per-publication
# labels file (or a 5th `publication` column in labels_multiclass.tsv).
PUBLICATION_REGISTRY = {
"1": "snyder", # Snyder 2016 Cell (FinaleDB API/S3 currently DOWN)
"6": "jiang", # Jiang 2015 PNAS (cached locally)
"7": "sun", # Sun 2019 (FinaleDB API/S3 currently DOWN)
"8": "cristiano", # Cristiano 2019 DELFI (cached locally)
"9": "adalsteinsson", # Adalsteinsson 2017
}
# Known study→publication fallback for labels files that only have a
# `study` column (the current local cache). Used when the labels file
# has no 5th `publication` column.
STUDY_TO_PUBLICATION = {
"jiang": "6",
"cristiano": "8",
"snyder": "1",
"sun": "7",
"adalsteinsson": "9",
}
# --------------------------------------------------------------------------- #
# Label loading (now publication-aware)
# --------------------------------------------------------------------------- #
def load_labels_multiclass(path: str, requested_publications: set[str]):
"""Load labels_multiclass.tsv → dicts.
Returns: (labels, studies, disease_class, publication)
labels[s] = 1 if cancer else 0
studies[s] = 'jiang' | 'cristiano' | ... (display label)
disease_class[s] = 'HCC_J' | 'LUAD' | 'BRCA' | 'HEALTHY' | ...
publication[s] = '6' | '8' | ... (FinaleDB publication id)
The function is backward-compatible: if the labels file has NO 5th
`publication` column, the publication is derived from the `study`
column via STUDY_TO_PUBLICATION. Samples whose publication is not in
`requested_publications` are dropped (with a warning listing them).
If the labels file has the `publication` column and it disagrees with
the `study` column, the `publication` column wins (publication is the
primary key for the cohort filter).
"""
labels, studies, disease_class, publication = {}, {}, {}, {}
skipped_outside_request = []
with open(path) as f:
header_seen = False
header_cols = None
for line in f:
p = line.strip().split("\t")
if len(p) < 4:
continue
if not header_seen:
if p[0] == "sample" and p[3] == "study":
header_seen = True
header_cols = p
continue
# No header row found yet — treat this as a data row.
header_seen = True
if p[0] == "sample" and p[3] == "study":
# Re-reading header on a different row (defensive)
header_cols = p
continue
if p[3] in ("study", ""):
continue
s = p[0]
# Publication id: prefer an explicit 5th column if present.
pub = ""
if len(p) >= 5 and p[4] and p[4] not in ("publication",):
pub = p[4]
else:
pub = STUDY_TO_PUBLICATION.get(p[3], "")
if pub not in requested_publications:
skipped_outside_request.append((s, p[3], pub))
continue
labels[s] = 1 if p[2] == "cancer" else 0
studies[s] = p[3]
disease_class[s] = p[1]
publication[s] = pub
if skipped_outside_request:
uniq = sorted({(st, pub) for _, st, pub in skipped_outside_request
if pub and pub not in requested_publications})
if uniq:
warnings.warn(
f"load_labels_multiclass: dropped {len(skipped_outside_request)} "
f"samples whose publication is outside the requested set "
f"{sorted(requested_publications)}. "
f"Dropped study→pub combos: {uniq}",
stacklevel=2,
)
return labels, studies, disease_class, publication
def apply_cell_line_filter(labels, studies, disease_class, publication):
"""Drop samples whose IDs match the cell-line regex. Return counts."""
drop_ids = [s for s in list(labels) if CELL_LINE_RE.match(s)]
for s in drop_ids:
labels.pop(s, None)
studies.pop(s, None)
disease_class.pop(s, None)
publication.pop(s, None)
return drop_ids
# --------------------------------------------------------------------------- #
# CV machinery
# --------------------------------------------------------------------------- #
def pooled_oof(X, y, st, seeds, pca_n, harmonize):
"""5-seed x 5-fold OOF predictions, pooled.
Returns (y_true, score_pooled, per_seed_aucs).
score_pooled = mean across seeds of per-seed OOF scores (each sample
gets exactly one prediction per seed).
"""
score_acc = np.zeros(len(y), dtype=float)
seed_aucs = []
for sd in seeds:
cv = StratifiedKFold(5, shuffle=True, random_state=sd)
oof = np.zeros(len(y), dtype=float)
for tr, te in cv.split(X, y):
Xtr = X[tr].copy()
Xte = X[te].copy()
if harmonize:
Xtr, sc = _harmonize(Xtr, st[tr], None)
Xte, _ = _harmonize(Xte, st[te], sc)
else:
sc = StandardScaler().fit(Xtr)
Xtr = sc.transform(Xtr)
Xte = sc.transform(Xte)
max_pca = min(Xtr.shape[0], Xtr.shape[1])
pca = PCA(n_components=min(pca_n, max_pca)).fit(Xtr)
Xtr_p = pca.transform(Xtr)
Xte_p = pca.transform(Xte)
m = LogisticRegression(max_iter=2000).fit(Xtr_p, y[tr])
oof[te] = m.predict_proba(Xte_p)[:, 1]
seed_aucs.append(float(roc_auc_score(y, oof)))
score_acc += oof
score_pooled = score_acc / len(seeds)
return y, score_pooled, seed_aucs
def sens_at_spec(y_true, y_score, spec):
"""Sensitivity at target specificity (LARGEST fpr <= target)."""
fpr, tpr, thr = roc_curve(y_true, y_score)
target_fpr = 1.0 - spec
idx = np.where(fpr <= target_fpr)[0]
if len(idx) == 0:
return 0.0, float("nan")
return float(tpr[idx[-1]]), float(thr[idx[-1]])
def bootstrap_ci_sens(y_true, y_score, spec, n_boot, seed):
"""Percentile bootstrap 95% CI on sens@spec."""
rng = np.random.default_rng(seed)
n = len(y_true)
sens_samples = np.empty(n_boot, dtype=float)
for b in range(n_boot):
idx = rng.integers(0, n, size=n)
s, _ = sens_at_spec(y_true[idx], y_score[idx], spec)
sens_samples[b] = s
lo = float(np.quantile(sens_samples, 0.025))
hi = float(np.quantile(sens_samples, 0.975))
return lo, hi
# --------------------------------------------------------------------------- #
# Shuffled-label null control
# --------------------------------------------------------------------------- #
def run_shuffled_label_control(X, y, st, seeds, pca_n,
perm_seed=SHUFFLED_CONTROL_RUN_SEED):
"""Label-permutation null control for the pooled cross-study pipeline.
Mirrors the P0-C fix in scripts/foundation_real_smoke.py (lines
~580-590): permute ``y`` ONCE (preserving sample-id pairing) and
run the same 5-seed x 5-fold pooled OOF with harmonize + PCA + LR.
A null that beats the SHUFFLED_AUC_NULL_FLOOR (= 0.55) suggests the
pooled 0.97 AUC is partially a batch-leakage artifact rather than a
cancer signal — exactly the reviewer question this control exists to
answer. A null AUC < 0.55 means the cancer signal dominates.
The shuffle is computed once, OUTSIDE the fold loop, so every fold
sees the same permutation (pair-consistent across folds). The same
per-publication z-score harmonization is used inside each fold,
matching the pooled OOF in `section_pooled(harmonize=True)`.
Parameters
----------
X, y, st : feature matrix, integer labels, study-array (str) — same
as inputs to `pooled_oof`.
seeds : list of int — pipeline-CV seeds (default DEFAULT_SEEDS).
pca_n : int — PCA components (default DEFAULT_PCA_N).
perm_seed : int — global seed for the label permutation.
Returns
-------
dict with keys:
shuffled_pooled_auc_mean : float — 5-seed mean OOF AUC.
shuffled_pooled_auc_std : float — 5-seed std.
shuffled_pooled_per_seed_auc : list[float] — per-seed AUCs.
shuffled_pooled_sens_at_95 : float — sens at spec 0.95.
shuffled_pooled_sens_at_99 : float — sens at spec 0.99.
control_passed : bool — True iff mean shuffled AUC < SHUFFLED_AUC_NULL_FLOOR.
perm_seed : int — echoes the seed used (reproducibility).
n_cancer, n_healthy : int — pooled counts.
"""
rng = np.random.default_rng(perm_seed)
y_shuf = rng.permutation(y) # global label perm (pair-broken)
_, score, seed_aucs = pooled_oof(
X, y_shuf, st, seeds, pca_n, harmonize=True,
)
s95, _ = sens_at_spec(y_shuf, score, 0.95)
s99, _ = sens_at_spec(y_shuf, score, 0.99)
auc_mean = float(np.mean(seed_aucs))
return {
"shuffled_pooled_auc_mean": auc_mean,
"shuffled_pooled_auc_std": float(np.std(seed_aucs)),
"shuffled_pooled_per_seed_auc": [float(a) for a in seed_aucs],
"shuffled_pooled_sens_at_95": float(s95),
"shuffled_pooled_sens_at_99": float(s99),
"control_passed": bool(auc_mean < SHUFFLED_AUC_NULL_FLOOR),
"perm_seed": int(perm_seed),
"n_cancer": int((y == 1).sum()),
"n_healthy": int((y == 0).sum()),
}
def write_shuffled_control_json(control_result, seeds, out_path):
"""Write the shuffled-control result to JSON.
Schema mirrors the top-level fields of cross_study_finallydb.json
(pooled_auc_mean, pooled_auc_std, pooled_sens_at_95,
pooled_sens_at_99, seeds, schema_version, generated_at) with an
additional ``control_passed`` bool. The nested block
``shuffled_control`` preserves the verbose keys (per-seed AUCs,
n_cancer, n_healthy, perm_seed) for full audit.
"""
payload = {
"schema_version": "1.0",
"generated_at": datetime.now(timezone.utc).isoformat(),
"seeds": list(seeds),
"pooled_auc_mean": control_result["shuffled_pooled_auc_mean"],
"pooled_auc_std": control_result["shuffled_pooled_auc_std"],
"pooled_sens_at_95": control_result["shuffled_pooled_sens_at_95"],
"pooled_sens_at_99": control_result["shuffled_pooled_sens_at_99"],
"control_passed": control_result["control_passed"],
"shuffled_control": control_result,
"interpretation": {
"null_floor": SHUFFLED_AUC_NULL_FLOOR,
"note": (
f"shuffled-pooled AUC < {SHUFFLED_AUC_NULL_FLOOR:.2f} means "
"the cross-study pooled OOF is a cancer signal, not a "
"batch-leakage artifact via fold structure. >0.55 is a "
"warning that batch effects may dominate and the main "
"0.97 AUC should be read with caution."
),
},
}
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
with open(out_path, "w") as f:
json.dump(payload, f, indent=2)
return payload
# --------------------------------------------------------------------------- #
# Sections
# --------------------------------------------------------------------------- #
def section_inventory(labels, studies, disease_class, publication, dropped,
samples_in_array):
n_total = len(labels)
n_cancer = sum(1 for v in labels.values() if v == 1)
n_healthy = n_total - n_cancer
by_study = {}
for s, st in studies.items():
d = by_study.setdefault(st, {"n_total": 0, "n_cancer": 0, "n_healthy": 0})
d["n_total"] += 1
if labels[s] == 1:
d["n_cancer"] += 1
else:
d["n_healthy"] += 1
by_publication = {}
for s, pub in publication.items():
d = by_publication.setdefault(pub, {
"n_total": 0, "n_cancer": 0, "n_healthy": 0,
"study_label": PUBLICATION_REGISTRY.get(pub, pub),
})
d["n_total"] += 1
if labels[s] == 1:
d["n_cancer"] += 1
else:
d["n_healthy"] += 1
by_cancer = {}
for s, dc in disease_class.items():
if labels[s] != 1:
continue
d = by_cancer.setdefault(dc, {"n_total": 0})
d["n_total"] += 1
for st_key in by_study:
if st_key not in d:
d[st_key] = 0
if studies[s] == st_key:
d[st_key] += 1
n_with_features = len(samples_in_array)
return {
"n_total_in_labels": n_total,
"n_with_features": n_with_features,
"n_dropped_due_to_missing_features": n_total - n_with_features,
"n_cancer_in_labels": n_cancer,
"n_healthy_in_labels": n_healthy,
"n_dropped_cell_line": len(dropped),
"dropped_cell_line_ids": dropped,
"per_study": by_study,
"per_publication": by_publication,
"per_cancer": by_cancer,
}
def section_per_publication(X, y, st, publication_arr, seeds, pca_n,
requested_publications):
"""Per-publication AUC, one fit per requested publication."""
out = {}
for pub in sorted(requested_publications):
mask = publication_arr == pub
n = int(mask.sum())
n_cancer = int((mask & (y == 1)).sum())
n_healthy = int((mask & (y == 0)).sum())
if n < 30 or n_cancer < 10 or n_healthy < 10:
out[pub] = {
"n_total": n,
"n_cancer": n_cancer,
"n_healthy": n_healthy,
"study_label": PUBLICATION_REGISTRY.get(pub, pub),
"skipped": True,
"reason": "insufficient samples for 5-fold CV",
}
continue
_, _, seed_aucs = pooled_oof(
X[mask], y[mask], st[mask], seeds, pca_n, harmonize=False
)
out[pub] = {
"n_total": n,
"n_cancer": n_cancer,
"n_healthy": n_healthy,
"study_label": PUBLICATION_REGISTRY.get(pub, pub),
"auc_mean": float(np.mean(seed_aucs)),
"auc_std": float(np.std(seed_aucs)),
"per_seed_auc": seed_aucs,
"skipped": False,
}
return out
def section_pooled(X, y, st, seeds, pca_n):
out = {}
for tag, harm in [("harmonized", True), ("no_harmonize", False)]:
y_true, score, seed_aucs = pooled_oof(X, y, st, seeds, pca_n, harmonize=harm)
s95, _ = sens_at_spec(y_true, score, 0.95)
s98, _ = sens_at_spec(y_true, score, 0.98)
s99, _ = sens_at_spec(y_true, score, 0.99)
out[tag] = {
"auc_mean": float(np.mean(seed_aucs)),
"auc_std": float(np.std(seed_aucs)),
"per_seed_auc": seed_aucs,
"sens_at_spec_95": s95,
"sens_at_spec_98": s98,
"sens_at_spec_99": s99,
}
return out
def _per_cancer_subset(X, y, st, dc_arr, cancer, n_min=10, healthy_min=10):
"""Return (mask, y_sub, X_sub, st_sub, n_cancer_n, n_healthy_n) for OvR.
Returns None when the cancer subset is too small or the healthy set
is too small for 5-fold CV.
"""
healthy_mask = y == 0
cancer_mask = (dc_arr == cancer) & (y == 1)
n_cancer = int(cancer_mask.sum())
if n_cancer < n_min or healthy_mask.sum() < healthy_min:
return None
mask = cancer_mask | healthy_mask
return (
mask,
cancer_mask[mask].astype(int),
X[mask],
st[mask],
n_cancer,
int(healthy_mask.sum()),
)
def _delong_ci_block(y_true, score):
"""Compute DeLong CI for AUC + Sens@spec at the canonical specificities.
Returns a dict with keys:
auc : DeLong point estimate
auc_se : DeLong SE
auc_ci : (ci_lo, ci_hi) tuple
sens_at_* : dict per specificity with DeLong CIs
"""
auc_d = delong_auc_ci(y_true, score)
sens_block = {}
for spec in DEFAULT_SPECIFICITIES:
sens_block[str(spec)] = delong_sens_at_spec_ci(y_true, score, spec)
return {
"auc": float(auc_d["auc"]),
"auc_se": float(auc_d["se"]),
"auc_ci": [float(auc_d["ci_lo"]), float(auc_d["ci_hi"])],
"sens_at_spec": {k: dict(v) for k, v in sens_block.items()},
}
def _run_all_cancer_ovr(
X, y, st, samples_in_array, disease_class, seeds, pca_n,
harmonize=True, min_n_cancer=10,
):
"""Run OvR (cancer vs ALL healthy) for every non-HEALTHY cancer.
Returns:
dc_arr : np.ndarray of per-sample disease class
artifacts : dict {cancer_name: {
"y_true", "score", "seed_aucs",
"n_cancer", "n_healthy", "skipped", "reason"
}}
"""
dc_arr = np.array(
[disease_class.get(s, "") for s in samples_in_array],
dtype=object,
)
healthy_mask = y == 0
cancer_types = sorted(
set(dc_arr[(y == 1) & (dc_arr != "HEALTHY")]) - {""}
)
artifacts = {}
for cancer in cancer_types:
sub = _per_cancer_subset(X, y, st, dc_arr, cancer, n_min=min_n_cancer)
if sub is None:
n_cancer = int(((dc_arr == cancer) & (y == 1)).sum())
artifacts[cancer] = {
"n_cancer": n_cancer,
"n_healthy": int(healthy_mask.sum()),
"skipped": True,
"reason": "insufficient samples for 5-fold CV",
}
continue
mask, y_sub, X_sub, st_sub, n_cancer, n_healthy = sub
y_true, score, seed_aucs = pooled_oof(
X_sub, y_sub, st_sub, seeds, pca_n, harmonize=harmonize
)
artifacts[cancer] = {
"y_true": y_true,
"score": score,
"seed_aucs": seed_aucs,
"n_cancer": n_cancer,
"n_healthy": n_healthy,
"skipped": False,
"study_sub": st_sub,
}
return dc_arr, artifacts
def _per_cancer_ci_bundle(y_true, score, n_cancer):
"""Build the per-cancer DeLong + bootstrap CI bundle for one OvR fit.
Used by both `section_per_cancer` and `build_per_cancer_standalone_payload`.
"""
delong_block = _delong_ci_block(y_true, score)
delong_rows = []
for spec in DEFAULT_SPECIFICITIES:
sb = delong_block["sens_at_spec"][str(spec)]
delong_rows.append({
"specificity": spec,
"sensitivity": sb["sensitivity"],
"ci95_lo": sb["ci_lo"],
"ci95_hi": sb["ci_hi"],
"operating_threshold": sb["threshold"],
"ci_unreliable": sb["ci_unreliable"],
"n_pos": sb["n_pos"],
"n_neg": sb["n_neg"],
})
delong_auc_dict = {
"auc": delong_block["auc"],
"se": delong_block["auc_se"],
"ci_lo": delong_block["auc_ci"][0],
"ci_hi": delong_block["auc_ci"][1],
}
boot_rows = []
for spec in SPECS_FOR_PER_CANCER:
sens, thr = sens_at_spec(y_true, score, spec)
lo, hi = bootstrap_ci_sens(
y_true, score, spec, N_BOOTSTRAP,
seed=BOOTSTRAP_SEED + int(round(n_cancer)),
)
boot_rows.append({
"specificity": spec,
"sensitivity": sens,
"ci95_lo": lo,
"ci95_hi": hi,
"operating_threshold": thr,
})
return {
"delong_auc": delong_auc_dict,
"delong_rows": delong_rows,
"boot_rows": boot_rows,
}
def build_per_cancer_standalone_payload(
ovr_artifacts, out_path,
pooled_harmonized=None,
pooled_n_pos=None,
pooled_n_neg=None,
):
"""Build the standalone JSON from a pre-computed OvR artifact map.
`ovr_artifacts` is the per-cancer OvR map returned by
`_run_all_cancer_ovr` — skips cancers with `skipped=True`.
`pooled_harmonized` is an optional dict (the `pooled.harmonized`
section of the cross-study JSON). When provided, the POOLED row
uses **these** values instead of re-deriving from concatenated
per-cancer OvR subsets. The cross-study pooled OOF is computed on
ALL cancer vs ALL healthy (each sample gets exactly one score),
whereas concatenating per-cancer OvR subsets would inflate n_neg
to (n_cancers * n_healthy) and is NOT a valid pooled test.
`pooled_n_pos` and `pooled_n_neg` are the actual sample counts
in the pooled OOF (e.g. 363 cancer + 264 healthy for the
harmonized cross-study cohort). When provided, they override
any derivation from per-cancer artifacts.
**Per-cancer iteration (not concatenated) for the same reason:**
n_neg=264 (full healthy count) per cancer, not 1848 (7×264).
Writes the JSON to `out_path` and returns the payload dict.
"""
rows = {}
for cancer, art in ovr_artifacts.items():
if art.get("skipped"):
# Match the canonical cfDNA schema even when skipped (n=0
# because we don't have a real OvR subset for this cancer).
n_cancer = int(art.get("n_cancer", 0))
n_healthy = int(art.get("n_healthy", 0))
rows[cancer] = {
"cancer": cancer,
"n": n_cancer + n_healthy,
"n_pos": n_cancer,
"n_neg": n_healthy,
"auc_mean": None,
"auc_ci": [None, None],
"auc_se": None,
"sens_at_95": None,
"sens_at_98": None,
"sens_at_99": None,
"sens_at_spec": {str(spec): None for spec in DEFAULT_SPECIFICITIES},
"ppv_at_prevalence": {f"prev_{p}": None for p in DEFAULT_PREVALENCES},
"skipped": True,
"skip_reason": art.get("reason", ""),
}
continue
y_sub = art["y_true"].astype(np.int64)
s_sub = art["score"].astype(np.float64)
# Build a 1-of-K label: this cancer vs HEALTHY for everyone else.
label_sub = np.array(
[cancer if v == 1 else "HEALTHY" for v in y_sub],
dtype=object,
)
study_sub = art.get("study_sub", np.array([""] * len(y_sub), dtype=object))
study_sub = study_sub.astype(object)
per_cancer_rows = build_per_cancer_table(
y=y_sub,
s=s_sub,
cancer_label=label_sub,
study_label=study_sub,
specificities=specificities_grid,
prevalences=DEFAULT_PREVALENCES,
include_pooled=False,
)
rows[cancer] = per_cancer_rows["per_cancer"][cancer]
if not rows or all(r.get("skipped") for r in rows.values()):
raise RuntimeError(
"build_per_cancer_standalone_payload: no cancer passed the "
"min-sample floor (n_cancer >= 10 and n_healthy >= 10)."
)
# POOLED row. Prefer the upstream pooled harmonized result (a true
# pooled OOF on cancer-vs-healthy, n_neg = real healthy count).
# Fallback: re-derive from concatenated OvR subsets (which inflates
# n_neg and is marked as fallback in `provenance.fallback_pooled`).
fallback_pooled = False
if pooled_harmonized:
pooled_sens_at_spec = {}
for spec in DEFAULT_SPECIFICITIES:
pooled_sens_at_spec[str(spec)] = {
"sensitivity": pooled_harmonized.get(
f"sens_at_spec_{int(round(spec * 100))}"
),
"specificity": spec,
"ci_method": "pooled_oof_at_target_spec",
}
n_pos_pooled = (int(pooled_n_pos) if pooled_n_pos is not None
else sum(int(art.get("n_cancer", 0))
for art in ovr_artifacts.values()
if not art.get("skipped")))
# Each OvR artifact's `n_healthy` reports the FULL pooled
# healthy count (~264 — every OvR uses the same healthy
# controls). Summing across cancers would give 7× the true
# value. Prefer `pooled_n_neg` if provided, else take the
# max (= the actual pooled healthy count).
n_neg_pooled = (int(pooled_n_neg) if pooled_n_neg is not None
else max(
(int(art.get("n_healthy", 0))
for art in ovr_artifacts.values()
if not art.get("skipped")),
default=0,
))
# Note: OvR's "n_healthy" reports the dataset-wide healthy count
# (~264 for the cross-study harmonized pooled cohort). The pooled
# row's n_pos + n_neg is therefore 2x the actual sample count —
# record the actual count from the upstream n_with_features.
sens99 = pooled_harmonized.get("sens_at_spec_99", 0.0)
pooled_row = {
"cancer": "POOLED",
"n": n_pos_pooled + n_neg_pooled,
"n_pos": n_pos_pooled,
"n_neg": n_neg_pooled,
"auc_mean": float(pooled_harmonized["auc_mean"]),
"auc_ci": [
max(0.0, float(pooled_harmonized["auc_mean"])
- 1.96 * float(pooled_harmonized["auc_std"])),
min(1.0, float(pooled_harmonized["auc_mean"])
+ 1.96 * float(pooled_harmonized["auc_std"])),
],
"auc_se": float(pooled_harmonized["auc_std"]),
"sens_at_95": pooled_harmonized.get("sens_at_spec_95"),
"sens_at_98": pooled_harmonized.get("sens_at_spec_98"),
"sens_at_99": sens99,
"sens_at_spec": pooled_sens_at_spec,
"ppv_at_prevalence": {
f"prev_{p}": ppv_at_prevalence(sens99, PPV_AT_SPEC, p)
for p in DEFAULT_PREVALENCES
},
"skipped": False,
"source": "upstream_pooled_oof",
}
else:
fallback_pooled = True
# Concatenate per-cancer OvR subsets to derive a pooled SENSs.
# n_neg is inflated to (n_cancers * n_healthy) — honest caveat
# recorded in `provenance.fallback_pooled = True`.
pooled_y, pooled_s, pooled_label = [], [], []
pooled_study = []
for cancer, art in ovr_artifacts.items():
if art.get("skipped"):
continue
y_sub = art["y_true"].astype(np.int64)
s_sub = art["score"].astype(np.float64)
pooled_y.append(y_sub)
pooled_s.append(s_sub)
pooled_label.append(np.array(
[cancer if v == 1 else "HEALTHY" for v in y_sub],
dtype=object,
))
pooled_study.append(art.get("study_sub", np.array([""] * len(y_sub), dtype=object)).astype(object))
pooled_table = build_per_cancer_table(
y=np.concatenate(pooled_y),
s=np.concatenate(pooled_s),
cancer_label=np.concatenate(pooled_label),
study_label=np.concatenate(pooled_study) if pooled_study else None,
specificities=specificities_grid,
prevalences=DEFAULT_PREVALENCES,
include_pooled=True,
)
pooled_row = pooled_table.get("pooled", {})
table = {
"per_cancer": rows,
"pooled": pooled_row,
"config": {
"specificities": list(DEFAULT_SPECIFICITIES),
"prevalences": list(DEFAULT_PREVALENCES),
"ppv_at_spec": PPV_AT_SPEC,
"min_positives_for_ci": MIN_POSITIVES_FOR_CI,
},
}
table["provenance"] = {
"source": "cross_study_finallydb.py",
"n_samples": sum(
int(art.get("n_cancer", 0)) + int(art.get("n_healthy", 0))
for art in ovr_artifacts.values()
if not art.get("skipped")
),
"n_cancer_types": len([1 for r in rows.values() if not r.get("skipped")]),
"specificities": list(DEFAULT_SPECIFICITIES),
"prevalences": list(DEFAULT_PREVALENCES),
"ppv_at_spec": PPV_AT_SPEC,
"min_positives_for_ci": MIN_POSITIVES_FOR_CI,
"harmonization": "per-publication z-score StandardScaler fit on train fold only",
"cv": "5-fold StratifiedKFold, 5-seed pooled OOF per OvR",
}
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
with open(out_path, "w") as f:
json.dump(table, f, indent=2)
return table
def section_per_cancer(ovr_artifacts, cancer_types):
"""Emit the per-cancer sens@spec dict from a pre-computed OvR artifact
map (returned by `_run_all_cancer_ovr`).
For each cancer in `cancer_types`, computes DeLong 95% CIs (primary;
DeLong 1988 for AUC, Sun & Xu 2014 for sens@spec) AND preserves the
original bootstrap 95% CIs under `bootstrap_ci` for the audit trail.
Cancers with `skipped=True` in the artifacts are passed through as
SKIPPED rows.
"""
out = {}
for cancer in cancer_types:
art = ovr_artifacts.get(cancer)
if art is None or art.get("skipped"):
reason = art.get("reason") if art else "no OOF artifact"
out[cancer] = {
"n_cancer": art.get("n_cancer", 0) if art else 0,
"skipped": True,
"reason": reason,
}
continue
bundle = _per_cancer_ci_bundle(
art["y_true"], art["score"], art["n_cancer"]
)
out[cancer] = {
"n_cancer": art["n_cancer"],
"n_healthy": art["n_healthy"],
"auc_mean": float(np.mean(art["seed_aucs"])),
"auc_std": float(np.std(art["seed_aucs"])),
"per_seed_auc": art["seed_aucs"],
"primary_ci": "delong",
"delong_ci": {
"auc": bundle["delong_auc"],
"per_specificity": bundle["delong_rows"],
},
"bootstrap_ci": {
"n_bootstrap": N_BOOTSTRAP,
"seed": BOOTSTRAP_SEED,
"method": "percentile",
"per_specificity": bundle["boot_rows"],
},
"per_specificity": bundle["delong_rows"],
"skipped": False,
}
return out
def section_true_confound(X, y, st, publication_arr, requested_publications,
seeds, pca_n):
"""TRUE cross-publication confound.
Run BOTH orientations and BOTH harmonization settings for every pair
of requested publications. With per-publication z-score harmonization
this should collapse to AUC ~0.50; without harmonization it reaches
~0.999 (the classifier learns the publication).
"""
out = {}
pubs = sorted(requested_publications)
if len(pubs) < 2:
# With only one publication, the true-confound is undefined.
return {
"skipped": True,
"reason": (f"true-confound control needs >=2 publications; "
f"got {pubs}"),
}
# All ordered pairs (cancer=pubA, healthy=pubB).
pairs = [(a, b) for a in pubs for b in pubs if a != b]
for pub_pos, pub_neg in pairs:
pos_mask = publication_arr == pub_pos
neg_mask = publication_arr == pub_neg
mask = pos_mask | neg_mask
n_pos = int((mask & pos_mask).sum())
n_neg = int((mask & neg_mask).sum())
tag = f"cancer_{PUBLICATION_REGISTRY.get(pub_pos, pub_pos)}_" \
f"healthy_{PUBLICATION_REGISTRY.get(pub_neg, pub_neg)}"
if n_pos < 10 or n_neg < 10:
out[tag] = {"skipped": True,
"reason": f"n_pos={n_pos}, n_neg={n_neg}",
"publication_cancer": pub_pos,
"publication_healthy": pub_neg}
continue
X_sub = X[mask]
y_sub = pos_mask[mask].astype(int)
st_sub = st[mask]
cfg = {}
for cfg_tag, harm in [("harmonized", True), ("no_harmonize", False)]:
_, _, seed_aucs = pooled_oof(
X_sub, y_sub, st_sub, seeds, pca_n, harmonize=harm
)
cfg[cfg_tag] = {
"auc_mean": float(np.mean(seed_aucs)),
"auc_std": float(np.std(seed_aucs)),
"per_seed_auc": seed_aucs,
}
out[tag] = {
"n_cancer": n_pos,
"n_healthy": n_neg,
"publication_cancer": pub_pos,
"publication_healthy": pub_neg,
**cfg,
}
return out
# --------------------------------------------------------------------------- #
# Markdown writer (kept in this file for one-shot run)
# --------------------------------------------------------------------------- #
def write_markdown(payload, md_path):
cfg = payload["config"]
cohort = payload["cohort"]
pc = payload.get("per_publication", payload.get("per_cohort", {}))
pooled = payload["pooled"]
percancer = payload["per_cancer"]
confound = payload["true_confound_control"]
interp = payload["interpretation"]
pubs = payload.get("publications", [])
api_status = payload.get("finaledb_api_status", "unknown")
L = []
L.append("# Cross-Study FinaleDB Benchmark (Open Data)\n")
pub_str = " + ".join(
f"{p} ({PUBLICATION_REGISTRY.get(p, '?')})" for p in pubs
)
L.append(f"> **Scope**: Open-data benchmark on FinaleDB publications: "
f"{pub_str}. **NOT** clinical validation. **NOT** external "
f"cohort validation. Pooled OOF on the same cohort that "
f"trained the model.\n")
if api_status != "ok":
L.append(f"> **FinaleDB API status**: `{api_status}`. Publications "
f"with no locally-cached features were skipped (see "
f"`results/publication_readiness.json`).\n")
L.append(f"- Generated: `{payload['generated_at']}`\n")
L.append(f"- Classifier: `{cfg['classifier']}`\n")
L.append(f"- Feature set: {cfg['feature_set']}\n")
L.append(f"- PCA n_components: {cfg['pca_n']} (capped at `min(n_train, n_features)` per fold)\n")
L.append(f"- CV: {cfg['cv']}\n")
L.append(f"- Seeds: `{cfg['seeds']}`\n")
L.append(f"- Bootstrap: n={cfg['n_bootstrap']}, seed={cfg['bootstrap_seed']}\n")
L.append(f"- Cell-line regex: `{cfg['cell_line_regex']}`\n")
L.append("\n## 1. Cohort inventory\n")
L.append(f"- Samples in labels file (filtered to requested publications): "
f"**{cohort['n_total_in_labels']}** "
f"({cohort['n_cancer_in_labels']} cancer + "
f"{cohort['n_healthy_in_labels']} healthy)\n")
L.append(f"- Samples with all 5-channel DELFI features: **{cohort['n_with_features']}** "
f"({cohort['n_dropped_due_to_missing_features']} dropped due to missing artifacts)\n")
L.append(f"- Cell-line filter removed: **{cohort['n_dropped_cell_line']}** samples "
f"(none matched the regex on this open-data cohort)\n")
if cohort["dropped_cell_line_ids"]:
L.append(f" - Dropped IDs: `{cohort['dropped_cell_line_ids']}`\n")