From 0a51844ca7a02ec73ba9327524dc8809c535cb2e Mon Sep 17 00:00:00 2001 From: Shanika Amarasoma Date: Wed, 7 Oct 2026 21:19:46 +0530 Subject: [PATCH] Fix plots and add_module_score reading the wrong rows of scale.data (#140) scale_data() scales only the variable features unless it is given others, so row i of scale.data is not feature i of the assay. dim_heatmap and the helper behind dot_plot, feature_plot, feature_scatter, ridge_plot, vln_plot and the spatial plots found a gene by its place in the assay's full list and used that to index scale.data: an IndexError when the place fell past the last scaled row, and another gene's row under the right label when it did not. add_module_score(layer="scale.data") had the same lookup. All three now go through the layer's own feature list. A gene that is in the assay but not in the layer raises a KeyError that names the layer and how many of the assay's features it holds. The plotting tests all scaled every feature, which makes a gene's place in the assay equal its row in the layer, so none could see it. The new tests use the standard workflow, check that their fixture can tell the two lookups apart, and were mutation-tested one site at a time. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 20 ++++ tests/test_layer_feature_alignment.py | 128 ++++++++++++++++++++++++++ truecell/module_score.py | 14 ++- truecell/plotting.py | 42 ++++++--- 4 files changed, 182 insertions(+), 22 deletions(-) create mode 100644 tests/test_layer_feature_alignment.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 791d16f..2c627ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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. +- **`dim_heatmap`, the plots that take `layer=`, and `add_module_score` read the wrong + rows of `scale.data` (#140).** `scale_data()` scales only the variable features + unless it is given others, so row *i* of `scale.data` is not feature *i* of the + assay. `dim_heatmap` and the helper behind `dot_plot`, `feature_plot`, + `feature_scatter`, `ridge_plot`, `vln_plot`, `image_feature_plot` and + `spatial_feature_plot` still found a gene by its place in the assay's full list. + That raised `IndexError` when the place fell past the last scaled row, and drew + another gene's row under the right label when it did not. + - `dim_heatmap` on the standard workflow raised, or drew rows that were none of the + genes it labelled. `feature_scatter(layer="scale.data")` plotted two other genes. + - `add_module_score(layer="scale.data")` had the same lookup, found while checking + the other users of `layer=`. It raised `IndexError` on the standard workflow. + - A gene that is in the assay but not in the layer now raises a `KeyError` that + names the layer and how many of the assay's features it holds, instead of + "not found in assay". + - Nothing changes for a full-width layer such as `data`. The plotting tests all + scaled every feature, which is why none of them saw this; + `tests/test_layer_feature_alignment.py` uses the standard workflow and checks + that its own fixture can tell the two lookups apart. + ### Documentation - **The README's roadmap and `ROADMAP.md` describe 2.0.0.** Both still read as of diff --git a/tests/test_layer_feature_alignment.py b/tests/test_layer_feature_alignment.py new file mode 100644 index 0000000..a3a0590 --- /dev/null +++ b/tests/test_layer_feature_alignment.py @@ -0,0 +1,128 @@ +"""Functions that take ``layer=`` read the layer's own rows, not the assay's. + +``scale_data()`` scales only the variable features unless it is given others, so +``scale.data`` is narrower than the assay and row *i* of it is not feature *i* of +the assay. ``dim_heatmap`` and the helper behind ``dot_plot``, ``feature_plot``, +``feature_scatter``, ``ridge_plot``, ``vln_plot`` and the spatial plots looked a +gene up in the assay's full list and used that position to index ``scale.data``: +an ``IndexError`` when the position fell past the last scaled row, and another +gene's row, silently, when it did not. ``add_module_score(layer="scale.data")`` +did the same. + +Every other plotting test scales *all* features, which makes a gene's position in +the assay equal its row in the layer, so none of them could see it. The fixture +here is the standard workflow, and checks its own premise. +""" +import numpy as np +import pytest +import scipy.sparse as sp + +import truecell as tc +from truecell.plotting import _get_expression + +N_VARIABLE = 60 + + +@pytest.fixture(scope="module") +def narrow(): + """The standard workflow, with ``scale.data`` holding only the variable features.""" + rng = np.random.default_rng(0) + n_genes, n_cells = 600, 240 + group = rng.integers(0, 3, n_cells) + base = rng.gamma(0.5, 1.0, n_genes) * 0.5 + mult = np.ones((n_genes, 3)) + for g in range(3): + mult[g * 60:(g + 1) * 60, g] = 6 + counts = rng.poisson(base[:, None] * mult[:, group] * 2) + # Shuffled, so the variable genes sit anywhere in the feature list, as in real data. + perm = rng.permutation(n_genes) + obj = tc.create_truecell_object( + counts=sp.csc_matrix(counts[perm]), feature_names=[f"G{i}" for i in perm], + cell_names=[f"c{i}" for i in range(n_cells)], min_cells=3, min_features=10) + tc.normalize_data(obj) + tc.find_variable_features(obj, nfeatures=N_VARIABLE) + tc.scale_data(obj) + tc.run_pca(obj, n_pcs=6) + a = obj.get_assay() + scaled, full = list(a._scaled_features), list(a._all_feature_names) + assert len(scaled) == N_VARIABLE < len(full) + # Were the scaled genes the assay's first rows, looking a gene up by its place in + # the assay would be right by accident, and nothing below could fail. + assert scaled != full[:len(scaled)] + return obj + + +def _scaled(obj): + """``(scaled gene names, scale.data as a dense array)`` read straight from the layer.""" + a = obj.get_assay() + sd = a.layer_data("scale.data") + return list(a._scaled_features), (sd.toarray() if sp.issparse(sd) else np.asarray(sd)) + + +def test_get_expression_reads_the_genes_own_scale_data_row(narrow): + scaled, sd = _scaled(narrow) + for gene in (scaled[0], scaled[len(scaled) // 2], scaled[-1]): + got = _get_expression(narrow, gene, layer="scale.data") + assert np.array_equal(got, sd[scaled.index(gene)]), gene + + +def test_get_expression_without_a_layer_still_reads_every_gene(narrow): + # The default layer is `data`, which does hold every gene: only a gene that + # scale.data lacks is out of reach there. + a = narrow.get_assay() + full, data = list(a._all_feature_names), a.layer_data("data") + unscaled = next(g for g in full if g not in set(a._scaled_features)) + assert np.array_equal(_get_expression(narrow, unscaled), data[full.index(unscaled)].toarray().ravel()) + + +def test_a_gene_the_layer_lacks_is_named_as_such_not_read_from_another_row(narrow): + a = narrow.get_assay() + unscaled = next(g for g in a._all_feature_names if g not in set(a._scaled_features)) + with pytest.raises(KeyError, match=rf"not in layer 'scale.data'.*{N_VARIABLE} of the assay's"): + _get_expression(narrow, unscaled, layer="scale.data") + with pytest.raises(KeyError, match="not found in assay or metadata"): + _get_expression(narrow, "NoSuchGene", layer="scale.data") + + +def test_feature_scatter_plots_the_two_genes_it_was_asked_for(narrow): + plt = pytest.importorskip("matplotlib.pyplot") + scaled, sd = _scaled(narrow) + g1, g2 = scaled[10], scaled[40] + fig = tc.feature_scatter(narrow, g1, g2, layer="scale.data") + try: + pts = np.vstack([np.asarray(c.get_offsets()) for c in fig.axes[0].collections]) + finally: + plt.close(fig) + assert np.array_equal(np.sort(pts[:, 0]), np.sort(sd[scaled.index(g1)])) + assert np.array_equal(np.sort(pts[:, 1]), np.sort(sd[scaled.index(g2)])) + + +def test_dim_heatmap_draws_each_labelled_gene_s_own_row(narrow): + plt = pytest.importorskip("matplotlib.pyplot") + scaled, sd = _scaled(narrow) + fig = tc.dim_heatmap(narrow, dims=[1, 2], cells=None) # every cell, so rows compare whole + try: + for ax in fig.axes: + if not ax.images: + continue + labels = [t.get_text() for t in ax.get_yticklabels()] + shown = np.asarray(ax.images[0].get_array()) + assert len(labels) == shown.shape[0] > 0 + for gene, row in zip(labels, shown): + # DimHeatmap clips at +-2.5 and orders the cells by score, so compare + # the clipped values as a multiset. + want = np.clip(sd[scaled.index(gene)], -2.5, 2.5) + assert np.array_equal(np.sort(row), np.sort(want)), gene + finally: + plt.close(fig) + + +def test_add_module_score_reads_the_scale_data_layer_by_its_own_features(narrow): + # One bin and a control pool that is the whole pool fixes the control set, so the + # score is exactly the program's mean minus the pool's mean, whatever the seed. + scaled, sd = _scaled(narrow) + program, pool = scaled[5:10], scaled[:40] + tc.add_module_score(narrow, [program], pool=pool, nbin=1, ctrl=len(pool), + layer="scale.data", name="M") + want = sd[[scaled.index(g) for g in program]].mean(axis=0) - sd[[scaled.index(g) for g in pool]].mean(axis=0) + np.testing.assert_allclose(narrow.meta_data["M1"].to_numpy(), want, rtol=0, atol=1e-12) diff --git a/truecell/module_score.py b/truecell/module_score.py index e3545b9..dcdb522 100644 --- a/truecell/module_score.py +++ b/truecell/module_score.py @@ -24,14 +24,12 @@ def _assay_data(seurat, assay: Optional[str], layer: str = "data"): assay_obj = seurat.assays[assay or seurat.active_assay] if isinstance(assay_obj, Assay5): - feats = assay_obj._all_feature_names - if layer in assay_obj.layers: - mat = assay_obj.layers[layer] - elif "data" in assay_obj.layers: - mat = assay_obj.layers["data"] - else: - mat = assay_obj.layers["counts"] - return mat, feats + key = layer if layer in assay_obj.layers else ( + "data" if "data" in assay_obj.layers else "counts") + # The layer's own features: scale.data holds only the ones that were + # scaled, so the assay's list names the wrong rows of it. + feats = assay_obj._layer_features.get(key, assay_obj._all_feature_names) + return assay_obj.layers[key], feats else: feats = assay_obj._feature_names if layer == "counts": diff --git a/truecell/plotting.py b/truecell/plotting.py index b18a19c..234cf2b 100644 --- a/truecell/plotting.py +++ b/truecell/plotting.py @@ -433,7 +433,12 @@ def _resolve_layer(assay_obj, layer: Optional[str] = None): def _get_expression(obj, feature: str, assay: Optional[str] = None, layer: Optional[str] = None) -> np.ndarray: - """Return a 1-D expression vector for *feature* (gene or metadata col).""" + """Return a 1-D expression vector for *feature* (gene or metadata col). + + The gene is looked up in *layer's own* feature list, not the assay's: + ``scale.data`` holds only the features that were scaled (the variable ones, by + default), so a gene's position in the assay is not its row in that layer. + """ import scipy.sparse as sp # Metadata columns (nFeature_RNA, percent.mt, nCount_RNA, …) @@ -441,13 +446,22 @@ def _get_expression(obj, feature: str, assay: Optional[str] = None, return obj.meta_data[feature].values.astype(float) assay_obj = _get_assay_obj(obj, assay) - mat = _get_data_matrix(assay_obj, layer) - feat_names = assay_obj._all_feature_names + mat, feat_names = _resolve_layer(assay_obj, layer) - if feature not in feat_names: - raise KeyError(f"Feature '{feature}' not found in assay or metadata.") + try: + idx = feat_names.index(feature) + except ValueError: + # Say so when the gene exists but this layer does not hold it, rather than + # claiming it is missing, or reading some other gene's row. + n_assay = len(assay_obj.features()) + if len(feat_names) < n_assay and feature in assay_obj.features(): + raise KeyError( + f"Feature '{feature}' is not in layer '{layer or 'data'}': that layer holds " + f"{len(feat_names)} of the assay's {n_assay} features (scale_data() scales " + f"only the variable features unless it is given others)." + ) from None + raise KeyError(f"Feature '{feature}' not found in assay or metadata.") from None - idx = feat_names.index(feature) row = mat[idx, :] if sp.issparse(row): return np.asarray(row.todense()).flatten() @@ -1375,6 +1389,10 @@ def dim_heatmap( fig, axes = plt.subplots(nrow, nc, figsize=figsize, squeeze=False) axes_flat = axes.flatten() + assay_obj = _get_assay_obj(obj, None) + mat, scaled_feats = _resolve_layer(assay_obj, "scale.data") + scaled_row = {g: i for i, g in enumerate(scaled_feats)} + for plot_i, (dim, d0) in enumerate(zip(dims, dims_0)): ax = axes_flat[plot_i] scores = emb[:, d0] @@ -1394,11 +1412,8 @@ def dim_heatmap( top_genes_idx = np.unique(top_genes_idx) top_genes_idx = top_genes_idx[np.argsort(col_loads[top_genes_idx])[::-1]] - # Build expression matrix: top genes × selected cells - assay_obj = _get_assay_obj(obj, None) - mat = _get_data_matrix(assay_obj, "scale.data") - all_feats = assay_obj._all_feature_names - + # Build expression matrix: top genes × selected cells. A gene's row is its + # place in scale.data's own feature list, which is narrower than the assay's. rows = [] gene_labels = [] for gi in top_genes_idx: @@ -1406,9 +1421,8 @@ def dim_heatmap( gname = feat_names[gi] else: continue - if gname in all_feats: - aidx = all_feats.index(gname) - row = mat[aidx, :] + if gname in scaled_row: + row = mat[scaled_row[gname], :] row = np.asarray(row.todense()).flatten() if sp.issparse(row) else np.asarray(row).flatten() rows.append(row[sel_cells]) gene_labels.append(gname)