Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/scripts/corpus/build_corpus_tables.py +265 -0
- paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/scripts/corpus/build_figure1_corpus.py +307 -0
- paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/source_data/corpus/README.md +36 -0
- paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/source_data/corpus/corpus_assay_condition.csv +25 -0
paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/scripts/corpus/build_corpus_tables.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
gsm_subject = dict(zip(g274.gsm, g274["subject id"]))
|
| 140 |
+
g132 = geo_samples("GSE132802")
|
| 141 |
+
dress_dx = dict(zip(g132.description_0.str.strip(), g132["disease diagnosis"]))
|
| 142 |
+
def classify(r, p, dis, cond, assay, sfile):
|
| 143 |
+
"""condition, source label, assay label, handling, CMV flag and donor of one label combination"""
|
| 144 |
+
donor = r.donor_id
|
| 145 |
+
if p == "061_A":
|
| 146 |
+
gsm = re.search(r"(GSM\d+)_", sfile).group(1)
|
| 147 |
+
dx, group, donor = GSE274680_GROUP[gsm_group[gsm]], gsm_group[gsm], gsm_subject[gsm]
|
| 148 |
+
elif p == "300b_A":
|
| 149 |
+
group = dress_dx[r.donor_id]
|
| 150 |
+
dx = "Healthy" if group == "Healthy" else "DRESS"
|
| 151 |
+
donor = "healthy volunteer" if dx == "Healthy" else "DRESS patient" # GEO: one patient, one volunteer
|
| 152 |
+
elif p == "304_A":
|
| 153 |
+
dx, group = "Healthy", "vendor: healthy donors"
|
| 154 |
+
else:
|
| 155 |
+
if dis not in DISEASE_MAP:
|
| 156 |
+
raise SystemExit(f"{r.dataset_id}: unmapped disease {dis!r}")
|
| 157 |
+
dx, group = DISEASE_MAP[dis], dis
|
| 158 |
+
a = ASSAY_BY_PREFIX.get(p) or ASSAY_MAP.get(assay)
|
| 159 |
+
if a is None:
|
| 160 |
+
raise SystemExit(f"{r.dataset_id}: unmapped assay {assay!r}")
|
| 161 |
+
iv = IN_VITRO.get(p)
|
| 162 |
+
in_vitro = iv == "all" or (isinstance(iv, set) and cond in iv)
|
| 163 |
+
return dx, group, a, "in vitro" if in_vitro else "ex vivo", dis == "cytomegalovirus infection", donor
|
| 164 |
+
|
| 165 |
+
rows, groups = [], []
|
| 166 |
+
for _, r in si.iterrows():
|
| 167 |
+
k, p = r.key, prefix(r.dataset_id)
|
| 168 |
+
n = cells.get(k, 0)
|
| 169 |
+
lab = labels.get(k, Counter())
|
| 170 |
+
if not lab:
|
| 171 |
+
raise SystemExit(f"{r.dataset_id}: a sample with overlay cells only")
|
| 172 |
+
combos = [(classify(r, p, *c), m) for c, m in lab.items()]
|
| 173 |
+
combos[max(range(len(combos)), key=lambda i: combos[i][1])] = (
|
| 174 |
+
combos[max(range(len(combos)), key=lambda i: combos[i][1])][0],
|
| 175 |
+
combos[max(range(len(combos)), key=lambda i: combos[i][1])][1] + n - sum(lab.values())) # overlay cells
|
| 176 |
+
agg = Counter()
|
| 177 |
+
for (dx, group, a, h, cmv, donor), m in combos:
|
| 178 |
+
agg[(dx, group, a, h, cmv, donor)] += m
|
| 179 |
+
for (dx, group, a, h, cmv, donor), m in agg.items():
|
| 180 |
+
groups.append({"sample_key": r.sample_key, "dataset_prefix": p, "platform": r.platform, "assay": a,
|
| 181 |
+
"split": r.split, "condition": dx, "source_disease": group, "handling": h,
|
| 182 |
+
"cmv_seropositive_healthy": cmv, "n_cells": m, "_donor": (r.dataset_id, donor)})
|
| 183 |
+
(dx, group, a, h, cmv, donor), m = agg.most_common(1)[0]
|
| 184 |
+
rows.append({"sample_key": r.sample_key, "dataset_prefix": p, "dataset_id": r.dataset_id,
|
| 185 |
+
"platform": r.platform, "assay": a, "split": r.split, "n_cells": n,
|
| 186 |
+
"n_cells_index": int(r.n_cells), "condition": dx, "source_disease": group, "handling": h,
|
| 187 |
+
"majority_share": m / n, "_donor": (r.dataset_id, donor)})
|
| 188 |
+
S, G = pd.DataFrame(rows), pd.DataFrame(groups)
|
| 189 |
+
if (S.n_cells != S.n_cells_index).any():
|
| 190 |
+
bad = S[S.n_cells != S.n_cells_index]
|
| 191 |
+
raise SystemExit(f"{len(bad)} samples: corpus cell counts differ from sample_index")
|
| 192 |
+
if S.n_cells.sum() != total or G.n_cells.sum() != total:
|
| 193 |
+
raise SystemExit("sample_index does not cover every corpus cell")
|
| 194 |
+
print("samples with more than one condition/handling/assay/donor group:", int((S.majority_share < 1).sum()))
|
| 195 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
G.drop(columns=["_donor"]).to_csv(OUT / "corpus_cellgroups.csv", index=False)
|
| 197 |
+
|
| 198 |
+
# ---- donors (GSE274680: GEO subject; others: corpus donor id) and split leakage check
|
| 199 |
+
donors = G.groupby("dataset_prefix")._donor.nunique()
|
| 200 |
+
leak = G.groupby("_donor").split.nunique()
|
| 201 |
+
leak_donors = leak[leak > 1]
|
| 202 |
+
leak_cells = int(G[G._donor.isin(leak_donors.index)].n_cells.sum())
|
| 203 |
+
S.drop(columns=["_donor", "n_cells_index"]).to_csv(OUT / "corpus_samples.csv", index=False)
|
| 204 |
+
|
| 205 |
+
# ---- per dataset
|
| 206 |
+
info = pd.read_csv(OUT / "dataset_info.csv").set_index("dataset_prefix")
|
| 207 |
+
D = []
|
| 208 |
+
for p, t in S.groupby("dataset_prefix"):
|
| 209 |
+
sp = t.groupby("split").n_cells.sum()
|
| 210 |
+
tg = G[G.dataset_prefix == p]
|
| 211 |
+
cd = tg.groupby("condition").n_cells.sum()
|
| 212 |
+
D.append({"dataset_prefix": p, "short_name": info.loc[p, "short_name"], "accession": info.loc[p, "accession"],
|
| 213 |
+
"enrichment": info.loc[p, "enrichment"], "dataset_id": t.dataset_id.iloc[0],
|
| 214 |
+
"platform": "/".join(sorted(t.platform.unique())), "assay": "/".join(sorted(t.assay.unique())),
|
| 215 |
+
"n_cells": int(t.n_cells.sum()), "n_samples": len(t), "n_donors": int(donors[p]),
|
| 216 |
+
"train_cells": int(sp.get("train", 0)), "val_cells": int(sp.get("val", 0)),
|
| 217 |
+
"test_cells": int(sp.get("test", 0)),
|
| 218 |
+
"in_vitro_cells": int(tg[tg.handling == "in vitro"].n_cells.sum()),
|
| 219 |
+
"conditions": "; ".join(f"{c} {int(n)}" for c, n in cd.sort_values(ascending=False).items())})
|
| 220 |
+
D = pd.DataFrame(D).sort_values("n_cells", ascending=False)
|
| 221 |
+
if len(D) != src["n_datasets"] or set(D.dataset_prefix) != set(info.index):
|
| 222 |
+
raise SystemExit("dataset_info.csv does not match the corpus datasets")
|
| 223 |
+
D.to_csv(OUT / "corpus_datasets.csv", index=False)
|
| 224 |
+
|
| 225 |
+
# ---- cell types (per dataset, L1/L2)
|
| 226 |
+
pre = {k: prefix(k[0]) for k in cells}
|
| 227 |
+
C = pd.DataFrame([{"dataset_prefix": pre[k], "celltype_l1": l1, "celltype_l2": l2, "n_cells": n}
|
| 228 |
+
for (k, l1, l2), n in ctypes.items()])
|
| 229 |
+
C = C.groupby(["dataset_prefix", "celltype_l1", "celltype_l2"], as_index=False).n_cells.sum()
|
| 230 |
+
if C.n_cells.sum() != total:
|
| 231 |
+
raise SystemExit("cell-type table does not cover every cell")
|
| 232 |
+
C.to_csv(OUT / "corpus_celltypes.csv", index=False)
|
| 233 |
+
|
| 234 |
+
# ---- assay x condition
|
| 235 |
+
A = G.groupby(["assay", "condition"], as_index=False).n_cells.sum()
|
| 236 |
+
A.to_csv(OUT / "corpus_assay_condition.csv", index=False)
|
| 237 |
+
|
| 238 |
+
fam = dict(CONDITIONS)
|
| 239 |
+
summ = {"cells": total, "base_cells": n_base, "overlay_cells": n_overlay, "datasets": int(len(D)),
|
| 240 |
+
"samples": int(len(S)), "donors": int(donors.sum()),
|
| 241 |
+
"split_cells": {k: int(v) for k, v in S.groupby("split").n_cells.sum().items()},
|
| 242 |
+
"split_samples": {k: int(v) for k, v in S.split.value_counts().items()},
|
| 243 |
+
"condition_cells": {k: int(v) for k, v in G.groupby("condition").n_cells.sum().items()},
|
| 244 |
+
"family_cells": {k: int(v) for k, v in G.assign(f=G.condition.map(fam)).groupby("f").n_cells.sum().items()},
|
| 245 |
+
"handling_cells": {k: int(v) for k, v in G.groupby("handling").n_cells.sum().items()},
|
| 246 |
+
"cmv_seropositive_healthy_cells": int(G[G.cmv_seropositive_healthy].n_cells.sum()),
|
| 247 |
+
"assay_cells": {k: int(v) for k, v in G.groupby("assay").n_cells.sum().items()},
|
| 248 |
+
"platform_cells": {k: int(v) for k, v in G.groupby("platform").n_cells.sum().items()},
|
| 249 |
+
"celltype_l1_cells": {k: int(v) for k, v in C.groupby("celltype_l1").n_cells.sum().items()},
|
| 250 |
+
"corpus_vs_block_donor_id_mismatch_rows": donor_mismatch,
|
| 251 |
+
"donors_in_more_than_one_split": int(len(leak_donors)), "cells_of_those_donors": leak_cells,
|
| 252 |
+
"donors_in_more_than_one_split_by_dataset": {k: int(v) for k, v in
|
| 253 |
+
Counter(d[0][:6] for d in leak_donors.index).items()},
|
| 254 |
+
"conditions_order": [c for c, _ in CONDITIONS], "condition_family": fam,
|
| 255 |
+
"inputs": {"corpus_obs": str(E2_OBS), "block_obs": str(BLOCK_OBS), "sample_index": str(SAMPLE_INDEX),
|
| 256 |
+
"source_manifest": str(SOURCE_MANIFEST), "geo": sorted(p.name for p in GEO.glob("*.gz"))},
|
| 257 |
+
"script": str(Path(__file__).resolve())}
|
| 258 |
+
(OUT / "corpus_summary.json").write_text(json.dumps(summ, indent=1) + "\n")
|
| 259 |
+
print(json.dumps({k: v for k, v in summ.items() if k not in ("inputs", "condition_family")}, indent=1))
|
| 260 |
+
print(D[["short_name", "assay", "n_cells", "n_samples", "n_donors", "train_cells", "in_vitro_cells"]].to_string(index=False))
|
| 261 |
+
return 0
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/scripts/corpus/build_figure1_corpus.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Figure 1 corpus panels: what the pretraining corpus contains (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. Panels (letters start at --first, default c, because Fig. 1 a-b is the architecture):
|
| 6 |
+
c corpus overview: split and sample handling (pies), assay shares (bars) and condition shares per assay
|
| 7 |
+
d datasets: cells (log scale), donors, samples, condition and cell-type composition per dataset
|
| 8 |
+
e cell types: L1 shares (donut) and L2 cell counts (log scale)
|
| 9 |
+
f data schema: what each cell carries, and what the model never receives
|
| 10 |
+
Outputs: figures/fig01_corpus.{pdf,png,svg} and figures/fig01_corpus.provenance.json.
|
| 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 main() -> int:
|
| 96 |
+
ap = argparse.ArgumentParser()
|
| 97 |
+
ap.add_argument("--first", default="c", help="letter of the first panel (Fig. 1 a-b is the architecture)")
|
| 98 |
+
a = ap.parse_args()
|
| 99 |
+
L = string.ascii_lowercase[string.ascii_lowercase.index(a.first):]
|
| 100 |
+
summ = json.loads((SRC / "corpus_summary.json").read_text())
|
| 101 |
+
D = pd.read_csv(SRC / "corpus_datasets.csv")
|
| 102 |
+
G = pd.read_csv(SRC / "corpus_cellgroups.csv")
|
| 103 |
+
C = pd.read_csv(SRC / "corpus_celltypes.csv")
|
| 104 |
+
conds = summ["conditions_order"]
|
| 105 |
+
if set(G.condition) - set(conds) or set(conds) != set(COND_COLOR):
|
| 106 |
+
raise SystemExit("condition categories differ from the colour map")
|
| 107 |
+
C["l1"] = C.celltype_l1.map(lambda x: L1_MERGE.get(x, x))
|
| 108 |
+
if set(C.l1) - set(L1_ORDER):
|
| 109 |
+
raise SystemExit(f"unexpected L1 labels: {set(C.l1) - set(L1_ORDER)}")
|
| 110 |
+
total = summ["cells"]
|
| 111 |
+
if G.n_cells.sum() != total or C.n_cells.sum() != total or D.n_cells.sum() != total:
|
| 112 |
+
raise SystemExit("tables do not add up to the corpus total")
|
| 113 |
+
W, H = 180, 200
|
| 114 |
+
fig = plt.figure(figsize=(W * MM, H * MM))
|
| 115 |
+
|
| 116 |
+
# ------------------------------------------------------------------ c: overview
|
| 117 |
+
y0 = 0.99
|
| 118 |
+
letter(fig, 0.0, y0, L[0])
|
| 119 |
+
fig.text(0.03, y0 - 0.002, f"Pretraining corpus – {total / 1e6:.1f} million cells from {summ['datasets']} "
|
| 120 |
+
f"datasets, {summ['donors']:,} donors and {summ['samples']:,} samples", fontsize=7, va="top")
|
| 121 |
+
pie(fig, [0.005, 0.835, 0.085, 0.085], summ["split_cells"], SPLIT_COLOR, "Split")
|
| 122 |
+
pie(fig, [0.005, 0.69, 0.085, 0.085], summ["handling_cells"], HAND_COLOR, "Sample handling")
|
| 123 |
+
A = G.groupby(["assay", "condition"]).n_cells.sum().unstack(fill_value=0)
|
| 124 |
+
small = A.sum(1) < 0.002 * total
|
| 125 |
+
other_lab = None
|
| 126 |
+
if small.any():
|
| 127 |
+
other_lab = "Other"
|
| 128 |
+
other_list = ", ".join(A.index[small])
|
| 129 |
+
A.loc[other_lab] = A[small].sum()
|
| 130 |
+
A = A[~small.reindex(A.index, fill_value=False)]
|
| 131 |
+
A = A.loc[A.drop(index=[other_lab] if other_lab else []).sum(1).sort_values(ascending=False).index.tolist()
|
| 132 |
+
+ ([other_lab] if other_lab else [])]
|
| 133 |
+
share = A.sum(1) / total
|
| 134 |
+
n = len(A)
|
| 135 |
+
top, bot = 0.915, 0.69
|
| 136 |
+
ax_a = fig.add_axes([0.29, bot, 0.075, top - bot])
|
| 137 |
+
ax_a.barh(np.arange(n), share.values, 0.62, color=LIGHT)
|
| 138 |
+
ax_a.set_ylim(n - 0.5, -0.5)
|
| 139 |
+
ax_a.set_xlim(0, 1.0)
|
| 140 |
+
strip(ax_a)
|
| 141 |
+
fig.text(0.29, top + 0.012, "Assay", fontsize=6.3, va="bottom")
|
| 142 |
+
for i, (lab, sh) in enumerate(share.items()):
|
| 143 |
+
ax_a.text(-0.04, i, lab, ha="right", va="center", fontsize=5.8, transform=ax_a.get_yaxis_transform())
|
| 144 |
+
ax_a.text(sh + 0.03, i, pct(sh), va="center", fontsize=5.6, color=SUB)
|
| 145 |
+
ax_c = fig.add_axes([0.405, bot, 0.59, top - bot])
|
| 146 |
+
ax_c.set_xlim(0, 1)
|
| 147 |
+
ax_c.set_ylim(n - 0.5, -0.5)
|
| 148 |
+
for i, (lab, row) in enumerate(A.iterrows()):
|
| 149 |
+
left, tot = 0.0, row.sum()
|
| 150 |
+
for c in conds:
|
| 151 |
+
w = row.get(c, 0) / tot
|
| 152 |
+
if w <= 0:
|
| 153 |
+
continue
|
| 154 |
+
ax_c.barh(i, w, 0.62, left=left, color=COND_COLOR[c], edgecolor="white", linewidth=0.4)
|
| 155 |
+
if w > 0.12:
|
| 156 |
+
dark = c not in ("Healthy", "ACPA+ at risk of RA", "Post-COVID-19", "Cytopenia", "JDM")
|
| 157 |
+
ax_c.text(left + w / 2, i, c, ha="center", va="center", fontsize=5.5,
|
| 158 |
+
color="white" if dark else INK)
|
| 159 |
+
left += w
|
| 160 |
+
strip(ax_c)
|
| 161 |
+
fig.text(0.405, top + 0.012, "Condition proportions", fontsize=6.3, va="bottom")
|
| 162 |
+
fig.text(0.405, top + 0.003, "0%", fontsize=5.4, color=SUB, va="bottom")
|
| 163 |
+
fig.text(0.995, top + 0.003, "100%", fontsize=5.4, color=SUB, va="bottom", ha="right")
|
| 164 |
+
fam = summ["condition_family"]
|
| 165 |
+
families = list(dict.fromkeys(fam[c] for c in conds))
|
| 166 |
+
width = {f: max([len(c) + 2 for c in conds if fam[c] == f] + [len(f) if f != "Healthy" else 0])
|
| 167 |
+
for f in families}
|
| 168 |
+
xs = 0.405 + np.cumsum([0] + [0.018 + 0.0068 * width[f] for f in families[:-1]])
|
| 169 |
+
for x, f in zip(xs, families):
|
| 170 |
+
if f != "Healthy":
|
| 171 |
+
fig.text(x, 0.672, f, fontsize=5.6, color=SUB, va="top")
|
| 172 |
+
for j, c in enumerate([c for c in conds if fam[c] == f]):
|
| 173 |
+
yy = 0.655 - j * 0.0125
|
| 174 |
+
fig.patches.append(Rectangle((x, yy - 0.004), 0.007, 0.008, transform=fig.transFigure, color=COND_COLOR[c]))
|
| 175 |
+
fig.text(x + 0.011, yy, c, fontsize=5.6, va="center")
|
| 176 |
+
if other_lab:
|
| 177 |
+
fig.text(0.29, 0.672, "Other:\n" + other_list.replace(", ", "\n"), fontsize=5.0, color=SUB, va="top",
|
| 178 |
+
linespacing=1.15)
|
| 179 |
+
|
| 180 |
+
# ------------------------------------------------------------------ d: datasets
|
| 181 |
+
yd = 0.6
|
| 182 |
+
letter(fig, 0.0, yd, L[1])
|
| 183 |
+
fig.text(0.03, yd - 0.002, "Datasets", fontsize=7, va="top")
|
| 184 |
+
D = D.sort_values("n_cells", ascending=False).reset_index(drop=True)
|
| 185 |
+
nd = len(D)
|
| 186 |
+
dtop, dbot = 0.565, 0.345
|
| 187 |
+
drh = (dtop - dbot) / nd
|
| 188 |
+
hdr = dtop + 0.006
|
| 189 |
+
x_assay, x_bar0, x_bar1 = 0.262, 0.27, 0.43
|
| 190 |
+
ax_n = fig.add_axes([x_bar0, dbot, x_bar1 - x_bar0, dtop - dbot])
|
| 191 |
+
ax_n.barh(np.arange(nd), D.n_cells, 0.62, color="#B8B8AE")
|
| 192 |
+
ax_n.set_xscale("log")
|
| 193 |
+
ax_n.set_xlim(1e4, 1e8)
|
| 194 |
+
ax_n.set_ylim(nd - 0.5, -0.5)
|
| 195 |
+
ax_n.set_yticks([])
|
| 196 |
+
ax_n.set_xticks([1e4, 1e5, 1e6, 1e7], ["10k", "100k", "1M", "10M"])
|
| 197 |
+
ax_n.minorticks_off()
|
| 198 |
+
ax_n.tick_params(axis="x", labelsize=5.3, pad=1)
|
| 199 |
+
for sp in ("top", "right", "left"):
|
| 200 |
+
ax_n.spines[sp].set_visible(False)
|
| 201 |
+
fig.text(x_bar0, hdr, "Cells", fontsize=6.3, va="bottom")
|
| 202 |
+
fig.text(x_assay, hdr, "Assay", fontsize=6.3, va="bottom", ha="right")
|
| 203 |
+
fig.text(0.005, hdr, "Dataset", fontsize=6.3, va="bottom")
|
| 204 |
+
x_don, x_smp = 0.512, 0.567
|
| 205 |
+
fig.text(x_don, hdr, "Donors", fontsize=6.3, va="bottom", ha="right")
|
| 206 |
+
fig.text(x_smp, hdr, "Samples", fontsize=6.3, va="bottom", ha="right")
|
| 207 |
+
for i, r in D.iterrows():
|
| 208 |
+
y = dtop - (i + 0.5) * drh
|
| 209 |
+
fig.text(0.005, y, r.short_name + NAME_SUFFIX.get(r.enrichment, ""), fontsize=5.6, va="center")
|
| 210 |
+
fig.text(x_assay, y, r.assay, fontsize=5.0, va="center", ha="right", color=SUB)
|
| 211 |
+
ax_n.text(r.n_cells * 1.15, i, fmt_cells(r.n_cells), va="center", fontsize=5.0, color=SUB)
|
| 212 |
+
fig.text(x_don, y, f"{r.n_donors:,}", fontsize=5.6, va="center", ha="right")
|
| 213 |
+
fig.text(x_smp, y, f"{r.n_samples:,}", fontsize=5.6, va="center", ha="right")
|
| 214 |
+
cg = G.groupby(["dataset_prefix", "condition"]).n_cells.sum().unstack(fill_value=0)
|
| 215 |
+
ct = C.groupby(["dataset_prefix", "l1"]).n_cells.sum().unstack(fill_value=0)
|
| 216 |
+
for x0, w0, tab, order, cmap, title in ((0.585, 0.195, cg, conds, COND_COLOR, "Condition"),
|
| 217 |
+
(0.80, 0.195, ct, L1_ORDER, L1_COLOR, "Cell type (L1)")):
|
| 218 |
+
ax = fig.add_axes([x0, dbot, w0, dtop - dbot])
|
| 219 |
+
for i, r in D.iterrows():
|
| 220 |
+
row = tab.loc[r.dataset_prefix]
|
| 221 |
+
left, tot = 0.0, row.sum()
|
| 222 |
+
for k in order:
|
| 223 |
+
v = row.get(k, 0) / tot
|
| 224 |
+
if v > 0:
|
| 225 |
+
ax.barh(i, v, 0.62, left=left, color=cmap[k], edgecolor="none")
|
| 226 |
+
left += v
|
| 227 |
+
ax.set_xlim(0, 1)
|
| 228 |
+
ax.set_ylim(nd - 0.5, -0.5)
|
| 229 |
+
strip(ax)
|
| 230 |
+
fig.text(x0, hdr, title, fontsize=6.3, va="bottom")
|
| 231 |
+
|
| 232 |
+
# ------------------------------------------------------------------ e: cell types
|
| 233 |
+
ye = 0.29
|
| 234 |
+
letter(fig, 0.0, ye, L[2])
|
| 235 |
+
fig.text(0.03, ye - 0.002, "Cell types (source labels mapped to a shared two-level hierarchy)", fontsize=7, va="top")
|
| 236 |
+
l1 = C.groupby("l1").n_cells.sum().reindex(L1_ORDER).fillna(0)
|
| 237 |
+
ax_d = fig.add_axes([0.0, 0.085, 0.165, 0.165])
|
| 238 |
+
w, _ = ax_d.pie(l1.values, colors=[L1_COLOR[k] for k in l1.index], startangle=90, counterclock=False,
|
| 239 |
+
wedgeprops={"width": 0.36, "linewidth": 0.6, "edgecolor": "white"})
|
| 240 |
+
ax_d.set_aspect("equal")
|
| 241 |
+
ax_d.text(0, 0, f"{total / 1e6:.1f} M\ncells", ha="center", va="center", fontsize=6.2)
|
| 242 |
+
for j, k in enumerate(L1_ORDER):
|
| 243 |
+
y = 0.245 - j * 0.0148
|
| 244 |
+
fig.patches.append(Rectangle((0.172, y - 0.004), 0.007, 0.008, transform=fig.transFigure, color=L1_COLOR[k]))
|
| 245 |
+
fig.text(0.183, y, k, fontsize=5.5, va="center")
|
| 246 |
+
fig.text(0.29, y, pct(l1[k] / total), fontsize=5.5, va="center", ha="right", color=SUB)
|
| 247 |
+
l2 = C[~C.l1.isin(["Other", "Unlabelled"]) & (C.celltype_l2 != "__unspecified__")]
|
| 248 |
+
l2 = l2[l2.celltype_l2 != l2.celltype_l1].groupby(["l1", "celltype_l2"]).n_cells.sum().reset_index()
|
| 249 |
+
l2["o"] = l2.l1.map({k: i for i, k in enumerate(L1_ORDER)})
|
| 250 |
+
l2 = l2.sort_values(["o", "n_cells"], ascending=[True, False]).reset_index(drop=True)
|
| 251 |
+
two = C[C.l1.isin(l2.l1.unique())]
|
| 252 |
+
resolved = l2.n_cells.sum() / two.n_cells.sum()
|
| 253 |
+
ax2 = fig.add_axes([0.355, 0.095, 0.425, 0.15])
|
| 254 |
+
ax2.bar(np.arange(len(l2)), l2.n_cells, 0.72, color=[L1_COLOR[k] for k in l2.l1], edgecolor="none")
|
| 255 |
+
ax2.set_yscale("log")
|
| 256 |
+
ax2.set_ylim(1e3, 2e7)
|
| 257 |
+
ax2.set_yticks([1e3, 1e4, 1e5, 1e6, 1e7], ["1k", "10k", "100k", "1M", "10M"])
|
| 258 |
+
ax2.minorticks_off()
|
| 259 |
+
ax2.set_xticks(np.arange(len(l2)), [L2_SHORT.get(x, x) for x in l2.celltype_l2], rotation=60, ha="right",
|
| 260 |
+
rotation_mode="anchor", fontsize=5.0)
|
| 261 |
+
ax2.tick_params(axis="x", length=0, pad=1.5)
|
| 262 |
+
ax2.tick_params(axis="y", labelsize=5.3, pad=1)
|
| 263 |
+
ax2.set_xlim(-0.6, len(l2) - 0.4)
|
| 264 |
+
for sp in ("top", "right"):
|
| 265 |
+
ax2.spines[sp].set_visible(False)
|
| 266 |
+
ax2.set_ylabel("Cells", fontsize=5.8, labelpad=1)
|
| 267 |
+
fig.text(0.355, 0.262, f"{len(l2)} L2 subtypes, {fmt_cells(l2.n_cells.min())} to {fmt_cells(l2.n_cells.max())} "
|
| 268 |
+
f"cells each (L2 resolved for {pct(resolved)} of their L1 cells)", fontsize=5.8, va="bottom")
|
| 269 |
+
|
| 270 |
+
# ------------------------------------------------------------------ f: per-cell record
|
| 271 |
+
xf = 0.81
|
| 272 |
+
letter(fig, xf - 0.025, ye, L[3])
|
| 273 |
+
fig.text(xf + 0.005, ye - 0.002, "Per-cell record", fontsize=7, va="top")
|
| 274 |
+
G_GENES = 20097
|
| 275 |
+
|
| 276 |
+
def gbox(x, y, w, h, txt, fs=5.6):
|
| 277 |
+
fig.patches.append(Rectangle((x, y), w, h, transform=fig.transFigure, color="#D9D9D1"))
|
| 278 |
+
fig.text(x + w / 2, y + h / 2, txt, ha="center", va="center", fontsize=fs, linespacing=1.1)
|
| 279 |
+
gbox(xf, 0.228, 0.13, 0.024, f"var: {G_GENES:,} genes")
|
| 280 |
+
gbox(xf, 0.155, 0.13, 0.066, "Raw counts\n+ measured-gene\nmask", fs=5.6)
|
| 281 |
+
gbox(xf + 0.137, 0.155, 0.04, 0.066, "obs", fs=5.6)
|
| 282 |
+
fig.text(xf, 0.142, "Used for bulks and splits", fontsize=5.6, fontweight="bold", va="top")
|
| 283 |
+
fig.text(xf, 0.127, "sample (cells of one sample),\nplatform (recipe share),\ndataset + donor (split)",
|
| 284 |
+
fontsize=5.3, va="top", linespacing=1.15)
|
| 285 |
+
fig.text(xf, 0.083, "Never given to the model", fontsize=5.6, fontweight="bold", va="top")
|
| 286 |
+
fig.text(xf, 0.068, "condition, cell type (L1/L2)", fontsize=5.3, va="top")
|
| 287 |
+
fig.text(xf, 0.048, "Bulk = sum of K cells,\nK = 250–4,000", fontsize=5.3, va="top", color=SUB,
|
| 288 |
+
linespacing=1.15)
|
| 289 |
+
|
| 290 |
+
out = {}
|
| 291 |
+
for ext in ("pdf", "png", "svg"):
|
| 292 |
+
p = FIG / f"fig01_corpus.{ext}"
|
| 293 |
+
fig.savefig(p, dpi=300 if ext == "png" else None)
|
| 294 |
+
out[ext] = {"path": str(p.relative_to(MS)), "sha256": hashlib.sha256(p.read_bytes()).hexdigest()}
|
| 295 |
+
prov = {"script": "scripts/corpus/build_figure1_corpus.py", "canvas_mm": [W, H],
|
| 296 |
+
"panels": {L[0]: "corpus overview", L[1]: "datasets", L[2]: "cell types", L[3]: "per-cell record"},
|
| 297 |
+
"inputs": {f.name: hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(SRC.glob("*.csv"))
|
| 298 |
+
+ [SRC / "corpus_summary.json"]},
|
| 299 |
+
"outputs": out,
|
| 300 |
+
"scope": "Rendering only; every value is read from source_data/corpus/ (build_corpus_tables.py)."}
|
| 301 |
+
(FIG / "fig01_corpus.provenance.json").write_text(json.dumps(prov, indent=1) + "\n")
|
| 302 |
+
print(json.dumps(out, indent=1))
|
| 303 |
+
return 0
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/source_data/corpus/README.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pretraining corpus tables (Figure 1 corpus panels)
|
| 2 |
+
|
| 3 |
+
Built 2026-10-06 by `scripts/corpus/build_corpus_tables.py` (CPU only); the figure is drawn by
|
| 4 |
+
`scripts/corpus/build_figure1_corpus.py` from these files only (`figures/fig01_corpus.{pdf,png,svg}`).
|
| 5 |
+
|
| 6 |
+
| File | Content |
|
| 7 |
+
|---|---|
|
| 8 |
+
| `corpus_summary.json` | totals and checks: 41,395,184 cells (41,270,779 base + 124,405 overlay), 22 datasets, 6,507 samples, split, condition, assay, cell-type totals, split-leakage check |
|
| 9 |
+
| `corpus_datasets.csv` | one row per dataset: cells, samples, donors, assay, cells per split, cells per condition |
|
| 10 |
+
| `corpus_samples.csv` | one row per registered sample (hashed `sample_key` only): platform, assay, split, majority condition |
|
| 11 |
+
| `corpus_cellgroups.csv` | cells per sample x condition x handling (cell-level condition) |
|
| 12 |
+
| `corpus_celltypes.csv` | cells per dataset x L1 x L2 (source labels mapped to the shared hierarchy) |
|
| 13 |
+
| `corpus_assay_condition.csv` | cells per assay x condition |
|
| 14 |
+
| `dataset_info.csv` | hand-written display names, accessions, enrichment and metadata notes |
|
| 15 |
+
| `geo/` | GEO series matrices used to complete metadata missing from the source obs |
|
| 16 |
+
|
| 17 |
+
Rules (all in the script): CMV-seropositive healthy donors (recorded as "cytomegalovirus infection") and
|
| 18 |
+
post-vaccination draws count as Healthy. GSE274680 groups come from the GEO sample-title suffix (CON1/CON2
|
| 19 |
+
control, ARI/LONG ACPA+ at risk, ERA early RA) and its donors from the GEO subject id. GSE132802 has one DRESS
|
| 20 |
+
patient and one healthy volunteer. Parse 10M donors are healthy per the vendor description. In vitro = Parse
|
| 21 |
+
cytokine panel (incl. PBS), GSE314010 (IL-36 or PBS, 7 h) and the GSE132802 cultured samples. Cell types are the
|
| 22 |
+
block's harmonized source labels for base cells; overlay cells have no label ("Unlabelled").
|
| 23 |
+
|
| 24 |
+
Split check: 7 donors have samples in more than one split (6 GSE274680 subjects, whose corpus donor key is the
|
| 25 |
+
per-visit sample id, and the GSE132802 patient); `corpus_summary.json` records their cell count.
|
| 26 |
+
|
| 27 |
+
## Caption draft (panels c-f)
|
| 28 |
+
|
| 29 |
+
**c**, Pretraining corpus: 41.4 million cells from 22 public datasets, 3,169 donors and 6,507 samples. Pies: share
|
| 30 |
+
of cells by split and by sample handling (in vitro = cultured or stimulated before sequencing). Bars: share of
|
| 31 |
+
cells by assay. Stacked bars: condition shares within each assay. Healthy includes CMV-seropositive donors and
|
| 32 |
+
post-vaccination draws. **d**, The 22 datasets: cells (log scale), donors, samples, and condition and cell-type
|
| 33 |
+
(L1) shares. **e**, Cell types from each dataset's own labels, mapped to a shared two-level hierarchy: L1 shares
|
| 34 |
+
and L2 cell counts (log scale). **f**, What each cell carries. Sample, platform, dataset and donor are used only to
|
| 35 |
+
form training bulks (sums of K cells from one sample) and splits; condition and cell-type labels are never given to
|
| 36 |
+
the model.
|
paper-releases/pbisc-diffusion/updates/20261006T054909Z-fig1-corpus-panels/diffusion/dataset/server_1/manuscript/source_data/corpus/corpus_assay_condition.csv
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
assay,condition,n_cells
|
| 2 |
+
10x (version n.r.),Healthy,64752
|
| 3 |
+
10x 3' (hashed),ACPA+ at risk of RA,1792129
|
| 4 |
+
10x 3' (hashed),Healthy,2113388
|
| 5 |
+
10x 3' (hashed),RA,211867
|
| 6 |
+
10x 3' v2,Healthy,1745033
|
| 7 |
+
10x 3' v2,SLE,792660
|
| 8 |
+
10x 3' v3,Cytopenia,100147
|
| 9 |
+
10x 3' v3,Healthy,16461514
|
| 10 |
+
10x 3' v3,JDM,82666
|
| 11 |
+
10x 3' v3,MDS,176233
|
| 12 |
+
10x 3' v3,MDS/MPN,130268
|
| 13 |
+
10x 3' v3,RA,48637
|
| 14 |
+
10x 5' v1,COVID-19,1251478
|
| 15 |
+
10x 5' v1,Healthy,360013
|
| 16 |
+
10x 5' v1,Influenza,19233
|
| 17 |
+
10x 5' v1,Post-COVID-19,97224
|
| 18 |
+
10x 5' v2,Healthy,1727658
|
| 19 |
+
10x Flex,Healthy,3758514
|
| 20 |
+
10x v2 (3'/5'),DRESS,25272
|
| 21 |
+
10x v2 (3'/5'),Healthy,8779
|
| 22 |
+
Parse,Healthy,9697974
|
| 23 |
+
ScaleBio,Healthy,685024
|
| 24 |
+
Seq-Well,COVID-19,28094
|
| 25 |
+
Seq-Well,Healthy,16627
|