Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **R's labelled PBMC 3k UMAP, `r_11_umap_labeled.png`.** `pbmc3k_verify.R` drew no
UMAP, so there was no R panel from the same run to set beside Truecell's
`11_umap_labeled.png`. It now draws one, for the Frontiers paper's Figure 3A/B.
It uses the same title and size, and the cell types in Truecell's order,
radix-sorted so the locale cannot reorder them: under `en_US.UTF-8`, R's default
sort puts "Naive CD4 T" before "NK", which would have swapped two colours. The
tutorial page keeps the published vignette's image on R's side, and the PBMC 3k
comparison's numbers do not change.

### Fixed

- **The CITE-seq tutorial's ADT-weight violins read as one comparison.** Reviewer 2
of the Frontiers paper found R's and Truecell's panels of figure 10 in different
orders and colours, which defeats a side-by-side. Both scripts now draw the cell
types in one order, `vln_plot`'s, and colour each from Seurat's `hue_pal` over
all twelve labels `annotate_cells` can return. The DC / Mono cluster that only R's
clustering finds therefore moves no other colour. Neither draws points, the R
script adds the median bar `vln_plot` draws, and the titles and y-axis labels
match. The CITE-seq comparison's numbers do not change.
- R also writes `r_10_adt_weight_by_celltype_manuscript.png`, laid out 3.30 in
wide as the paper prints it, with its type at the sizes Truecell's panel prints
at. With Seurat's defaults at that width the y-axis labels overprinted.
- `tests/test_multimodal_tutorial.py` keeps the two scripts' label lists equal,
and the smoke suite checks the figure's layout at the width the paper uses.

## [2.0.0] - 2026-09-18

The release the Frontiers revision asked for. Re-running the paper against 1.2.0
Expand Down
117 changes: 114 additions & 3 deletions tests/test_multimodal_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
annotate_cells(), the run_wnn() joint-clustering flow, and the figures the
walkthrough's Step 8 embeds. Network-free.
"""
import ast
import json
import re
import sys
from pathlib import Path

Expand All @@ -24,9 +26,12 @@
normalize_data, find_variable_features, scale_data,
)
from truecell.reduction import run_pca # noqa: E402
from truecell.plotting import dim_plot, vln_plot # noqa: E402
from tutorials.cbmc_citeseq_tutorial import annotate_cells, run_wnn # noqa: E402
from tutorials.generate_multimodal_plots import _group_panel # noqa: E402
from truecell.plotting import dim_plot, hue_pal, vln_plot # noqa: E402
from truecell._utils import ident_sort_key
from tutorials.cbmc_citeseq_tutorial import CELL_TYPES, annotate_cells, run_wnn # noqa: E402
from tutorials.generate_multimodal_plots import _group_panel, adt_weight_violins # noqa: E402

TUTORIALS = Path(__file__).resolve().parent.parent / "tutorials"


def _two_assay_object(rna_levels, adt_levels, n=6):
Expand Down Expand Up @@ -208,6 +213,112 @@ def test_group_panel_colours_labels_consistently():
plt.close(fig)


# ---------------------------------------------------------------------------
# Figure 10 is an R | Truecell pair
# ---------------------------------------------------------------------------
# Reviewer 2 of the Frontiers paper found R's and Truecell's ADT-weight violins
# in different orders and colours. Both scripts now take both from CELL_TYPES.

def _strings(node):
return {c.value for c in ast.walk(node)
if isinstance(c, ast.Constant) and isinstance(c.value, str)}


def _python_labels():
"""Every label the Python annotate_cells can return, read from its source."""
import tutorials.cbmc_citeseq_tutorial as tutorial

tree = ast.parse(Path(tutorial.__file__).read_text())
func = next(node for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef) and node.name == "annotate_cells")
labels = set(tutorial._RNA_FALLBACK)
for node in ast.walk(func):
if not isinstance(node, ast.Assign):
continue
target = node.targets[0]
# assignment[c] = "B", or = "CD8 T" if cd8 > 1.0 else "CD4 T"
if isinstance(target, ast.Subscript) and getattr(target.value, "id", None) == "assignment":
labels |= _strings(node.value)
# rna_fallback's default: best, best_score = "Other", 0.30
if isinstance(target, ast.Tuple) and any(getattr(e, "id", None) == "best"
for e in target.elts):
labels |= _strings(node.value)
return labels


def _r_source():
return (TUTORIALS / "cbmc_citeseq_verify.R").read_text()


def _r_labels():
"""Every label the R port of annotate_cells can return, read from its source."""
text = _r_source()
fallback = text[text.index("RNA_FALLBACK <- list("):text.index("annotate_cells <- function")]
labels = set(re.findall(r"(\w+) = c\(", fallback))
for line in text.splitlines():
if "assignment[c] <-" in line: # the gene names sit left of the arrow
labels |= set(re.findall(r'"([^"]+)"', line.split("assignment[c] <-", 1)[1]))
return labels | set(re.findall(r'best <- "([^"]+)"', text))


def test_both_scripts_draw_the_violins_from_one_list():
"""R keeps its own copy of CELL_TYPES, since it cannot import Python's. A copy
edited on one side only would put the two panels out of step again."""
text = _r_source()
block = text[text.index("CELL_TYPES <- c("):]
assert re.findall(r'"([^"]+)"', block[:block.index(")")]) == list(CELL_TYPES)


def test_the_list_is_in_the_order_vln_plot_draws_groups():
"""vln_plot sorts its groups and matches the palette to them by position, and
R draws in the list's order, so the list has to be vln_plot's order already."""
assert list(CELL_TYPES) == sorted(CELL_TYPES, key=ident_sort_key)
assert len(set(CELL_TYPES)) == len(CELL_TYPES)


def test_the_list_is_every_label_annotate_cells_can_return():
"""The colours are spread over the whole list, so a type one side lacks keeps
its slot. A label missing from it would stop the R script, and one that
annotate_cells can no longer return would shift every colour after it."""
assert _python_labels() == set(CELL_TYPES)
assert _r_labels() == set(CELL_TYPES)


def _weights_by_type(labels, seed=0):
rng = np.random.default_rng(seed)
obj = create_truecell_object(
counts=sp.csc_matrix(rng.poisson(2.0, size=(5, len(labels))).astype(float)),
feature_names=[f"g{i}" for i in range(5)],
cell_names=[f"c{i}" for i in range(len(labels))])
obj.meta_data["protein_celltype"] = labels
obj.meta_data["ADT.weight"] = rng.uniform(0.0, 1.0, size=len(labels))
return obj


def test_adt_weight_violins_keep_each_type_in_its_colour_slot():
"""Three of the twelve types: drawn in list order, each in the colour its place
in the whole list gives it, with no points and the paired titles."""
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex

fig = adt_weight_violins(_weights_by_type(["pDC", "B", "NK"] * 10))
ax = fig.axes[0]
present = ["B", "NK", "pDC"]
assert [t.get_text() for t in ax.get_xticklabels()] == present
# One filled violin per type and nothing else: points would add collections.
palette = hue_pal(len(CELL_TYPES))
assert [to_hex(c.get_facecolor()[0]) for c in ax.collections] == \
[palette[CELL_TYPES.index(g)].lower() for g in present]
assert ax.get_title() == "ADT weight by cell type"
assert ax.get_ylabel() == "ADT weight"
plt.close(fig)


def test_adt_weight_violins_refuse_a_type_outside_the_list():
with pytest.raises(ValueError, match="Mystery"):
adt_weight_violins(_weights_by_type(["B", "Mystery"] * 10))


# ----------------------------------------------------------------------
# The numeric handoff against R
# ----------------------------------------------------------------------
Expand Down
4 changes: 4 additions & 0 deletions tests/test_plotting_theme.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ def _clean_theme():
"#00BFC4", "#00A9FF", "#C77CFF", "#FF61CC"],
9: ["#F8766D", "#D39200", "#93AA00", "#00BA38", "#00C19F",
"#00B9E3", "#619CFF", "#DB72FB", "#FF61C3"],
# The CITE-seq tutorial's violins colour its twelve possible cell types from
# this one, in R and in Python alike (R 4.6.1, scales 1.4).
12: ["#F8766D", "#DE8C00", "#B79F00", "#7CAE00", "#00BA38", "#00C08B",
"#00BFC4", "#00B4F0", "#619CFF", "#C77CFF", "#F564E3", "#FF64B0"],
}


Expand Down
27 changes: 27 additions & 0 deletions tests/test_tutorial_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,33 @@ def test_pbmc3k_labelled_umap_is_laid_out_cleanly():
plt.close(fig)


def test_cbmc_adt_weight_violins_are_laid_out_cleanly():
"""The CITE-seq tutorial's figure 10 is the Truecell half of an R | Truecell
pair in the Frontiers paper, which prints each panel 3.30 in wide. Checked on
the real data at the tutorial's size, at 0.55, and at that width."""
if not (DATA_ROOT / "cbmc").is_dir():
pytest.skip("dataset 'cbmc' not cached")

import matplotlib.pyplot as plt

sys.path.insert(0, str(REPO_ROOT))
sys.path.insert(0, str(REPO_ROOT / "tests"))
import _layout

from tutorials.cbmc_citeseq_tutorial import run_full
from tutorials.generate_multimodal_plots import adt_weight_violins

obj, _, _ = run_full(verbose=False)
for scale in (1.0, _layout.MANUSCRIPT_SCALE, 3.30 / 9):
fig = adt_weight_violins(obj)
try:
if scale != 1.0:
_layout.shrink(fig, scale)
assert _layout.check_layout(fig) == [], f"at {scale:.2f} of its size"
finally:
plt.close(fig)


def test_pbmc3k_variable_feature_names_are_laid_out_cleanly():
"""The ten gene names crowd the top of the plot, where vst's clip stacks the
most variable genes. Unrepelled they overlapped, and the first repelled
Expand Down
12 changes: 12 additions & 0 deletions tutorials/cbmc_citeseq_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,18 @@ def run_wnn(obj, rna_dims=range(15), resolution=0.6):
"Cycling": ["STMN1", "MKI67", "TUBB"],
}

# Every label annotate_cells can return, in the order vln_plot draws groups:
# plain string order, which puts "pDC" last. The ADT-weight violins are an R |
# Truecell pair, so cbmc_citeseq_verify.R draws its groups in this order too and
# takes one colour per label from Seurat's hue_pal over all twelve. A type one
# side lacks then keeps its colour slot: R's clustering finds a DC / Mono cluster
# that Truecell's folds into CD14+ Mono, and no other colour moves because of it.
# tests/test_multimodal_tutorial.py holds the R copy of this list to this one.
CELL_TYPES = (
"B", "CD14+ Mono", "CD4 T", "CD8 T", "Cycling", "DC / Mono", "Erythroid",
"NK", "Other", "Platelet", "Progenitor", "pDC",
)


def annotate_cells(obj):
"""Annotate RNA clusters using surface protein first, RNA as a fallback.
Expand Down
49 changes: 45 additions & 4 deletions tutorials/cbmc_citeseq_verify.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
# WNN joint clustering. Writes the R-side figures for the side-by-side tables
# into tutorials/figures_multimodal/:
# * r_01_rna_umap_clusters.png ... r_10_adt_weight_by_celltype.png
# * r_10_adt_weight_by_celltype_manuscript.png, figure 10 laid out at the
# width the Frontiers paper prints it
# * r_adt_clr.csv per-protein CLR summary (mean/sd/min/max)
# * r_cell_weights.csv per-cell WNN modality weights, keyed by barcode
# * r_anchors.json scalars: cell/gene/protein counts, cluster counts
Expand Down Expand Up @@ -245,9 +247,48 @@ sv(brand((DimPlot(obj, reduction = "umap", group.by = "protein_celltype", label
"R Seurat - RNA-only vs WNN joint embedding"),
"r_09_wnn_vs_rna_umap.png", 14, 6.5)

# 10 learned per-cell modality weights
sv(titled(VlnPlot(obj, features = "ADT.weight", group.by = "protein_celltype",
pt.size = 0, sort = FALSE) + NoLegend(),
"R Seurat - ADT weight by cell type"), "r_10_adt_weight_by_celltype.png", 9, 5)
# 10 learned per-cell modality weights, drawn to pair with Truecell's figure 10.
# Reviewer 2 of the Frontiers paper found the two panels in different orders and
# colours, which defeats a side-by-side. Both now draw the groups in CELL_TYPES
# order, which is Truecell's vln_plot order, and colour each type from hue_pal
# over every label annotate_cells can return, so a type one side lacks keeps its
# colour slot. cbmc_citeseq_tutorial.py holds the same list, and
# tests/test_multimodal_tutorial.py keeps the two copies equal. Neither side
# draws points, and this one adds the median bar Truecell's vln_plot draws.
CELL_TYPES <- c("B", "CD14+ Mono", "CD4 T", "CD8 T", "Cycling", "DC / Mono",
"Erythroid", "NK", "Other", "Platelet", "Progenitor", "pDC")
labels <- as.character(obj$protein_celltype)
stopifnot(all(labels %in% CELL_TYPES))
present <- CELL_TYPES[CELL_TYPES %in% labels]
obj$violin_celltype <- factor(labels, levels = present) # this figure's order only
colours <- setNames(scales::hue_pal()(length(CELL_TYPES)), CELL_TYPES)[present]
# The median bar spans the violin at the median, as Truecell's does. ggplot draws
# the violin from an nrd0 density over the observed range (trim = TRUE), every
# group scaled to the same peak width (scale = "width"), 0.9 by default.
medians <- do.call(rbind, lapply(seq_along(present), function(i) {
y <- obj$ADT.weight[obj$violin_celltype == present[i]]
if (length(y) < 2 || diff(range(y)) == 0) return(NULL)
d <- density(y, bw = "nrd0", n = 512, from = min(y), to = max(y))
m <- median(y)
data.frame(x = i, y = m, half = approx(d$x, d$y / max(d$y), xout = m)$y * 0.9 / 2)
}))
p <- titled(VlnPlot(obj, features = "ADT.weight", group.by = "violin_celltype",
pt.size = 0, cols = colours) + NoLegend() +
geom_segment(data = medians, inherit.aes = FALSE,
aes(x = x - half, xend = x + half, y = y, yend = y),
colour = "black", linewidth = 0.7) + # 1.5 pt, Truecell's
labs(x = NULL, y = "ADT weight"),
"ADT weight by cell type")
sv(p, "r_10_adt_weight_by_celltype.png", 9, 5)
# The paper prints this panel 3.30 in wide, where the 9 in figure's type would
# land at about 4 pt. This copy is laid out at that width, with the dpi raised to
# keep the same 1350 x 750 pixels. Its type is set to the sizes Truecell's panel
# prints at, since tests/_layout.py's shrink() keeps each string's size: laid out
# at 3.30 in, Seurat's larger defaults left the violins a sliver, with the y-axis
# labels printed on top of each other.
ggsave(file.path(FIG, "r_10_adt_weight_by_celltype_manuscript.png"),
p + theme(plot.title = element_text(size = 11), axis.title.y = element_text(size = 10),
axis.text.x = element_text(size = 9), axis.text.y = element_text(size = 10)),
width = 3.30, height = 3.30 * 5 / 9, dpi = 150 * 9 / 3.30, bg = "white")

cat("\nAll R-side multimodal figures written to", FIG, "\n")
Binary file added tutorials/figures/r_11_umap_labeled.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified tutorials/figures_multimodal/10_adt_weight_by_celltype.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified tutorials/figures_multimodal/r_10_adt_weight_by_celltype.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
37 changes: 33 additions & 4 deletions tutorials/generate_multimodal_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))

from tutorials.cbmc_citeseq_tutorial import run_full
from tutorials.cbmc_citeseq_tutorial import CELL_TYPES, run_full
from truecell.plotting import (
dim_plot, feature_plot, ridge_plot, feature_scatter, vln_plot,
dim_plot, feature_plot, ridge_plot, feature_scatter, hue_pal, vln_plot,
_get_expression, _get_embedding, _palette,
)

Expand Down Expand Up @@ -90,6 +90,36 @@ def _group_panel(ax, emb, labels, title, legend=False):
s.set_visible(False)


def adt_weight_violins(obj):
"""The learned ADT weight per cell type (figure 10), drawn to pair with R's.

Reviewer 2 of the Frontiers paper found the R and Truecell panels in
different orders and colours, which defeats a side-by-side. Both scripts now
draw the groups in CELL_TYPES order, which is vln_plot's own, and colour each
type from Seurat's hue_pal over all of CELL_TYPES, so a type only one side
finds leaves every other colour where it was. Neither draws points, and
cbmc_citeseq_verify.R adds the median bar vln_plot draws. Its own function
so the smoke suite checks the layout of the figure this script saves.
"""
labels = set(obj.meta_data["protein_celltype"].astype(str))
unknown = labels - set(CELL_TYPES)
if unknown:
raise ValueError(f"cell types missing from CELL_TYPES: {sorted(unknown)}")
colours = dict(zip(CELL_TYPES, hue_pal(len(CELL_TYPES))))
present = [g for g in CELL_TYPES if g in labels]
fig = vln_plot(obj, "ADT.weight", group_by="protein_celltype", pt_size=0,
palette=[colours[g] for g in present], figsize=(9, 5))
ax = fig.axes[0]
# vln_plot matches the palette to its groups by position, so check it drew
# them in the order the colours were listed in.
drawn = [t.get_text() for t in ax.get_xticklabels()]
if drawn != present:
raise ValueError(f"vln_plot drew {drawn}, coloured for {present}")
ax.title.set_text("ADT weight by cell type")
ax.set_ylabel("ADT weight")
return fig


def main(data_dir=None):
obj, all_markers, anno = run_full(data_dir=data_dir, verbose=False)
print("\nGenerating multimodal figures...")
Expand Down Expand Up @@ -146,8 +176,7 @@ def main(data_dir=None):
# 10. The learned per-cell modality weights, read as a metadata "feature".
# Seurat's WNN vignette plots RNA.weight; ADT.weight is 1 - RNA.weight, and
# reads more directly as "how much this cell leans on protein".
_save(vln_plot(obj, "ADT.weight", group_by="protein_celltype", figsize=(9, 5)),
"10_adt_weight_by_celltype.png")
_save(adt_weight_violins(obj), "10_adt_weight_by_celltype.png")

print(f"\nAll multimodal figures saved to {FIGURES}/")

Expand Down
11 changes: 10 additions & 1 deletion tutorials/multimodal_citeseq.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,8 +469,17 @@ description of a typical cell:
</tr>
</table>

The two panels are drawn to be read against each other. Both put the cell types in
the same order and give each one the same colour, taken from Seurat's `hue_pal`
over all twelve labels `annotate_cells` can return. Both mark the median, which
`vln_plot` always draws and the R script adds, and neither draws points. R has one
more violin: its clustering finds a 69-cell **DC / Mono** cluster, and Truecell's
puts the same 69 cells in CD14+ Mono. The colours are spread over the whole list,
so the type Truecell lacks moves no other colour.

> `ADT.weight` is a metadata column, not a gene, but `vln_plot` resolves it the
> same way Seurat's `VlnPlot` does — hence the generic `Expression` y-axis label.
> same way Seurat's `VlnPlot` does. Both panels label the axis `ADT weight` rather
> than the generic `Expression`.

> The whole flow is wrapped as `run_wnn(obj)` in
> [`cbmc_citeseq_tutorial.py`](cbmc_citeseq_tutorial.py); `run_full()` prints the
Expand Down
2 changes: 1 addition & 1 deletion tutorials/pbmc3k_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def run_tutorial(data_dir: str | None = None) -> None:
# 0.5 is given **last** on purpose. Seurat leaves the object on the last
# resolution in the sequence — last as given, not largest — so every step
# below this one sees exactly the partition it saw before this sweep
# existed, and the tutorial's published numbers (9 clusters, ARI 0.938,
# existed, and the tutorial's published numbers (9 clusters, ARI 0.928,
# the marker tables) are unaffected. A resolution's partition does not
# depend on the ones before it, so 0.5 here is the same 0.5 as a lone call.
t0 = time.time()
Expand Down
Loading
Loading