junidude14 commited on
Commit
97702e6
·
verified ·
1 Parent(s): 679aff1

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec01_corpus.pdf ADDED
Binary file (25.6 kB). View file
 
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec10_paired_subset_cohorts.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 10 (planned): cohorts that have a paired bulk-sc subset plus bulk-only samples.
2
+
3
+ Counts only; no new model output. Every number is read from the pairing manifests / tables below.
4
+ Outputs
5
+ data/sec10_cohort_counts.csv one row per cohort (samples, donors, flags, LoRA status, sources)
6
+ data/sec10_bulk_only_groups.csv paired-usable vs bulk-only samples per clinical group
7
+ data/sec10_quoted_numbers.csv every number on the slide with its source
8
+ figures/sec10_paired_subset_cohorts.png/.pdf
9
+ """
10
+ import json
11
+ import re
12
+ import sys
13
+ from collections import Counter
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
20
+ sys.path.insert(0, str(DECK / "tools"))
21
+ import style # noqa: E402
22
+ import matplotlib.pyplot as plt # noqa: E402
23
+ from matplotlib.patches import Patch # noqa: E402
24
+
25
+ FIG = DECK / "figures"
26
+ DATA = DECK / "data"
27
+ PFT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
28
+ PF = PFT / "data"
29
+ SCORES = PFT / "scores"
30
+ GEN = PFT / "generated"
31
+ US = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925")
32
+ IMPERIAL_HTSEQ = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/datasets/Zenodo_6497251/raw/htseq_counts.csv")
33
+ JI_SC_LIBS = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/ji2025_chili_v1_20260928/pairing/"
34
+ "sc_gex_libraries_with_bulk_match.csv")
35
+
36
+ rows, groups, quoted = [], [], []
37
+
38
+
39
+ def q(item, value, source):
40
+ quoted.append(dict(item=item, value=value, source=str(source)))
41
+
42
+
43
+ def add_groups(cohort, paired_usable_by_group, bulk_only_by_group, src):
44
+ for g in sorted(set(paired_usable_by_group) | set(bulk_only_by_group)):
45
+ groups.append(dict(cohort=cohort, group=g,
46
+ paired_usable=int(paired_usable_by_group.get(g, 0)),
47
+ bulk_only=int(bulk_only_by_group.get(g, 0)), source=src))
48
+
49
+
50
+ def excl_breakdown(pairs, usable_mask):
51
+ """Why paired rows are excluded: identity fail / borderline, or identity pass but <200 cells."""
52
+ ex = pairs[~usable_mask]
53
+ kind = ex.identity_check.str.split(":").str[0].str.strip()
54
+ c = Counter(kind)
55
+ c["below_200_cells_only"] = int((kind == "pass").sum())
56
+ c.pop("pass", None)
57
+ return dict(c)
58
+
59
+
60
+ def lora_status(ds):
61
+ """5-fold LoRA composition L1 (fold mean) and the leave-one-out composition null from AGGREGATE."""
62
+ agg = json.load(open(SCORES / ds / "aggregate.json"))
63
+ md = (SCORES / ds / "AGGREGATE.md").read_text()
64
+ null = float(re.search(r"Leave-one-out composition null \(fold mean\): ([0-9.]+)", md).group(1))
65
+ lora = agg["arms"]["real_lora__raw"]
66
+ assert lora["n_folds"] == 5
67
+ return lora["comp_l1"]["mean"], null, agg["contrast"]["real_lora__raw"], agg["contrast"]["zs__raw"]
68
+
69
+
70
+ def no_bulk_only_generation(ds, n_paired_usable):
71
+ """PLANNED check: nothing generated for this cohort's bulk-only samples (file names + pooled manifests)."""
72
+ names = [p.name.lower() for p in (GEN / ds).rglob("*")]
73
+ assert not [n for n in names if "bulkonly" in n or "bulk_only" in n], f"{ds}: bulk-only generation exists"
74
+ pm = GEN / ds / "pooled" / "POOL_MANIFEST.json"
75
+ if pm.exists():
76
+ for arm, v in json.load(open(pm))["arms"].items():
77
+ assert v["n_samples"] <= n_paired_usable, (ds, arm, v["n_samples"])
78
+ return True
79
+
80
+
81
+ # ---------------- Ye 2026 sepsis (GSE279448 bulk / GSE279452 sc) ----------------
82
+ ds = "ye2026_sepsis"
83
+ d = PF / ds
84
+ man = json.load(open(d / "MANIFEST.json"))
85
+ pairs = pd.read_csv(d / "pairs.csv")
86
+ bulk_all = pd.read_csv(d / "identity_sex_bulk_all.csv")
87
+ bulk_only = man["excluded"]["bulk_samples_without_sc"]
88
+ assert len(pairs) == man["rows"]
89
+ assert len(pairs) + len(bulk_only) == len(bulk_all), "Ye: paired + bulk-only != all bulks"
90
+ umask = pairs.identity_pass.astype(bool)
91
+ usable = pairs[umask]
92
+ ye_map_bo = {"Adult Sepsis": "sepsis", "Adult Healthy Control": "control", "Adult ICU Control": "control",
93
+ "Pediatric ICU Control": "control", "Pediatric Sepsis": "sepsis",
94
+ "Pediatric Healthy Control": "control"}
95
+ bo_raw = Counter(x["ch_group"] for x in bulk_only)
96
+ assert set(bo_raw) <= set(ye_map_bo), bo_raw
97
+ bo_grp = Counter()
98
+ for k, v in bo_raw.items():
99
+ bo_grp[ye_map_bo[k]] += v
100
+ pu_grp = Counter("sepsis" if "sepsis" in g else "control" for g in usable.group)
101
+ bo_ids = {x["sample_id"] for x in bulk_only}
102
+ flag_list = man["findings"]["sex_vs_geo"]["bulk_all_samples_discordant_or_ambiguous"]
103
+ ye_flag_bo = sorted(x["sample_id"] for x in flag_list if x["sample_id"] in bo_ids)
104
+ assert len(ye_flag_bo) == len(flag_list), "Ye: a sex-flagged bulk is paired"
105
+ paired_don, usable_don = set(pairs.donor_id), set(usable.donor_id)
106
+ comp, null, c_lora, c_zs = lora_status(ds)
107
+ no_bulk_only_generation(ds, len(usable))
108
+ add_groups("Ye 2026 sepsis", pu_grp, bo_grp, f"{d/'MANIFEST.json'} (excluded.bulk_samples_without_sc); {d/'pairs.csv'}")
109
+ rows.append(dict(
110
+ cohort="Ye 2026 sepsis", specimen="PBMC bulk",
111
+ bulk_total=len(bulk_all), paired=len(pairs), seg_train=len(usable), seg_nocomp=0,
112
+ seg_excl=len(pairs) - len(usable), excl_why=json.dumps(excl_breakdown(pairs, umask)), bulk_only=len(bulk_only),
113
+ donors_bulk_total=len(bulk_all), # one sample per donor (QC_REPORT: donor = sample)
114
+ donors_paired_usable=len(usable_don), donors_bulk_only=len(bo_ids), donors_excl_only=len(paired_don - usable_don),
115
+ bulk_only_groups=f"{bo_grp['sepsis']} sepsis, {bo_grp['control']} control",
116
+ sex_flag_bulk_only=len(ye_flag_bo), sex_flag_ids=";".join(ye_flag_bo),
117
+ lora_cv="5-fold", lora_comp_l1=comp, comp_null=null,
118
+ lora_logfc_r=c_lora["r_generated"], zs_raw_logfc_r=c_zs["r_generated"],
119
+ extra=f"controls: paired QC pass {pu_grp['control']} + bulk-only {bo_grp['control']}",
120
+ usable_rule="identity_pass",
121
+ source=f"{d/'MANIFEST.json'}; {d/'pairs.csv'}; {d/'identity_sex_bulk_all.csv'}; {SCORES/ds/'aggregate.json'}; "
122
+ f"{SCORES/ds/'AGGREGATE.md'}",
123
+ ))
124
+ ye_controls_paired, ye_controls_bulk_only = pu_grp["control"], bo_grp["control"]
125
+ q("Sepsis controls, paired QC pass", ye_controls_paired, d / "pairs.csv")
126
+ q("Sepsis controls, bulk-only (36 adult HC + 17 adult ICU + 1 ped ICU)", ye_controls_bulk_only,
127
+ f"{d/'MANIFEST.json'} excluded.bulk_samples_without_sc ch_group")
128
+
129
+ # ---------------- Imperial ESKD COVID (Zenodo 6497251 bulk / COVID-19 Cell Atlas sc) ----------------
130
+ ds = "imperial_eskd"
131
+ d = PF / ds
132
+ man = json.load(open(d / "MANIFEST.json"))
133
+ pairs = pd.read_csv(d / "pairs.csv")
134
+ with open(IMPERIAL_HTSEQ) as fh: # header only; the matrix is never loaded
135
+ header = [c.strip().strip('"') for c in fh.readline().rstrip("\n").split(",")]
136
+ bulk_cols = header[1:]
137
+ assert header[0] == "gencode_id"
138
+ bulk_only = man["excluded"]["bulk_samples_without_sc"]
139
+ assert len(pairs) + len(bulk_only) == len(bulk_cols), "Imperial: paired + bulk-only != htseq columns"
140
+ assert set(pairs.bulk_sample) | {x["bulk_sample"] for x in bulk_only} == set(bulk_cols)
141
+ umask = pairs.identity_pass.astype(bool) & ~pairs.below_200_cells.astype(bool)
142
+ usable = pairs[umask]
143
+ pid = lambda s: s.split("_")[0] # noqa: E731 column names are <patient>_<status>[_<day>]
144
+ bulk_pat = {pid(c) for c in bulk_cols}
145
+ paired_pat, usable_pat = set(pairs.donor_id), set(usable.donor_id)
146
+ assert paired_pat <= bulk_pat
147
+ sexb = pd.read_csv(d / "identity_sex_bulk_all.csv")
148
+ assert set(sexb.donor_id) == bulk_pat and len(sexb) == len(bulk_cols)
149
+ bo_sex = sexb[~sexb.paired.astype(bool)]
150
+ imp_flag = bo_sex[(bo_sex.bulk_sex_call == "ambiguous")
151
+ | (bo_sex.bulk_sex_call.str[0].str.upper() != bo_sex.sex_meta.str.upper())]
152
+ bo_grp = Counter({"covid_positive": 0, "covid_negative": 0, "recovery": 0})
153
+ for x in bulk_only:
154
+ bo_grp[{"positive": "covid_positive", "negative": "covid_negative", "recovery": "recovery"}[x["status"]]] += 1
155
+ pu_grp = Counter(usable.group)
156
+ comp, null, c_lora, c_zs = lora_status(ds)
157
+ no_bulk_only_generation(ds, len(usable))
158
+ add_groups("Imperial ESKD COVID", pu_grp, bo_grp, f"{d/'MANIFEST.json'} (excluded.bulk_samples_without_sc); {d/'pairs.csv'}")
159
+ rows.append(dict(
160
+ cohort="Imperial ESKD COVID", specimen="PBMC bulk, longitudinal",
161
+ bulk_total=len(bulk_cols), paired=len(pairs), seg_train=len(usable), seg_nocomp=0,
162
+ seg_excl=len(pairs) - len(usable), excl_why=json.dumps(excl_breakdown(pairs, umask)), bulk_only=len(bulk_only),
163
+ donors_bulk_total=len(bulk_pat),
164
+ donors_paired_usable=len(usable_pat), donors_bulk_only=len(bulk_pat - paired_pat),
165
+ donors_excl_only=len(paired_pat - usable_pat),
166
+ bulk_only_groups=f"{bo_grp['covid_positive']} COVID+, {bo_grp['covid_negative']} COVID−, "
167
+ f"{bo_grp['recovery']} recovery",
168
+ sex_flag_bulk_only=len(imp_flag), sex_flag_ids=";".join(imp_flag.bulk_sample),
169
+ lora_cv="5-fold", lora_comp_l1=comp, comp_null=null,
170
+ lora_logfc_r=c_lora["r_generated"], zs_raw_logfc_r=c_zs["r_generated"],
171
+ extra="donors excluded-only: " + ";".join(sorted(paired_pat - usable_pat)),
172
+ usable_rule="identity_pass and not below_200_cells",
173
+ source=f"{d/'MANIFEST.json'}; {d/'pairs.csv'}; {d/'identity_sex_bulk_all.csv'}; header of {IMPERIAL_HTSEQ}; "
174
+ f"{SCORES/ds/'aggregate.json'}; {SCORES/ds/'AGGREGATE.md'}",
175
+ ))
176
+
177
+ # ---------------- Ji 2025 ChILI (GSE287540 bulk = PAXgene whole blood / GSE287541 sc) ----------------
178
+ ds = "ji2025_chili"
179
+ d = PF / ds
180
+ man = json.load(open(d / "MANIFEST.json"))
181
+ pairs = pd.read_csv(d / "pairs.csv")
182
+ bulk_all = pd.read_csv(d / "identity_sex_bulk_all.csv")
183
+ bulk_only = man["excluded"]["bulk_samples_without_sc"]
184
+ assert len(pairs) + len(bulk_only) == len(bulk_all), "Ji: paired + bulk-only != all bulks"
185
+ assert "whole blood" in json.dumps(man["specimen_warning"]).lower()
186
+ umask = pairs.identity_pass.astype(bool)
187
+ usable = pairs[umask]
188
+ norm = lambda s: "N%03d" % int(re.match(r"N0*(\d+)", s).group(1)) # noqa: E731 N87 == N087
189
+ bulk_pat = {norm(s) for s in bulk_all.sample_id}
190
+ paired_pat, usable_pat = {norm(s) for s in pairs.donor_id}, {norm(s) for s in usable.donor_id}
191
+ assert paired_pat <= bulk_pat
192
+ bo_gsm = {x["gsm"] for x in bulk_only}
193
+ bo_raw = Counter(x["Sample_title"].split("_", 1)[1] for x in bulk_only) # e.g. chili_BC, control_AC
194
+ bo_grp = Counter()
195
+ for k, v in bo_raw.items():
196
+ bo_grp["ChILI" if k.startswith("chili") else "control"] += v
197
+ pu_grp = Counter("ChILI" if o == "ChILI" else "control" for o in usable.outcome)
198
+ chili_bc_bulk_only = int(bo_raw.get("chili_BC", 0))
199
+ chili_bc_paired = int(man["pairs_by_outcome_timepoint"].get("ChILI_BC", 0))
200
+ flag = bulk_all[bulk_all.sex_discordant_with_geo.astype(bool) | (bulk_all.bulk_sex_call == "ambiguous")]
201
+ assert set(flag.bulk_gsm) <= bo_gsm, "Ji: a sex-flagged bulk is paired"
202
+ ji_flag_bo = sorted(flag.sample_id)
203
+ ji_flag_bc = [s for s in ji_flag_bo if s.endswith("_chili_BC")]
204
+ sclib = pd.read_csv(JI_SC_LIBS)
205
+ ji_bc_sc_unpaired = sclib[(sclib.outcome == "ChILI") & (sclib.timepoint == "BC") & ~sclib.paired.astype(bool)]
206
+ comp, null, c_lora, c_zs = lora_status(ds)
207
+ no_bulk_only_generation(ds, len(usable))
208
+ add_groups("Ji 2025 ChILI", pu_grp, bo_grp, f"{d/'MANIFEST.json'} (excluded.bulk_samples_without_sc); {d/'pairs.csv'}")
209
+ for k in sorted(bo_raw):
210
+ groups.append(dict(cohort="Ji 2025 ChILI", group="detail:" + k, paired_usable=int(
211
+ ((usable.outcome == ("ChILI" if k.startswith("chili") else "control")) & (usable.timepoint == k.split("_")[1])).sum()),
212
+ bulk_only=int(bo_raw[k]), source=str(d / "MANIFEST.json")))
213
+ rows.append(dict(
214
+ cohort="Ji 2025 ChILI", specimen="whole-blood bulk",
215
+ bulk_total=len(bulk_all), paired=len(pairs), seg_train=len(usable), seg_nocomp=0,
216
+ seg_excl=len(pairs) - len(usable), excl_why=json.dumps(excl_breakdown(pairs, umask)), bulk_only=len(bulk_only),
217
+ donors_bulk_total=len(bulk_pat),
218
+ donors_paired_usable=len(usable_pat), donors_bulk_only=len(bulk_pat - paired_pat),
219
+ donors_excl_only=len(paired_pat - usable_pat),
220
+ bulk_only_groups=f"{bo_grp['ChILI']} ChILI ({chili_bc_bulk_only} pre-ICI), {bo_grp['control']} control",
221
+ sex_flag_bulk_only=len(ji_flag_bo), sex_flag_ids=";".join(ji_flag_bo),
222
+ lora_cv="5-fold", lora_comp_l1=comp, comp_null=null,
223
+ lora_logfc_r=c_lora["r_generated"], zs_raw_logfc_r=c_zs["r_generated"],
224
+ extra=(f"ChILI before ICI (BC): paired {chili_bc_paired}, bulk-only {chili_bc_bulk_only} "
225
+ f"({len(ji_flag_bc)} sex-flagged: {';'.join(ji_flag_bc)}), unpaired ChILI BC sc libraries "
226
+ f"{len(ji_bc_sc_unpaired)} ({';'.join(ji_bc_sc_unpaired.sample_id)}); donors excluded-only: "
227
+ + ";".join(sorted(paired_pat - usable_pat))),
228
+ usable_rule="identity_pass",
229
+ source=f"{d/'MANIFEST.json'}; {d/'pairs.csv'}; {d/'identity_sex_bulk_all.csv'}; {JI_SC_LIBS}; "
230
+ f"{SCORES/ds/'aggregate.json'}; {SCORES/ds/'AGGREGATE.md'}",
231
+ ))
232
+ q("ChILI before ICI (BC), bulk-only", chili_bc_bulk_only, f"{d/'MANIFEST.json'} excluded.bulk_samples_without_sc Sample_title")
233
+ q("ChILI before ICI (BC), paired", chili_bc_paired, f"{d/'MANIFEST.json'} pairs_by_outcome_timepoint")
234
+ q("ChILI before ICI (BC), unpaired sc libraries (patients absent from bulk)", len(ji_bc_sc_unpaired), JI_SC_LIBS)
235
+ q("ChILI before ICI (BC), bulk-only sex-flagged", len(ji_flag_bc), f"{d/'identity_sex_bulk_all.csv'} sex_discordant_with_geo")
236
+
237
+ # ---------------- Arunachalam 2020 COVID (GSE152418 bulk / GSE155673 sc) ----------------
238
+ meta = US / "arunachalam" / "metadata"
239
+ bc = pd.read_csv(meta / "bulk_cohort.csv")
240
+ rec = pd.read_csv(meta / "pairs_reconciliation.csv")
241
+ assert int(bc.has_sc.sum()) == len(rec)
242
+ assert set(rec.sample_id) == set(bc.sample_id[bc.has_sc.astype(bool)])
243
+ id_ok = rec.sex_all_four_agree.astype(bool) & rec.expr_identity_own_is_best.astype(bool)
244
+ comp_ok = rec.composition_eligible.astype(bool)
245
+ n_train = int((id_ok & comp_ok).sum())
246
+ n_nocomp = int((id_ok & ~comp_ok).sum())
247
+ n_excl = int((~id_ok).sum())
248
+ n_strict = int(rec.strict_identity_eligible.astype(bool).sum())
249
+ bo = bc[~bc.has_sc.astype(bool)]
250
+ pu = bc[bc.sample_id.isin(set(rec.sample_id[id_ok & comp_ok]))]
251
+ bo_grp, pu_grp = Counter(bo.group), Counter(pu.group)
252
+ add_groups("Arunachalam 2020 COVID", pu_grp, bo_grp, str(meta / "bulk_cohort.csv"))
253
+ paired_subj = set(bc.subject_norm[bc.has_sc.astype(bool)])
254
+ arun_flag = bo[~bo.expr_sex_matches_geo.astype(bool)]
255
+ # zero-shot (no LoRA) cells for all bulk-only samples already exist: base model, raw / TPM / cal inputs
256
+ rc = json.load(open(US / "arunachalam_4arm" / "receipts" / "receipt_checks.json"))
257
+ assert rc["all_ok"]
258
+ zs_bo = {k: v for k, v in rc["tags"].items() if v["block"].startswith("bulkonly")}
259
+ zs_bo_arms = sorted({v["arm"] for v in zs_bo.values()})
260
+ zs_bo_bulks = {a: sum(v["bulks"] for v in zs_bo.values() if v["arm"] == a) for a in zs_bo_arms}
261
+ assert set(zs_bo_bulks.values()) == {len(bo)}, zs_bo_bulks
262
+ zs_ckpt = rc["checkpoint"]["path"]
263
+ assert zs_ckpt.endswith("f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
264
+ dr = pd.read_csv(US / "arunachalam_4arm" / "global_r" / "decision_rule.csv")
265
+ dr_pre = dr[dr.preregistered.astype(bool)]
266
+ arun_best_pass = int(dr_pre["n_populations_exceeding_raw_broadcast_by_0.018"].max())
267
+ arun_npop = int(dr_pre.populations.iloc[0])
268
+ rows.append(dict(
269
+ cohort="Arunachalam 2020 COVID", specimen="PBMC bulk; DC-enriched sc",
270
+ bulk_total=len(bc), paired=len(rec), seg_train=n_train, seg_nocomp=n_nocomp, seg_excl=n_excl,
271
+ excl_why=json.dumps({"identity_fail": n_excl}), bulk_only=len(bo),
272
+ donors_bulk_total=bc.subject_norm.nunique(),
273
+ donors_paired_usable=pu.subject_norm.nunique(), donors_bulk_only=len(set(bc.subject_norm) - paired_subj),
274
+ donors_excl_only=0,
275
+ bulk_only_groups=f"{bo_grp.get('COVID', 0)} COVID, {bo_grp.get('HC', 0)} healthy, {bo_grp.get('CONV', 0)} conv.",
276
+ sex_flag_bulk_only=len(arun_flag), sex_flag_ids=";".join(arun_flag.sample_id),
277
+ lora_cv="none", lora_comp_l1=np.nan, comp_null=np.nan, lora_logfc_r=np.nan, zs_raw_logfc_r=np.nan,
278
+ extra=(f"paired identity pass {int(id_ok.sum())}/{len(rec)}, composition_eligible {int(comp_ok.sum())}/{len(rec)} "
279
+ f"(material {';'.join(sorted(set(rec.material_status)))}), strict_identity_eligible {n_strict}; "
280
+ f"zero-shot bulk-only generated: arms {','.join(zs_bo_arms)}, {len(bo)} bulks each ({zs_ckpt}); "
281
+ f"prereg decision rule: best arm beats broadcast in {arun_best_pass}/{arun_npop} populations"),
282
+ usable_rule="identity pass (sex_all_four_agree & expr_identity_own_is_best) AND composition_eligible",
283
+ source=f"{meta/'bulk_cohort.csv'}; {meta/'pairs_reconciliation.csv'}; "
284
+ f"{US/'arunachalam_4arm/receipts/receipt_checks.json'}; {US/'arunachalam_4arm/global_r/decision_rule.csv'}",
285
+ ))
286
+ q("Arunachalam paired, composition-eligible", int(comp_ok.sum()), f"{meta/'pairs_reconciliation.csv'} composition_eligible")
287
+ q("Arunachalam zero-shot bulk-only samples generated (per input arm)", len(bo),
288
+ f"{US/'arunachalam_4arm/receipts/receipt_checks.json'} tags *_bulkonly_a/b bulks")
289
+ q("Arunachalam prereg: populations where any zero-shot arm beats broadcast", f"{arun_best_pass}/{arun_npop}",
290
+ US / "arunachalam_4arm" / "global_r" / "decision_rule.csv")
291
+
292
+ # ---------------- not plotted: Asan vaccine (no donor map), Giroux 2022 (broadcast beats LoRA) ----------------
293
+ asan_bulk = pd.read_csv(US / "asan_cll" / "conditions" / "asan" / "samples.csv")
294
+ asan_sc = pd.read_csv(US / "asan_cll" / "observed" / "asan" / "libraries.csv")
295
+ asan_note = dict(bulk=len(asan_bulk), subjects=asan_bulk.subject.nunique(), sc_libraries=len(asan_sc),
296
+ reason="no bulk-sc donor map (asan_cll/RESULTS.md section 1)")
297
+ gd = PF / "giroux2022"
298
+ gpairs = pd.read_csv(gd / "pairs.csv")
299
+ gman = json.load(open(gd / "MANIFEST.json"))
300
+ g_bo = [x for x in gman["excluded"]["bulk_count_columns_without_pair"]
301
+ if x["unpaired_reason"] == "no_sc_library_for_this_subject_day"]
302
+ gh = json.load(open(SCORES / "giroux2022" / "pooled" / "summary.json"))["headline"]["real_lora__raw"]
303
+ g_r, g_rb = gh["contrast_mean_cp10k_r_gen"], gh["contrast_mean_cp10k_r_broadcast"]
304
+ g_deg, g_degb = gh["deg_top50_sum"], gh["deg_top50_sum_broadcast"]
305
+ assert g_rb > g_r and g_degb > g_deg, "Giroux: broadcast no longer beats LoRA"
306
+ giroux_note = dict(pairs_qc_pass=int(gpairs.identity_pass.astype(bool).sum()), bulk_only_author_columns=len(g_bo),
307
+ lora_r=g_r, broadcast_r=g_rb, lora_deg=g_deg, broadcast_deg=g_degb)
308
+ q("Giroux QC-pass pairs (not shown)", giroux_note["pairs_qc_pass"], gd / "pairs.csv")
309
+ q("Giroux author bulk columns without sc (not shown)", len(g_bo),
310
+ f"{gd/'MANIFEST.json'} excluded.bulk_count_columns_without_pair (no_sc_library_for_this_subject_day)")
311
+ q("Giroux pooled LoRA vs broadcast: severe-mild r / top-50 DEG sum",
312
+ f"{g_r:.2f} vs {g_rb:.2f} / {g_deg} vs {g_degb}", SCORES / "giroux2022" / "pooled" / "summary.json")
313
+ lora_rank = int(re.search(r"Rank (\d+), alpha", (PFT / "README.md").read_text()).group(1))
314
+ q("LoRA rank", lora_rank, PFT / "README.md")
315
+
316
+ tab = pd.DataFrame(rows)
317
+ assert (tab.seg_train + tab.seg_nocomp + tab.seg_excl == tab.paired).all()
318
+ assert (tab.paired + tab.bulk_only == tab.bulk_total).all()
319
+ assert (tab.donors_paired_usable + tab.donors_bulk_only + tab.donors_excl_only
320
+ + np.where(tab.seg_nocomp > 0, tab.donors_bulk_total - tab.donors_bulk_only, 0) == tab.donors_bulk_total).all()
321
+ tab["lora_cv_source"] = [str(SCORES / k / "AGGREGATE.md") if r.lora_cv != "none" else "no paired-FT dataset built"
322
+ for k, r in zip(["ye2026_sepsis", "imperial_eskd", "ji2025_chili", None], tab.itertuples())]
323
+ for r in tab.itertuples():
324
+ for item in ["bulk_total", "seg_train", "seg_nocomp", "seg_excl", "bulk_only", "donors_paired_usable",
325
+ "donors_bulk_only", "donors_excl_only", "donors_bulk_total", "sex_flag_bulk_only"]:
326
+ q(f"{r.cohort}: {item}", getattr(r, item), r.source)
327
+ if r.lora_cv != "none":
328
+ q(f"{r.cohort}: LoRA 5-fold comp L1 / LOO null", f"{r.lora_comp_l1:.2f} / {r.comp_null:.2f}", r.lora_cv_source)
329
+ tab.to_csv(DATA / "sec10_cohort_counts.csv", index=False)
330
+ pd.DataFrame(groups).to_csv(DATA / "sec10_bulk_only_groups.csv", index=False)
331
+ qt = pd.DataFrame(quoted)
332
+ qt.to_csv(DATA / "sec10_quoted_numbers.csv", index=False)
333
+ print(tab.drop(columns=["source"]).T.to_string())
334
+ print("Asan (not plotted):", asan_note)
335
+ print("Giroux (not plotted):", giroux_note)
336
+
337
+ # ---------------- figure ----------------
338
+ C_TRAIN = style.INK
339
+ C_BO, C_BO_EDGE = style.PBISC_PALE, style.ARM["pbisc"]
340
+ DASH = (0, (3, 2))
341
+ W = style.TALL[0]
342
+ ROW = 1.10 # inches per cohort block
343
+ BAR_Y, BAR_H = 0.40, 0.27 # bar centre offset from block top, bar height (inches)
344
+ TOP = 0.78 # inches above the first block for the PLANNED line and the legend
345
+ AX_BOTTOM = 0.48 # inches for the x axis under the last block
346
+ n = len(tab)
347
+ H = TOP + n * ROW + AX_BOTTOM
348
+ fig = plt.figure(figsize=(W, H))
349
+ ax = fig.add_axes([0.0, AX_BOTTOM / H, 1.0, (n * ROW) / H])
350
+ xmax = tab.bulk_total.max()
351
+ XR = xmax * 1.30 # room right of the longest bar for its total label
352
+ ax.set_xlim(0, XR)
353
+ ax.set_ylim(n * ROW, 0) # y in inches from the top of the first block
354
+ FS_MAIN, FS_SUB = 13, 11
355
+
356
+ inbar = [] # (text, patch, row index)
357
+ for i, r in enumerate(tab.itertuples()):
358
+ y0 = i * ROW
359
+ yb = y0 + BAR_Y
360
+ ax.text(0, y0, r.cohort, ha="left", va="top", fontsize=FS_MAIN, fontweight="bold", color=style.INK)
361
+ if r.lora_cv != "none":
362
+ status = f"LoRA 5-fold: comp L1 {r.lora_comp_l1:.2f} vs null {r.comp_null:.2f}"
363
+ else:
364
+ status = f"no LoRA; zero-shot beats broadcast in {arun_best_pass}/{arun_npop} populations"
365
+ ax.text(XR, y0, status, ha="right", va="top", fontsize=FS_SUB, color=style.SUBINK)
366
+ x = 0
367
+ p_tr = ax.barh(yb, r.seg_train, left=x, height=BAR_H, color=C_TRAIN, edgecolor=C_TRAIN, linewidth=0.8)[0]
368
+ x += r.seg_train
369
+ p_nc = ax.barh(yb, r.seg_nocomp, left=x, height=BAR_H, facecolor="white", edgecolor=style.INK, hatch="////",
370
+ linewidth=0.8)[0]
371
+ x += r.seg_nocomp
372
+ ax.barh(yb, r.seg_excl, left=x, height=BAR_H, facecolor="white", edgecolor=style.GREY, hatch="xxx", linewidth=0.8)
373
+ x += r.seg_excl
374
+ p_bo = ax.barh(yb, r.bulk_only, left=x, height=BAR_H, color=C_BO, edgecolor=C_BO_EDGE, linewidth=1.0,
375
+ linestyle=DASH)[0]
376
+ if r.seg_train:
377
+ inbar.append((ax.text(r.seg_train / 2, yb, f"{r.seg_train}", ha="center", va="center", color="white",
378
+ fontsize=12, fontweight="bold"), p_tr, i))
379
+ if r.seg_nocomp:
380
+ inbar.append((ax.text(r.seg_train + r.seg_nocomp / 2, yb, f"{r.seg_nocomp}", ha="center", va="center",
381
+ color=style.INK, fontsize=12, fontweight="bold",
382
+ bbox=dict(facecolor="white", edgecolor="none", pad=0.6)), p_nc, i))
383
+ inbar.append((ax.text(r.paired + r.bulk_only / 2, yb, f"{r.bulk_only}", ha="center", va="center",
384
+ color=style.INK, fontsize=12, fontweight="bold"), p_bo, i))
385
+ excl = f" ({r.seg_excl} excl.)" if r.seg_excl else ""
386
+ ax.text(r.bulk_total + xmax * 0.015, yb, f"{r.bulk_total}{excl}", ha="left", va="center", color=style.INK,
387
+ fontsize=12, gid=f"total{i}")
388
+ flag = f"; {r.sex_flag_bulk_only} sex-flagged" if r.sex_flag_bulk_only else ""
389
+ if r.cohort.startswith("Ji"):
390
+ flag += f" ({len(ji_flag_bc)} ChILI pre-ICI)"
391
+ if r.cohort.startswith("Arunachalam"):
392
+ flag += "; zero-shot cells made"
393
+ line1 = f"{r.specimen} · bulk-only: {r.bulk_only_groups}{flag}"
394
+ if r.seg_nocomp:
395
+ line2 = (f"donors: {r.donors_bulk_total - r.donors_bulk_only} paired "
396
+ f"({r.seg_train}/{r.paired} composition-eligible), {r.donors_bulk_only} bulk-only")
397
+ else:
398
+ line2 = (f"donors: {r.donors_paired_usable} paired, {r.donors_bulk_only} bulk-only, "
399
+ f"{r.donors_excl_only} excluded")
400
+ if r.cohort.startswith("Ji"):
401
+ line2 += f"; {len(ji_bc_sc_unpaired)} pre-ICI ChILI sc, no bulk"
402
+ ax.text(0, yb + BAR_H / 2 + 0.07, line1, ha="left", va="top", fontsize=FS_SUB, color=style.SUBINK)
403
+ ax.text(0, yb + BAR_H / 2 + 0.27, line2, ha="left", va="top", fontsize=FS_SUB, color=style.SUBINK)
404
+
405
+ ax.set_yticks([])
406
+ ax.spines["left"].set_visible(False)
407
+ ax.set_xticks([0, 100, 200, 300])
408
+ ax.spines["bottom"].set_bounds(0, 300)
409
+ ax.set_xlabel("bulk samples", fontsize=12)
410
+ ax.xaxis.set_label_coords(150 / XR, -0.05) # centred under the drawn 0-300 spine
411
+
412
+ leg = [Patch(facecolor=C_TRAIN, edgecolor=C_TRAIN, label="paired, QC pass: LoRA training"),
413
+ Patch(facecolor="white", edgecolor=style.GREY, hatch="xxx", label="paired, excluded (fail / borderline / <200 cells)"),
414
+ Patch(facecolor="white", edgecolor=style.INK, hatch="////", label="paired, DC-enriched sc: no composition"),
415
+ Patch(facecolor=C_BO, edgecolor=C_BO_EDGE, linestyle=DASH, label="bulk only: LoRA cells to generate")]
416
+ fig.legend(handles=leg, loc="upper left", bbox_to_anchor=(0.0, 1 - 0.30 / H), ncol=2, fontsize=11,
417
+ handlelength=1.5, handleheight=1.0, columnspacing=1.0, labelspacing=0.35, borderaxespad=0.0, borderpad=0.0)
418
+ fig.text(1.0, 1.0, "PLANNED: no LoRA cells for bulk-only yet", ha="right", va="top", fontsize=13,
419
+ fontweight="bold", color=style.INK)
420
+
421
+ # in-bar numbers that do not fit their segment move to one "a + b = total" label right of the bar
422
+ fig.canvas.draw()
423
+ rend = fig.canvas.get_renderer()
424
+ misfit = {i for t, pch, i in inbar if t.get_window_extent(rend).width > pch.get_window_extent(rend).width - 6}
425
+ for i in misfit:
426
+ r = tab.iloc[i]
427
+ for t, pch, j in inbar:
428
+ if j == i:
429
+ t.remove()
430
+ tot = [t for t in ax.texts if t.get_gid() == f"total{i}"][0]
431
+ parts = [str(v) for v in (r.seg_train, r.seg_nocomp, r.seg_excl) if v] + [str(r.bulk_only)]
432
+ tot.set_text(" + ".join(parts) + f" = {r.bulk_total}")
433
+ print("rows with outside labels:", [tab.iloc[i].cohort for i in sorted(misfit)])
434
+
435
+ # guard: no two text boxes overlap, and every text stays inside the figure
436
+ fig.canvas.draw()
437
+ texts = [t for t in ax.texts + fig.texts if t.get_visible() and t.get_text()]
438
+ boxes = [(t.get_text()[:30], t.get_window_extent(rend)) for t in texts]
439
+ boxes.append(("legend", fig.legends[0].get_window_extent(rend)))
440
+ fb = fig.bbox
441
+ for k, (s1, b1) in enumerate(boxes):
442
+ assert b1.x0 >= fb.x0 - 1 and b1.x1 <= fb.x1 + 1 and b1.y0 >= fb.y0 - 1 and b1.y1 <= fb.y1 + 1, f"outside: {s1}"
443
+ for s2, b2 in boxes[k + 1:]:
444
+ assert not b1.overlaps(b2), f"text overlap: {s1!r} / {s2!r}"
445
+ print(f"figure {W:.2f} x {H:.2f} in; {len(boxes)} text boxes, no overlap")
446
+ style.save(fig, "sec10_paired_subset_cohorts", FIG)
447
+ print("saved", FIG / "sec10_paired_subset_cohorts.png")
448
+ print(qt.to_string())
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/style.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared matplotlib style for every figure of the 2026-09-30 paper-summary deck.
2
+
3
+ Figures are drawn at their on-slide size (inches), so font sizes are the sizes seen on the slide.
4
+ Slide: 13.333 x 7.5 in (16:9). Content area below the title: about 12.3 x 5.7 in.
5
+ Use FULL, HALF or TALL for figsize unless a figure needs something else.
6
+ Plain look: white background, no top/right spines, no titles inside figures (the slide title says it),
7
+ no shadows, no gradients, no decorative elements. Colour carries meaning only.
8
+ """
9
+ import matplotlib
10
+ matplotlib.use("Agg")
11
+ import matplotlib.pyplot as plt
12
+
13
+ FULL = (12.3, 5.6) # figure fills the content area
14
+ HALF = (6.0, 5.4) # one of two side-by-side figures
15
+ TALL = (7.8, 5.6) # figure + a keyword column on the right
16
+ DPI = 200
17
+
18
+ FS = 14 # base font size on the slide (pt)
19
+ plt.rcParams.update({
20
+ "font.family": "sans-serif",
21
+ "font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"],
22
+ "font.size": FS, "axes.titlesize": FS, "axes.labelsize": FS,
23
+ "xtick.labelsize": FS - 2, "ytick.labelsize": FS - 2, "legend.fontsize": FS - 2,
24
+ "axes.spines.top": False, "axes.spines.right": False,
25
+ "axes.linewidth": 1.0, "xtick.major.width": 1.0, "ytick.major.width": 1.0,
26
+ "legend.frameon": False, "figure.facecolor": "white", "axes.facecolor": "white",
27
+ "savefig.facecolor": "white", "savefig.bbox": "tight", "savefig.pad_inches": 0.05,
28
+ "pdf.fonttype": 42, "ps.fonttype": 42,
29
+ })
30
+
31
+ # One colour per method, identical across every figure (Okabe-Ito, same as the paper's paired figures)
32
+ ARM = {
33
+ "pbisc": "#D55E00", # PBISC (final model, or LoRA fine-tune)
34
+ "lora": "#D55E00",
35
+ "full_ft": "#E07B39",
36
+ "zs_cal": "#0072B2", # zero-shot, paired calibration
37
+ "zs_raw": "#A6CBE3", # zero-shot, raw bulk
38
+ "pseudo": "#1A1A1A", # zero-shot from sc pseudobulk (reference line)
39
+ "scsemi": "#E69F00", # scSemiProfiler
40
+ "vae": "#56B4E9", # PBISC-VAE
41
+ "sconly": "#CC79A7", # sc-only fine-tune
42
+ "broadcast": "#9A9A9A", # real-bulk broadcast baseline
43
+ "other": "#009E73",
44
+ "refcal": "#D55E00", # zero-shot + reference calibration (PBISC's no-pair real-bulk path; = sec04 PBISC colour)
45
+ "tpm": "#DDCC77", # zero-shot, TPM (length-corrected) bulk input (sec05; not used by any other key)
46
+ }
47
+ # Architecture variants (section 3 only). trunk4x / prop avoid the PBISC-VAE (#56B4E9) and
48
+ # scSemiProfiler (#E69F00) reference-line colours drawn on the same slide.
49
+ VARIANT = {"1x": "#D55E00", "4x": "#0072B2", "trunk4x": "#332288", "ctx4x": "#009E73", "16x": "#CC79A7", "prop": "#999933"}
50
+ # Gene panels (section 3 only); 3k avoids the PBISC-VAE line colour
51
+ PANEL = {"2k": "#A6CBE3", "3k": "#882255", "6k": "#D55E00", "15k": "#0072B2"}
52
+ GREY = "#8C8C8C"
53
+ INK = "#1A1A1A"
54
+ SUBINK = "#4D4D4D" # secondary text (sub-lines under bars)
55
+ PBISC_PALE = "#F3C9A8" # light PBISC orange: planned / not yet generated (outlined in ARM["pbisc"])
56
+
57
+
58
+ def save(fig, name, figdir):
59
+ """Save PNG (slide) and PDF (vector) with the same stem."""
60
+ from pathlib import Path
61
+ figdir = Path(figdir)
62
+ fig.savefig(figdir / f"{name}.png", dpi=DPI)
63
+ fig.savefig(figdir / f"{name}.pdf")
64
+ plt.close(fig)
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sync_sec09_text.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Copy section 9 slide text from data/sec09_slide_text.json into data/slides_spec.json.
3
+
4
+ sec09_paired_validation.py regenerates titles, keywords and footnotes from the
5
+ scores (the scSemiProfiler verdicts can change when the missing draws arrive).
6
+ Run after that script and before generate_deck.py:
7
+
8
+ python3 tools/sec09_paired_validation.py
9
+ python3 tools/sync_sec09_text.py
10
+ python3 generate_deck.py
11
+
12
+ Titles, keywords and footnote_full are overwritten. The on-slide footnote is a
13
+ shortened copy; if footnote_full changed, the script lists the slide so the
14
+ short copy can be checked by hand (the deck build fails if it exceeds 2 lines).
15
+ """
16
+ import json
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ DECK = Path(__file__).resolve().parents[1]
21
+ SPEC = Path(sys.argv[1]) if len(sys.argv) > 1 else DECK / "data" / "slides_spec.json"
22
+ SRC = DECK / "data" / "sec09_slide_text.json"
23
+
24
+
25
+ def main() -> None:
26
+ spec = json.loads(SPEC.read_text())
27
+ src = json.loads(SRC.read_text())["slides"]
28
+ review = []
29
+ n = 0
30
+ for s in spec["slides"]:
31
+ i = s.get("sec09_index")
32
+ if i is None:
33
+ continue
34
+ g = src[i]
35
+ figs = [str(Path(f).relative_to(DECK)) for f in g["figures"]]
36
+ have = [str(Path(f).relative_to(DECK)) if Path(f).is_absolute() else f for f in s["figures"]]
37
+ if figs != have:
38
+ raise SystemExit(f"figure mismatch for sec09 slide {i}: {figs} vs {s['figures']}")
39
+ s["figures"] = figs
40
+ s["title"] = g["title"]
41
+ s["keywords"] = g["keywords"]
42
+ if s.get("footnote_full", s.get("footnote")) != g["footnote"]:
43
+ review.append(g["title"])
44
+ s["footnote_full"] = g["footnote"]
45
+ n += 1
46
+ if n != len(src):
47
+ raise SystemExit(f"spec has {n} sec09 slides, source has {len(src)}")
48
+ SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
49
+ print(f"synced {n} section 9 slides")
50
+ for t in review:
51
+ print(f"REVIEW short footnote (source footnote changed): {t}")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()