Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/dataset/server_1/manuscript/scripts/build_figure1_architecture_nature.py +435 -0
- paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/dataset/server_1/manuscript/scripts/corpus/build_figure1_corpus.py +416 -0
- paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/metadata/inference_locations.json +5 -0
- paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/metadata/request.json +127 -0
paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/dataset/server_1/manuscript/scripts/build_figure1_architecture_nature.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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figure 1 overview (a-c), 2026-10-06; plan in editorial/fig1_nature_redesign_plan_20261006.md.
|
| 3 |
+
|
| 4 |
+
Writes the editable master figures/fig01_architecture_nature.svg and renders .pdf/.png with cairosvg.
|
| 5 |
+
Schematic only: tiles, clouds and mini-plots are drawn from a fixed seed and show no data. The corpus numbers in
|
| 6 |
+
panel a are read from source_data/corpus/corpus_summary.json. Canvas 180 mm wide, 8 SVG units per mm, Arial.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import cairosvg
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 18 |
+
OUT = ROOT / "figures" / "fig01_architecture_nature.svg"
|
| 19 |
+
U = 8.0 # SVG units per mm
|
| 20 |
+
PT = 25.4 / 72 * U # SVG units per typographic point
|
| 21 |
+
W, H = 1440, 760
|
| 22 |
+
FONT = "Arial, Helvetica, sans-serif"
|
| 23 |
+
INK, SUB, LINE = "#222222", "#5A5A5A", "#8C8C8C"
|
| 24 |
+
GOLD, GOLD_L = "#B8862B", "#E9D3A6" # bulk / condition
|
| 25 |
+
BLUE, BLUE_L = "#3F6E9E", "#C9D8E8" # expression value
|
| 26 |
+
TEAL = "#2E8B7A" # detection
|
| 27 |
+
SLATE, SLATE_L = "#5B6E8F", "#E6EAF1" # model
|
| 28 |
+
PURPLE = "#8E6C9E" # adaptation
|
| 29 |
+
GREY, GREY_L = "#9A9A9A", "#E4E4E4" # noise, unmeasured
|
| 30 |
+
CT = {"T cell": "#4C6E91", "Monocyte": "#5E8C6A", "B cell": "#C98A4B", "NK cell": "#8FB0CF"}
|
| 31 |
+
rng = np.random.default_rng(20261006)
|
| 32 |
+
parts: list[str] = []
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def t(x, y, s, size=6.5, weight="normal", color=INK, anchor="start", style="normal", extra=""):
|
| 36 |
+
parts.append(f'<text x="{x:.1f}" y="{y:.1f}" font-family="{FONT}" font-size="{size * PT:.1f}" '
|
| 37 |
+
f'font-weight="{weight}" font-style="{style}" fill="{color}" text-anchor="{anchor}" {extra}>{s}</text>')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def rect(x, y, w, h, fill="none", stroke="none", sw=1.0, rx=0, dash=None, op=1.0):
|
| 41 |
+
d = f' stroke-dasharray="{dash}"' if dash else ""
|
| 42 |
+
parts.append(f'<rect x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" rx="{rx}" fill="{fill}" '
|
| 43 |
+
f'stroke="{stroke}" stroke-width="{sw}"{d} opacity="{op}"/>')
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def line(x1, y1, x2, y2, color=LINE, sw=1.4, arrow=None, dash=None):
|
| 47 |
+
m = f' marker-end="url(#{arrow})"' if arrow else ""
|
| 48 |
+
d = f' stroke-dasharray="{dash}"' if dash else ""
|
| 49 |
+
parts.append(f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="{color}" '
|
| 50 |
+
f'stroke-width="{sw}"{d}{m}/>')
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def path(d, color=LINE, sw=1.4, arrow=None, dash=None, fill="none"):
|
| 54 |
+
m = f' marker-end="url(#{arrow})"' if arrow else ""
|
| 55 |
+
ds = f' stroke-dasharray="{dash}"' if dash else ""
|
| 56 |
+
parts.append(f'<path d="{d}" fill="{fill}" stroke="{color}" stroke-width="{sw}"{ds}{m}/>')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def circle(x, y, r, fill, stroke="none", sw=1.0):
|
| 60 |
+
parts.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{r:.1f}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"/>')
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
from PIL import ImageFont # noqa: E402
|
| 64 |
+
|
| 65 |
+
ARIAL = "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def text_w(s, size):
|
| 69 |
+
return ImageFont.truetype(ARIAL, max(1, round(size * PT * 4))).getlength(s) / 4
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def ts(x, y, base, idx, size=6.5, anchor="start", color=INK, weight="normal"):
|
| 73 |
+
"""text with a subscript placed from measured Arial widths (cairosvg misplaces tspans)"""
|
| 74 |
+
wb, wi = text_w(base, size), text_w(idx, size * 0.72)
|
| 75 |
+
x0 = x - (wb + wi) / 2 if anchor == "middle" else (x - wb - wi if anchor == "end" else x)
|
| 76 |
+
t(x0, y, base, size=size, color=color, weight=weight)
|
| 77 |
+
t(x0 + wb + 0.5, y + size * PT * 0.22, idx, size=size * 0.72, color=color, weight=weight)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def letter(x, y, s):
|
| 81 |
+
t(x, y, s, size=9, weight="bold")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def header(x, y, s):
|
| 85 |
+
t(x, y, s, size=7.5, weight="bold")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def shade(base, v):
|
| 89 |
+
"""mix white -> base by v in [0, 1]"""
|
| 90 |
+
b = [int(base[i:i + 2], 16) for i in (1, 3, 5)]
|
| 91 |
+
c = [round(255 + (bb - 255) * v) for bb in b]
|
| 92 |
+
return "#" + "".join(f"{x:02X}" for x in c)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def hatch_rect(x, y, w, h):
|
| 96 |
+
rect(x, y, w, h, fill="url(#hatch)", stroke=GREY, sw=0.6)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def cell_profile(x, y, vals, det, unmeasured, gw=12, bh=34, noise=0.0, tag=None):
|
| 100 |
+
"""one cell over genes: value bars (blue) above detection dots (teal); unmeasured genes hatched"""
|
| 101 |
+
n = len(vals)
|
| 102 |
+
rect(x - 4, y - 4, n * gw + 8, bh + 26, fill="white", stroke="#C8C8C8", sw=0.8, rx=4)
|
| 103 |
+
for g in range(n):
|
| 104 |
+
gx = x + g * gw
|
| 105 |
+
if g in unmeasured:
|
| 106 |
+
hatch_rect(gx + 1, y, gw - 2, bh + 18)
|
| 107 |
+
continue
|
| 108 |
+
v = vals[g]
|
| 109 |
+
col = BLUE if noise < 0.5 else GREY
|
| 110 |
+
if noise > 0:
|
| 111 |
+
col = shade(GREY, 0.9) if noise >= 0.99 else (BLUE if noise < 0.4 else "#7F94AB")
|
| 112 |
+
if v > 0:
|
| 113 |
+
rect(gx + 2, y + bh - v * bh, gw - 4, v * bh, fill=col)
|
| 114 |
+
dcol = TEAL if noise < 0.99 else GREY
|
| 115 |
+
circle(gx + gw / 2, y + bh + 9, 3.6, dcol if det[g] else "white", stroke=dcol, sw=1.0)
|
| 116 |
+
if tag:
|
| 117 |
+
t(x + n * gw / 2, y - 10, tag, size=6.5, anchor="middle", color=INK)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def arrow_defs():
|
| 121 |
+
parts.append('<defs>')
|
| 122 |
+
for name, col in (("a-ink", INK), ("a-grey", LINE), ("a-gold", GOLD), ("a-slate", SLATE), ("a-purple", PURPLE),
|
| 123 |
+
("a-teal", TEAL)):
|
| 124 |
+
parts.append(f'<marker id="{name}" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6.5" markerHeight="6.5" '
|
| 125 |
+
f'orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="{col}"/></marker>')
|
| 126 |
+
parts.append('<pattern id="hatch" width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">'
|
| 127 |
+
f'<rect width="5" height="5" fill="{GREY_L}"/><line x1="0" y1="0" x2="0" y2="5" stroke="#B5B5B5" '
|
| 128 |
+
'stroke-width="1.6"/></pattern>')
|
| 129 |
+
parts.append('</defs>')
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def panel_a(summ):
|
| 133 |
+
letter(6, 24, "a")
|
| 134 |
+
header(32, 24, "Pretraining on pseudobulk")
|
| 135 |
+
# corpus cloud
|
| 136 |
+
cx, cy = 92, 150
|
| 137 |
+
cols = list(CT.values())
|
| 138 |
+
pts = rng.normal(size=(70, 2))
|
| 139 |
+
pts = pts / np.maximum(1, np.hypot(*pts.T) / 1.9)[:, None] * [26, 21] # keep inside the cloud
|
| 140 |
+
for i, (dx, dy) in enumerate(pts):
|
| 141 |
+
circle(cx + dx, cy + dy, 4.0, cols[i % 4])
|
| 142 |
+
t(cx, 76, "Blood scRNA-seq", size=6.5, anchor="middle")
|
| 143 |
+
t(cx, 222, f"{summ['cells'] / 1e6:.1f} M cells", size=7, weight="bold", anchor="middle")
|
| 144 |
+
t(cx, 240, f"{summ['datasets']} datasets", size=6.2, anchor="middle", color=SUB)
|
| 145 |
+
t(cx, 257, f"{summ['donors']:,} donors", size=6.2, anchor="middle", color=SUB)
|
| 146 |
+
# one sample: K cells x genes
|
| 147 |
+
x0, y0, cw, ch, nr, nc = 238, 98, 14, 12.5, 8, 10
|
| 148 |
+
unmeas = {3, 7}
|
| 149 |
+
line(160, 150, x0 - 10, 150, arrow="a-grey")
|
| 150 |
+
t((160 + x0 - 10) / 2, 140, "one sample", size=6, anchor="middle", color=SUB)
|
| 151 |
+
t(x0 + nc * cw / 2, 86, "K cells × genes", size=6.5, anchor="middle")
|
| 152 |
+
vals = rng.gamma(0.7, 0.5, size=(nr, nc)) * (rng.random((nr, nc)) > 0.45)
|
| 153 |
+
for r in range(nr):
|
| 154 |
+
for c in range(nc):
|
| 155 |
+
if c in unmeas:
|
| 156 |
+
hatch_rect(x0 + c * cw, y0 + r * ch, cw - 1.5, ch - 1.5)
|
| 157 |
+
else:
|
| 158 |
+
v = min(vals[r, c], 1.2) / 1.2
|
| 159 |
+
rect(x0 + c * cw, y0 + r * ch, cw - 1.5, ch - 1.5, fill=shade(BLUE, 0.08 + 0.85 * v))
|
| 160 |
+
hr = 4
|
| 161 |
+
rect(x0 - 2.5, y0 + hr * ch - 2.5, nc * cw + 2, ch + 2, stroke=INK, sw=1.6)
|
| 162 |
+
# sum -> bulk row, mask row
|
| 163 |
+
by = y0 + nr * ch + 24
|
| 164 |
+
path(f"M{x0 + nc * cw + 4},{y0 + nr * ch - 6} C{x0 + nc * cw + 22},{y0 + nr * ch + 4} "
|
| 165 |
+
f"{x0 + nc * cw + 22},{by - 2} {x0 + nc * cw + 6},{by + 5}", color=GOLD, sw=1.3, arrow="a-gold")
|
| 166 |
+
t(x0 + nc * cw + 26, y0 + nr * ch + 16, "Σ", size=8, color=GOLD, weight="bold")
|
| 167 |
+
bulk = vals.sum(0)
|
| 168 |
+
for c in range(nc):
|
| 169 |
+
if c in unmeas:
|
| 170 |
+
hatch_rect(x0 + c * cw, by, cw - 1.5, ch - 1.5)
|
| 171 |
+
else:
|
| 172 |
+
rect(x0 + c * cw, by, cw - 1.5, ch - 1.5, fill=shade(GOLD, 0.15 + 0.85 * bulk[c] / bulk.max()))
|
| 173 |
+
t(x0 - 8, by + 9, "bulk", size=6.5, color=GOLD, weight="bold", anchor="end")
|
| 174 |
+
my = by + ch + 5
|
| 175 |
+
for c in range(nc):
|
| 176 |
+
rect(x0 + c * cw, my, cw - 1.5, 5, fill=GREY_L if c in unmeas else "#6E6E6E")
|
| 177 |
+
t(x0 - 8, my + 6, "measured", size=6, color=SUB, anchor="end")
|
| 178 |
+
t(x0 + nc * cw / 2, my + 26, "K = 250–4,000 cells", size=6, anchor="middle", color=SUB)
|
| 179 |
+
# training pair: highlighted cell + its bulk -> model
|
| 180 |
+
px = x0 + nc * cw + 58
|
| 181 |
+
rect(px, 104, 98, 120, fill="#FAFAFA", stroke="#C8C8C8", sw=0.8, rx=6)
|
| 182 |
+
t(px + 49, 96, "training pair", size=6.3, anchor="middle")
|
| 183 |
+
t(px + 8, 124, "one cell", size=6, color=SUB)
|
| 184 |
+
for c in range(nc):
|
| 185 |
+
col = GREY_L if c in unmeas else shade(BLUE, 0.08 + 0.85 * min(vals[hr, c], 1.2) / 1.2)
|
| 186 |
+
rect(px + 8 + c * 8.2, 132, 7, 12, fill=col)
|
| 187 |
+
t(px + 49, 166, "+", size=8, anchor="middle", color=SUB)
|
| 188 |
+
t(px + 8, 186, "its own bulk", size=6, color=SUB)
|
| 189 |
+
for c in range(nc):
|
| 190 |
+
col = GREY_L if c in unmeas else shade(GOLD, 0.15 + 0.85 * bulk[c] / bulk.max())
|
| 191 |
+
rect(px + 8 + c * 8.2, 194, 7, 12, fill=col)
|
| 192 |
+
line(x0 + nc * cw + 2, y0 + hr * ch + ch / 2, px - 4, 138, color=INK, sw=1.1, arrow="a-ink")
|
| 193 |
+
t(20, 300, "Each cell is learned with the bulk of its own sample.", size=6.2, color=SUB)
|
| 194 |
+
t(20, 318, "The model never sees cell-type or disease labels.", size=6.2, color=SUB)
|
| 195 |
+
line(px + 100, 164, 548, 164, color=INK, sw=1.5, arrow="a-ink")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def panel_b():
|
| 199 |
+
bx = 562
|
| 200 |
+
letter(bx, 24, "b")
|
| 201 |
+
header(bx + 26, 24, "Diffusion on each gene’s value and detection")
|
| 202 |
+
n, gw = 10, 13
|
| 203 |
+
unmeas = {3, 7}
|
| 204 |
+
v0 = np.clip(rng.gamma(1.0, 0.35, n), 0, 1) * (rng.random(n) > 0.3)
|
| 205 |
+
d0 = v0 > 0
|
| 206 |
+
xs = [bx + 34, bx + 244, bx + 454]
|
| 207 |
+
gwid = n * gw
|
| 208 |
+
labs = [("clean cell x", "0"), ("noisy cell x", "t"), ("noise x", "T")]
|
| 209 |
+
for i, x in enumerate(xs):
|
| 210 |
+
frac = (0.0, 0.5, 1.0)[i]
|
| 211 |
+
if i == 0:
|
| 212 |
+
vals, det = v0, d0
|
| 213 |
+
else:
|
| 214 |
+
vals = np.clip((1 - frac) * v0 + frac * rng.random(n) * 0.9, 0.05, 1)
|
| 215 |
+
det = rng.random(n) > 0.5 if frac >= 0.99 else d0 | (rng.random(n) > 0.7)
|
| 216 |
+
cell_profile(x, 104, vals, det, unmeas, gw=gw, noise=frac)
|
| 217 |
+
ts(x + gwid / 2, 90, *labs[i], size=6.5, anchor="middle")
|
| 218 |
+
line(xs[0], 64, xs[2] + gwid, 64, color=GREY, sw=1.3, arrow="a-grey")
|
| 219 |
+
t((xs[0] + xs[2] + gwid) / 2, 56, "add noise (training)", size=6, anchor="middle", color=GREY)
|
| 220 |
+
line(xs[2] + gwid, 178, xs[0], 178, color=SLATE, sw=1.6, arrow="a-slate")
|
| 221 |
+
t((xs[0] + xs[2] + gwid) / 2, 194, "remove noise step by step (generation)", size=6, anchor="middle", color=SLATE)
|
| 222 |
+
# glyph legend
|
| 223 |
+
lx = bx + 646
|
| 224 |
+
rect(lx, 98, 10, 14, fill=BLUE)
|
| 225 |
+
t(lx + 16, 110, "expression value", size=6)
|
| 226 |
+
circle(lx + 5, 126, 3.6, TEAL, stroke=TEAL)
|
| 227 |
+
t(lx + 16, 130, "detected", size=6)
|
| 228 |
+
circle(lx + 5, 142, 3.6, "white", stroke=TEAL)
|
| 229 |
+
t(lx + 16, 146, "not detected (zero)", size=6)
|
| 230 |
+
hatch_rect(lx, 154, 10, 12)
|
| 231 |
+
t(lx + 16, 164, "gene not measured", size=6)
|
| 232 |
+
# inputs
|
| 233 |
+
iy, ix, iw, ih = 236, bx + 4, 148, 22
|
| 234 |
+
inputs = [(("noisy cell x", "t"), GREY, None), ("previous estimate", SLATE, "4,3"), ("time step t", GREY, None)]
|
| 235 |
+
dx0, dy0, dwid, dh = bx + 178, 226, 284, 92
|
| 236 |
+
for k, (lab, col, dash) in enumerate(inputs):
|
| 237 |
+
yy = iy + k * 28
|
| 238 |
+
rect(ix, yy, iw, ih, fill="white", stroke=col, sw=1.0, rx=5, dash=dash)
|
| 239 |
+
if isinstance(lab, tuple):
|
| 240 |
+
ts(ix + iw / 2, yy + 15, *lab, size=6, anchor="middle")
|
| 241 |
+
else:
|
| 242 |
+
t(ix + iw / 2, yy + 15, lab, size=6, anchor="middle")
|
| 243 |
+
line(ix + iw, yy + ih / 2, dx0 - 4, dy0 + 26 + k * 20, color=col, sw=1.1, arrow="a-grey")
|
| 244 |
+
# denoiser
|
| 245 |
+
rect(dx0, dy0, dwid, dh, fill=SLATE_L, stroke=SLATE, sw=1.2, rx=10)
|
| 246 |
+
t(dx0 + dwid / 2, dy0 - 8, "Denoiser", size=7, anchor="middle", weight="bold", color=SLATE)
|
| 247 |
+
nb, bw = 7, 20
|
| 248 |
+
gap = (dwid - 60 - nb * bw) / (nb - 1)
|
| 249 |
+
bxs = [dx0 + 30 + k * (bw + gap) for k in range(nb)]
|
| 250 |
+
for k, xx in enumerate(bxs):
|
| 251 |
+
rect(xx, dy0 + 30, bw, 50, fill=shade(SLATE, 0.55), rx=3)
|
| 252 |
+
for a, b in ((0, 6), (1, 5), (2, 4)):
|
| 253 |
+
xa, xb = bxs[a] + bw / 2, bxs[b] + bw / 2
|
| 254 |
+
lift = 8 + 5 * (3 - (b - a) // 2)
|
| 255 |
+
path(f"M{xa},{dy0 + 30} C{xa},{dy0 + 30 - lift - 8} {xb},{dy0 + 30 - lift - 8} {xb},{dy0 + 30}",
|
| 256 |
+
color=SLATE, sw=1.0)
|
| 257 |
+
# bulk condition into every block
|
| 258 |
+
cyb = dy0 + dh + 30
|
| 259 |
+
rect(ix, cyb - 13, iw, 26, fill="white", stroke=GOLD, sw=1.3, rx=5)
|
| 260 |
+
t(ix + iw / 2, cyb + 4, "bulk condition", size=6.3, anchor="middle", color=GOLD, weight="bold")
|
| 261 |
+
line(ix + iw, cyb, bxs[-1] + bw / 2, cyb, color=GOLD, sw=1.6)
|
| 262 |
+
for xx in bxs:
|
| 263 |
+
line(xx + bw / 2, cyb, xx + bw / 2, dy0 + dh - 8, color=GOLD, sw=1.0, arrow="a-gold")
|
| 264 |
+
t(ix, cyb + 30, "bulk expression, depth and measured genes: fixed per sample, enters every block",
|
| 265 |
+
size=5.9, color=SUB)
|
| 266 |
+
# two heads
|
| 267 |
+
hx = dx0 + dwid + 40
|
| 268 |
+
vals = np.clip(v0 + 0.15, 0, 1)
|
| 269 |
+
probs = np.clip(np.where(d0, 0.75, 0.2) + rng.normal(0, 0.1, n), 0.05, 0.95)
|
| 270 |
+
line(dx0 + dwid, dy0 + 40, hx - 6, dy0 + 22, color=SLATE, sw=1.3, arrow="a-slate")
|
| 271 |
+
line(dx0 + dwid, dy0 + 56, hx - 6, dy0 + 82, color=SLATE, sw=1.3, arrow="a-slate")
|
| 272 |
+
for g in range(n):
|
| 273 |
+
gx = hx + g * 11
|
| 274 |
+
if g in unmeas:
|
| 275 |
+
hatch_rect(gx + 1, dy0 + 2, 9, 40)
|
| 276 |
+
hatch_rect(gx + 1, dy0 + 64, 9, 40)
|
| 277 |
+
continue
|
| 278 |
+
rect(gx + 1, dy0 + 42 - vals[g] * 40, 9, vals[g] * 40, fill=BLUE)
|
| 279 |
+
rect(gx + 1, dy0 + 104 - probs[g] * 40, 9, probs[g] * 40, fill=TEAL)
|
| 280 |
+
t(hx + 55, dy0 - 8, "value", size=6.3, anchor="middle", color=BLUE)
|
| 281 |
+
t(hx + 55, dy0 + 122, "detection probability", size=6.3, anchor="middle", color=TEAL)
|
| 282 |
+
# read-out
|
| 283 |
+
ox = hx + 150
|
| 284 |
+
drawn = rng.random(n) < probs
|
| 285 |
+
out = np.where(drawn, vals, 0)
|
| 286 |
+
path(f"M{hx + 112},{dy0 + 84} C{ox - 14},{dy0 + 84} {ox - 14},{dy0 + 62} {ox - 2},{dy0 + 62}",
|
| 287 |
+
color=TEAL, sw=1.3, arrow="a-teal")
|
| 288 |
+
path(f"M{hx + 112},{dy0 + 22} C{ox - 14},{dy0 + 22} {ox - 14},{dy0 + 44} {ox - 2},{dy0 + 44}",
|
| 289 |
+
color=BLUE, sw=1.3, arrow="a-ink")
|
| 290 |
+
t(ox + 55, dy0 - 8, "generated cell", size=6.3, anchor="middle", weight="bold")
|
| 291 |
+
for g in range(n):
|
| 292 |
+
gx = ox + g * 11
|
| 293 |
+
if g in unmeas:
|
| 294 |
+
hatch_rect(gx + 1, dy0 + 32, 9, 40)
|
| 295 |
+
continue
|
| 296 |
+
if out[g] > 0:
|
| 297 |
+
rect(gx + 1, dy0 + 72 - out[g] * 40, 9, out[g] * 40, fill=BLUE)
|
| 298 |
+
else:
|
| 299 |
+
t(gx + 5.5, dy0 + 70, "0", size=5.2, anchor="middle", color=SUB)
|
| 300 |
+
t(ox, dy0 + 94, "detection drawn from", size=5.9, color=SUB)
|
| 301 |
+
t(ox, dy0 + 109, "its probability; exact", size=5.9, color=SUB)
|
| 302 |
+
t(ox, dy0 + 124, "zeros elsewhere", size=5.9, color=SUB)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def panel_c(top):
|
| 306 |
+
letter(6, top + 24, "c")
|
| 307 |
+
header(32, top + 24, "From a measured bulk to single cells")
|
| 308 |
+
y = top + 44
|
| 309 |
+
# blood tube and bulk profile
|
| 310 |
+
tx, ty = 58, y + 52
|
| 311 |
+
rect(tx, ty, 22, 70, fill="white", stroke=INK, sw=1.2, rx=9)
|
| 312 |
+
rect(tx + 1.5, ty + 30, 19, 38, fill="#B5544F", rx=8)
|
| 313 |
+
rect(tx - 3, ty - 6, 28, 10, fill="#6E6E6E", rx=2)
|
| 314 |
+
t(tx + 11, ty + 92, "blood sample,", size=6, anchor="middle", color=SUB)
|
| 315 |
+
t(tx + 11, ty + 107, "bulk RNA-seq", size=6, anchor="middle", color=SUB)
|
| 316 |
+
bx0, by0, nc, cw = 112, y + 84, 10, 11
|
| 317 |
+
unmeas = {2, 8}
|
| 318 |
+
line(tx + 26, ty + 40, bx0 - 6, by0 + 6, color=GREY, sw=1.2, arrow="a-grey")
|
| 319 |
+
bulk = rng.gamma(1.2, 1.0, nc)
|
| 320 |
+
for c in range(nc):
|
| 321 |
+
if c in unmeas:
|
| 322 |
+
hatch_rect(bx0 + c * cw, by0, cw - 1.5, 12)
|
| 323 |
+
else:
|
| 324 |
+
rect(bx0 + c * cw, by0, cw - 1.5, 12, fill=shade(GOLD, 0.2 + 0.8 * bulk[c] / bulk.max()))
|
| 325 |
+
rect(bx0 + c * cw, by0 + 17, cw - 1.5, 5, fill=GREY_L if c in unmeas else "#6E6E6E")
|
| 326 |
+
t(bx0 + nc * cw / 2, by0 - 10, "bulk profile", size=6.3, anchor="middle", color=GOLD, weight="bold")
|
| 327 |
+
# optional adaptation
|
| 328 |
+
ax0, ay0, aw, ah = 262, y + 6, 196, 84
|
| 329 |
+
rect(ax0, ay0, aw, ah, fill="white", stroke=PURPLE, sw=1.2, rx=8, dash="5,4")
|
| 330 |
+
t(ax0 + aw / 2, ay0 + 19, "Optional: adapt", size=6.3, anchor="middle", color=PURPLE, weight="bold")
|
| 331 |
+
t(ax0 + aw / 2, ay0 + 37, "a few paired bulk +", size=6, anchor="middle")
|
| 332 |
+
t(ax0 + aw / 2, ay0 + 52, "single-cell samples", size=6, anchor="middle")
|
| 333 |
+
t(ax0 + aw / 2, ay0 + 70, "low-rank update, minutes", size=6, anchor="middle", color=SUB)
|
| 334 |
+
# model with K noise draws
|
| 335 |
+
mx0, my0, mw, mh = 470, y + 110, 160, 74
|
| 336 |
+
rect(mx0, my0, mw, mh, fill=SLATE_L, stroke=SLATE, sw=1.2, rx=10)
|
| 337 |
+
for k in range(5):
|
| 338 |
+
rect(mx0 + 28 + k * 22, my0 + 32, 14, 32, fill=shade(SLATE, 0.55), rx=2)
|
| 339 |
+
t(mx0 + mw / 2, my0 + 20, "pretrained model", size=6.5, anchor="middle", color=SLATE, weight="bold")
|
| 340 |
+
nx = mx0 + 16
|
| 341 |
+
for k in range(3):
|
| 342 |
+
for g in range(8):
|
| 343 |
+
v = rng.random()
|
| 344 |
+
rect(nx + k * 44 + g * 4.4, y + 44 + (1 - v) * 18, 3.4, v * 18, fill=GREY)
|
| 345 |
+
t(nx + 134, y + 58, "…", size=7, color=SUB)
|
| 346 |
+
t(mx0 + mw / 2, y + 30, "K noise draws", size=6.3, anchor="middle", color=SUB)
|
| 347 |
+
line(mx0 + mw / 2, y + 68, mx0 + mw / 2, my0 - 4, color=GREY, sw=1.2, arrow="a-grey")
|
| 348 |
+
path(f"M{ax0 + aw / 2},{ay0 + ah + 2} C{ax0 + aw / 2},{my0 + 20} {mx0 - 40},{my0 + 22} {mx0 - 4},{my0 + 22}",
|
| 349 |
+
color=PURPLE, sw=1.2, dash="5,4", arrow="a-purple")
|
| 350 |
+
line(bx0 + nc * cw + 4, by0 + 8, mx0 - 4, my0 + 54, color=GOLD, sw=1.6, arrow="a-gold")
|
| 351 |
+
t(300, my0 + 84, "one shared condition", size=6, anchor="middle", color=GOLD)
|
| 352 |
+
# generated cells
|
| 353 |
+
gx0, gy0 = 776, my0 + 34
|
| 354 |
+
line(mx0 + mw + 4, my0 + mh / 2, gx0 - 84, gy0, color=SLATE, sw=1.6, arrow="a-slate")
|
| 355 |
+
centers = {"T": ("T cell", -28, -22, 26), "Mono": ("Monocyte", 44, 14, 16), "B": ("B cell", -6, 40, 9),
|
| 356 |
+
"NK": ("NK cell", -58, 18, 9)}
|
| 357 |
+
for short, (lab, ox, oy, n) in centers.items():
|
| 358 |
+
pts = rng.normal(size=(n, 2)) * [12, 9]
|
| 359 |
+
for dx, dy in pts:
|
| 360 |
+
circle(gx0 + ox + dx, gy0 + oy + dy, 3.5, CT[lab])
|
| 361 |
+
for short, (lx, ly) in {"T": (-28, -48), "Mono": (44, -10), "B": (24, 58), "NK": (-80, 46)}.items():
|
| 362 |
+
t(gx0 + lx, gy0 + ly, short, size=6, anchor="middle", color=SUB)
|
| 363 |
+
t(gx0, y + 30, "K generated cells", size=6.5, anchor="middle", weight="bold")
|
| 364 |
+
t(gx0, y + 46, "labelled after generation", size=6, anchor="middle", color=SUB)
|
| 365 |
+
fy = my0 + mh + 64
|
| 366 |
+
path(f"M{gx0},{gy0 + 62} C{gx0},{fy} {gx0 - 80},{fy} {gx0 - 200},{fy} L{bx0 + 120},{fy} "
|
| 367 |
+
f"C{bx0 + 60},{fy} {bx0 + 60},{fy - 20} {bx0 + 60},{by0 + 30}", color=GREY, sw=1.0, dash="4,4",
|
| 368 |
+
arrow="a-grey")
|
| 369 |
+
t((gx0 + bx0) / 2, fy + 18, "summed cells are compared with the bulk, not forced to match; no cell-type quotas",
|
| 370 |
+
size=5.9, anchor="middle", color=SUB)
|
| 371 |
+
# uses
|
| 372 |
+
ux, bw_, bh_ = 920, 158, 150
|
| 373 |
+
line(gx0 + 96, gy0, ux - 8, gy0, color=INK, sw=1.4, arrow="a-ink")
|
| 374 |
+
for i, ttl in enumerate(["Composition", "Cell-type effects", "Rare subsets"]):
|
| 375 |
+
px0 = ux + i * (bw_ + 18)
|
| 376 |
+
rect(px0, y + 40, bw_, bh_, fill="#FAFAFA", stroke="#D0D0D0", sw=0.8, rx=6)
|
| 377 |
+
t(px0 + bw_ / 2, y + 30, ttl, size=6.5, anchor="middle")
|
| 378 |
+
order = ["T cell", "NK cell", "B cell", "Monocyte"]
|
| 379 |
+
for s in range(4):
|
| 380 |
+
sh = rng.dirichlet([6, 1.5, 1.5, 3])
|
| 381 |
+
bot = y + 160
|
| 382 |
+
for k, lab in enumerate(order):
|
| 383 |
+
hgt = sh[k] * 104
|
| 384 |
+
rect(ux + 22 + s * 32, bot - hgt, 22, hgt, fill=CT[lab])
|
| 385 |
+
bot -= hgt
|
| 386 |
+
t(ux + bw_ / 2, y + 178, "samples", size=5.8, anchor="middle", color=SUB)
|
| 387 |
+
sx0, sy0 = ux + bw_ + 18 + 26, y + 160
|
| 388 |
+
line(sx0, sy0, sx0 + 118, sy0, color=LINE, sw=0.9)
|
| 389 |
+
line(sx0, sy0, sx0, sy0 - 108, color=LINE, sw=0.9)
|
| 390 |
+
line(sx0 + 6, sy0 - 6, sx0 + 110, sy0 - 102, color="#B0B0B0", sw=0.9, dash="3,3")
|
| 391 |
+
xx = rng.normal(0, 1, 26)
|
| 392 |
+
yy = 0.8 * xx + rng.normal(0, 0.45, 26)
|
| 393 |
+
for a, b in zip(xx, yy):
|
| 394 |
+
circle(sx0 + 58 + a * 20, sy0 - 54 - b * 20, 2.7, CT["Monocyte"])
|
| 395 |
+
t(sx0 + 58, sy0 + 14, "observed", size=5.8, anchor="middle", color=SUB)
|
| 396 |
+
t(sx0 - 10, sy0 - 54, "generated", size=5.8, anchor="middle", color=SUB,
|
| 397 |
+
extra=f'transform="rotate(-90 {sx0 - 10} {sy0 - 54})"')
|
| 398 |
+
cx0, cy0 = ux + 2 * (bw_ + 18) + bw_ / 2, y + 108
|
| 399 |
+
for dx, dy in rng.normal(size=(40, 2)) * [26, 18]:
|
| 400 |
+
circle(cx0 + dx, cy0 + dy, 2.9, shade(CT["Monocyte"], 0.45))
|
| 401 |
+
for dx, dy in rng.normal(size=(9, 2)) * [7, 6] + [24, -18]:
|
| 402 |
+
circle(cx0 + dx, cy0 + dy, 2.9, "#B5544F")
|
| 403 |
+
parts.append(f'<ellipse cx="{cx0 + 24}" cy="{cy0 - 18}" rx="21" ry="16" fill="none" stroke="#B5544F" '
|
| 404 |
+
'stroke-width="1.1" stroke-dasharray="3,2"/>')
|
| 405 |
+
t(cx0, y + 164, "e.g. C1Q-high", size=5.8, anchor="middle", color=SUB)
|
| 406 |
+
t(cx0, y + 178, "monocytes", size=5.8, anchor="middle", color=SUB)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def main() -> int:
|
| 410 |
+
summ = json.loads((ROOT / "source_data/corpus/corpus_summary.json").read_text())
|
| 411 |
+
parts.append(f'<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" '
|
| 412 |
+
f'width="{W / U:g}mm" height="{H / U:g}mm" viewBox="0 0 {W} {H}" role="img">')
|
| 413 |
+
parts.append("<title>PBISC-Diffusion overview: pretraining, gene-space diffusion, generation from bulk</title>")
|
| 414 |
+
arrow_defs()
|
| 415 |
+
rect(0, 0, W, H, fill="white")
|
| 416 |
+
panel_a(summ)
|
| 417 |
+
panel_b()
|
| 418 |
+
line(10, 418, W - 10, 418, color="#E2E2E2", sw=1.0)
|
| 419 |
+
panel_c(424)
|
| 420 |
+
parts.append("</svg>")
|
| 421 |
+
OUT.write_text("\n".join(parts) + "\n", encoding="utf-8")
|
| 422 |
+
pdf, png = OUT.with_suffix(".pdf"), OUT.with_suffix(".png")
|
| 423 |
+
cairosvg.svg2pdf(url=str(OUT), write_to=str(pdf))
|
| 424 |
+
cairosvg.svg2png(url=str(OUT), write_to=str(png), output_width=2126)
|
| 425 |
+
rec = {"source_svg": str(OUT.relative_to(ROOT)), "canvas_mm": [W / U, H / U],
|
| 426 |
+
"outputs": {p.suffix: hashlib.sha256(p.read_bytes()).hexdigest() for p in (OUT, pdf, png)},
|
| 427 |
+
"data": "schematic; corpus numbers from source_data/corpus/corpus_summary.json",
|
| 428 |
+
"plan": "editorial/fig1_nature_redesign_plan_20261006.md"}
|
| 429 |
+
OUT.with_suffix(".provenance.json").write_text(json.dumps(rec, indent=1) + "\n")
|
| 430 |
+
print(json.dumps(rec, indent=1))
|
| 431 |
+
return 0
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
if __name__ == "__main__":
|
| 435 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/dataset/server_1/manuscript/scripts/corpus/build_figure1_corpus.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.3, 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.3, 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.3, 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.3)
|
| 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", "Hematologic": "#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, nature=False):
|
| 304 |
+
"""Fig. 1 strip: assay shares, disease-family shares per assay, L1 cell-type shares.
|
| 305 |
+
nature=True: the variant under the Nature-style overview (panel d; a-c carry the corpus size, so the title names
|
| 306 |
+
the content only and is set bold like the a-c headers)"""
|
| 307 |
+
summ, D, G, C, conds, total = load()
|
| 308 |
+
fam = summ["condition_family"]
|
| 309 |
+
W, H = 180, 38
|
| 310 |
+
fig = plt.figure(figsize=(W * MM, H * MM))
|
| 311 |
+
fs, fsl = 7.2, 6.8
|
| 312 |
+
letter(fig, 0.0, 0.96, L[0])
|
| 313 |
+
if nature:
|
| 314 |
+
fig.text(0.03, 0.96, "Pretraining corpus: assays, conditions and cell types", fontsize=7.5, va="top",
|
| 315 |
+
fontweight="bold")
|
| 316 |
+
else:
|
| 317 |
+
fig.text(0.03, 0.96, f"Pretraining corpus: {total / 1e6:.1f} million cells from {summ['datasets']} datasets, "
|
| 318 |
+
f"{summ['donors']:,} donors and {summ['samples']:,} samples", fontsize=8.2, va="top")
|
| 319 |
+
G = G.assign(group=G.assay.map(lambda a: ASSAY_GROUP.get(a, "Other")), family=G.condition.map(fam))
|
| 320 |
+
A = G.groupby(["group", "family"]).n_cells.sum().unstack(fill_value=0)
|
| 321 |
+
order = A.drop(index=["Other"], errors="ignore").sum(1).sort_values(ascending=False).index.tolist()
|
| 322 |
+
A = A.loc[order + (["Other"] if "Other" in A.index else [])]
|
| 323 |
+
fams = [f for f in FAMILY_COLOR if f in A.columns]
|
| 324 |
+
share = A.sum(1) / total
|
| 325 |
+
n = len(A)
|
| 326 |
+
top, bot = 0.76, 0.32
|
| 327 |
+
ax_a = fig.add_axes([0.105, bot, 0.06, top - bot])
|
| 328 |
+
ax_a.barh(np.arange(n), share.values, 0.8, color=LIGHT)
|
| 329 |
+
ax_a.set_ylim(n - 0.5, -0.5)
|
| 330 |
+
ax_a.set_xlim(0, 1)
|
| 331 |
+
strip(ax_a)
|
| 332 |
+
fig.text(0.105, top + 0.035, "Assay", fontsize=fsl, va="bottom")
|
| 333 |
+
for i, (lab, sh) in enumerate(share.items()):
|
| 334 |
+
ax_a.text(-0.05, i, lab, ha="right", va="center", fontsize=fsl, transform=ax_a.get_yaxis_transform())
|
| 335 |
+
ax_a.text(sh + 0.04, i, pct(sh), va="center", fontsize=fsl - 0.6, color=SUB)
|
| 336 |
+
ax_c = fig.add_axes([0.215, bot, 0.40, top - bot])
|
| 337 |
+
ax_c.set_xlim(0, 1)
|
| 338 |
+
ax_c.set_ylim(n - 0.5, -0.5)
|
| 339 |
+
for i, (lab, row) in enumerate(A.iterrows()):
|
| 340 |
+
left, tot = 0.0, row.sum()
|
| 341 |
+
for f in fams:
|
| 342 |
+
w = row.get(f, 0) / tot
|
| 343 |
+
if w <= 0:
|
| 344 |
+
continue
|
| 345 |
+
ax_c.barh(i, w, 0.8, left=left, color=FAMILY_COLOR[f], edgecolor="white", linewidth=0.4)
|
| 346 |
+
seg_mm = w * 0.40 * W
|
| 347 |
+
if seg_mm > 1.35 * len(f) + 3: # label only segments wide enough for it
|
| 348 |
+
ax_c.text(left + w / 2, i, f, ha="center", va="center", fontsize=fsl - 1.2,
|
| 349 |
+
color=INK if f == "Healthy" else "white")
|
| 350 |
+
left += w
|
| 351 |
+
strip(ax_c)
|
| 352 |
+
fig.text(0.215, top + 0.035, "Condition proportions", fontsize=fsl, va="bottom")
|
| 353 |
+
x, y, rend = 0.215, 0.19, fig.canvas.get_renderer()
|
| 354 |
+
for f in fams: # two legend rows, kept left of the cell-type ring
|
| 355 |
+
sh = G[G.family == f].n_cells.sum() / total
|
| 356 |
+
r = Rectangle((x, y - 0.03), 0.009, 0.06, transform=fig.transFigure, color=FAMILY_COLOR[f])
|
| 357 |
+
t = fig.text(x + 0.013, y, f"{f} {pct(sh)}", fontsize=fsl - 0.6, va="center")
|
| 358 |
+
bb = t.get_window_extent(renderer=rend).transformed(fig.transFigure.inverted())
|
| 359 |
+
if bb.x1 > 0.615:
|
| 360 |
+
x, y = 0.215, y - 0.12
|
| 361 |
+
r.set_xy((x, y - 0.03))
|
| 362 |
+
t.set_position((x + 0.013, y))
|
| 363 |
+
bb = t.get_window_extent(renderer=rend).transformed(fig.transFigure.inverted())
|
| 364 |
+
fig.patches.append(r)
|
| 365 |
+
x = bb.x1 + 0.018
|
| 366 |
+
# cell types
|
| 367 |
+
l1 = C.groupby("l1").n_cells.sum()
|
| 368 |
+
show = l1.reindex(L1_SHOW)
|
| 369 |
+
rest = total - show.sum()
|
| 370 |
+
vals = list(show.values) + [rest]
|
| 371 |
+
keys = L1_SHOW + ["Other"]
|
| 372 |
+
ax_d = fig.add_axes([0.645, 0.02, 0.14, 0.84])
|
| 373 |
+
ax_d.pie(vals, colors=[L1_COLOR[k] for k in keys], startangle=90, counterclock=False,
|
| 374 |
+
wedgeprops={"width": 0.36, "linewidth": 0.6, "edgecolor": "white"})
|
| 375 |
+
ax_d.set_aspect("equal")
|
| 376 |
+
ax_d.text(0, 0, "Cell\ntypes", ha="center", va="center", fontsize=fsl)
|
| 377 |
+
for j, (k, v) in enumerate(zip(keys, vals)):
|
| 378 |
+
y = 0.80 - j * 0.118
|
| 379 |
+
fig.patches.append(Rectangle((0.80, y - 0.03), 0.009, 0.06, transform=fig.transFigure, color=L1_COLOR[k]))
|
| 380 |
+
fig.text(0.813, y, k.replace("Progenitor cell", "Progenitor"), fontsize=fsl, va="center")
|
| 381 |
+
fig.text(0.995, y, pct(v / total), fontsize=fsl, va="center", ha="right", color=SUB)
|
| 382 |
+
return fig, (W, H), {L[0]: "pretraining corpus: assay, condition family and L1 cell-type shares"}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def save(fig, stem, canvas, panels, note):
|
| 386 |
+
out = {}
|
| 387 |
+
for ext in ("pdf", "png", "svg"):
|
| 388 |
+
p = FIG / f"{stem}.{ext}"
|
| 389 |
+
fig.savefig(p, dpi=300 if ext == "png" else None)
|
| 390 |
+
out[ext] = {"path": str(p.relative_to(MS)), "sha256": hashlib.sha256(p.read_bytes()).hexdigest()}
|
| 391 |
+
prov = {"script": "scripts/corpus/build_figure1_corpus.py", "canvas_mm": list(canvas), "panels": panels,
|
| 392 |
+
"inputs": {f.name: hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(SRC.glob("*.csv"))
|
| 393 |
+
+ [SRC / "corpus_summary.json"]},
|
| 394 |
+
"outputs": out, "note": note,
|
| 395 |
+
"scope": "Rendering only; every value is read from source_data/corpus/ (build_corpus_tables.py)."}
|
| 396 |
+
(FIG / f"{stem}.provenance.json").write_text(json.dumps(prov, indent=1) + "\n")
|
| 397 |
+
plt.close(fig)
|
| 398 |
+
print(stem, canvas)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def main() -> int:
|
| 402 |
+
ap = argparse.ArgumentParser()
|
| 403 |
+
a = ap.parse_args()
|
| 404 |
+
abc = string.ascii_lowercase
|
| 405 |
+
fig, canvas, panels = draw_compact(abc[abc.index("c"):])
|
| 406 |
+
save(fig, "fig01_corpus", canvas, panels, "Fig. 1c strip under the current fig01_architecture (a-b); 180 mm")
|
| 407 |
+
with plt.rc_context({"font.family": "Arial"}): # the Nature-style overview is set in Arial
|
| 408 |
+
fig, canvas, panels = draw_compact(abc[abc.index("d"):], nature=True)
|
| 409 |
+
save(fig, "fig01_corpus_nature", canvas, panels, "Fig. 1d strip under fig01_architecture_nature (a-c); 180 mm")
|
| 410 |
+
fig, canvas, panels = draw_full(abc)
|
| 411 |
+
save(fig, "figS_corpus", canvas, panels, "Supplementary: detailed corpus description")
|
| 412 |
+
return 0
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
if __name__ == "__main__":
|
| 416 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/metadata/inference_locations.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"locations": [],
|
| 3 |
+
"project_id": "pbisc-diffusion",
|
| 4 |
+
"update_id": "20261006T133650Z-fig1-nature-style-candidate"
|
| 5 |
+
}
|
paper-releases/pbisc-diffusion/updates/20261006T133650Z-fig1-nature-style-candidate/diffusion/metadata/request.json
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"assets": [
|
| 3 |
+
{
|
| 4 |
+
"host": "server_1",
|
| 5 |
+
"kind": "document",
|
| 6 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/editorial/fig1_nature_redesign_plan_20261006.md",
|
| 7 |
+
"state": "completed"
|
| 8 |
+
},
|
| 9 |
+
{
|
| 10 |
+
"host": "server_1",
|
| 11 |
+
"kind": "figure",
|
| 12 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/drafts/fig01_nature_preview_20261006.png",
|
| 13 |
+
"state": "completed"
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"host": "server_1",
|
| 17 |
+
"kind": "figure",
|
| 18 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_architecture_nature.pdf",
|
| 19 |
+
"state": "completed"
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"host": "server_1",
|
| 23 |
+
"kind": "figure",
|
| 24 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_architecture_nature.png",
|
| 25 |
+
"state": "completed"
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"host": "server_1",
|
| 29 |
+
"kind": "config",
|
| 30 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_architecture_nature.provenance.json",
|
| 31 |
+
"state": "completed"
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"host": "server_1",
|
| 35 |
+
"kind": "figure",
|
| 36 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_architecture_nature.svg",
|
| 37 |
+
"state": "completed"
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"host": "server_1",
|
| 41 |
+
"kind": "figure",
|
| 42 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus.pdf",
|
| 43 |
+
"state": "completed"
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"host": "server_1",
|
| 47 |
+
"kind": "figure",
|
| 48 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus.png",
|
| 49 |
+
"state": "completed"
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"host": "server_1",
|
| 53 |
+
"kind": "config",
|
| 54 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus.provenance.json",
|
| 55 |
+
"state": "completed"
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"host": "server_1",
|
| 59 |
+
"kind": "figure",
|
| 60 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus.svg",
|
| 61 |
+
"state": "completed"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"host": "server_1",
|
| 65 |
+
"kind": "figure",
|
| 66 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus_nature.pdf",
|
| 67 |
+
"state": "completed"
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"host": "server_1",
|
| 71 |
+
"kind": "figure",
|
| 72 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus_nature.png",
|
| 73 |
+
"state": "completed"
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"host": "server_1",
|
| 77 |
+
"kind": "config",
|
| 78 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus_nature.provenance.json",
|
| 79 |
+
"state": "completed"
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"host": "server_1",
|
| 83 |
+
"kind": "figure",
|
| 84 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/fig01_corpus_nature.svg",
|
| 85 |
+
"state": "completed"
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"host": "server_1",
|
| 89 |
+
"kind": "figure",
|
| 90 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/figS_corpus.pdf",
|
| 91 |
+
"state": "completed"
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"host": "server_1",
|
| 95 |
+
"kind": "figure",
|
| 96 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/figS_corpus.png",
|
| 97 |
+
"state": "completed"
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"host": "server_1",
|
| 101 |
+
"kind": "config",
|
| 102 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/figS_corpus.provenance.json",
|
| 103 |
+
"state": "completed"
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"host": "server_1",
|
| 107 |
+
"kind": "figure",
|
| 108 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/figures/figS_corpus.svg",
|
| 109 |
+
"state": "completed"
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"host": "server_1",
|
| 113 |
+
"kind": "code",
|
| 114 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/scripts/build_figure1_architecture_nature.py",
|
| 115 |
+
"state": "completed"
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"host": "server_1",
|
| 119 |
+
"kind": "code",
|
| 120 |
+
"source": "/home/sj_server_1/PBISC/paper-release-20260928/manuscript/scripts/corpus/build_figure1_corpus.py",
|
| 121 |
+
"state": "completed"
|
| 122 |
+
}
|
| 123 |
+
],
|
| 124 |
+
"inference_locations": [],
|
| 125 |
+
"project_id": "pbisc-diffusion",
|
| 126 |
+
"summary": "Candidate Nature-style Figure 1 (not yet in the manuscript): plan from six Nature-family Fig. 1 overviews (editorial/fig1_nature_redesign_plan_20261006.md); new SVG master fig01_architecture_nature (a pretraining on pseudobulk, b diffusion on each gene's value and detection with the drawn read-out, c from a measured bulk to cells with optional few-pair low-rank adaptation and uses), Arial, 180 x 95 mm, schematic with corpus numbers from corpus_summary.json; panel-d strip variant fig01_corpus_nature; preview in figures/drafts. The current fig01_corpus (panel c) and overview_figure.tex are unchanged."
|
| 127 |
+
}
|