From d4eb55fff55825f1460cf1651f025d139cf36a21 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 17:21:06 +0000 Subject: [PATCH 1/3] Elements written by import array (B6, #140) What `import array` writes is now what anndata reads back. - F199: a column written into a dataframe is added to its column-order, which anndata reads a frame's columns from; before, `obs/score` exited 0 and anndata never showed it. A column of any dataframe (obs, var, raw/var, or one in obsm or uns) must be 1-D, as long as the frame, in a frame the store has, and not named as its index (which `obs/_index` used to replace), `_index` or `__categories`. - F200: a column of raw/var is measured against raw's own variables; it was written at any length. - F201: an aligned path needs the dimensions it is aligned on, and the refusal names the shape: a scalar into obsm failed with 'tuple index out of range', and a 1-D array into obsp or varp was written, though anndata cannot read a store holding one. - F202: obs and var are no longer matched as bare prefixes. A top-level name outside the AnnData layout, such as `variance_explained`, is refused for what it is: anndata hands every top-level member to `AnnData()` and cannot read a store holding one it does not know. - docs: the import section of commands.md, troubleshooting, and the test map's row for test_validate.py. Co-Authored-By: Claude Opus 5.5 --- docs/reference/commands.md | 37 ++-- docs/reference/testing.md | 2 +- docs/troubleshooting.md | 11 +- src/adata/formats/array.py | 26 ++- src/adata/formats/validate.py | 309 +++++++++++++++++++++++++--------- tests/test_import.py | 238 +++++++++++++++++++++++++- tests/test_validate.py | 72 +++++++- 7 files changed, 590 insertions(+), 105 deletions(-) diff --git a/docs/reference/commands.md b/docs/reference/commands.md index ce88b37..e572fc6 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -519,8 +519,9 @@ back exactly. ## `import` -Write data into a store at any path. All subcommands need `--output`/`-o` or -`--inplace`, and refuse both at once. +Write data into a store at any path of the AnnData layout: in `X`, `obs`, +`var`, `obsm`, `varm`, `obsp`, `varp`, `layers`, `uns` or `raw`. All +subcommands need `--output`/`-o` or `--inplace`, and refuse both at once. An import never edits a store in place. The source is copied beside the destination (beside itself with `--inplace`), the element is written into @@ -549,17 +550,33 @@ adata import image data.h5ad uns/spatial/hires tissue.png --inplace | `--chunk`, `-C` | `array` | Elements a block (below) | Dimensions are validated against the existing obs/var where the path implies -an axis. For `array` and `sparse` that is done from the file's header, -before the store is copied, so a matrix of the wrong shape is refused at -once rather than after a copy of a large store. +an axis, and under `raw/` against raw's own variables (a column of +`raw/var` included). A path needs the dimensions it is aligned on: a scalar +is refused in `obsm`, `varm` or `raw/varm`, and anything less than a matrix +in `obsp` or `varp`, with the shape it needs. For `array` and `sparse` that +is done from the file's header, before the store is copied, so a matrix of +the wrong shape is refused at once rather than after a copy of a large +store. An element of a kind the AnnData layout does not allow where it would go is refused before anything is written, since anndata could not then read the -store: an array, a matrix, an image or JSON in place of `obs`, `var` or -`raw/var`; anything in place of the whole of `obsm`, `varm`, `obsp`, `varp` -or `layers`, or of `uns` but a JSON object; JSON or a dataframe as `X`; an -array that is not 1-D as a column of a dataframe. Name the entry to write, -such as `obsm/X_pca` or `uns/params`: an entry is replaced whatever it held. +store: anything outside the layout's top level, such as `variance_explained` +(put it in `uns`), since anndata cannot read a store holding a top-level +element it does not know; an array, a matrix, an image or JSON in place of +`obs`, `var` or `raw/var`; anything in place of the whole of `obsm`, `varm`, +`obsp`, `varp` or `layers`, or of `uns` but a JSON object; JSON or a +dataframe as `X`; an array that is not 1-D as a column of a dataframe. Name +the entry to write, such as `obsm/X_pca` or `uns/params`: an entry is +replaced whatever it held. + +An array written into a dataframe, such as `obs/score` (or a column of +`var`, of `raw/var`, or of a frame in `obsm` or `uns`), is a column of it: +it is added to the frame's `column-order`, from which anndata reads a +frame's columns, and a column it replaces keeps its place. It is refused if +it is not as long as the frame or the store has no such frame, and if it is +named as the frame's index, which it would replace, or `_index` or +`__categories`, which anndata keeps for a frame's index and, in older +stores, its categories. For `array`: the `.npy` is read a block of rows at a time, so its size is not a limit; `--chunk`, `-C` sets how many elements a block holds (1,048,576 by diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 1dcd98e..5ed40f3 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -65,7 +65,7 @@ inside every release before PyPI has it. | `test_write_safety.py` | Every way a command used to destroy or corrupt a store while reporting success, or leave a half-written one: outputs that alias the input, failed selections, `--inplace`, failed closes, a full disk, two runs on one output, SIGTERM | | `test_formats.py` | `.npy`, `.mtx`, image and JSON export/import, including their failure modes | | `test_cli_output.py` | What the CLI prints: names, labels and paths with square brackets or a trailing backslash as the store spells them (`util/markup.literal`), a failure as one plain `Error:` line in a log file, help text that keeps its brackets, `main(argv)` raising rather than ending the process | -| `test_validate.py` | Dimension validation for every axis-bearing path, including `raw/` | +| `test_validate.py` | Where an import may write and what fits there: dimension validation for every axis-bearing path, including `raw/` and the dimensions each needs, the columns of any dataframe (length, index name, a frame the store has), and the layout's top level | | `test_invariants.py` | Relationships that must hold for any data: subsetting everything is the identity, split partitions exactly, concat undoes split | | `test_anndata_roundtrip.py` | anndata writes the fixtures, reads back our output | | `test_anndata_versions.py` | Compatibility with seven real anndata releases (see below) | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 0b927b3..5b59df5 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -178,8 +178,9 @@ The ordering operators compare numbers. For text, use `==`, `!=` or `in`. See ### `First dimension mismatch: input has 2000 rows, but obs has 2688 cells.` `import` checks an array's length against the axis its path implies: -`obsm/...` against obs, `varm/...` against var, `X` and layers against both. -The input belongs to another store, or is transposed. +`obsm/...` and obs's columns against obs, `varm/...` and var's columns +against var, `X` and layers against both, and `raw/...` against raw's own +variables. The input belongs to another store, or is transposed. ### `'obs' must hold a dataframe; writing an array there would leave a store anndata cannot read.` @@ -188,6 +189,12 @@ and `var` are dataframes, and `obsm`, `layers` or `uns` hold one element per key. Name the entry instead, such as `obsm/X_pca` or `uns/params`, or use `import dataframe` for a table. See [Commands](reference/commands.md#import). +### `'variance_explained' is outside the AnnData layout, whose top level holds only X, obs, var, obsm, varm, obsp, varp, layers, uns and raw` + +anndata hands every element at a store's top level to `AnnData()`, so it +cannot read a store holding one it does not know. Put the element in `uns`, +such as `uns/variance_explained`, which holds anything. + ### `Cannot subset obsm/ragged: it is a group encoded as awkward-array, which subset cannot narrow.` `subset` and `split` narrow every element to the rows kept, and this one diff --git a/src/adata/formats/array.py b/src/adata/formats/array.py index 9066a25..79c4b90 100644 --- a/src/adata/formats/array.py +++ b/src/adata/formats/array.py @@ -21,7 +21,7 @@ from adata.elements import spec from adata.elements.read import decode_str_array -from adata.elements.write import write_dense, write_mapping, write_scalar +from adata.elements.write import set_column_order, write_dense, write_mapping, write_scalar from adata.formats.common import _get_encoding_type, _resolve, stdout_reader_may_stop from adata.formats.validate import check_target, validate_dimensions from adata.storage import create_dataset, is_dataset, is_group, is_zarr_group, row_bands @@ -197,6 +197,23 @@ def convert(start: Optional[int], end: Optional[int]) -> np.ndarray: fh.write(convert(start, end).tobytes()) +def _list_column(frame: Any, name: str) -> None: + """Add `name` to the dataframe's `column-order`, unless it is there. + + anndata reads a frame's columns from that list alone: a column written + without it was in the file, but never in anndata's `obs` (F199). A + column replaced keeps its place. + """ + declared = frame.attrs.get("column-order", None) + order = ( + [] + if declared is None + else [str(spec.decode_attr(c)) for c in np.asarray(declared).reshape(-1).tolist()] + ) + if name not in order: + set_column_order(frame, order + [name]) + + def import_npy( root: Any, obj: str, @@ -207,7 +224,9 @@ def import_npy( """Import a .npy file as a dense array, a block of rows at a time. The file is mapped, not loaded, so only the rows being copied are held. - Text (` str: where the layout fixes one (an array in place of `obs`, a matrix in place of the whole of `obsm`) used to be written, and anndata could then not read the store at all. An entry the user names inside such a - group (`obsm/X_pca`, `uns/params`) is theirs to replace. + group (`obsm/X_pca`, `uns/params`) is theirs to replace. A name outside + the layout's top level is refused: a top-level `variance_explained` was + measured against var, as if it were one of var's, and refused for that + (F202), but written it would leave a store anndata cannot read. """ path = norm_path(obj_path).strip("/") what = _WHAT[kind] @@ -85,6 +109,12 @@ def check_target(obj_path: str, kind: str) -> str: f"'{path or '/'}' is a group of elements, not one; name the entry " "to write, such as 'X', 'obsm/X_pca' or 'uns/params'." ) + if path.split("/", 1)[0] not in TOP_LEVEL: + raise ValueError( + f"'{path}' is outside the AnnData layout, whose top level holds only " + f"{', '.join(TOP_LEVEL[:-1])} and {TOP_LEVEL[-1]}: writing {what} there " + f"{_UNREADABLE}. Put it in uns, such as 'uns/{path}'." + ) if path in DATAFRAME_PATHS: if kind != "dataframe": raise ValueError( @@ -145,11 +175,112 @@ def _raw_var_length(root: Any) -> Optional[int]: return None -def _validate_raw( - root: Any, obj_path: str, data_shape: Tuple[int, ...], console: Console -) -> bool: +def _member(root: Any, path: str) -> Optional[Any]: + """The element at `path`, or None where the store has none.""" + node = root + for part in path.split("/"): + if not is_group(node) or part not in node: + return None + node = node[part] + return node + + +def _check_ndim( + path: str, data_shape: Tuple[int, ...], ndim: int, n: Optional[int], row: str +) -> None: + """Refuse an input with fewer dimensions than `path` is aligned on, + naming the shape it needs: `ndim` axes of `n` rows, a `row` each. + + A scalar into obsm, varm, obsp or raw/varm used to fail on its first + dimension with 'tuple index out of range' (F201), and a 1-D array into + obsp or varp was written, though anndata cannot read a store with one. + """ + if len(data_shape) >= ndim: + return + if ndim == 1: + needed = f"one row per {row}" + (f" ({n})" if n is not None else "") + else: + square = f"a {n}×{n} matrix" if n is not None else "a square matrix" + needed = f"{square}, a row and a column per {row}" + given = ( + f"{len(data_shape)}-D ({'×'.join(map(str, data_shape))})" if data_shape else "a scalar" + ) + raise ValueError(f"'{path}' needs {needed}, but the input is {given}.") + + +#: The axis each frame the layout fixes is indexed by, for `resolve_index`. +_FRAME_AXIS = {"obs": "obs", "var": "var", "raw/var": "var"} + + +def _frame_of(root: Any, path: str) -> Optional[str]: + """The dataframe `path` would be a column of, or None. + + obs, var and raw/var are frames by the layout, whether or not this + store has them; elsewhere (a frame in obsm or uns) a group is one when + its encoding says so. + """ + parent = parent_of(path) + if parent in DATAFRAME_PATHS: + return parent + group = _member(root, parent) if parent else None + if group is not None and is_group(group) and spec.encoding_type(group) == spec.DATAFRAME: + return parent + return None + + +def _validate_column( + root: Any, path: str, data_shape: Tuple[int, ...] +) -> Optional[Tuple[str, Optional[int]]]: + """Refuse what no column of a dataframe can be, where `path` names one. + + Returns the frame's path and its number of rows (None if unknown), or + None when `path` is no column. A column is 1-D, in a frame the store + holds, and not the frame's index: written there, the array would + replace the index. Nor is it `_index`, which anndata keeps for the + index, or `__categories`, where anndata 0.7 kept categoricals' labels. + """ + frame_path = _frame_of(root, path) + if frame_path is None: + return None + if len(data_shape) != 1: + raise ValueError( + f"'{path}' would be a column of '{frame_path}', which holds 1-D arrays, " + f"but the input's shape is {'x'.join(map(str, data_shape)) or 'a scalar'}." + ) + frame = _member(root, frame_path) + if frame is None or not is_group(frame): + raise ValueError( + f"'{path}' would be a column of '{frame_path}', which this store " + "does not hold as a dataframe." + ) + name = path.rsplit("/", 1)[1] + declared = spec.decode_attr(frame.attrs.get("_index", None)) + try: + index, index_name = resolve_index(frame, _FRAME_AXIS.get(frame_path)) + except KeyError: + index, index_name = None, None + if name in {str(n) for n in (declared, index_name) if n}: + raise ValueError( + f"'{path}' is the index of '{frame_path}', not a column: an array " + "imported there would replace its names. To change them, import " + "the whole frame with `adata import dataframe`." + ) + if name in spec.RESERVED_DATAFRAME_KEYS: + raise ValueError( + f"'{path}' cannot be a column of '{frame_path}': anndata keeps " + f"'{name}' for a dataframe's own members, its index or, in older " + "stores, its categories." + ) + try: + rows = element_len(index) if index is not None else None + except (TypeError, ValueError): + rows = None + return frame_path, rows + + +def _validate_raw(root: Any, obj_path: str, data_shape: Tuple[int, ...]) -> bool: """Validate a path under `raw/`. Returns whether the path was recognised.""" - if obj_path == "raw" or not obj_path.startswith("raw/"): + if not obj_path.startswith("raw/"): return False n_raw_var = _raw_var_length(root) @@ -165,6 +296,17 @@ def _validate_raw( ) return True + if rest.startswith("var/"): + # A column of raw/var, which `_validate_column` has found 1-D. It + # used to pass unchecked, and a column of any length was written + # (F200). + if n_raw_var is not None and data_shape[0] != n_raw_var: + raise ValueError( + f"Row count mismatch: input has {data_shape[0]} rows, but raw " + f"has {n_raw_var} variables." + ) + return True + if rest == "X": if len(data_shape) < 2: raise ValueError( @@ -183,6 +325,7 @@ def _validate_raw( return True if rest.startswith("varm/"): + _check_ndim(obj_path, data_shape, 1, n_raw_var, "variable of raw") if n_raw_var is not None and data_shape[0] != n_raw_var: raise ValueError( f"First dimension mismatch: input has {data_shape[0]} rows, " @@ -193,89 +336,95 @@ def _validate_raw( return False -def validate_dimensions( - root: Any, - obj_path: str, - data_shape: Tuple[int, ...], - console: Console, -) -> None: - obj_path = norm_path(obj_path) - - if parent_of(obj_path.strip("/")) in DATAFRAME_PATHS and len(data_shape) != 1: - raise ValueError( - f"'{obj_path}' would be a column of '{parent_of(obj_path.strip('/'))}', " - f"which holds 1-D arrays, but the input's shape is " - f"{'x'.join(map(str, data_shape)) or 'a scalar'}." - ) - - if _validate_raw(root, obj_path, data_shape, console): - return - +def _validate_aligned(root: Any, path: str, data_shape: Tuple[int, ...]) -> bool: + """Validate a path aligned to obs or var: the frames themselves, X, + layers, the entries of obsm, obsp, varm and varp, and the columns of + obs and var. Returns whether the path was recognised.""" n_obs = _get_axis_length(root, "obs") n_var = _get_axis_length(root, "var") - if obj_path == "obs": + if path == "obs": if n_obs is not None and data_shape[0] != n_obs: raise ValueError( f"Row count mismatch: input has {data_shape[0]} rows, " f"but obs has {n_obs} cells." ) - return - if obj_path == "var": + return True + if path == "var": if n_var is not None and data_shape[0] != n_var: raise ValueError( f"Row count mismatch: input has {data_shape[0]} rows, " f"but var has {n_var} features." ) - return + return True - for prefix in MATRIX_PREFIXES: - if obj_path == prefix or obj_path.startswith(prefix + "/") or obj_path.startswith(prefix): - if obj_path == "X" or obj_path.startswith("layers/"): - if len(data_shape) < 2: - raise ValueError( - f"Matrix data requires 2D shape, got {len(data_shape)}D." - ) - if n_obs is not None and data_shape[0] != n_obs: - raise ValueError( - f"First dimension mismatch: input has {data_shape[0]} rows, " - f"but obs has {n_obs} cells." - ) - if n_var is not None and data_shape[1] != n_var: - raise ValueError( - f"Second dimension mismatch: input has {data_shape[1]} columns, " - f"but var has {n_var} features." - ) - return - - for prefix in OBS_AXIS_PREFIXES: - if obj_path.startswith(prefix) and obj_path != "obs": - if n_obs is not None and data_shape[0] != n_obs: - raise ValueError( - f"First dimension mismatch: input has {data_shape[0]} rows, " - f"but obs has {n_obs} cells." - ) - if obj_path.startswith("obsp/") and len(data_shape) >= 2: - if data_shape[1] != n_obs: - raise ValueError( - "obsp matrix must be square (n_obs × n_obs): " - f"got {data_shape[0]}×{data_shape[1]}, expected {n_obs}×{n_obs}." - ) - return - - for prefix in VAR_AXIS_PREFIXES: - if obj_path.startswith(prefix) and obj_path != "var": - if n_var is not None and data_shape[0] != n_var: - raise ValueError( - f"First dimension mismatch: input has {data_shape[0]} rows, " - f"but var has {n_var} features." - ) - if obj_path.startswith("varp/") and len(data_shape) >= 2: - if data_shape[1] != n_var: - raise ValueError( - "varp matrix must be square (n_var × n_var): " - f"got {data_shape[0]}×{data_shape[1]}, expected {n_var}×{n_var}." - ) - return - - console.print(f"[dim]Note: No dimension validation for path '{literal(obj_path)}'[/]") + if path == "X" or path.startswith("layers/"): + if len(data_shape) < 2: + raise ValueError( + f"Matrix data requires 2D shape, got {len(data_shape)}D." + ) + if n_obs is not None and data_shape[0] != n_obs: + raise ValueError( + f"First dimension mismatch: input has {data_shape[0]} rows, " + f"but obs has {n_obs} cells." + ) + if n_var is not None and data_shape[1] != n_var: + raise ValueError( + f"Second dimension mismatch: input has {data_shape[1]} columns, " + f"but var has {n_var} features." + ) + return True + + for prefix, axis, ndim in _ALIGNED: + if not path.startswith(prefix): + continue + n = n_obs if axis == "obs" else n_var + _check_ndim(path, data_shape, ndim, n, _ROW[axis]) + if n is None: + return True + if data_shape[0] != n: + raise ValueError( + f"First dimension mismatch: input has {data_shape[0]} rows, " + f"but {axis} has {n} {_ROW[axis]}s." + ) + if ndim == 2 and data_shape[1] != n: + raise ValueError( + f"{prefix[:-1]} matrix must be square (n_{axis} × n_{axis}): " + f"got {data_shape[0]}×{data_shape[1]}, expected {n}×{n}." + ) + return True + + return False + + +def validate_dimensions( + root: Any, + obj_path: str, + data_shape: Tuple[int, ...], + console: Console, +) -> None: + """Refuse an input whose shape cannot go where `obj_path` puts it. + + A path aligned to an axis is measured against it: X, layers, obsm, + obsp and obs's columns against obs; varm, varp and var's columns + against var; raw's X, varm, var and var's columns against raw's own + variables. A column of any dataframe, obs's or one in obsm or uns, is + also 1-D, as long as the frame, and not named as its index. A path + none of this covers passes, with a note. + """ + path = norm_path(obj_path).strip("/") + data_shape = tuple(data_shape) + + column = _validate_column(root, path, data_shape) + known = _validate_raw(root, path, data_shape) or _validate_aligned(root, path, data_shape) + if column is not None: + # obs's, var's and raw/var's columns were measured against their + # axis, in its words, above; this covers a frame no axis names. + frame_path, rows = column + if rows is not None and data_shape[0] != rows: + raise ValueError( + f"Row count mismatch: input has {data_shape[0]} rows, but " + f"'{frame_path}' has {rows}." + ) + elif not known: + console.print(f"[dim]Note: No dimension validation for path '{literal(path)}'[/]") diff --git a/tests/test_import.py b/tests/test_import.py index e409753..6982d59 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -591,6 +591,18 @@ def _read(path: Path): return ad.read_h5ad(path) if path.suffix == ".h5ad" else ad.read_zarr(path) +def _write_as(obj, temp_dir: Path, backend: str, stem: str) -> Path: + """`obj` as anndata writes it, on the test's backend.""" + path = backend_path(temp_dir, backend, stem) + previous = ad.settings.zarr_write_format + ad.settings.zarr_write_format = backend_zarr_format(backend) or previous + try: + obj.write_h5ad(path) if backend == "h5ad" else obj.write_zarr(path) + finally: + ad.settings.zarr_write_format = previous + return path + + @pytest.fixture def written(temp_dir, backend): """A store anndata wrote, holding every slot an import can aim at.""" @@ -605,14 +617,7 @@ def written(temp_dir, backend): obj.obsp["distances"] = sparse.csr_matrix(np.eye(N_OBS, dtype="float32")) obj.uns["keep"] = {"a": 1} obj.raw = obj - path = backend_path(temp_dir, backend, "written") - previous = ad.settings.zarr_write_format - ad.settings.zarr_write_format = backend_zarr_format(backend) or previous - try: - obj.write_h5ad(path) if backend == "h5ad" else obj.write_zarr(path) - finally: - ad.settings.zarr_write_format = previous - return path + return _write_as(obj, temp_dir, backend, "written") def _import(kind, store, entry, source, *extra): @@ -1088,3 +1093,220 @@ def test_a_column_name_no_element_can_have_is_refused_before_writing(written, te assert result.exit_code == 1 assert message in _out(result) assert list(_read(written).obs.columns) == ["n"] + + +# --------------------------------------------------------------------------- +# What `import array` writes into a dataframe or an aligned entry, as anndata +# reads it back (#140). + + +@pytest.mark.parametrize( + "entry,rows,frame", + [ + ("obs/score", N_OBS, lambda obj: obj.obs), + ("var/score", 3, lambda obj: obj.var), + ("raw/var/score", 3, lambda obj: obj.raw.var), + ], + ids=["obs", "var", "raw-var"], +) +def test_an_imported_column_is_one_anndata_lists(written, temp_dir, entry, rows, frame): + """F199: `import array obs/score` exited 0 with the column in the file, + but not in obs's `column-order`, the list anndata reads a frame's + columns from: anndata never showed it, and a round trip through + anndata dropped it.""" + source = temp_dir / "score.npy" + np.save(source, np.linspace(0.5, 2.5, rows)) + before = list(frame(_read(written)).columns) + + result, out = _import("array", written, entry, source) + + assert result.exit_code == 0, _out(result) + got = frame(_read(out)) + assert list(got.columns) == before + ["score"] + np.testing.assert_array_equal(got["score"].to_numpy(), np.load(source)) + + +def test_a_replaced_column_keeps_its_place_and_is_listed_once(written, temp_dir): + """F199: a new column is added to `column-order`, but one that + replaces a listed column stays where it was: listed twice, anndata + would read two columns of one name.""" + np.save(temp_dir / "a.npy", np.arange(N_OBS) * 2.0) + np.save(temp_dir / "n.npy", np.arange(N_OBS)[::-1].copy()) + + result, first = _import("array", written, "obs/a", temp_dir / "a.npy") + assert result.exit_code == 0, _out(result) + result, second = _import("array", first, "obs/n", temp_dir / "n.npy") + assert result.exit_code == 0, _out(result) + + obs = _read(second).obs + assert list(obs.columns) == ["n", "a"] + np.testing.assert_array_equal(obs["n"].to_numpy(), np.load(temp_dir / "n.npy")) + np.testing.assert_array_equal(obs["a"].to_numpy(), np.load(temp_dir / "a.npy")) + + +def test_a_column_of_a_frame_in_obsm_or_uns_is_listed_and_measured(temp_dir, backend): + """F199: a column of any dataframe, not only obs's, was written without + being listed, so anndata never read it. A frame in uns, which no axis + measures, also took a column of any length, which listed would leave a + store anndata cannot read.""" + obj = ad.AnnData( + X=np.zeros((N_OBS, 2), dtype="float32"), + obs=pd.DataFrame(index=[f"c{i}" for i in range(N_OBS)]), + ) + obj.obsm["meta"] = pd.DataFrame({"a": np.arange(N_OBS)}, index=obj.obs_names) + obj.uns["table"] = pd.DataFrame({"b": [1.0, 2.0, 3.0, 4.0]}, index=list("wxyz")) + store = _write_as(obj, temp_dir, backend, "frames") + np.save(temp_dir / "rows.npy", np.arange(N_OBS) + 0.5) + np.save(temp_dir / "four.npy", np.array([4.0, 3.0, 2.0, 1.0])) + + result, out = _import("array", store, "obsm/meta/score", temp_dir / "rows.npy") + assert result.exit_code == 0, _out(result) + meta = _read(out).obsm["meta"] + assert list(meta.columns) == ["a", "score"] + np.testing.assert_array_equal(meta["score"].to_numpy(), np.load(temp_dir / "rows.npy")) + + result, out = _import("array", store, "uns/table/score", temp_dir / "four.npy") + assert result.exit_code == 0, _out(result) + table = _read(out).uns["table"] + assert list(table.columns) == ["b", "score"] + np.testing.assert_array_equal(table["score"].to_numpy(), np.load(temp_dir / "four.npy")) + + result, out = _import("array", store, "uns/table/wrong", temp_dir / "rows.npy") + assert result.exit_code == 1 + assert "Row count mismatch: input has 6 rows, but 'uns/table' has 4." in _out(result) + assert not out.exists() + assert list(_read(store).uns["table"].columns) == ["b"] + + +@pytest.mark.parametrize( + "index_name,entry,message", + [ + (None, "obs/_index", "'obs/_index' is the index of 'obs', not a column"), + ("cell", "obs/cell", "'obs/cell' is the index of 'obs', not a column"), + ("cell", "obs/_index", "anndata keeps '_index' for a dataframe's own members"), + (None, "obs/__categories", "anndata keeps '__categories' for a dataframe's own members"), + ], +) +def test_a_column_named_as_the_index_is_refused(temp_dir, backend, index_name, entry, message): + """F199: a column named as obs's index replaced the index: `import + array obs/_index` exited 0, and anndata's obs_names became '0.0', + '1.0', ... `_index` and `__categories` are anndata's own names in a + frame, whatever the index is called, and are refused too.""" + names = pd.Index([f"c{i}" for i in range(N_OBS)], name=index_name) + obj = ad.AnnData( + X=np.zeros((N_OBS, 2), dtype="float32"), + obs=pd.DataFrame({"n": np.arange(N_OBS)}, index=names), + ) + store = _write_as(obj, temp_dir, backend, "named") + np.save(temp_dir / "v.npy", np.arange(N_OBS, dtype="float64")) + + result, out = _import("array", store, entry, temp_dir / "v.npy") + + assert result.exit_code == 1 + assert message in _out(result) + assert not out.exists() + kept = _read(store).obs + assert list(kept.index) == [f"c{i}" for i in range(N_OBS)] + assert list(kept.columns) == ["n"] + + +def test_a_raw_var_column_is_measured_against_raw_not_var(temp_dir, backend): + """F200: `import array raw/var/` checked the column against + nothing, and wrote one of any length into raw/var. raw has variables + of its own, here 4 where var has 2.""" + full = ad.AnnData( + X=np.ones((N_OBS, 4), dtype="float32"), + obs=pd.DataFrame(index=[f"c{i}" for i in range(N_OBS)]), + var=pd.DataFrame(index=[f"g{i}" for i in range(4)]), + ) + full.raw = full + store = _write_as(full[:, :2].copy(), temp_dir, backend, "raw") + np.save(temp_dir / "two.npy", np.arange(2.0)) + np.save(temp_dir / "four.npy", np.arange(4.0) + 0.5) + + result, out = _import("array", store, "raw/var/score", temp_dir / "two.npy") + assert result.exit_code == 1 + assert "Row count mismatch: input has 2 rows, but raw has 4 variables." in _out(result) + assert not out.exists() + + result, out = _import("array", store, "raw/var/score", temp_dir / "four.npy") + assert result.exit_code == 0, _out(result) + raw_var = _read(out).raw.var + assert list(raw_var.index) == [f"g{i}" for i in range(4)] + np.testing.assert_array_equal(raw_var["score"].to_numpy(), np.load(temp_dir / "four.npy")) + + +@pytest.mark.parametrize( + "entry,shape,message", + [ + ("obsm/s", (), "'obsm/s' needs one row per cell (6), but the input is a scalar."), + ("varm/s", (), "'varm/s' needs one row per feature (3), but the input is a scalar."), + ("obsp/s", (), "'obsp/s' needs a 6×6 matrix, a row and a column per cell, but the input is a scalar."), + ("varp/s", (), "'varp/s' needs a 3×3 matrix, a row and a column per feature, but the input is a scalar."), + ("raw/varm/s", (), "'raw/varm/s' needs one row per variable of raw (3), but the input is a scalar."), + ("obsp/s", (N_OBS,), "'obsp/s' needs a 6×6 matrix, a row and a column per cell, but the input is 1-D (6)."), + ("varp/s", (3,), "'varp/s' needs a 3×3 matrix, a row and a column per feature, but the input is 1-D (3)."), + ], +) +def test_an_input_without_the_dimensions_its_path_needs_is_refused_by_name( + written, temp_dir, entry, shape, message +): + """F201: a scalar .npy into obsm, varm, obsp, varp or raw/varm failed + with 'Error: tuple index out of range'. A 1-D array into obsp or varp + was written, though anndata cannot read a store holding one.""" + source = temp_dir / "v.npy" + np.save(source, np.ones(shape)) + + result, out = _import("array", written, entry, source) + + assert result.exit_code == 1 + assert message in _out(result) + assert "tuple index" not in _out(result) + assert not out.exists() + kept = _read(written) + assert set(kept.obsm) == {"X_pca"} and set(kept.obsp) == {"distances"} + + +@pytest.mark.parametrize( + "kind,entry,source", + [ + ("array", "variance_explained", "v.npy"), + ("array", "observations", "v.npy"), + ("array", "Xtra/emb", "v.npy"), + ("dict", "params", "p.json"), + ], +) +def test_a_top_level_key_outside_the_layout_is_refused_for_what_it_is( + written, temp_dir, kind, entry, source +): + """F202: `obs` and `var` were matched as bare prefixes, so a top-level + key that starts with them was measured against an axis: `import array + variance_explained` of 7 values was refused because "var has 3 + features". Such a key is refused for what it is, whatever its name and + kind: written, it would leave a store anndata cannot read (below).""" + np.save(temp_dir / "v.npy", np.arange(7, dtype="float64")) + (temp_dir / "p.json").write_text('{"a": 1}') + + result, out = _import(kind, written, entry, temp_dir / source) + + assert result.exit_code == 1 + assert f"'{entry}' is outside the AnnData layout" in _out(result) + assert f"Put it in uns, such as 'uns/{entry}'" in _out(result) + assert "features" not in _out(result) + assert not out.exists() + assert _read(written).shape == (N_OBS, 3) + + +def test_anndata_cannot_read_a_store_holding_a_top_level_key_outside_its_layout(temp_dir): + """F202's oracle: anndata hands every top-level member to `AnnData()`, + so one it does not know leaves the whole store unreadable. That is why + `import` refuses such a key, where the audit expected it written.""" + path = temp_dir / "extra.h5ad" + ad.AnnData(X=np.zeros((2, 3), dtype="float32")).write_h5ad(path) + with h5py.File(path, "a") as handle: + extra = handle.create_dataset("variance_explained", data=np.arange(3.0)) + extra.attrs["encoding-type"] = "array" + extra.attrs["encoding-version"] = "0.2.0" + + with pytest.raises(TypeError, match="variance_explained"): + _read(path) diff --git a/tests/test_validate.py b/tests/test_validate.py index 53375f7..560b7a9 100644 --- a/tests/test_validate.py +++ b/tests/test_validate.py @@ -7,12 +7,14 @@ from __future__ import annotations +import re + import numpy as np import pytest from rich.console import Console from adata.elements import write as ew -from adata.formats.validate import DATAFRAME_PATHS, validate_dimensions +from adata.formats.validate import DATAFRAME_PATHS, TOP_LEVEL, check_target, validate_dimensions console = Console(stderr=True) @@ -50,6 +52,9 @@ def root(new_store): ("raw/var", (N_RAW_VAR,)), ("raw/X", (N_OBS, N_RAW_VAR)), ("raw/varm/PCs", (N_RAW_VAR, 3)), + ("obs/score", (N_OBS,)), + ("var/score", (N_VAR,)), + ("raw/var/score", (N_RAW_VAR,)), ], ) def test_correct_shapes_are_accepted(root, path, shape): @@ -74,10 +79,21 @@ def test_correct_shapes_are_accepted(root, path, shape): ("raw/X", (N_OBS, 99), "raw has 5 variables"), ("raw/X", (N_OBS,), "raw/X requires 2D"), ("raw/varm/PCs", (99, 3), "raw has 5 variables"), + ("obs/score", (99,), "obs has 3 cells"), + ("obs/score", (N_OBS, 2), "which holds 1-D arrays, but the input's shape is 3x2"), + ("raw/var/score", (N_VAR,), "raw has 5 variables"), + ("obsm/s", (), "'obsm/s' needs one row per cell (3), but the input is a scalar"), + ("varm/s", (), "'varm/s' needs one row per feature (2), but the input is a scalar"), + ("obsp/conn", (N_OBS,), "'obsp/conn' needs a 3×3 matrix, a row and a column per cell, but the input is 1-D (3)"), + ("varp/corr", (), "'varp/corr' needs a 2×2 matrix, a row and a column per feature, but the input is a scalar"), + ("raw/varm/PCs", (), "'raw/varm/PCs' needs one row per variable of raw (5), but the input is a scalar"), + ("obs/_index", (N_OBS,), "'obs/_index' is the index of 'obs', not a column"), + ("raw/var/_index", (N_RAW_VAR,), "'raw/var/_index' is the index of 'raw/var', not a column"), + ("var/__categories", (N_VAR,), "anndata keeps '__categories' for a dataframe's own members"), ], ) def test_wrong_shapes_are_rejected(root, path, shape, message): - with pytest.raises(ValueError, match=message): + with pytest.raises(ValueError, match=re.escape(message)): validate_dimensions(root, path, shape, console) @@ -108,6 +124,8 @@ def test_validation_is_skipped_when_an_axis_cannot_be_read(new_store): del root["obs"] with opener("r") as root: validate_dimensions(root, "obsm/x", (99, 2), console) + # Not "expected None×None", as obsp's square check said with no obs. + validate_dimensions(root, "obsp/x", (99, 2), console) def test_raw_without_x_falls_back_to_raw_var(new_store): @@ -119,3 +137,53 @@ def test_raw_without_x_falls_back_to_raw_var(new_store): validate_dimensions(root, "raw/var", (4,), console) with pytest.raises(ValueError, match="raw has 4 variables"): validate_dimensions(root, "raw/var", (2,), console) + + +@pytest.mark.parametrize("path", ["variance_explained", "observations", "obsolete/x", "varnish"]) +def test_a_path_that_only_starts_with_an_axis_name_is_not_measured_against_it(root, path, capsys): + """F202: 'obs' and 'var' were matched as bare prefixes, so a path that + only began with the letters was measured against an axis, and + `variance_explained` refused because "var has 2 features".""" + validate_dimensions(root, path, (99,), console) + assert "No dimension validation" in capsys.readouterr().err + + +@pytest.mark.parametrize("path", ["variance_explained", "params", "Xtra/emb", "x", "raw.X", "shape"]) +def test_a_top_level_name_outside_the_layout_is_refused(path): + """F202: such a name is not measured against an axis, but refused for + what it is: anndata hands every top-level member to `AnnData()`, and + cannot read a store holding one it does not know.""" + with pytest.raises(ValueError, match="outside the AnnData layout"): + check_target(path, "array") + + +@pytest.mark.parametrize("path", [*TOP_LEVEL[:-1], "raw/X", "raw/varm/PCs", "uns/anything/deep"]) +def test_every_name_of_the_layout_is_still_a_target(path): + kind = "dataframe" if path in DATAFRAME_PATHS else "dict" if path == "uns" else "array" + if path in ("obsm", "varm", "obsp", "varp", "layers"): + path = f"{path}/entry" + assert check_target(path, kind) == path + + +def test_a_column_of_a_frame_the_store_does_not_have_is_refused(new_store): + """F199: `raw/var/score` in a store with no raw was written into + mappings made for it and exited 0; anndata then showed a raw copied + from X, without the column.""" + path, opener = new_store() + with opener("r") as root: + with pytest.raises(ValueError, match="which this store does not hold as a dataframe"): + validate_dimensions(root, "raw/var/score", (N_VAR,), console) + + +def test_a_column_of_a_frame_outside_obs_and_var_is_measured_against_its_index(new_store): + """F199: a frame anywhere, such as one in uns, takes a column as long as + its index; no axis measures it, and pandas builds no frame otherwise.""" + path, opener = new_store() + with opener("a") as root: + ew.write_dataframe_header(root["uns"], "table", ["a", "b", "c", "d"], []) + with opener("r") as root: + validate_dimensions(root, "uns/table/score", (4,), console) + with pytest.raises(ValueError, match="input has 3 rows, but 'uns/table' has 4"): + validate_dimensions(root, "uns/table/score", (3,), console) + with pytest.raises(ValueError, match="is the index of 'uns/table'"): + validate_dimensions(root, "uns/table/_index", (4,), console) From 61475d6beca98600190874a102c91f70a84b61f3 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 17:47:45 +0000 Subject: [PATCH 2/3] Review fixes: raw/var's columns only, MuData's own groups, encoded frames MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A path inside a column of raw/var (a categorical's categories) is no longer measured against raw's variables as if it were a column, nor fails on a scalar with 'tuple index out of range'; every dimension lookup in validate.py now follows a check that the input has it. - A frame encoded as anything but a dataframe (the dict raw/var 0.17.8 left behind) takes no column; one with no encoding still does, since anndata reads its every member as a column. - MuData's own top-level groups (mod, obsmap, varmap) are written to as before: an .h5mu is HDF5 to import, and `mod/rna/obsm/...` is AnnData. - Messages: a frame's length in rows; shapes with '×' throughout. - Tests: refusals run with --inplace, so the source read afterwards is the store a write would have changed; anndata's refusal of an unknown top-level key on every backend; a text column into a frame with none; an unencoded obs; an .h5mu modality; anndata 0.7's layout. - Docs: the troubleshooting entries for both length messages, MuData's groups and the frame refusal in commands.md. Co-Authored-By: Claude Opus 5.5 --- docs/reference/commands.md | 12 ++-- docs/troubleshooting.md | 15 +++- src/adata/formats/validate.py | 56 ++++++++------- tests/test_import.py | 128 ++++++++++++++++++++++++++++++---- tests/test_validate.py | 47 ++++++++++++- 5 files changed, 207 insertions(+), 51 deletions(-) diff --git a/docs/reference/commands.md b/docs/reference/commands.md index e572fc6..d4346a6 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -520,8 +520,9 @@ back exactly. ## `import` Write data into a store at any path of the AnnData layout: in `X`, `obs`, -`var`, `obsm`, `varm`, `obsp`, `varp`, `layers`, `uns` or `raw`. All -subcommands need `--output`/`-o` or `--inplace`, and refuse both at once. +`var`, `obsm`, `varm`, `obsp`, `varp`, `layers`, `uns` or `raw` (and, in a +MuData `.h5mu`, its own `mod`, `obsmap` and `varmap`). All subcommands need +`--output`/`-o` or `--inplace`, and refuse both at once. An import never edits a store in place. The source is copied beside the destination (beside itself with `--inplace`), the element is written into @@ -561,8 +562,7 @@ store. An element of a kind the AnnData layout does not allow where it would go is refused before anything is written, since anndata could not then read the store: anything outside the layout's top level, such as `variance_explained` -(put it in `uns`), since anndata cannot read a store holding a top-level -element it does not know; an array, a matrix, an image or JSON in place of +(put it in `uns`); an array, a matrix, an image or JSON in place of `obs`, `var` or `raw/var`; anything in place of the whole of `obsm`, `varm`, `obsp`, `varp` or `layers`, or of `uns` but a JSON object; JSON or a dataframe as `X`; an array that is not 1-D as a column of a dataframe. Name @@ -573,8 +573,8 @@ An array written into a dataframe, such as `obs/score` (or a column of `var`, of `raw/var`, or of a frame in `obsm` or `uns`), is a column of it: it is added to the frame's `column-order`, from which anndata reads a frame's columns, and a column it replaces keeps its place. It is refused if -it is not as long as the frame or the store has no such frame, and if it is -named as the frame's index, which it would replace, or `_index` or +it is not as long as the frame, if the store holds no such dataframe, or if +it is named as the frame's index, which it would replace, or `_index` or `__categories`, which anndata keeps for a frame's index and, in older stores, its categories. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 5b59df5..46fdeff 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -178,9 +178,18 @@ The ordering operators compare numbers. For text, use `==`, `!=` or `in`. See ### `First dimension mismatch: input has 2000 rows, but obs has 2688 cells.` `import` checks an array's length against the axis its path implies: -`obsm/...` and obs's columns against obs, `varm/...` and var's columns -against var, `X` and layers against both, and `raw/...` against raw's own -variables. The input belongs to another store, or is transposed. +`obsm/...`, `obsp/...` and obs's columns against obs; `varm/...`, `varp/...` +and var's columns against var; `X`, layers and `raw/X` against obs (and +their columns against var, or raw's variables); `raw/varm/...` against raw's +own variables. The input belongs to another store, or is transposed. + +### `Row count mismatch: input has 2 rows, but raw has 4 variables.` + +A table imported as a whole frame, or an array imported as a column of one, +has a row for each of the frame's: obs's cells, var's features, raw's own +variables for `raw/var`, which are usually more than var's, and for a frame +elsewhere, such as one in `uns`, its own rows (`... but 'uns/table' has 4 +rows.`). ### `'obs' must hold a dataframe; writing an array there would leave a store anndata cannot read.` diff --git a/src/adata/formats/validate.py b/src/adata/formats/validate.py index 49ef39e..339c077 100644 --- a/src/adata/formats/validate.py +++ b/src/adata/formats/validate.py @@ -34,6 +34,11 @@ #: is a second raw. TOP_LEVEL = ("X", "obs", "var", "obsm", "varm", "obsp", "varp", "layers", "uns", "raw") +#: A MuData store's own top-level groups, written to as they are: an .h5mu +#: is an HDF5 file like any other here, and its modalities, such as +#: `mod/rna/obsm/X_umap`, are AnnData. +_MUDATA_TOP_LEVEL = ("mod", "obsmap", "varmap") + #: Paths that must hold a dataframe, so writing an array there would corrupt #: the store rather than merely mis-size it. DATAFRAME_PATHS = frozenset({"obs", "var", "raw/var"}) @@ -109,7 +114,7 @@ def check_target(obj_path: str, kind: str) -> str: f"'{path or '/'}' is a group of elements, not one; name the entry " "to write, such as 'X', 'obsm/X_pca' or 'uns/params'." ) - if path.split("/", 1)[0] not in TOP_LEVEL: + if path.split("/", 1)[0] not in TOP_LEVEL + _MUDATA_TOP_LEVEL: raise ValueError( f"'{path}' is outside the AnnData layout, whose top level holds only " f"{', '.join(TOP_LEVEL[:-1])} and {TOP_LEVEL[-1]}: writing {what} there " @@ -238,6 +243,11 @@ def _validate_column( holds, and not the frame's index: written there, the array would replace the index. Nor is it `_index`, which anndata keeps for the index, or `__categories`, where anndata 0.7 kept categoricals' labels. + + A frame with no encoding at all is one anndata reads every member of + as a column, as older writers left obs; a group encoded as anything but + a dataframe (such as the dict a column of a missing raw/var used to + make) takes no column anndata would read. """ frame_path = _frame_of(root, path) if frame_path is None: @@ -245,10 +255,11 @@ def _validate_column( if len(data_shape) != 1: raise ValueError( f"'{path}' would be a column of '{frame_path}', which holds 1-D arrays, " - f"but the input's shape is {'x'.join(map(str, data_shape)) or 'a scalar'}." + f"but the input's shape is {'×'.join(map(str, data_shape)) or 'a scalar'}." ) frame = _member(root, frame_path) - if frame is None or not is_group(frame): + encoding = spec.encoding_type(frame) if frame is not None and is_group(frame) else None + if frame is None or not is_group(frame) or encoding not in (None, "", spec.DATAFRAME): raise ValueError( f"'{path}' would be a column of '{frame_path}', which this store " "does not hold as a dataframe." @@ -288,6 +299,7 @@ def _validate_raw(root: Any, obj_path: str, data_shape: Tuple[int, ...]) -> bool rest = obj_path[len("raw/"):] if rest == "var": + _check_ndim(obj_path, data_shape, 1, n_raw_var, "variable of raw") if n_raw_var is not None and data_shape[0] != n_raw_var: raise ValueError( f"Row count mismatch: input has {data_shape[0]} rows, but raw " @@ -296,10 +308,11 @@ def _validate_raw(root: Any, obj_path: str, data_shape: Tuple[int, ...]) -> bool ) return True - if rest.startswith("var/"): + if rest.startswith("var/") and "/" not in rest[len("var/"):]: # A column of raw/var, which `_validate_column` has found 1-D. It # used to pass unchecked, and a column of any length was written - # (F200). + # (F200). A path inside one, such as a categorical's `categories`, + # is no column: it is left to the note, as before. if n_raw_var is not None and data_shape[0] != n_raw_var: raise ValueError( f"Row count mismatch: input has {data_shape[0]} rows, but raw " @@ -343,20 +356,15 @@ def _validate_aligned(root: Any, path: str, data_shape: Tuple[int, ...]) -> bool n_obs = _get_axis_length(root, "obs") n_var = _get_axis_length(root, "var") - if path == "obs": - if n_obs is not None and data_shape[0] != n_obs: - raise ValueError( - f"Row count mismatch: input has {data_shape[0]} rows, " - f"but obs has {n_obs} cells." - ) - return True - if path == "var": - if n_var is not None and data_shape[0] != n_var: - raise ValueError( - f"Row count mismatch: input has {data_shape[0]} rows, " - f"but var has {n_var} features." - ) - return True + for frame, n in (("obs", n_obs), ("var", n_var)): + if path == frame: + _check_ndim(path, data_shape, 1, n, _ROW[frame]) + if n is not None and data_shape[0] != n: + raise ValueError( + f"Row count mismatch: input has {data_shape[0]} rows, " + f"but {frame} has {n} {_ROW[frame]}s." + ) + return True if path == "X" or path.startswith("layers/"): if len(data_shape) < 2: @@ -407,10 +415,10 @@ def validate_dimensions( A path aligned to an axis is measured against it: X, layers, obsm, obsp and obs's columns against obs; varm, varp and var's columns - against var; raw's X, varm, var and var's columns against raw's own - variables. A column of any dataframe, obs's or one in obsm or uns, is - also 1-D, as long as the frame, and not named as its index. A path - none of this covers passes, with a note. + against var; raw's var, its columns and raw/varm against raw's own + variables, and raw/X against obs and them. A column of any dataframe, + obs's or one in obsm or uns, is also 1-D, as long as the frame, and not + named as its index. A path none of this covers passes, with a note. """ path = norm_path(obj_path).strip("/") data_shape = tuple(data_shape) @@ -424,7 +432,7 @@ def validate_dimensions( if rows is not None and data_shape[0] != rows: raise ValueError( f"Row count mismatch: input has {data_shape[0]} rows, but " - f"'{frame_path}' has {rows}." + f"'{frame_path}' has {rows} rows." ) elif not known: console.print(f"[dim]Note: No dimension validation for path '{literal(path)}'[/]") diff --git a/tests/test_import.py b/tests/test_import.py index 6982d59..1866e06 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -18,6 +18,7 @@ from adata.cli import app from tests.conftest import backend_path, backend_zarr_format +from tests.reference_stores import legacy_store runner = CliRunner() @@ -1144,6 +1145,35 @@ def test_a_replaced_column_keeps_its_place_and_is_listed_once(written, temp_dir) np.testing.assert_array_equal(obs["a"].to_numpy(), np.load(temp_dir / "a.npy")) +@pytest.mark.parametrize("fmt", ["h5ad", "zarr"]) +def test_a_column_imported_into_a_store_anndata_0_7_wrote_is_listed(temp_dir, fmt): + """F199, in anndata 0.7's layout (frames of version 0.1.0, categoricals' + labels in `__categories`): the new column is listed after the others, + which read back as they did.""" + + def read(path): + # anndata warns that the layout is old; that is the point here. + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return ad.read_h5ad(path) if fmt == "h5ad" else ad.read_zarr(path) + + source = legacy_store(fmt, temp_dir / "legacy") + before = read(source).obs + np.save(temp_dir / "v.npy", np.arange(len(before), dtype="float64")) + out = temp_dir / f"out.{fmt}" + + result = runner.invoke( + app, ["import", "array", str(source), "obs/imported", str(temp_dir / "v.npy"), "-o", str(out)] + ) + + assert result.exit_code == 0, _out(result) + after = read(out).obs + assert list(after.columns) == list(before.columns) + ["imported"] + for column in before.columns: + pd.testing.assert_series_equal(after[column], before[column]) + np.testing.assert_array_equal(after["imported"].to_numpy(), np.load(temp_dir / "v.npy")) + + def test_a_column_of_a_frame_in_obsm_or_uns_is_listed_and_measured(temp_dir, backend): """F199: a column of any dataframe, not only obs's, was written without being listed, so anndata never read it. A frame in uns, which no axis @@ -1173,7 +1203,7 @@ def test_a_column_of_a_frame_in_obsm_or_uns_is_listed_and_measured(temp_dir, bac result, out = _import("array", store, "uns/table/wrong", temp_dir / "rows.npy") assert result.exit_code == 1 - assert "Row count mismatch: input has 6 rows, but 'uns/table' has 4." in _out(result) + assert "Row count mismatch: input has 6 rows, but 'uns/table' has 4 rows." in _out(result) assert not out.exists() assert list(_read(store).uns["table"].columns) == ["b"] @@ -1200,11 +1230,10 @@ def test_a_column_named_as_the_index_is_refused(temp_dir, backend, index_name, e store = _write_as(obj, temp_dir, backend, "named") np.save(temp_dir / "v.npy", np.arange(N_OBS, dtype="float64")) - result, out = _import("array", store, entry, temp_dir / "v.npy") + result = runner.invoke(app, ["import", "array", str(store), entry, str(temp_dir / "v.npy"), "--inplace"]) assert result.exit_code == 1 assert message in _out(result) - assert not out.exists() kept = _read(store).obs assert list(kept.index) == [f"c{i}" for i in range(N_OBS)] assert list(kept.columns) == ["n"] @@ -1257,12 +1286,11 @@ def test_an_input_without_the_dimensions_its_path_needs_is_refused_by_name( source = temp_dir / "v.npy" np.save(source, np.ones(shape)) - result, out = _import("array", written, entry, source) + result = runner.invoke(app, ["import", "array", str(written), entry, str(source), "--inplace"]) assert result.exit_code == 1 assert message in _out(result) assert "tuple index" not in _out(result) - assert not out.exists() kept = _read(written) assert set(kept.obsm) == {"X_pca"} and set(kept.obsp) == {"distances"} @@ -1287,26 +1315,96 @@ def test_a_top_level_key_outside_the_layout_is_refused_for_what_it_is( np.save(temp_dir / "v.npy", np.arange(7, dtype="float64")) (temp_dir / "p.json").write_text('{"a": 1}') - result, out = _import(kind, written, entry, temp_dir / source) + result = runner.invoke(app, ["import", kind, str(written), entry, str(temp_dir / source), "--inplace"]) assert result.exit_code == 1 assert f"'{entry}' is outside the AnnData layout" in _out(result) assert f"Put it in uns, such as 'uns/{entry}'" in _out(result) assert "features" not in _out(result) - assert not out.exists() assert _read(written).shape == (N_OBS, 3) -def test_anndata_cannot_read_a_store_holding_a_top_level_key_outside_its_layout(temp_dir): +def test_anndata_cannot_read_a_store_holding_a_top_level_key_outside_its_layout(written, backend): """F202's oracle: anndata hands every top-level member to `AnnData()`, so one it does not know leaves the whole store unreadable. That is why `import` refuses such a key, where the audit expected it written.""" - path = temp_dir / "extra.h5ad" - ad.AnnData(X=np.zeros((2, 3), dtype="float32")).write_h5ad(path) - with h5py.File(path, "a") as handle: - extra = handle.create_dataset("variance_explained", data=np.arange(3.0)) - extra.attrs["encoding-type"] = "array" - extra.attrs["encoding-version"] = "0.2.0" + from adata.elements.write import write_dense + from adata.storage import open_store + + with open_store(written, "a", zarr_format=backend_zarr_format(backend)) as store: + write_dense(store.root, "variance_explained", np.arange(3.0)) with pytest.raises(TypeError, match="variance_explained"): - _read(path) + _read(written) + + +def test_a_text_column_goes_into_a_frame_that_had_none(temp_dir, backend): + """F199 for text, into a frame with no columns, whose `column-order` is + empty (on HDF5, an empty array of floats): anndata lists the column.""" + obj = ad.AnnData( + X=np.zeros((N_OBS, 2), dtype="float32"), + obs=pd.DataFrame(index=[f"c{i}" for i in range(N_OBS)]), + ) + store = _write_as(obj, temp_dir, backend, "bare") + labels = np.array([f"type {i % 2}" for i in range(N_OBS)]) + np.save(temp_dir / "labels.npy", labels) + + result, out = _import("array", store, "obs/label", temp_dir / "labels.npy") + + assert result.exit_code == 0, _out(result) + obs = _read(out).obs + assert list(obs.columns) == ["label"] + assert obs["label"].astype(str).tolist() == labels.tolist() + + +def test_a_column_goes_into_an_obs_with_no_encoding_as_anndata_reads_one(temp_dir): + """anndata reads an obs group with no encoding, as some older writers + left it, with every member but `obs_names` as a column. Such a frame + takes a column, with no `column-order` to list it in, rather than + being refused as a frame encoded as something else is.""" + store = temp_dir / "unencoded.h5ad" + with h5py.File(store, "w") as handle: + for axis, names in (("obs", [f"c{i}" for i in range(N_OBS)]), ("var", ["g1", "g2"])): + group = handle.create_group(axis) + group.attrs["_index"] = f"{axis}_names" + group.create_dataset(f"{axis}_names", data=np.array(names, dtype="S")) + handle["obs"].create_dataset("n", data=np.arange(N_OBS)) + handle.create_dataset("X", data=np.zeros((N_OBS, 2), dtype="float32")) + np.save(temp_dir / "v.npy", np.arange(N_OBS) + 0.5) + + result, out = _import("array", store, "obs/score", temp_dir / "v.npy") + + assert result.exit_code == 0, _out(result) + with warnings.catch_warnings(): + # anndata warns that the store has no encoding; that is the point. + warnings.simplefilter("ignore") + got = ad.read_h5ad(out) + assert list(got.obs_names) == [f"c{i}" for i in range(N_OBS)] + assert sorted(got.obs.columns) == ["n", "score"] + np.testing.assert_array_equal(got.obs["score"].to_numpy(), np.load(temp_dir / "v.npy")) + + +def test_a_modality_of_an_h5mu_is_still_a_target(temp_dir): + """`import` takes a MuData `.h5mu` as the HDF5 file it is, and its + modalities are AnnData: `mod/rna/obsm/X_new` is written as before, + though `mod` is no part of AnnData's own top level.""" + obj = ad.AnnData( + X=np.ones((N_OBS, 3), dtype="float32"), + obs=pd.DataFrame(index=[f"c{i}" for i in range(N_OBS)]), + var=pd.DataFrame(index=["g1", "g2", "g3"]), + ) + obj.write_h5ad(temp_dir / "one.h5ad") + result = runner.invoke(app, ["convert", str(temp_dir / "one.h5ad"), "-o", str(temp_dir / "one.h5mu")]) + assert result.exit_code == 0, _out(result) + np.save(temp_dir / "e.npy", np.full((N_OBS, 2), 3.0)) + + result = runner.invoke( + app, + ["import", "array", str(temp_dir / "one.h5mu"), "mod/rna/obsm/X_new", str(temp_dir / "e.npy"), + "-o", str(temp_dir / "out.h5mu")], + ) + + assert result.exit_code == 0, _out(result) + with h5py.File(temp_dir / "out.h5mu", "r") as handle: + rna = ad.io.read_elem(handle["mod/rna"]) + np.testing.assert_array_equal(rna.obsm["X_new"], np.load(temp_dir / "e.npy")) diff --git a/tests/test_validate.py b/tests/test_validate.py index 560b7a9..01fd08f 100644 --- a/tests/test_validate.py +++ b/tests/test_validate.py @@ -80,7 +80,7 @@ def test_correct_shapes_are_accepted(root, path, shape): ("raw/X", (N_OBS,), "raw/X requires 2D"), ("raw/varm/PCs", (99, 3), "raw has 5 variables"), ("obs/score", (99,), "obs has 3 cells"), - ("obs/score", (N_OBS, 2), "which holds 1-D arrays, but the input's shape is 3x2"), + ("obs/score", (N_OBS, 2), "which holds 1-D arrays, but the input's shape is 3×2"), ("raw/var/score", (N_VAR,), "raw has 5 variables"), ("obsm/s", (), "'obsm/s' needs one row per cell (3), but the input is a scalar"), ("varm/s", (), "'varm/s' needs one row per feature (2), but the input is a scalar"), @@ -157,8 +157,12 @@ def test_a_top_level_name_outside_the_layout_is_refused(path): check_target(path, "array") -@pytest.mark.parametrize("path", [*TOP_LEVEL[:-1], "raw/X", "raw/varm/PCs", "uns/anything/deep"]) +@pytest.mark.parametrize( + "path", [*TOP_LEVEL[:-1], "raw/X", "raw/varm/PCs", "uns/anything/deep", "mod/rna/obsm/X_umap", "obsmap/rna"] +) def test_every_name_of_the_layout_is_still_a_target(path): + """A MuData store's own groups (`mod/rna/...`) are written to as before: + an .h5mu is an HDF5 file like any other here.""" kind = "dataframe" if path in DATAFRAME_PATHS else "dict" if path == "uns" else "array" if path in ("obsm", "varm", "obsp", "varp", "layers"): path = f"{path}/entry" @@ -183,7 +187,44 @@ def test_a_column_of_a_frame_outside_obs_and_var_is_measured_against_its_index(n ew.write_dataframe_header(root["uns"], "table", ["a", "b", "c", "d"], []) with opener("r") as root: validate_dimensions(root, "uns/table/score", (4,), console) - with pytest.raises(ValueError, match="input has 3 rows, but 'uns/table' has 4"): + with pytest.raises(ValueError, match="input has 3 rows, but 'uns/table' has 4 rows"): validate_dimensions(root, "uns/table/score", (3,), console) with pytest.raises(ValueError, match="is the index of 'uns/table'"): validate_dimensions(root, "uns/table/_index", (4,), console) + + +@pytest.mark.parametrize("path", ["raw/var/ft/categories", "raw/var/sub/col"]) +@pytest.mark.parametrize("shape", [(2,), ()], ids=["two", "scalar"]) +def test_a_path_inside_a_column_of_raw_var_is_not_measured_as_a_column(root, path, shape, capsys): + """F200's check measures the columns of raw/var, not paths inside one: a + categorical's two labels were refused because raw has 5 variables, and + a scalar there failed with 'tuple index out of range'.""" + validate_dimensions(root, path, shape, console) + assert "No dimension validation" in capsys.readouterr().err + + +def test_a_frame_encoded_as_anything_but_a_dataframe_takes_no_column(new_store): + """F199: a column of a raw/var that 0.17.8 had made a dict (importing + into a store with no raw did) was written unmeasured and unlisted, and + anndata showed no column.""" + path, opener = new_store() + with opener("a") as root: + ew.write_mapping(ew.write_mapping(root, "raw"), "var") + with opener("r") as root: + with pytest.raises(ValueError, match="which this store does not hold as a dataframe"): + validate_dimensions(root, "raw/var/other", (7,), console) + + +def test_a_frame_with_no_encoding_takes_a_column(new_store): + """anndata reads an obs group with no encoding, as older writers left + it, with every member as a column, so such a frame takes one.""" + path, opener = new_store() + with opener("a") as root: + for key in list(root["obs"].attrs): + if key != "_index": + del root["obs"].attrs[key] + with opener("r") as root: + assert "encoding-type" not in root["obs"].attrs + validate_dimensions(root, "obs/score", (N_OBS,), console) + with pytest.raises(ValueError, match="is the index of 'obs'"): + validate_dimensions(root, "obs/_index", (N_OBS,), console) From 8c53a255bd426aecf25b24666a345010e0f8634c Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 17:57:23 +0000 Subject: [PATCH 3/3] Refuse MuData's groups in a store that is no MuData check_target cannot see the store, so it let `mod`, `obsmap` and `varmap` through everywhere, and `import array data.h5ad mod/x` wrote a store anndata cannot read. validate_dimensions, which sees the store and runs in import's precheck, now refuses them unless the store is laid out as a MuData (a `mod` group). It asks the layout, not the root's encoding: open_store stamps AnnData's encoding on the copy an import writes into, so an .h5mu says "anndata" there. The troubleshooting entry for "Row count mismatch" no longer claims the columns of obs and var, which fail with "First dimension mismatch". Co-Authored-By: Claude Opus 5.5 --- docs/troubleshooting.md | 11 +++++----- src/adata/formats/validate.py | 39 +++++++++++++++++++++++++++++------ tests/test_import.py | 14 +++++++++++++ tests/test_validate.py | 28 +++++++++++++++++++++++-- 4 files changed, 79 insertions(+), 13 deletions(-) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 46fdeff..bb230ab 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -185,11 +185,12 @@ own variables. The input belongs to another store, or is transposed. ### `Row count mismatch: input has 2 rows, but raw has 4 variables.` -A table imported as a whole frame, or an array imported as a column of one, -has a row for each of the frame's: obs's cells, var's features, raw's own -variables for `raw/var`, which are usually more than var's, and for a frame -elsewhere, such as one in `uns`, its own rows (`... but 'uns/table' has 4 -rows.`). +A table imported as a whole frame has a row for each of the frame's: obs's +cells, var's features, or for `raw/var` raw's own variables, which are +usually more than var's. So has an array imported as a column of `raw/var`, +or of a frame elsewhere, such as one in `uns` (`... but 'uns/table' has 4 +rows.`). A column of obs or var is measured as their other entries are +(above). ### `'obs' must hold a dataframe; writing an array there would leave a store anndata cannot read.` diff --git a/src/adata/formats/validate.py b/src/adata/formats/validate.py index 339c077..5b1ba45 100644 --- a/src/adata/formats/validate.py +++ b/src/adata/formats/validate.py @@ -36,7 +36,9 @@ #: A MuData store's own top-level groups, written to as they are: an .h5mu #: is an HDF5 file like any other here, and its modalities, such as -#: `mod/rna/obsm/X_umap`, are AnnData. +#: `mod/rna/obsm/X_umap`, are AnnData. `check_target` cannot see the store +#: and lets them through; `validate_dimensions`, which can, refuses them in +#: a store that is no MuData, where anndata could not read them. _MUDATA_TOP_LEVEL = ("mod", "obsmap", "varmap") #: Paths that must hold a dataframe, so writing an array there would corrupt @@ -94,6 +96,15 @@ def parent_of(path: str) -> str: return path.rsplit("/", 1)[0] if "/" in path else "" +def _outside_layout(path: str, what: str, note: str = "") -> ValueError: + """The refusal of a path outside the layout's top level.""" + return ValueError( + f"'{path}' is outside the AnnData layout, whose top level holds only " + f"{', '.join(TOP_LEVEL[:-1])} and {TOP_LEVEL[-1]}: writing {what} there " + f"{_UNREADABLE}.{note} Put it in uns, such as 'uns/{path}'." + ) + + def check_target(obj_path: str, kind: str) -> str: """The normalised path, once it is known that a `kind` element may go there: "array", "sparse", "dict" or "dataframe". @@ -106,6 +117,7 @@ def check_target(obj_path: str, kind: str) -> str: the layout's top level is refused: a top-level `variance_explained` was measured against var, as if it were one of var's, and refused for that (F202), but written it would leave a store anndata cannot read. + MuData's own groups pass here, for `validate_dimensions` to judge. """ path = norm_path(obj_path).strip("/") what = _WHAT[kind] @@ -115,11 +127,7 @@ def check_target(obj_path: str, kind: str) -> str: "to write, such as 'X', 'obsm/X_pca' or 'uns/params'." ) if path.split("/", 1)[0] not in TOP_LEVEL + _MUDATA_TOP_LEVEL: - raise ValueError( - f"'{path}' is outside the AnnData layout, whose top level holds only " - f"{', '.join(TOP_LEVEL[:-1])} and {TOP_LEVEL[-1]}: writing {what} there " - f"{_UNREADABLE}. Put it in uns, such as 'uns/{path}'." - ) + raise _outside_layout(path, what) if path in DATAFRAME_PATHS: if kind != "dataframe": raise ValueError( @@ -190,6 +198,17 @@ def _member(root: Any, path: str) -> Optional[Any]: return node +def _is_mudata(root: Any) -> bool: + """Is the store laid out as a MuData, with its modalities under `mod`? + + Asked of the layout, not of the root's encoding as + `conversion/mudata.is_mudata_root` asks: `open_store` stamps AnnData's + encoding on any store it opens to write, so the copy an import writes + into says "anndata" even when it is an .h5mu. + """ + return "mod" in root and is_group(root["mod"]) + + def _check_ndim( path: str, data_shape: Tuple[int, ...], ndim: int, n: Optional[int], row: str ) -> None: @@ -419,10 +438,18 @@ def validate_dimensions( variables, and raw/X against obs and them. A column of any dataframe, obs's or one in obsm or uns, is also 1-D, as long as the frame, and not named as its index. A path none of this covers passes, with a note. + + MuData's own groups (`mod`, `obsmap`, `varmap`), which `check_target` + lets through, are refused unless the store is a MuData: written into + an AnnData store, they leave one anndata cannot read. """ path = norm_path(obj_path).strip("/") data_shape = tuple(data_shape) + top = path.split("/", 1)[0] + if top in _MUDATA_TOP_LEVEL and not _is_mudata(root): + raise _outside_layout(path, "it", f" '{top}' belongs to a MuData store, and this is none.") + column = _validate_column(root, path, data_shape) known = _validate_raw(root, path, data_shape) or _validate_aligned(root, path, data_shape) if column is not None: diff --git a/tests/test_import.py b/tests/test_import.py index 1866e06..ab5e017 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -1384,6 +1384,20 @@ def test_a_column_goes_into_an_obs_with_no_encoding_as_anndata_reads_one(temp_di np.testing.assert_array_equal(got.obs["score"].to_numpy(), np.load(temp_dir / "v.npy")) +@pytest.mark.parametrize("entry", ["mod/x", "obsmap/rna"]) +def test_a_mudata_group_in_an_anndata_store_is_refused(written, temp_dir, entry): + """F202: a top-level `mod` or `obsmap`, as a MuData store has, was + written into an AnnData store, which anndata then could not read.""" + np.save(temp_dir / "v.npy", np.arange(N_OBS, dtype="float64")) + + result = runner.invoke(app, ["import", "array", str(written), entry, str(temp_dir / "v.npy"), "--inplace"]) + + assert result.exit_code == 1 + assert f"'{entry}' is outside the AnnData layout" in _out(result) + assert "belongs to a MuData store, and this is none" in _out(result) + assert _read(written).shape == (N_OBS, 3) + + def test_a_modality_of_an_h5mu_is_still_a_target(temp_dir): """`import` takes a MuData `.h5mu` as the HDF5 file it is, and its modalities are AnnData: `mod/rna/obsm/X_new` is written as before, diff --git a/tests/test_validate.py b/tests/test_validate.py index 01fd08f..9863e36 100644 --- a/tests/test_validate.py +++ b/tests/test_validate.py @@ -161,8 +161,9 @@ def test_a_top_level_name_outside_the_layout_is_refused(path): "path", [*TOP_LEVEL[:-1], "raw/X", "raw/varm/PCs", "uns/anything/deep", "mod/rna/obsm/X_umap", "obsmap/rna"] ) def test_every_name_of_the_layout_is_still_a_target(path): - """A MuData store's own groups (`mod/rna/...`) are written to as before: - an .h5mu is an HDF5 file like any other here.""" + """`check_target` cannot see the store, so it also lets a MuData + store's own groups (`mod/rna/...`) through; `validate_dimensions`, which + can, judges them (below).""" kind = "dataframe" if path in DATAFRAME_PATHS else "dict" if path == "uns" else "array" if path in ("obsm", "varm", "obsp", "varp", "layers"): path = f"{path}/entry" @@ -228,3 +229,26 @@ def test_a_frame_with_no_encoding_takes_a_column(new_store): validate_dimensions(root, "obs/score", (N_OBS,), console) with pytest.raises(ValueError, match="is the index of 'obs'"): validate_dimensions(root, "obs/_index", (N_OBS,), console) + + +@pytest.mark.parametrize("path", ["mod/x", "obsmap/rna", "varmap/rna"]) +def test_a_mudata_group_is_refused_in_a_store_that_is_no_mudata(root, path): + """F202: `mod`, `obsmap` and `varmap` are a MuData store's own groups; + written into an AnnData store, they left one anndata could not read + ("unexpected keyword argument 'mod'").""" + with pytest.raises(ValueError, match="outside the AnnData layout.*belongs to a MuData store"): + validate_dimensions(root, path, (N_OBS,), console) + + +def test_a_mudata_group_passes_in_a_store_laid_out_as_a_mudata(new_store, capsys): + """Judged by the layout (modalities under `mod`), not the root's + encoding: opening a store to write stamps AnnData's on it, so the copy + an import writes into says "anndata" even when it is an .h5mu.""" + path, opener = new_store() + with opener("a") as root: + ew.write_mapping(ew.write_mapping(root, "mod"), "rna") + with opener("r") as root: + assert str(root.attrs["encoding-type"]) == "anndata" + validate_dimensions(root, "mod/rna/obsm/x", (N_OBS, 2), console) + validate_dimensions(root, "obsmap/rna", (N_OBS,), console) + assert "No dimension validation" in capsys.readouterr().err