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
7 changes: 7 additions & 0 deletions STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ The conversion epic's sub-issues (#21–#30) are all done and ticked in #20.

- #124: `import dataframe --categorical` reads numeric-looking labels as
text (#125), for 0.17.7.
- #127: `convert --feature-type` and `--split-feature-types` take a 10x
input that records no feature types (Cell Ranger 2, two-column features
files) as gene expression, for 0.17.7.

The fixes from the October 2026 audit (epic #87, 164 findings in 16
batches) finished with 0.17.6; the sub-issues (#88–#103) are all done and
Expand All @@ -36,6 +39,10 @@ theirs.

## Follow-ups noticed

- From #127: `convert` from h5ad refuses `--feature-type` and
`--split-feature-types`; they could filter on var's `feature_types`
column, so one h5ad converted from a multiome `.h5` splits as the `.h5`
would.
- From #124 (`--categorical` now reads numeric-looking labels as text):
- `import dataframe --keep-dtypes`, to keep the encodings the existing
frame has for columns of the same name (category order, `ordered`,
Expand Down
9 changes: 9 additions & 0 deletions docs/reference/formats/10x-h5.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ entry whose feature index lies outside the features is refused as the
matrix is copied, and the output is not kept. `--genome` with
`--feature-type` is refused when that genome has no feature of the type.

A file in Cell Ranger 2's layout (CellBender run on one included) records
no feature types: Cell Ranger 2 measured gene expression alone, so its
features are taken as `Gene Expression`, and the same flags work on any 10x
input. `--feature-type "Gene Expression"` keeps every feature, with a
warning saying so, and any other type is refused; `--split-feature-types`
writes one `OUT.Gene_Expression.h5ad` (or `.zarr`). var gains no
`feature_types` column: the output is the one the conversion gives without
the flag.

The matrix is stored genes x cells in CSC, which is byte for byte cells x
genes in CSR, so `data`, `indices` and `indptr` stream straight across;
`--split-feature-types` reads them once for every output.
Expand Down
18 changes: 12 additions & 6 deletions docs/reference/formats/10x-mtx.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,18 @@ adata convert counts.h5ad -o counts_mtx --to 10x-mtx --layer counts
The import flags are those of the [10x HDF5 format](10x-h5.md) (`--genome`,
`--var-names`, `--make-unique`, `--feature-type`, `--split-feature-types`),
plus `--compression` for the output store, which is gzip on h5ad unless
given. Features are named by gene id unless `--var-names gene_symbols` is
given; with it, reading gives the var names and columns
`scanpy.read_10x_mtx(gex_only=False)` gives, checked against scanpy in CI,
except that integer counts stay integers (int32, int64 when a value needs
it) where scanpy converts them to float32; a `real` matrix is read as
float64. Duplicate entries are summed, as scipy does.
given. A folder whose features file has no type column (Cell Ranger 2's
`genes.tsv`, older STARsolo's two-column `features.tsv`) holds gene
expression alone, so `--feature-type "Gene Expression"` keeps every feature,
with a warning, any other type is refused, and `--split-feature-types`
writes one `OUT.Gene_Expression.h5ad` (or `.zarr`), as for a Cell Ranger 2
`.h5`. A `genes.tsv` with a third column refuses them: Cell Ranger 2's
records no types, and scanpy ignores the column. Features are named by gene
id unless `--var-names gene_symbols` is given; with it, reading gives the
var names and columns `scanpy.read_10x_mtx(gex_only=False)` gives, checked
against scanpy in CI, except that integer counts stay integers (int32, int64
when a value needs it) where scanpy converts them to float32; a `real`
matrix is read as float64. Duplicate entries are summed, as scipy does.

The matrix is read in two streaming passes, so its size is not a limit: the
first checks the whole folder -- barcode and feature counts against the
Expand Down
34 changes: 32 additions & 2 deletions src/adata/conversion/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@

VAR_NAMES = ("gene_symbols", "gene_ids")

#: The type of every feature of an input that records none: Cell Ranger 2
#: and STARsolo's two-column files measured gene expression alone.
GENE_EXPRESSION = "Gene Expression"

#: Rows of a string column handled per read when streaming one.
STRING_STEP = 1 << 18

Expand Down Expand Up @@ -137,13 +141,40 @@ def plan_targets(
options: Options,
*,
noun: str,
untyped: Optional[str] = None,
) -> Tuple[List[Path], List[Target], List[str]]:
"""The outputs to write, the features each keeps, and any warnings.

One output, unless `--split-feature-types` asks for one per type. `keep`
is what survives filters the caller applied first, such as `--genome`;
`noun` names the input in messages ("file", "folder").

`types` is None for an input that records no feature types; `untyped`
then says why ("genes.tsv records no feature types"). Such an input
holds gene expression alone, so the type flags work on it as on a v3
input of that one type, and a pipeline can pass the same flags for any
10x input (#127). Without `untyped` the flags are refused.
"""
warnings: List[str] = []
if types is None and (options.feature_type is not None or options.split_feature_types):
if untyped is None:
raise ValueError(
f"This {noun} records no feature types; --feature-type and "
"--split-feature-types need them."
)
if options.feature_type is not None and options.feature_type != GENE_EXPRESSION:
raise ValueError(
f"No features of type {options.feature_type!r}; {untyped}, so "
f"this {noun} holds gene expression only."
)
# Used only to select: var gains no feature_types column, so the
# output is the one the conversion gives without the flag.
types = np.full(len(names), GENE_EXPRESSION, dtype=object)
warnings.append(
f"{untyped}; every feature is taken as "
f"{GENE_EXPRESSION!r}, the only type such a {noun} holds."
)

groups: List[Tuple[Optional[str], np.ndarray]] = []
if options.feature_type is not None:
available = [t for t, _ in type_counts(types)]
Expand Down Expand Up @@ -176,7 +207,6 @@ def plan_targets(
stems = unique_names([label for label, _ in groups if label is not None])
outputs: List[Path] = []
targets: List[Target] = []
warnings: List[str] = []
for label, mask in groups:
path = output
if options.split_feature_types:
Expand Down Expand Up @@ -403,7 +433,7 @@ def requested(flag: str, name: Optional[str]) -> Optional[str]:
types = column(types_col)
else:
missing.append("feature types (a feature_types column, or --feature-types-column)")
types = ["Gene Expression"] * n
types = [GENE_EXPRESSION] * n

if missing:
if not options.force:
Expand Down
17 changes: 12 additions & 5 deletions src/adata/conversion/mtx.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,15 +351,22 @@ def plan(
if width >= 3 and not folder.legacy:
types = np.array([row[2] for row in rows], dtype=object)
columns["feature_types"] = types
if types is None and (options.feature_type is not None or options.split_feature_types):
if types is None and width >= 3 and (
options.feature_type is not None or options.split_feature_types
):
# Not untyped, though not read: GEO often serves a Cell Ranger 3
# features.tsv renamed genes.tsv for old Seurat, antibodies and
# all, and taking it as gene expression would keep them.
raise ValueError(
f"{folder.features.name} records no feature types; "
"--feature-type and --split-feature-types need a third column."
f"{folder.features.name} has a third column, which is not read: "
"Cell Ranger 2's genes.tsv records no feature types, and scanpy "
"ignores it. If it holds Cell Ranger 3's feature types, name the "
"file features.tsv to filter on them."
)

keep = np.ones(n_features, dtype=bool)
outputs, targets, warnings = plan_targets(
output, names, columns, types, keep, options, noun="folder"
output, names, columns, types, keep, options, noun="folder",
untyped=f"{folder.features.name} records no feature types",
)
if width > 3:
warnings.append(
Expand Down
10 changes: 1 addition & 9 deletions src/adata/conversion/tenx.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,14 +375,6 @@ def plan_matrix_import(
check_import_options(options)
matrix = _read_matrix(handle, options.genome)

if matrix.version == 2 and (
options.feature_type is not None or options.split_feature_types
):
raise ValueError(
"This is a Cell Ranger 2 file, which records no feature types; "
"--feature-type and --split-feature-types need a v3 file."
)

keep = np.ones(matrix.n_features, dtype=bool)
if options.genome is not None and matrix.version == 3:
genomes = matrix.columns.get("genome")
Expand All @@ -397,7 +389,7 @@ def plan_matrix_import(

outputs, targets, warnings = plan_targets(
output, matrix.names, matrix.columns, matrix.feature_types, keep, options,
noun="file",
noun="file", untyped="Cell Ranger 2's layout records no feature types",
)
return matrix, outputs, targets, warnings

Expand Down
21 changes: 21 additions & 0 deletions tests/test_cellbender.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,27 @@ def test_cellbender_0_2_on_cell_ranger_2_input(tmp_path):
assert "genome" not in got.uns["cellranger"], "background_removed is not a genome"


def test_cellbender_on_cell_ranger_2_input_takes_the_type_flags_as_gene_expression(tmp_path):
"""#127: the type flags work on any input in Cell Ranger 2's layout,
which records no feature types; CellBender 0.2 keeps that layout."""
truth = _cellbender(tmp_path, version="0.2", cellranger_v2=True)
plain, typed = tmp_path / "plain.h5ad", tmp_path / "typed.h5ad"
_ok(truth.path, "-o", plain)

result = _ok(truth.path, "-o", typed, "--feature-type", "Gene Expression")

got, expected = _read(typed), _read(plain)
assert list(got.var_names) == list(expected.var_names)
assert np.array_equal(got.X.toarray(), expected.X.toarray())
assert list(got.obs.columns) == list(expected.obs.columns)
assert "Cell Ranger 2's layout records no feature types" in _out(result)

refused = _convert(truth.path, "-o", tmp_path / "peaks.h5ad", "--feature-type", "Peaks")
assert refused.exit_code == 1
assert "so this file holds gene expression only" in _out(refused)
assert not (tmp_path / "peaks.h5ad").exists()


# ---------------------------------------------------------------------------
# sniffing

Expand Down
90 changes: 87 additions & 3 deletions tests/test_mtx.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,16 @@ def test_a_broken_folder_writes_nothing(tmp_path, counts, spoil, message):
@pytest.mark.parametrize(
"layout,args,message",
[
("starsolo2col", ["--feature-type", "Gene Expression"], "records no feature types"),
("cr2", ["--split-feature-types"], "records no feature types"),
(
"starsolo2col", ["--feature-type", "Peaks"],
"No features of type 'Peaks'; features.tsv records no feature types, "
"so this folder holds gene expression only.",
),
(
"cr2", ["--feature-type", "Antibody Capture"],
"No features of type 'Antibody Capture'; genes.tsv records no feature "
"types, so this folder holds gene expression only.",
),
("cr3", ["--genome", "hg19"], "no genome per feature"),
("cr3", ["--var-names", "symbols"], "--var-names must be one of"),
("cr3", ["--compression", "zstd"], "not available for h5ad"),
Expand All @@ -380,7 +388,83 @@ def test_options_that_do_not_fit_are_refused(tmp_path, counts, layout, args, mes
result = _convert(folder, "-o", tmp_path / "out.h5ad", *args)
assert result.exit_code == 1
assert message in _out(result)
assert not (tmp_path / "out.h5ad").exists()
assert list(tmp_path.glob("out*")) == []


@pytest.mark.parametrize(
"layout, prefix, features",
[
("cr2", "", "genes.tsv"),
("starsolo2col", "", "features.tsv"),
("cr2", "GSM1_", "GSM1_genes.tsv"), # as GEO serves them
],
ids=["cr2", "starsolo2col", "geo-prefix"],
)
@pytest.mark.parametrize(
"flags, written",
[
(["--feature-type", "Gene Expression"], "out.h5ad"),
(["--split-feature-types"], "out.Gene_Expression.h5ad"),
],
ids=["feature-type", "split"],
)
def test_the_type_flags_take_an_untyped_folder_as_gene_expression(
tmp_path, counts, layout, prefix, features, flags, written
):
"""#127: --feature-type and --split-feature-types were refused on a
folder whose features file has no type column, so a pipeline had to
look inside each 10x input before it chose its flags. Such a folder
(Cell Ranger 2, older STARsolo) holds gene expression alone."""
folder = write_10x_mtx(
tmp_path / "in", counts, barcodes=_barcodes(), ids=IDS, names=NAMES,
layout=layout, prefix=prefix,
)
plain = tmp_path / "plain.h5ad"
_ok(folder, "-o", plain)

result = _ok(folder, "-o", tmp_path / "out.h5ad", *flags)

assert sorted(p.name for p in tmp_path.glob("out*.h5ad")) == [written]
got, expected = _read(tmp_path / written), _read(plain)
assert list(got.obs_names) == list(expected.obs_names)
assert list(got.var_names) == list(expected.var_names)
assert list(got.var.columns) == list(expected.var.columns)
for name in expected.var.columns:
assert list(got.var[name]) == list(expected.var[name]), name
assert "feature_types" not in got.var.columns
assert got.X.dtype == expected.X.dtype
assert np.array_equal(got.X.toarray(), expected.X.toarray())
assert (
f"Warning: {features} records no feature types; every feature is taken "
"as 'Gene Expression', the only type such a folder holds."
) in _out(result)
assert _debris(tmp_path) == []


@pytest.mark.parametrize("flags", [["--feature-type", "Gene Expression"], ["--split-feature-types"]])
def test_a_genes_tsv_with_a_third_column_refuses_the_type_flags(tmp_path, counts, flags):
"""GEO often serves a Cell Ranger 3 features.tsv renamed genes.tsv, as
old Seurat wanted, antibodies and all. Its third column is not read (as
in scanpy), so taking the folder as gene expression would keep the
antibodies; the flags are refused, saying what to do."""
folder = tmp_path / "in"
write_10x_mtx(
folder, counts, barcodes=_barcodes(), ids=IDS, names=NAMES, types=TYPES,
layout="starsolo",
)
(folder / "features.tsv").rename(folder / "genes.tsv")

result = _convert(folder, "-o", tmp_path / "out.h5ad", *flags)

assert result.exit_code == 1
assert (
"genes.tsv has a third column, which is not read: Cell Ranger 2's "
"genes.tsv records no feature types, and scanpy ignores it. If it holds "
"Cell Ranger 3's feature types, name the file features.tsv to filter on them."
) in _out(result)
assert list(tmp_path.glob("out*")) == []
# Without the flags it converts as before, the third column unread.
_ok(folder, "-o", tmp_path / "plain.h5ad")


def test_a_single_mtx_file_points_to_its_folder(tmp_path, counts):
Expand Down
43 changes: 42 additions & 1 deletion tests/test_tenx.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,13 +258,54 @@ def test_a_cell_ranger_2_file_with_one_genome_needs_no_flag(tmp_path):
"extra,message",
[
(["--genome", "dm6"], "No genome 'dm6' in this file; it has: hg19, mm10"),
(["--genome", "hg19", "--feature-type", "Gene Expression"], "records no feature types"),
(
["--genome", "hg19", "--feature-type", "Peaks"],
"No features of type 'Peaks'; Cell Ranger 2's layout records no "
"feature types, so this file holds gene expression only.",
),
],
)
def test_bad_cell_ranger_2_options_are_refused(tmp_path, extra, message):
result = _convert(_v2(tmp_path), "-o", tmp_path / "o.h5ad", *extra)
assert result.exit_code == 1
assert message in _out(result)
assert list(tmp_path.glob("o*")) == []


def _same_conversion(got, expected) -> None:
assert list(got.obs_names) == list(expected.obs_names)
assert list(got.var_names) == list(expected.var_names)
assert list(got.var.columns) == list(expected.var.columns)
for name in expected.var.columns:
assert list(got.var[name]) == list(expected.var[name]), name
assert got.X.dtype == expected.X.dtype
assert np.array_equal(got.X.toarray(), expected.X.toarray())


@pytest.mark.parametrize(
"flags, written",
[
(["--feature-type", "Gene Expression"], "o.h5ad"),
(["--split-feature-types"], "o.Gene_Expression.h5ad"),
],
ids=["feature-type", "split"],
)
def test_the_type_flags_take_a_cell_ranger_2_file_as_gene_expression(tmp_path, flags, written):
"""#127: --feature-type and --split-feature-types were refused on a Cell
Ranger 2 file, so a pipeline had to know each input's 10x version before
it chose its flags. Cell Ranger 2 measured gene expression alone."""
h5 = _v2(tmp_path)
plain = tmp_path / "plain.h5ad"
_ok(h5, "-o", plain, "--genome", "hg19")

result = _ok(h5, "-o", tmp_path / "o.h5ad", "--genome", "hg19", *flags)

assert sorted(p.name for p in tmp_path.glob("o*.h5ad")) == [written]
_same_conversion(_read(tmp_path / written), _read(plain))
assert (
"Warning: Cell Ranger 2's layout records no feature types; every feature "
"is taken as 'Gene Expression', the only type such a file holds."
) in _out(result)


def test_an_inconsistent_matrix_is_refused_before_writing(tenx, tmp_path):
Expand Down
Loading