diff --git a/CHANGELOG.md b/CHANGELOG.md index 9354941..e4a1fa2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,6 +135,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `tests/test_layer_feature_alignment.py` uses the standard workflow and checks that its own fixture can tell the two lookups apart. +- **`feature_plot`'s quantile cutoffs are Seurat's, so `min_cutoff="q05", max_cutoff="q95"` + works for a sparse gene (#145).** That call, the one the skills recommend for a + washed-out scale, collapsed the colour bar of a gene detected in under 5% of cells to + (0, 1e-9): every expressing cell the same colour, and no sign anything was wrong. The + committed SCTransform tutorial figure showed it, on `XCL1`. + - Seurat's `SetQuantile` takes the percentile over the cells that express the feature, + the values above zero. `feature_plot` took it over every cell, so a sparse gene's 5th + and 95th percentiles were both 0. The values are pinned to `Seurat:::SetQuantile` on + Seurat 5.5.1 in `tests/test_feature_plot_cutoffs.py`, negatives and all-zero + features included. + - Only the strings `"q05"` and `"q95"` were recognised, and `"q99"` raised a + `TypeError` from comparing a string with a float. Any `q` and one or two digits + works now, as in Seurat, and anything else is a `ValueError` that says what is + allowed. + - Cutoffs that still leave the scale no range, whether equal, inverted, or because + every expresser has the same value, now warn and draw the feature over its own + range, instead of one colour. + - `tutorials/figures_sctransform/03_sct_featureplots_1.png` and + `04_sct_featureplots_2.png` are redrawn. The other four figures from the same + script are identical to the pixel. The CITE-seq ADT panel does not change: every + cell has a positive CLR value there, so the cells that express a protein are all + of them, and R's panel already used these quantiles. + - **The generics the docs list now work (#142).** `truecell.generics` declared 72 functions and 39 had only the fallback, so they raised `NotImplementedError` for every object. `skills/truecell/reference/api-map.md` listed many as the way to do things, diff --git a/skills/truecell-plotting/SKILL.md b/skills/truecell-plotting/SKILL.md index a20b331..92fb9ac 100644 --- a/skills/truecell-plotting/SKILL.md +++ b/skills/truecell-plotting/SKILL.md @@ -91,8 +91,12 @@ fig = truecell.do_heatmap(obj, list(top["gene"]), layer="scale.data") ``` `min_cutoff` / `max_cutoff` on `feature_plot` accept a number **or** a quantile -string (`"q05"`, `"q95"`) — the usual fix when one outlier cell flattens the -whole colour scale. +string, `"q"` and one or two digits (`"q05"`, `"q95"`, `"q99"`) — the usual fix when one +outlier cell flattens the whole colour scale. As in Seurat, a quantile is taken over +the cells that express the feature, the values above zero, so it suits a gene detected +in a few percent of cells too. If two cutoffs leave no range, for instance when every +expressing cell has the same value, `feature_plot` warns and draws the feature over +its own range. `do_heatmap` reads `scale.data` by default, so the genes you pass must have been scaled. If your heatmap is empty, that is usually why: `scale_data` defaults to @@ -169,7 +173,7 @@ for gene in genes: | `ModuleNotFoundError: matplotlib` | Install `truecell[analysis]`. | | Hangs or errors in CI / headless | Set `matplotlib.use("Agg")` before importing pyplot. | | `do_heatmap` blank | Genes not in `scale.data` — see above. | -| Colour scale washed out | One outlier cell; use `min_cutoff="q05"`, `max_cutoff="q95"`. | +| Colour scale washed out | One outlier cell; use `min_cutoff="q05"`, `max_cutoff="q95"`. They are taken over the cells expressing the gene, as in Seurat, so a sparse gene is fine. | | Plotting protein shows RNA | Pass `assay="ADT"`; there is no default-assay switch. | | Spatial plot mirrored | Toggle `flip_y`. | | Memory grows across a loop | Figures never closed. | diff --git a/tests/test_feature_plot_cutoffs.py b/tests/test_feature_plot_cutoffs.py new file mode 100644 index 0000000..8ddff3f --- /dev/null +++ b/tests/test_feature_plot_cutoffs.py @@ -0,0 +1,151 @@ +"""``feature_plot`` cutoffs: Seurat's ``SetQuantile``, and a scale that cannot collapse silently. + +The skills recommend ``min_cutoff="q05", max_cutoff="q95"`` as the fix for a washed-out +colour scale. ``feature_plot`` took those percentiles over every cell, so for a gene +detected in under 5% of cells both were 0 and the colour bar spanned (0, 1e-9): every +expressing cell the same colour. Seurat's ``SetQuantile`` takes the percentile over the +cells that express the feature, so the same call works there, and it accepts any +``q`` and one or two digits where ``feature_plot`` recognised only the strings +``"q05"`` and ``"q95"``, and failed on the rest. + +The reference values below are from ``Seurat:::SetQuantile`` on Seurat 5.5.1. +""" +import warnings + +import numpy as np +import pytest +import scipy.sparse as sp + +import truecell as tc +from truecell.plotting import _set_quantile + +# x = c(0, 0, 0, 0, 0.5, 1, 2, 3, 10, 20), run through Seurat:::SetQuantile +X = np.array([0, 0, 0, 0, 0.5, 1, 2, 3, 10, 20], dtype=float) +R_QUANTILES = {"q05": 0.625, "q5": 0.625, "q10": 0.75, "q50": 2.5, "q95": 17.5, "q99": 19.5, "q00": 0.5} + + +@pytest.mark.parametrize("cutoff,expected", sorted(R_QUANTILES.items())) +def test_a_quantile_is_seurats_over_the_expressing_cells(cutoff, expected): + assert _set_quantile(cutoff, X) == pytest.approx(expected, rel=1e-12) + + +def test_the_zeros_do_not_count_toward_a_quantile(): + # Over every cell the 5th percentile of X is 0; over the expressing cells it is 0.625. + assert np.percentile(X, 5) == 0.0 + assert _set_quantile("q05", X) == pytest.approx(0.625) + # R's sparse example: 97 zeros and three expressers + sparse = np.r_[np.zeros(97), [0.5, 1.5, 3.0]] + assert _set_quantile("q05", sparse) == pytest.approx(0.6) + assert _set_quantile("q95", sparse) == pytest.approx(2.85) + + +def test_negatives_are_not_expression_either(): + """`data[data > 0]`, so a scaled value below zero is left out, as in R (0.575).""" + assert _set_quantile("q05", np.array([-2, -1, 0, 0.5, 1, 2, 3.0])) == pytest.approx(0.575) + + +def test_a_number_is_itself_and_a_feature_nothing_expresses_is_zero(): + assert _set_quantile(2.5, X) == 2.5 and _set_quantile(0, X) == 0.0 + assert _set_quantile("q05", np.zeros(5)) == 0.0 # R gives NA; a scale needs a number + + +@pytest.mark.parametrize("bad", ["q100", "q", "q1.5", "95", "Q05", "q05 ", "", "median", "q-5"]) +def test_anything_else_is_an_error_that_says_what_is_allowed(bad): + with pytest.raises(ValueError, match="a number or a quantile such as 'q05'"): + _set_quantile(bad, X) + + +@pytest.fixture(scope="module") +def obj(): + pytest.importorskip("matplotlib") + rng = np.random.default_rng(0) + o = tc.create_truecell_object( + counts=sp.csc_matrix(rng.poisson(2.0, size=(30, 400)).astype(float)), + feature_names=[f"G{i}" for i in range(30)], cell_names=[f"c{i}" for i in range(400)]) + tc.normalize_data(o) + tc.find_variable_features(o, nfeatures=20) + tc.scale_data(o) + tc.run_pca(o, n_pcs=4) + # exact expression vectors, as metadata columns + sparse = np.zeros(400) + sparse[:12] = np.linspace(0.5, 3.0, 12) # 3% of cells express it + o.meta_data["sparse"] = sparse + o.meta_data["dense"] = np.linspace(0.0, 10.0, 400) + o.meta_data["flat"] = np.r_[np.zeros(380), np.ones(20)] # every expresser is 1 + o.meta_data["silent"] = np.zeros(400) + return o + + +def _clim(fig): + """The colour scale of the first panel's expressing cells.""" + return tuple(round(float(v), 9) for v in fig.axes[0].collections[1].get_clim()) + + +def _draw(obj, feature, **kwargs): + plt = pytest.importorskip("matplotlib.pyplot") + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + fig = tc.feature_plot(obj, feature, reduction="pca", **kwargs) + clim = _clim(fig) + plt.close(fig) + return clim, [str(w.message) for w in seen if "colour scale no range" in str(w.message)] + + +def test_the_documented_quantiles_work_for_a_gene_few_cells_express(obj): + """The report: the colour bar was (0, 1e-9) and the expression gradient was gone.""" + expressed = obj.meta_data["sparse"].to_numpy() + expressed = expressed[expressed > 0] + clim, warned = _draw(obj, "sparse", min_cutoff="q05", max_cutoff="q95") + assert clim == (round(np.percentile(expressed, 5), 9), round(np.percentile(expressed, 95), 9)) + assert clim[1] - clim[0] > 1.0 # a range, not 1e-9 + assert not warned + + +def test_every_quantile_is_accepted_not_only_q05_and_q95(obj): + expressed = obj.meta_data["dense"].to_numpy() + expressed = expressed[expressed > 0] + clim, _ = _draw(obj, "dense", min_cutoff="q10", max_cutoff="q99") + assert clim == (round(np.percentile(expressed, 10), 9), round(np.percentile(expressed, 99), 9)) + + +def test_numbers_and_the_defaults_are_as_they_were(obj): + assert _draw(obj, "dense", min_cutoff=2.0, max_cutoff=7.0)[0] == (2.0, 7.0) + assert _draw(obj, "dense")[0] == (0.0, 10.0) + assert _draw(obj, "dense", min_cutoff="q05")[0][1] == 10.0 # the max default is the feature's max + + +@pytest.mark.parametrize("kwargs", [ + {"min_cutoff": 5.0, "max_cutoff": 5.0}, # equal + {"min_cutoff": 7.0, "max_cutoff": 2.0}, # inverted + {"max_cutoff": 0.0}, # a maximum of zero +]) +def test_cutoffs_that_leave_no_range_warn_and_fall_back_to_the_features_range(obj, kwargs): + clim, warned = _draw(obj, "dense", **kwargs) + assert clim == (0.0, 10.0) + assert len(warned) == 1 and "'dense'" in warned[0] and "0 to 10" in warned[0] + + +def test_quantiles_that_collapse_warn_too(obj): + """Every expresser is 1, so q05 and q95 are both 1: one colour for every expresser.""" + clim, warned = _draw(obj, "flat", min_cutoff="q05", max_cutoff="q95") + assert clim == (0.0, 1.0) and len(warned) == 1 + + +def test_a_feature_nothing_expresses_is_not_a_cutoff_problem(obj): + clim, warned = _draw(obj, "silent", min_cutoff="q05", max_cutoff="q95") + assert clim == (0.0, 1e-9) and not warned + + +def test_split_by_still_shares_one_scale_computed_over_every_cell(obj): + plt = pytest.importorskip("matplotlib.pyplot") + obj.meta_data["half"] = ["a"] * 200 + ["b"] * 200 + fig = tc.feature_plot(obj, "dense", reduction="pca", min_cutoff="q05", max_cutoff="q95", + split_by="half") + try: + clims = {tuple(round(float(v), 9) for v in ax.collections[1].get_clim()) + for ax in fig.axes if len(ax.collections) > 1} + finally: + plt.close(fig) + expressed = obj.meta_data["dense"].to_numpy() + expressed = expressed[expressed > 0] + assert clims == {(round(np.percentile(expressed, 5), 9), round(np.percentile(expressed, 95), 9))} diff --git a/truecell/plotting.py b/truecell/plotting.py index 00f7f3c..1a94f12 100644 --- a/truecell/plotting.py +++ b/truecell/plotting.py @@ -797,6 +797,29 @@ def vln_plot( # 2. feature_plot — FeaturePlot # --------------------------------------------------------------------------- +def _set_quantile(cutoff, values: np.ndarray) -> float: + """Seurat's ``SetQuantile``: a number is itself, ``"q05"`` is a percentile. + + Any ``q`` and one or two digits is a percentile, and it is taken over the cells + that express the feature, the values above zero, not over every cell. Over every + cell, a gene detected in under 5% of them has a 5th and a 95th percentile of 0, + which leaves the colour scale no range. + + A feature nothing expresses has no percentile; R returns ``NA`` there, and 0 is + what a colour scale can use. + """ + if isinstance(cutoff, str): + if not re.fullmatch(r"q[0-9]{1,2}", cutoff): + raise ValueError( + f"A cutoff is a number or a quantile such as 'q05' or 'q95', got {cutoff!r}." + ) + expressed = values[values > 0] + if expressed.size == 0: + return 0.0 + return float(np.percentile(expressed, int(cutoff[1:]))) + return float(cutoff) + + def feature_plot( obj, features: Union[str, list[str]], @@ -805,8 +828,8 @@ def feature_plot( layer: Optional[str] = None, ncol: Optional[int] = None, order: bool = True, - min_cutoff: Optional[float] = None, - max_cutoff: Optional[float] = None, + min_cutoff: float | str | None = None, + max_cutoff: float | str | None = None, colormap: str = "YlOrRd", pt_size: float = 3.0, figsize: Optional[tuple] = None, @@ -822,8 +845,15 @@ def feature_plot( features : gene name(s) or metadata column(s) to plot reduction : which reduction to use ("umap", "pca", …) order : plot cells with highest expression on top - min_cutoff : clip expression below this percentile (e.g. "q05") - max_cutoff : clip expression above this percentile + min_cutoff : expression at or below this is drawn as not expressed (grey). A + number, or a quantile such as ``"q05"``; default 0. + max_cutoff : expression above this takes the top of the colour scale. A number, + or a quantile such as ``"q95"``; default the feature's maximum. + As in Seurat, a quantile is taken over the cells that express the + feature (values above zero), so ``"q05"``/``"q95"`` suit a gene + detected in a few percent of cells. If the two cutoffs leave the + scale no range, a warning says so and the feature is drawn over + its own range instead. colormap : matplotlib colormap name for expression pt_size : scatter point size raster : draw the cells as a raster layer instead of vector paths. @@ -867,8 +897,19 @@ def feature_plot( # Cutoffs from every cell, not the panel's subset — that is what makes # the row comparable. - vmin = np.percentile(expr, 5) if min_cutoff == "q05" else (min_cutoff or 0) - vmax = np.percentile(expr, 95) if max_cutoff == "q95" else (max_cutoff or expr.max()) + vmin = 0.0 if min_cutoff is None else _set_quantile(min_cutoff, expr) + vmax = float(expr.max()) if max_cutoff is None else _set_quantile(max_cutoff, expr) + if not vmax > vmin and expr.max() > 0: + # The feature varies, so it is the cutoffs that left the scale no range: + # one colour for every cell, and nothing to tell the plot is wrong. + warnings.warn( + f"feature_plot: for {feat!r}, min_cutoff={min_cutoff!r} and " + f"max_cutoff={max_cutoff!r} give {vmin:.3g} and {vmax:.3g}, which leaves " + f"the colour scale no range. Drawing it over the feature's own range, " + f"0 to {expr.max():.3g}, instead.", + stacklevel=2, + ) + vmin, vmax = 0.0, float(expr.max()) vmax = max(vmax, vmin + 1e-9) for ci, (level, in_panel) in enumerate(cells): diff --git a/tutorials/figures_sctransform/03_sct_featureplots_1.png b/tutorials/figures_sctransform/03_sct_featureplots_1.png index d9d771e..97d9f72 100644 Binary files a/tutorials/figures_sctransform/03_sct_featureplots_1.png and b/tutorials/figures_sctransform/03_sct_featureplots_1.png differ diff --git a/tutorials/figures_sctransform/04_sct_featureplots_2.png b/tutorials/figures_sctransform/04_sct_featureplots_2.png index 86a5019..a5f86be 100644 Binary files a/tutorials/figures_sctransform/04_sct_featureplots_2.png and b/tutorials/figures_sctransform/04_sct_featureplots_2.png differ