junidude14 commited on
Commit
8b575c1
·
verified ·
1 Parent(s): 5db6d98

Archive 4 checkpoints (1-4)

Browse files
.gitattributes CHANGED
@@ -89,3 +89,4 @@ paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-t
89
  paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
90
  paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf filter=lfs diff=lfs merge=lfs -text
91
  paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
 
 
89
  paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
90
  paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf filter=lfs diff=lfs merge=lfs -text
91
  paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
92
+ paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/main.pdf filter=lfs diff=lfs merge=lfs -text
paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/main.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10882ac1427eaf947d0dc74c9468209f12c6adc43880201705b6c605a642ca61
3
+ size 263422
paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/scripts/corpus/build_corpus_tables.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aggregate tables describing the pretraining corpus, for the Figure 1 corpus panels (CPU only, 2026-10-06).
3
+
4
+ Every registered corpus cell (41,395,184 = 41,270,779 base + 124,405 overlay rows) is counted once.
5
+ - Corpus rows: model_7 e2_full_source/metadata/obs_sc.parquet/<shard>.parquet (dataset, donor, sample per cell).
6
+ - Labels: the base block obs (PBISC-data/single-cell-data-block-blood/metadata/obs_sc.parquet/<same shard>.parquet),
7
+ joined row by row (same shard file, same source_row_index; checked). Overlay rows carry no cell label; they take
8
+ their sample's condition and assay.
9
+ - Split and platform: model_7 e2_full_index/metadata/sample_index.parquet (one row per registered sample).
10
+ - Datasets whose source obs lacks a usable disease or assay field are completed from public metadata stored in
11
+ source_data/corpus/geo/ (GEO series matrices) and source_data/corpus/dataset_info.csv (notes and sources).
12
+ Outputs (source_data/corpus/): corpus_samples.csv, corpus_cellgroups.csv (cell-level condition), corpus_datasets.csv, corpus_celltypes.csv,
13
+ corpus_assay_condition.csv, corpus_summary.json. No donor or sample identifiers are written (samples keep the
14
+ index's hashed sample_key).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import gzip
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ from collections import Counter
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ M7 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data")
30
+ E2_OBS = M7 / "e2_full_source/metadata/obs_sc.parquet"
31
+ BLOCK_OBS = Path("/home/sj_server_1/PBISC/PBISC-data/single-cell-data-block-blood/metadata/obs_sc.parquet")
32
+ SAMPLE_INDEX = M7 / "e2_full_index/metadata/sample_index.parquet"
33
+ SOURCE_MANIFEST = M7 / "e2_full_source/dataset_manifest.json"
34
+ MS = Path(__file__).resolve().parents[2]
35
+ OUT = MS / "source_data" / "corpus"
36
+ GEO = OUT / "geo"
37
+ KEY = ["dataset_id", "donor_id", "sample_id"]
38
+ BLOCK_COLS = ["source_row_index", "donor_id", "disease", "condition", "assay", "source_file", "celltype_l1",
39
+ "celltype_l2"]
40
+
41
+ # condition (diagnosis) categories, in plotting order, with their disease family
42
+ CONDITIONS = [("Healthy", "Healthy"), ("SLE", "Autoimmune"), ("RA", "Autoimmune"),
43
+ ("ACPA+ at risk of RA", "Autoimmune"), ("JDM", "Autoimmune"), ("COVID-19", "Infection"),
44
+ ("Post-COVID-19", "Infection"), ("Influenza", "Infection"), ("MDS", "Haematological"),
45
+ ("MDS/MPN", "Haematological"), ("Cytopenia", "Haematological"), ("DRESS", "Drug reaction")]
46
+ DISEASE_MAP = {"normal": "Healthy", "healthy": "Healthy", "healthy_control": "Healthy",
47
+ "healthy_donor_SLE_mechanism": "Healthy", "cytomegalovirus infection": "Healthy",
48
+ "systemic lupus erythematosus": "SLE", "SLE": "SLE", "rheumatoid arthritis": "RA",
49
+ "juvenile dermatomyositis": "JDM", "COVID-19": "COVID-19", "post-COVID-19 disorder": "Post-COVID-19",
50
+ "influenza": "Influenza", "myelodysplastic syndrome": "MDS",
51
+ "myelodysplastic/myeloproliferative disease": "MDS/MPN", "hematologic disorder": "Cytopenia",
52
+ "DRESS": "DRESS"}
53
+ GSE274680_GROUP = {"CON1": "Healthy", "CON2": "Healthy", "ARI": "ACPA+ at risk of RA",
54
+ "LONG": "ACPA+ at risk of RA", "ERA": "RA"}
55
+ ASSAY_MAP = {"EFO:0009922": "10x 3' v3", "EFO:0009899": "10x 3' v2", "10x 3' v2": "10x 3' v2",
56
+ "EFO:0009900": "10x 5' v2", "EFO:0011025": "10x 5' v1", "EFO:0022606": "10x Flex",
57
+ "EFO:0022490": "ScaleBio", "EFO:0008919": "Seq-Well"}
58
+ # source obs without an assay field; protocols from the GEO series matrices in geo/ or the vendor page
59
+ ASSAY_BY_PREFIX = {"061_A": "10x 3' (hashed)", "301_A": "10x 3' v2", "300b_A": "10x v2 (3'/5')",
60
+ "302_A": "10x (version n.r.)", "304_A": "Parse"}
61
+ IN_VITRO = {"304_A": "all", "302_A": "all", "300b_A": {"bacterial_stim", "tofacitinib", "control"}}
62
+
63
+
64
+ def prefix(dataset_id: str) -> str:
65
+ return dataset_id.split("_")[0] + "_" + dataset_id.split("_")[1]
66
+
67
+
68
+ def geo_samples(acc: str) -> pd.DataFrame:
69
+ """Sample table of a GEO series matrix: accession, title, characteristics and descriptions."""
70
+ rows = {}
71
+ with gzip.open(GEO / f"{acc}_series_matrix.txt.gz", "rt") as f:
72
+ for line in f:
73
+ if not line.startswith("!Sample_"):
74
+ continue
75
+ k, *vals = line.rstrip("\n").split("\t")
76
+ vals = [v.strip('"') for v in vals]
77
+ rows.setdefault(k, []).append(vals)
78
+ df = pd.DataFrame({"gsm": rows["!Sample_geo_accession"][0], "title": rows["!Sample_title"][0]})
79
+ for vals in rows.get("!Sample_characteristics_ch1", []):
80
+ for i, v in enumerate(vals):
81
+ if ": " in v:
82
+ k, x = v.split(": ", 1)
83
+ df.loc[i, k.strip()] = x.strip()
84
+ for j, vals in enumerate(rows.get("!Sample_description", [])):
85
+ df[f"description_{j}"] = vals
86
+ return df
87
+
88
+
89
+ def main() -> int:
90
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
91
+ si = pd.read_parquet(SAMPLE_INDEX)
92
+ si["key"] = list(zip(si.dataset_id, si.donor_id.astype(str), si.sample_id.astype(str)))
93
+ if si.key.duplicated().any():
94
+ raise SystemExit("sample_index keys are not unique")
95
+ shards = sorted(os.listdir(E2_OBS))
96
+ base_files = set(os.listdir(BLOCK_OBS))
97
+ cells, labels, ctypes = Counter(), {}, Counter()
98
+ n_base = n_overlay = 0
99
+ donor_mismatch = 0
100
+ for f in shards:
101
+ e = pd.read_parquet(E2_OBS / f, columns=KEY + ["source_row_index"])
102
+ e["donor_id"], e["sample_id"] = e.donor_id.astype(str), e.sample_id.astype(str)
103
+ g = e.groupby(KEY, observed=True).size()
104
+ for k, n in g.items():
105
+ cells[k] += int(n)
106
+ if f.endswith("__strict_overlay.parquet"):
107
+ n_overlay += len(e)
108
+ for k, n in g.items():
109
+ ctypes[(k, "No label (overlay)", "No label (overlay)")] += int(n)
110
+ continue
111
+ if f not in base_files:
112
+ raise SystemExit(f"{f}: no block obs part")
113
+ b = pd.read_parquet(BLOCK_OBS / f, columns=BLOCK_COLS)
114
+ if len(b) != len(e) or not np.array_equal(b.source_row_index.to_numpy(), e.source_row_index.to_numpy()):
115
+ raise SystemExit(f"{f}: corpus and block rows differ")
116
+ donor_mismatch += int((b.donor_id.astype(str).to_numpy() != e.donor_id.to_numpy()).sum())
117
+ n_base += len(e)
118
+ j = pd.concat([e[KEY].reset_index(drop=True), b[["disease", "condition", "assay", "source_file",
119
+ "celltype_l1", "celltype_l2"]].astype(str)], axis=1)
120
+ for (d, dn, s, *r), n in j.groupby(KEY + ["disease", "condition", "assay", "source_file"],
121
+ observed=True).size().items():
122
+ labels.setdefault((d, dn, s), Counter())[tuple(r)] += int(n)
123
+ for (d, dn, s, l1, l2), n in j.groupby(KEY + ["celltype_l1", "celltype_l2"], observed=True).size().items():
124
+ ctypes[((d, dn, s), l1, l2)] += int(n)
125
+ total = sum(cells.values())
126
+ missing = set(cells) - set(si.key)
127
+ if missing:
128
+ raise SystemExit(f"{len(missing)} corpus sample keys are not in sample_index, e.g. {sorted(missing)[:3]}")
129
+ src = json.loads(SOURCE_MANIFEST.read_text())
130
+ if total != src["logical_cells"] or n_base != src["base_cells"] or n_overlay != src["overlay_cells"]:
131
+ raise SystemExit(f"cell totals differ from the source manifest: {total} {n_base} {n_overlay}")
132
+
133
+ # ---- per-sample labels (majority over the sample's base cells; purity recorded)
134
+ g274 = geo_samples("GSE274680")
135
+ g274["group"] = g274.title.str.rsplit("_", n=1).str[-1]
136
+ if not set(g274.group) <= set(GSE274680_GROUP):
137
+ raise SystemExit(f"unexpected GSE274680 groups: {set(g274.group)}")
138
+ gsm_group = dict(zip(g274.gsm, g274.group))
139
+ # the person is under "subject id" for some samples and "subject" for others (CON2 and part of ARI)
140
+ subj = g274["subject id"].fillna(g274["subject"]) if "subject" in g274 else g274["subject id"]
141
+ if subj.isna().any():
142
+ raise SystemExit("GSE274680 samples without a subject id")
143
+ gsm_subject = dict(zip(g274.gsm, subj))
144
+ g132 = geo_samples("GSE132802")
145
+ dress_dx = dict(zip(g132.description_0.str.strip(), g132["disease diagnosis"]))
146
+ def classify(r, p, dis, cond, assay, sfile):
147
+ """condition, source label, assay label, handling, CMV flag and donor of one label combination"""
148
+ donor = r.donor_id
149
+ if p == "061_A":
150
+ gsm = re.search(r"(GSM\d+)_", sfile).group(1)
151
+ dx, group, donor = GSE274680_GROUP[gsm_group[gsm]], gsm_group[gsm], gsm_subject[gsm]
152
+ elif p == "300b_A":
153
+ group = dress_dx[r.donor_id]
154
+ dx = "Healthy" if group == "Healthy" else "DRESS"
155
+ donor = "healthy volunteer" if dx == "Healthy" else "DRESS patient" # GEO: one patient, one volunteer
156
+ elif p == "304_A":
157
+ dx, group = "Healthy", "vendor: healthy donors"
158
+ else:
159
+ if dis not in DISEASE_MAP:
160
+ raise SystemExit(f"{r.dataset_id}: unmapped disease {dis!r}")
161
+ dx, group = DISEASE_MAP[dis], dis
162
+ a = ASSAY_BY_PREFIX.get(p) or ASSAY_MAP.get(assay)
163
+ if a is None:
164
+ raise SystemExit(f"{r.dataset_id}: unmapped assay {assay!r}")
165
+ iv = IN_VITRO.get(p)
166
+ in_vitro = iv == "all" or (isinstance(iv, set) and cond in iv)
167
+ return dx, group, a, "in vitro" if in_vitro else "ex vivo", dis == "cytomegalovirus infection", donor
168
+
169
+ rows, groups = [], []
170
+ for _, r in si.iterrows():
171
+ k, p = r.key, prefix(r.dataset_id)
172
+ n = cells.get(k, 0)
173
+ lab = labels.get(k, Counter())
174
+ if not lab:
175
+ raise SystemExit(f"{r.dataset_id}: a sample with overlay cells only")
176
+ combos = [(classify(r, p, *c), m) for c, m in lab.items()]
177
+ combos[max(range(len(combos)), key=lambda i: combos[i][1])] = (
178
+ combos[max(range(len(combos)), key=lambda i: combos[i][1])][0],
179
+ combos[max(range(len(combos)), key=lambda i: combos[i][1])][1] + n - sum(lab.values())) # overlay cells
180
+ agg = Counter()
181
+ for (dx, group, a, h, cmv, donor), m in combos:
182
+ agg[(dx, group, a, h, cmv, donor)] += m
183
+ for (dx, group, a, h, cmv, donor), m in agg.items():
184
+ groups.append({"sample_key": r.sample_key, "dataset_prefix": p, "platform": r.platform, "assay": a,
185
+ "split": r.split, "condition": dx, "source_disease": group, "handling": h,
186
+ "cmv_seropositive_healthy": cmv, "n_cells": m, "_donor": (r.dataset_id, donor)})
187
+ (dx, group, a, h, cmv, donor), m = agg.most_common(1)[0]
188
+ rows.append({"sample_key": r.sample_key, "dataset_prefix": p, "dataset_id": r.dataset_id,
189
+ "platform": r.platform, "assay": a, "split": r.split, "n_cells": n,
190
+ "n_cells_index": int(r.n_cells), "condition": dx, "source_disease": group, "handling": h,
191
+ "majority_share": m / n, "_donor": (r.dataset_id, donor)})
192
+ S, G = pd.DataFrame(rows), pd.DataFrame(groups)
193
+ if (S.n_cells != S.n_cells_index).any():
194
+ bad = S[S.n_cells != S.n_cells_index]
195
+ raise SystemExit(f"{len(bad)} samples: corpus cell counts differ from sample_index")
196
+ if S.n_cells.sum() != total or G.n_cells.sum() != total:
197
+ raise SystemExit("sample_index does not cover every corpus cell")
198
+ print("samples with more than one condition/handling/assay/donor group:", int((S.majority_share < 1).sum()))
199
+ OUT.mkdir(parents=True, exist_ok=True)
200
+ G.drop(columns=["_donor"]).to_csv(OUT / "corpus_cellgroups.csv", index=False)
201
+
202
+ # ---- donors (GSE274680: GEO subject; others: corpus donor id) and split leakage check
203
+ donors = G.groupby("dataset_prefix")._donor.nunique()
204
+ leak = G.groupby("_donor").split.nunique()
205
+ leak_donors = leak[leak > 1]
206
+ leak_cells = int(G[G._donor.isin(leak_donors.index)].n_cells.sum())
207
+ in_train = set(G[G.split == "train"]._donor)
208
+ held = G[(G.split != "train") & G._donor.isin(in_train)]
209
+ held_cells = {k: int(v) for k, v in held.groupby("split").n_cells.sum().items()}
210
+ held_samples = int(held.sample_key.nunique())
211
+ S.drop(columns=["_donor", "n_cells_index"]).to_csv(OUT / "corpus_samples.csv", index=False)
212
+
213
+ # ---- per dataset
214
+ info = pd.read_csv(OUT / "dataset_info.csv").set_index("dataset_prefix")
215
+ D = []
216
+ for p, t in S.groupby("dataset_prefix"):
217
+ sp = t.groupby("split").n_cells.sum()
218
+ tg = G[G.dataset_prefix == p]
219
+ cd = tg.groupby("condition").n_cells.sum()
220
+ D.append({"dataset_prefix": p, "short_name": info.loc[p, "short_name"], "accession": info.loc[p, "accession"],
221
+ "enrichment": info.loc[p, "enrichment"], "dataset_id": t.dataset_id.iloc[0],
222
+ "platform": "/".join(sorted(t.platform.unique())), "assay": "/".join(sorted(t.assay.unique())),
223
+ "n_cells": int(t.n_cells.sum()), "n_samples": len(t), "n_donors": int(donors[p]),
224
+ "train_cells": int(sp.get("train", 0)), "val_cells": int(sp.get("val", 0)),
225
+ "test_cells": int(sp.get("test", 0)),
226
+ "in_vitro_cells": int(tg[tg.handling == "in vitro"].n_cells.sum()),
227
+ "conditions": "; ".join(f"{c} {int(n)}" for c, n in cd.sort_values(ascending=False).items())})
228
+ D = pd.DataFrame(D).sort_values("n_cells", ascending=False)
229
+ if len(D) != src["n_datasets"] or set(D.dataset_prefix) != set(info.index):
230
+ raise SystemExit("dataset_info.csv does not match the corpus datasets")
231
+ D.to_csv(OUT / "corpus_datasets.csv", index=False)
232
+
233
+ # ---- cell types (per dataset, L1/L2)
234
+ pre = {k: prefix(k[0]) for k in cells}
235
+ C = pd.DataFrame([{"dataset_prefix": pre[k], "celltype_l1": l1, "celltype_l2": l2, "n_cells": n}
236
+ for (k, l1, l2), n in ctypes.items()])
237
+ C = C.groupby(["dataset_prefix", "celltype_l1", "celltype_l2"], as_index=False).n_cells.sum()
238
+ if C.n_cells.sum() != total:
239
+ raise SystemExit("cell-type table does not cover every cell")
240
+ C.to_csv(OUT / "corpus_celltypes.csv", index=False)
241
+
242
+ # ---- assay x condition
243
+ A = G.groupby(["assay", "condition"], as_index=False).n_cells.sum()
244
+ A.to_csv(OUT / "corpus_assay_condition.csv", index=False)
245
+
246
+ fam = dict(CONDITIONS)
247
+ summ = {"cells": total, "base_cells": n_base, "overlay_cells": n_overlay, "datasets": int(len(D)),
248
+ "samples": int(len(S)), "donors": int(donors.sum()),
249
+ "split_cells": {k: int(v) for k, v in S.groupby("split").n_cells.sum().items()},
250
+ "split_samples": {k: int(v) for k, v in S.split.value_counts().items()},
251
+ "condition_cells": {k: int(v) for k, v in G.groupby("condition").n_cells.sum().items()},
252
+ "family_cells": {k: int(v) for k, v in G.assign(f=G.condition.map(fam)).groupby("f").n_cells.sum().items()},
253
+ "handling_cells": {k: int(v) for k, v in G.groupby("handling").n_cells.sum().items()},
254
+ "cmv_seropositive_healthy_cells": int(G[G.cmv_seropositive_healthy].n_cells.sum()),
255
+ "assay_cells": {k: int(v) for k, v in G.groupby("assay").n_cells.sum().items()},
256
+ "platform_cells": {k: int(v) for k, v in G.groupby("platform").n_cells.sum().items()},
257
+ "celltype_l1_cells": {k: int(v) for k, v in C.groupby("celltype_l1").n_cells.sum().items()},
258
+ "corpus_vs_block_donor_id_mismatch_rows": donor_mismatch,
259
+ "samples_in_more_than_one_split": int((S.groupby("sample_key").split.nunique() > 1).sum()),
260
+ "donors_in_more_than_one_split": int(len(leak_donors)), "cells_of_those_donors": leak_cells,
261
+ "val_test_cells_whose_donor_has_train_samples": held_cells,
262
+ "val_test_samples_whose_donor_has_train_samples": held_samples,
263
+ "donors_in_more_than_one_split_by_dataset": {k: int(v) for k, v in
264
+ Counter(d[0][:6] for d in leak_donors.index).items()},
265
+ "conditions_order": [c for c, _ in CONDITIONS], "condition_family": fam,
266
+ "inputs": {"corpus_obs": str(E2_OBS), "block_obs": str(BLOCK_OBS), "sample_index": str(SAMPLE_INDEX),
267
+ "source_manifest": str(SOURCE_MANIFEST), "geo": sorted(p.name for p in GEO.glob("*.gz"))},
268
+ "script": str(Path(__file__).resolve())}
269
+ (OUT / "corpus_summary.json").write_text(json.dumps(summ, indent=1) + "\n")
270
+ print(json.dumps({k: v for k, v in summ.items() if k not in ("inputs", "condition_family")}, indent=1))
271
+ print(D[["short_name", "assay", "n_cells", "n_samples", "n_donors", "train_cells", "in_vitro_cells"]].to_string(index=False))
272
+ return 0
273
+
274
+
275
+ if __name__ == "__main__":
276
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/scripts/corpus/build_figure1_corpus.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pretraining-corpus figures (2026-10-06; style after Nicheformer Fig. 2).
3
+
4
+ Reads only source_data/corpus/ (written by scripts/corpus/build_corpus_tables.py); every number is computed here
5
+ from those tables.
6
+ figures/fig01_corpus.* Fig. 1 strip (panel c after the architecture a-b): assay shares, disease-family shares per
7
+ assay and L1 cell-type shares; authored at 180 mm like fig01_architecture
8
+ figures/figS_corpus.* Supplementary, panels a-d: overview (split, sample handling, assay, 12 conditions), the 22
9
+ datasets, L1/L2 cell types, and the per-cell record
10
+ Each output has a .provenance.json with input and output hashes.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import hashlib
16
+ import json
17
+ import string
18
+ from pathlib import Path
19
+
20
+ import matplotlib
21
+
22
+ matplotlib.use("Agg")
23
+ import matplotlib.pyplot as plt # noqa: E402
24
+ import numpy as np # noqa: E402
25
+ import pandas as pd # noqa: E402
26
+ from matplotlib.patches import FancyBboxPatch, Rectangle # noqa: E402
27
+
28
+ MS = Path(__file__).resolve().parents[2]
29
+ SRC = MS / "source_data" / "corpus"
30
+ FIG = MS / "figures"
31
+ MM = 1 / 25.4
32
+ INK, SUB, LIGHT = "#222222", "#5A5A5A", "#D3D3CB"
33
+ plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 6.5, "axes.linewidth": 0.6,
34
+ "xtick.major.width": 0.6, "ytick.major.width": 0.6, "xtick.major.size": 2,
35
+ "ytick.major.size": 2, "pdf.fonttype": 42, "ps.fonttype": 42, "svg.fonttype": "none"})
36
+
37
+ COND_COLOR = {"Healthy": "#A9B8CC", "SLE": "#7A4F6E", "RA": "#B5655E", "ACPA+ at risk of RA": "#DDA59B",
38
+ "JDM": "#A58BB0", "COVID-19": "#D08C3C", "Post-COVID-19": "#E8C68E", "Influenza": "#9C6B2A",
39
+ "MDS": "#3F7A73", "MDS/MPN": "#6FA39B", "Cytopenia": "#A9D0C8", "DRESS": "#5F5F5F"}
40
+ L1_ORDER = ["T cell", "NK cell", "B cell", "Monocyte", "DC", "Progenitor cell", "Platelet", "Erythrocyte", "ILC",
41
+ "Other", "Unlabelled"]
42
+ L1_COLOR = {"T cell": "#4C6E91", "NK cell": "#8FB0CF", "B cell": "#C98A4B", "Monocyte": "#5E8C6A",
43
+ "DC": "#A8C79C", "Progenitor cell": "#8E6C9E", "Platelet": "#D3B5D3", "Erythrocyte": "#B5655E",
44
+ "ILC": "#7FB3B0", "Other": "#9A9A9A", "Unlabelled": "#E2E2E2"}
45
+ L1_MERGE = {"NKT cell": "Other", "Granulocyte": "Other", "Neutrophil": "Other", "Mast cell": "Other",
46
+ "__unknown__": "Unlabelled", "No label (overlay)": "Unlabelled"}
47
+ SPLIT_COLOR = {"train": "#5B6E8F", "val": "#9AACC4", "test": "#C9D2DF"}
48
+ HAND_COLOR = {"ex vivo": "#5B6E8F", "in vitro": "#C9D2DF"}
49
+
50
+
51
+ def fmt_cells(n: float) -> str:
52
+ return f"{n / 1e6:.1f} M" if n >= 1e6 else f"{n / 1e3:.0f} k"
53
+
54
+
55
+ def pct(x: float) -> str:
56
+ return f"{100 * x:.1f}%" if x >= 0.001 else "<0.1%"
57
+
58
+
59
+ def letter(fig, x, y, s):
60
+ fig.text(x, y, s, fontsize=9, fontweight="bold", va="top", ha="left")
61
+
62
+
63
+ def pie(fig, rect, vals: dict, colors: dict, title: str):
64
+ """small pie with its key to the right (shares of cells)"""
65
+ ax = fig.add_axes(rect)
66
+ keys = [k for k in colors if k in vals]
67
+ tot = sum(vals.values())
68
+ ax.pie([vals[k] for k in keys], colors=[colors[k] for k in keys], startangle=90, counterclock=False,
69
+ wedgeprops={"linewidth": 0.8, "edgecolor": "white"})
70
+ ax.set_aspect("equal")
71
+ x, y = rect[0] + rect[2] + 0.004, rect[1] + rect[3] * 0.62
72
+ fig.text(rect[0], rect[1] + rect[3] + 0.006, title, ha="left", va="bottom", fontsize=6.3)
73
+ for j, k in enumerate(keys):
74
+ fig.patches.append(Rectangle((x, y - j * 0.022 - 0.005), 0.008, 0.010, transform=fig.transFigure,
75
+ color=colors[k]))
76
+ fig.text(x + 0.012, y - j * 0.022, f"{k} {pct(vals[k] / tot)}", fontsize=5.6, va="center")
77
+
78
+
79
+ def strip(ax):
80
+ ax.set_yticks([])
81
+ ax.set_xticks([])
82
+ for sp in ax.spines.values():
83
+ sp.set_visible(False)
84
+
85
+
86
+ L2_SHORT = {"Intermediate monocyte": "Int. monocyte", "Proliferating T cell": "Prolif. T cell",
87
+ "Proliferating NK cell": "Prolif. NK cell", "Transitional B cell": "Transitional B",
88
+ "Memory CD4 T cell": "Memory CD4 T", "Naive CD4 T cell": "Naive CD4 T", "Memory CD8 T cell": "Memory CD8 T",
89
+ "Naive CD8 T cell": "Naive CD8 T", "Naive B cell": "Naive B", "Memory B cell": "Memory B",
90
+ "Effector B cell": "Effector B", "CD56dim NK cell": "CD56dim NK", "CD56bright NK cell": "CD56bright NK",
91
+ "CD14 monocyte": "CD14 mono", "CD16 monocyte": "CD16 mono", "DN T cell": "DN T"}
92
+ NAME_SUFFIX = {"B-cell enriched": " (sorted B cells)"} # the HSPC dataset's name already says HSPC
93
+
94
+
95
+ def load():
96
+ """corpus tables with consistency checks"""
97
+ summ = json.loads((SRC / "corpus_summary.json").read_text())
98
+ D = pd.read_csv(SRC / "corpus_datasets.csv")
99
+ G = pd.read_csv(SRC / "corpus_cellgroups.csv")
100
+ C = pd.read_csv(SRC / "corpus_celltypes.csv")
101
+ conds = summ["conditions_order"]
102
+ if set(G.condition) - set(conds) or set(conds) != set(COND_COLOR):
103
+ raise SystemExit("condition categories differ from the colour map")
104
+ C["l1"] = C.celltype_l1.map(lambda x: L1_MERGE.get(x, x))
105
+ if set(C.l1) - set(L1_ORDER):
106
+ raise SystemExit(f"unexpected L1 labels: {set(C.l1) - set(L1_ORDER)}")
107
+ total = summ["cells"]
108
+ if G.n_cells.sum() != total or C.n_cells.sum() != total or D.n_cells.sum() != total:
109
+ raise SystemExit("tables do not add up to the corpus total")
110
+ return summ, D, G, C, conds, total
111
+
112
+
113
+ def draw_full(L):
114
+ """detailed version (Supplementary): overview, datasets, cell types, per-cell record"""
115
+ summ, D, G, C, conds, total = load()
116
+ W, H = 180, 200
117
+ fig = plt.figure(figsize=(W * MM, H * MM))
118
+
119
+ # ------------------------------------------------------------------ c: overview
120
+ y0 = 0.99
121
+ letter(fig, 0.0, y0, L[0])
122
+ fig.text(0.03, y0 - 0.002, f"Pretraining corpus – {total / 1e6:.1f} million cells from {summ['datasets']} "
123
+ f"datasets, {summ['donors']:,} donors and {summ['samples']:,} samples", fontsize=7, va="top")
124
+ pie(fig, [0.005, 0.835, 0.085, 0.085], summ["split_cells"], SPLIT_COLOR, "Split")
125
+ pie(fig, [0.005, 0.69, 0.085, 0.085], summ["handling_cells"], HAND_COLOR, "Sample handling")
126
+ A = G.groupby(["assay", "condition"]).n_cells.sum().unstack(fill_value=0)
127
+ small = A.sum(1) < 0.002 * total
128
+ other_lab = None
129
+ if small.any():
130
+ other_lab = "Other"
131
+ other_list = ", ".join(A.index[small])
132
+ A.loc[other_lab] = A[small].sum()
133
+ A = A[~small.reindex(A.index, fill_value=False)]
134
+ A = A.loc[A.drop(index=[other_lab] if other_lab else []).sum(1).sort_values(ascending=False).index.tolist()
135
+ + ([other_lab] if other_lab else [])]
136
+ share = A.sum(1) / total
137
+ n = len(A)
138
+ top, bot = 0.915, 0.69
139
+ ax_a = fig.add_axes([0.29, bot, 0.075, top - bot])
140
+ ax_a.barh(np.arange(n), share.values, 0.62, color=LIGHT)
141
+ ax_a.set_ylim(n - 0.5, -0.5)
142
+ ax_a.set_xlim(0, 1.0)
143
+ strip(ax_a)
144
+ fig.text(0.29, top + 0.012, "Assay", fontsize=6.3, va="bottom")
145
+ for i, (lab, sh) in enumerate(share.items()):
146
+ ax_a.text(-0.04, i, lab, ha="right", va="center", fontsize=5.8, transform=ax_a.get_yaxis_transform())
147
+ ax_a.text(sh + 0.03, i, pct(sh), va="center", fontsize=5.6, color=SUB)
148
+ ax_c = fig.add_axes([0.405, bot, 0.59, top - bot])
149
+ ax_c.set_xlim(0, 1)
150
+ ax_c.set_ylim(n - 0.5, -0.5)
151
+ for i, (lab, row) in enumerate(A.iterrows()):
152
+ left, tot = 0.0, row.sum()
153
+ for c in conds:
154
+ w = row.get(c, 0) / tot
155
+ if w <= 0:
156
+ continue
157
+ ax_c.barh(i, w, 0.62, left=left, color=COND_COLOR[c], edgecolor="white", linewidth=0.4)
158
+ if w > 0.12:
159
+ dark = c not in ("Healthy", "ACPA+ at risk of RA", "Post-COVID-19", "Cytopenia", "JDM")
160
+ ax_c.text(left + w / 2, i, c, ha="center", va="center", fontsize=5.5,
161
+ color="white" if dark else INK)
162
+ left += w
163
+ strip(ax_c)
164
+ fig.text(0.405, top + 0.012, "Condition proportions", fontsize=6.3, va="bottom")
165
+ fig.text(0.405, top + 0.003, "0%", fontsize=5.4, color=SUB, va="bottom")
166
+ fig.text(0.995, top + 0.003, "100%", fontsize=5.4, color=SUB, va="bottom", ha="right")
167
+ fam = summ["condition_family"]
168
+ families = list(dict.fromkeys(fam[c] for c in conds))
169
+ width = {f: max([len(c) + 2 for c in conds if fam[c] == f] + [len(f) if f != "Healthy" else 0])
170
+ for f in families}
171
+ xs = 0.405 + np.cumsum([0] + [0.018 + 0.0068 * width[f] for f in families[:-1]])
172
+ for x, f in zip(xs, families):
173
+ if f != "Healthy":
174
+ fig.text(x, 0.672, f, fontsize=5.6, color=SUB, va="top")
175
+ for j, c in enumerate([c for c in conds if fam[c] == f]):
176
+ yy = 0.655 - j * 0.0125
177
+ fig.patches.append(Rectangle((x, yy - 0.004), 0.007, 0.008, transform=fig.transFigure, color=COND_COLOR[c]))
178
+ fig.text(x + 0.011, yy, c, fontsize=5.6, va="center")
179
+ if other_lab:
180
+ fig.text(0.29, 0.672, "Other:\n" + other_list.replace(", ", "\n"), fontsize=5.0, color=SUB, va="top",
181
+ linespacing=1.15)
182
+
183
+ # ------------------------------------------------------------------ d: datasets
184
+ yd = 0.6
185
+ letter(fig, 0.0, yd, L[1])
186
+ fig.text(0.03, yd - 0.002, "Datasets", fontsize=7, va="top")
187
+ D = D.sort_values("n_cells", ascending=False).reset_index(drop=True)
188
+ nd = len(D)
189
+ dtop, dbot = 0.565, 0.345
190
+ drh = (dtop - dbot) / nd
191
+ hdr = dtop + 0.006
192
+ x_assay, x_bar0, x_bar1 = 0.262, 0.27, 0.43
193
+ ax_n = fig.add_axes([x_bar0, dbot, x_bar1 - x_bar0, dtop - dbot])
194
+ ax_n.barh(np.arange(nd), D.n_cells, 0.62, color="#B8B8AE")
195
+ ax_n.set_xscale("log")
196
+ ax_n.set_xlim(1e4, 1e8)
197
+ ax_n.set_ylim(nd - 0.5, -0.5)
198
+ ax_n.set_yticks([])
199
+ ax_n.set_xticks([1e4, 1e5, 1e6, 1e7], ["10k", "100k", "1M", "10M"])
200
+ ax_n.minorticks_off()
201
+ ax_n.tick_params(axis="x", labelsize=5.3, pad=1)
202
+ for sp in ("top", "right", "left"):
203
+ ax_n.spines[sp].set_visible(False)
204
+ fig.text(x_bar0, hdr, "Cells", fontsize=6.3, va="bottom")
205
+ fig.text(x_assay, hdr, "Assay", fontsize=6.3, va="bottom", ha="right")
206
+ fig.text(0.005, hdr, "Dataset", fontsize=6.3, va="bottom")
207
+ x_don, x_smp = 0.512, 0.567
208
+ fig.text(x_don, hdr, "Donors", fontsize=6.3, va="bottom", ha="right")
209
+ fig.text(x_smp, hdr, "Samples", fontsize=6.3, va="bottom", ha="right")
210
+ for i, r in D.iterrows():
211
+ y = dtop - (i + 0.5) * drh
212
+ fig.text(0.005, y, r.short_name + NAME_SUFFIX.get(r.enrichment, ""), fontsize=5.6, va="center")
213
+ fig.text(x_assay, y, r.assay, fontsize=5.0, va="center", ha="right", color=SUB)
214
+ ax_n.text(r.n_cells * 1.15, i, fmt_cells(r.n_cells), va="center", fontsize=5.0, color=SUB)
215
+ fig.text(x_don, y, f"{r.n_donors:,}", fontsize=5.6, va="center", ha="right")
216
+ fig.text(x_smp, y, f"{r.n_samples:,}", fontsize=5.6, va="center", ha="right")
217
+ cg = G.groupby(["dataset_prefix", "condition"]).n_cells.sum().unstack(fill_value=0)
218
+ ct = C.groupby(["dataset_prefix", "l1"]).n_cells.sum().unstack(fill_value=0)
219
+ for x0, w0, tab, order, cmap, title in ((0.585, 0.195, cg, conds, COND_COLOR, "Condition"),
220
+ (0.80, 0.195, ct, L1_ORDER, L1_COLOR, "Cell type (L1)")):
221
+ ax = fig.add_axes([x0, dbot, w0, dtop - dbot])
222
+ for i, r in D.iterrows():
223
+ row = tab.loc[r.dataset_prefix]
224
+ left, tot = 0.0, row.sum()
225
+ for k in order:
226
+ v = row.get(k, 0) / tot
227
+ if v > 0:
228
+ ax.barh(i, v, 0.62, left=left, color=cmap[k], edgecolor="none")
229
+ left += v
230
+ ax.set_xlim(0, 1)
231
+ ax.set_ylim(nd - 0.5, -0.5)
232
+ strip(ax)
233
+ fig.text(x0, hdr, title, fontsize=6.3, va="bottom")
234
+
235
+ # ------------------------------------------------------------------ e: cell types
236
+ ye = 0.29
237
+ letter(fig, 0.0, ye, L[2])
238
+ fig.text(0.03, ye - 0.002, "Cell types (source labels mapped to a shared two-level hierarchy)", fontsize=7, va="top")
239
+ l1 = C.groupby("l1").n_cells.sum().reindex(L1_ORDER).fillna(0)
240
+ ax_d = fig.add_axes([0.0, 0.085, 0.165, 0.165])
241
+ w, _ = ax_d.pie(l1.values, colors=[L1_COLOR[k] for k in l1.index], startangle=90, counterclock=False,
242
+ wedgeprops={"width": 0.36, "linewidth": 0.6, "edgecolor": "white"})
243
+ ax_d.set_aspect("equal")
244
+ ax_d.text(0, 0, f"{total / 1e6:.1f} M\ncells", ha="center", va="center", fontsize=6.2)
245
+ for j, k in enumerate(L1_ORDER):
246
+ y = 0.245 - j * 0.0148
247
+ fig.patches.append(Rectangle((0.172, y - 0.004), 0.007, 0.008, transform=fig.transFigure, color=L1_COLOR[k]))
248
+ fig.text(0.183, y, k, fontsize=5.5, va="center")
249
+ fig.text(0.29, y, pct(l1[k] / total), fontsize=5.5, va="center", ha="right", color=SUB)
250
+ l2 = C[~C.l1.isin(["Other", "Unlabelled"]) & (C.celltype_l2 != "__unspecified__")]
251
+ l2 = l2[l2.celltype_l2 != l2.celltype_l1].groupby(["l1", "celltype_l2"]).n_cells.sum().reset_index()
252
+ l2["o"] = l2.l1.map({k: i for i, k in enumerate(L1_ORDER)})
253
+ l2 = l2.sort_values(["o", "n_cells"], ascending=[True, False]).reset_index(drop=True)
254
+ two = C[C.l1.isin(l2.l1.unique())]
255
+ resolved = l2.n_cells.sum() / two.n_cells.sum()
256
+ ax2 = fig.add_axes([0.355, 0.095, 0.425, 0.15])
257
+ ax2.bar(np.arange(len(l2)), l2.n_cells, 0.72, color=[L1_COLOR[k] for k in l2.l1], edgecolor="none")
258
+ ax2.set_yscale("log")
259
+ ax2.set_ylim(1e3, 2e7)
260
+ ax2.set_yticks([1e3, 1e4, 1e5, 1e6, 1e7], ["1k", "10k", "100k", "1M", "10M"])
261
+ ax2.minorticks_off()
262
+ ax2.set_xticks(np.arange(len(l2)), [L2_SHORT.get(x, x) for x in l2.celltype_l2], rotation=60, ha="right",
263
+ rotation_mode="anchor", fontsize=5.0)
264
+ ax2.tick_params(axis="x", length=0, pad=1.5)
265
+ ax2.tick_params(axis="y", labelsize=5.3, pad=1)
266
+ ax2.set_xlim(-0.6, len(l2) - 0.4)
267
+ for sp in ("top", "right"):
268
+ ax2.spines[sp].set_visible(False)
269
+ ax2.set_ylabel("Cells", fontsize=5.8, labelpad=1)
270
+ fig.text(0.355, 0.262, f"{len(l2)} L2 subtypes, {fmt_cells(l2.n_cells.min())} to {fmt_cells(l2.n_cells.max())} "
271
+ f"cells each (L2 resolved for {pct(resolved)} of their L1 cells)", fontsize=5.8, va="bottom")
272
+
273
+ # ------------------------------------------------------------------ f: per-cell record
274
+ xf = 0.81
275
+ letter(fig, xf - 0.025, ye, L[3])
276
+ fig.text(xf + 0.005, ye - 0.002, "Per-cell record", fontsize=7, va="top")
277
+ G_GENES = 20097
278
+
279
+ def gbox(x, y, w, h, txt, fs=5.6):
280
+ fig.patches.append(Rectangle((x, y), w, h, transform=fig.transFigure, color="#D9D9D1"))
281
+ fig.text(x + w / 2, y + h / 2, txt, ha="center", va="center", fontsize=fs, linespacing=1.1)
282
+ gbox(xf, 0.228, 0.13, 0.024, f"var: {G_GENES:,} genes")
283
+ gbox(xf, 0.155, 0.13, 0.066, "Raw counts\n+ measured-gene\nmask", fs=5.6)
284
+ gbox(xf + 0.137, 0.155, 0.04, 0.066, "obs", fs=5.6)
285
+ fig.text(xf, 0.142, "Used for bulks and splits", fontsize=5.6, fontweight="bold", va="top")
286
+ fig.text(xf, 0.127, "sample (cells of one sample),\nplatform (recipe share),\ndataset + donor (split)",
287
+ fontsize=5.3, va="top", linespacing=1.15)
288
+ fig.text(xf, 0.083, "Never given to the model", fontsize=5.6, fontweight="bold", va="top")
289
+ fig.text(xf, 0.068, "condition, cell type (L1/L2)", fontsize=5.3, va="top")
290
+ fig.text(xf, 0.048, "Bulk = sum of K cells,\nK = 250–4,000", fontsize=5.3, va="top", color=SUB,
291
+ linespacing=1.15)
292
+
293
+ return fig, (W, H), {L[0]: "corpus overview", L[1]: "datasets", L[2]: "cell types", L[3]: "per-cell record"}
294
+
295
+
296
+ FAMILY_COLOR = {"Healthy": "#A9B8CC", "Autoimmune": "#7A4F6E", "Infection": "#D08C3C", "Haematological": "#3F7A73",
297
+ "Drug reaction": "#5F5F5F"}
298
+ ASSAY_GROUP = {"10x 3' v3": "10x 3'", "10x 3' v2": "10x 3'", "10x 3' (hashed)": "10x 3'", "10x 5' v1": "10x 5'",
299
+ "10x 5' v2": "10x 5'", "10x Flex": "10x Flex", "Parse": "Parse", "ScaleBio": "ScaleBio"}
300
+ L1_SHOW = ["T cell", "Monocyte", "B cell", "NK cell", "Progenitor cell", "DC"]
301
+
302
+
303
+ def draw_compact(L):
304
+ """Fig. 1 strip: assay shares, disease-family shares per assay, L1 cell-type shares"""
305
+ summ, D, G, C, conds, total = load()
306
+ fam = summ["condition_family"]
307
+ W, H = 180, 38
308
+ fig = plt.figure(figsize=(W * MM, H * MM))
309
+ fs, fsl = 7.2, 6.8
310
+ letter(fig, 0.0, 0.96, L[0])
311
+ fig.text(0.03, 0.96, f"Pretraining corpus: {total / 1e6:.1f} million cells from {summ['datasets']} datasets, "
312
+ f"{summ['donors']:,} donors and {summ['samples']:,} samples", fontsize=8.2, va="top")
313
+ G = G.assign(group=G.assay.map(lambda a: ASSAY_GROUP.get(a, "Other")), family=G.condition.map(fam))
314
+ A = G.groupby(["group", "family"]).n_cells.sum().unstack(fill_value=0)
315
+ order = A.drop(index=["Other"], errors="ignore").sum(1).sort_values(ascending=False).index.tolist()
316
+ A = A.loc[order + (["Other"] if "Other" in A.index else [])]
317
+ fams = [f for f in FAMILY_COLOR if f in A.columns]
318
+ share = A.sum(1) / total
319
+ n = len(A)
320
+ top, bot = 0.76, 0.32
321
+ ax_a = fig.add_axes([0.105, bot, 0.06, top - bot])
322
+ ax_a.barh(np.arange(n), share.values, 0.8, color=LIGHT)
323
+ ax_a.set_ylim(n - 0.5, -0.5)
324
+ ax_a.set_xlim(0, 1)
325
+ strip(ax_a)
326
+ fig.text(0.105, top + 0.035, "Assay", fontsize=fsl, va="bottom")
327
+ for i, (lab, sh) in enumerate(share.items()):
328
+ ax_a.text(-0.05, i, lab, ha="right", va="center", fontsize=fsl, transform=ax_a.get_yaxis_transform())
329
+ ax_a.text(sh + 0.04, i, pct(sh), va="center", fontsize=fsl - 0.6, color=SUB)
330
+ ax_c = fig.add_axes([0.215, bot, 0.40, top - bot])
331
+ ax_c.set_xlim(0, 1)
332
+ ax_c.set_ylim(n - 0.5, -0.5)
333
+ for i, (lab, row) in enumerate(A.iterrows()):
334
+ left, tot = 0.0, row.sum()
335
+ for f in fams:
336
+ w = row.get(f, 0) / tot
337
+ if w <= 0:
338
+ continue
339
+ ax_c.barh(i, w, 0.8, left=left, color=FAMILY_COLOR[f], edgecolor="white", linewidth=0.4)
340
+ seg_mm = w * 0.40 * W
341
+ if seg_mm > 1.35 * len(f) + 3: # label only segments wide enough for it
342
+ ax_c.text(left + w / 2, i, f, ha="center", va="center", fontsize=fsl - 1.2,
343
+ color=INK if f == "Healthy" else "white")
344
+ left += w
345
+ strip(ax_c)
346
+ fig.text(0.215, top + 0.035, "Condition proportions", fontsize=fsl, va="bottom")
347
+ x, y, rend = 0.215, 0.19, fig.canvas.get_renderer()
348
+ for f in fams: # two legend rows, kept left of the cell-type ring
349
+ sh = G[G.family == f].n_cells.sum() / total
350
+ r = Rectangle((x, y - 0.03), 0.009, 0.06, transform=fig.transFigure, color=FAMILY_COLOR[f])
351
+ t = fig.text(x + 0.013, y, f"{f} {pct(sh)}", fontsize=fsl - 0.6, va="center")
352
+ bb = t.get_window_extent(renderer=rend).transformed(fig.transFigure.inverted())
353
+ if bb.x1 > 0.615:
354
+ x, y = 0.215, y - 0.12
355
+ r.set_xy((x, y - 0.03))
356
+ t.set_position((x + 0.013, y))
357
+ bb = t.get_window_extent(renderer=rend).transformed(fig.transFigure.inverted())
358
+ fig.patches.append(r)
359
+ x = bb.x1 + 0.018
360
+ # cell types
361
+ l1 = C.groupby("l1").n_cells.sum()
362
+ show = l1.reindex(L1_SHOW)
363
+ rest = total - show.sum()
364
+ vals = list(show.values) + [rest]
365
+ keys = L1_SHOW + ["Other"]
366
+ ax_d = fig.add_axes([0.645, 0.02, 0.14, 0.84])
367
+ ax_d.pie(vals, colors=[L1_COLOR[k] for k in keys], startangle=90, counterclock=False,
368
+ wedgeprops={"width": 0.36, "linewidth": 0.6, "edgecolor": "white"})
369
+ ax_d.set_aspect("equal")
370
+ ax_d.text(0, 0, "Cell\ntypes", ha="center", va="center", fontsize=fsl)
371
+ for j, (k, v) in enumerate(zip(keys, vals)):
372
+ y = 0.80 - j * 0.118
373
+ fig.patches.append(Rectangle((0.80, y - 0.03), 0.009, 0.06, transform=fig.transFigure, color=L1_COLOR[k]))
374
+ fig.text(0.813, y, k.replace("Progenitor cell", "Progenitor"), fontsize=fsl, va="center")
375
+ fig.text(0.995, y, pct(v / total), fontsize=fsl, va="center", ha="right", color=SUB)
376
+ return fig, (W, H), {L[0]: "pretraining corpus: assay, condition family and L1 cell-type shares"}
377
+
378
+
379
+ def save(fig, stem, canvas, panels, note):
380
+ out = {}
381
+ for ext in ("pdf", "png", "svg"):
382
+ p = FIG / f"{stem}.{ext}"
383
+ fig.savefig(p, dpi=300 if ext == "png" else None)
384
+ out[ext] = {"path": str(p.relative_to(MS)), "sha256": hashlib.sha256(p.read_bytes()).hexdigest()}
385
+ prov = {"script": "scripts/corpus/build_figure1_corpus.py", "canvas_mm": list(canvas), "panels": panels,
386
+ "inputs": {f.name: hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(SRC.glob("*.csv"))
387
+ + [SRC / "corpus_summary.json"]},
388
+ "outputs": out, "note": note,
389
+ "scope": "Rendering only; every value is read from source_data/corpus/ (build_corpus_tables.py)."}
390
+ (FIG / f"{stem}.provenance.json").write_text(json.dumps(prov, indent=1) + "\n")
391
+ plt.close(fig)
392
+ print(stem, canvas)
393
+
394
+
395
+ def main() -> int:
396
+ ap = argparse.ArgumentParser()
397
+ ap.add_argument("--fig1-letter", default="c", help="letter of the Fig. 1 corpus panel (a-b = architecture)")
398
+ a = ap.parse_args()
399
+ abc = string.ascii_lowercase
400
+ fig, canvas, panels = draw_compact(abc[abc.index(a.fig1_letter):])
401
+ save(fig, "fig01_corpus", canvas, panels, "Fig. 1 strip; authored at the 180 mm width of fig01_architecture")
402
+ fig, canvas, panels = draw_full(abc)
403
+ save(fig, "figS_corpus", canvas, panels, "Supplementary: detailed corpus description")
404
+ return 0
405
+
406
+
407
+ if __name__ == "__main__":
408
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/sections/overview_figure.tex ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ \begin{figure}[p]
2
+ \centering
3
+ % Both parts are authored at the 180 mm double-column width, so one scale keeps their type
4
+ % sizes equal; 1.05 keeps panels a-c and the legend on one float page with about one caption line to spare.
5
+ \makebox[\textwidth][c]{\includegraphics[width=1.05\textwidth]{figures/fig01_architecture.pdf}}\\[0.8mm]
6
+ \makebox[\textwidth][c]{\includegraphics[width=1.05\textwidth]{figures/fig01_corpus.pdf}}
7
+ \caption{\textbf{\method{}: diffusion of gene values and zero/nonzero states, pretrained on 41 million blood cells.}
8
+ \textbf{a}, Model and training. Fixed transforms turn raw counts into expression values and zero/nonzero states and back; diffusion acts on this joint state in $2G$ gene coordinates at every noise level. The network $f_\theta$ estimates the clean state, with self-conditioning on its own earlier estimate, and every block receives the fixed bulk condition (expression, depth features and measured-gene mask) with the time step. A final hard zero/nonzero choice and the output gene mask give nonnegative values with exact zeros (Methods).
9
+ \textbf{b}, Generating cells. A bulk sample, its depth, the cell count $K$ and the gene mask define one condition; $K$ independent noise draws give $K$ different cells. Cell types are labelled afterwards: the sampler receives no cell-type labels or target shares and does not force totals or shares to match the input. The cells are examples, not measurements.
10
+ \textbf{c}, Pretraining corpus: share of cells by assay (Other: Seq-Well and 10x of unreported chemistry), condition shares within each assay by disease family (Healthy includes CMV-seropositive donors, post-vaccination draws and cultured healthy-donor cells) and cell-type shares from each dataset's labels. The model never receives condition or cell-type labels.}
11
+ \label{fig:architecture}
12
+ \end{figure}