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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **`as_anndata` no longer fails on an object from the standard workflow (#141).**
`scale_data()` scales only the variable features unless it is given others, so
`scale.data` has one row per variable feature, and AnnData rejects a layer that is
not as wide as `var`. `as_anndata` raised a `ValueError` from inside AnnData on any
object that had been through `normalize_data`, `find_variable_features` and
`scale_data`, in either assay class.
- A layer with fewer features than the assay is now left out, with a warning that
names it and says how to keep it: `scale_data(obj, features=obj.feature_names())`
before converting, which scales every feature and exports the layer as before.
- It is left out rather than padded because `from_anndata` turns every layer back
into an assay layer, and padded rows would read back as scaled values that never
were.
- No test had converted an object that had been scaled. `tests/test_anndata_compat.py`
now does, for both assay classes, and `docs/interop.md` says what is left out.

- **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
Expand Down
5 changes: 5 additions & 0 deletions docs/interop.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ The conversion transposes for you, so don't transpose again by hand.
`from_anndata` reverses the table, with `X` as the counts layer. Pass the assay name
on the way back, because it is not read from `uns`.

An AnnData layer is as wide as `var`, so a layer with fewer features than the assay
stays behind, and `as_anndata` warns and names it. That is `scale.data` after
`scale_data()`'s default, which scales only the variable features. To keep it, scale
every feature first: `scale_data(obj, features=obj.feature_names())`.

## Space

The spatial fields follow the layout Scanpy and Squidpy read.
Expand Down
71 changes: 71 additions & 0 deletions tests/test_anndata_compat.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import warnings

import numpy as np
import pytest
import scipy.sparse as sp

anndata = pytest.importorskip("anndata", reason="anndata not installed")

from truecell import create_truecell_object, find_variable_features, normalize_data, scale_data
from truecell.compat import as_anndata, from_anndata


Expand Down Expand Up @@ -46,3 +51,69 @@ def test_from_anndata_makes_no_layer_out_of_x(small_seurat):
seurat2 = from_anndata(as_anndata(small_seurat), assay="RNA")
assert list(seurat2.assays["RNA"].layers) == ["counts"]
assert as_anndata(seurat2).n_obs == 20


# ---------------------------------------------------------------------------
# The standard workflow: scale_data() scales only the variable features
# ---------------------------------------------------------------------------

N_GENES, N_CELLS, N_VARIABLE = 300, 120, 40

# (use_v5, the scale layer's name, the one non-default layer that is full width).
# Assay5 makes `counts` the default layer, so `data` goes to `layers`; the legacy
# Assay puts `data` in X and `counts` in `layers`. The two name scale.data differently.
ASSAYS = [(True, "scale.data", "data"), (False, "scale_data", "counts")]


def _standard(use_v5, every_feature=False):
"""normalize, find variable features, scale: what the docs and the tutorials run."""
rng = np.random.default_rng(0)
obj = create_truecell_object(
counts=sp.csc_matrix(rng.poisson(2.0, size=(N_GENES, N_CELLS)).astype(float)),
feature_names=[f"g{i}" for i in range(N_GENES)],
cell_names=[f"c{j}" for j in range(N_CELLS)],
use_v5=use_v5,
)
normalize_data(obj)
find_variable_features(obj, nfeatures=N_VARIABLE)
scale_data(obj, features=obj.feature_names() if every_feature else None)
return obj


def _dense(matrix):
return matrix.toarray() if sp.issparse(matrix) else np.asarray(matrix)


@pytest.mark.parametrize("use_v5,scale_layer,other", ASSAYS)
def test_a_scale_layer_narrower_than_the_assay_is_left_out_with_a_warning(use_v5, scale_layer, other):
"""AnnData layers are as wide as var. scale_data() scales only the variable
features, so the layer has 40 rows against 300, and as_anndata raised a
ValueError from inside AnnData on every object the standard workflow makes."""
obj = _standard(use_v5)
with pytest.warns(UserWarning, match=rf"left out '{scale_layer}' \({N_VARIABLE} features\).*{N_GENES} features"):
adata = as_anndata(obj)
assert adata.shape == (N_CELLS, N_GENES)
assert scale_layer not in adata.layers
# What does fit is all still there.
assert other in adata.layers and adata.layers[other].shape == (N_CELLS, N_GENES)


@pytest.mark.parametrize("use_v5,scale_layer,other", ASSAYS)
def test_a_scale_layer_that_covers_every_feature_is_kept(use_v5, scale_layer, other):
obj = _standard(use_v5, every_feature=True)
with warnings.catch_warnings(record=True) as seen:
warnings.simplefilter("always")
adata = as_anndata(obj)
assert not [w for w in seen if "left out" in str(w.message)]
source = obj.get_assay().layer_data("scale.data") if use_v5 else obj.get_assay().scale_data
assert adata.layers[scale_layer].shape == (N_CELLS, N_GENES)
np.testing.assert_array_equal(_dense(adata.layers[scale_layer]), _dense(source).T)


def test_a_converted_standard_workflow_object_comes_back_without_the_narrow_layer():
obj = _standard(use_v5=True)
with pytest.warns(UserWarning, match="left out"):
adata = as_anndata(obj)
back = from_anndata(adata, assay="RNA")
assert back.feature_names() == obj.feature_names()
assert "scale.data" not in back.assays["RNA"].layers
24 changes: 24 additions & 0 deletions truecell/compat/anndata.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ def as_anndata(

AnnData has nowhere to put cell polygons or molecules, so those stay behind, as
does a second image of cells another image already placed, such as a crop.

An AnnData layer is as wide as ``var``, so a layer with fewer features than the
assay also stays behind, with a warning. That is ``scale.data`` after
``scale_data()``'s default, which scales only the variable features; scaling every
feature first, ``scale_data(obj, features=obj.feature_names())``, keeps it.
"""
try:
import anndata
Expand Down Expand Up @@ -113,9 +118,28 @@ def as_anndata(
var.index = feature_names

# ---- layers ----
# An AnnData layer is as wide as `var`. scale_data() scales only the variable
# features unless it is given others, so scale.data is usually narrower, and has
# no place here: AnnData rejects it, and padding it would hand `from_anndata` a
# layer of rows that were never scaled. The varm loop below guards the same
# mismatch.
layers_out = {}
narrow = {}
for layer_name, mat in extra_layers.items():
if mat.shape[0] != len(feature_names):
narrow[layer_name] = mat.shape[0]
continue
layers_out[layer_name] = mat.T if sp.issparse(mat) else mat.T
if narrow:
held = ", ".join(f"{name!r} ({n} features)" for name, n in narrow.items())
warnings.warn(
f"as_anndata left out {held}: an AnnData layer has to be as wide as var, "
f"which has {len(feature_names)} features. scale_data() scales only the "
f"variable features unless it is given others, so "
f"scale_data(obj, features=obj.feature_names()) before converting keeps "
f"a scale.data layer.",
stacklevel=2,
)

# ---- obsm ----
obsm = {}
Expand Down
Loading