diff --git a/docs/reference/commands.md b/docs/reference/commands.md index ce88b37..d4346a6 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -519,8 +519,10 @@ 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` (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 @@ -549,17 +551,32 @@ 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`); 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, 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. 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..bb230ab 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -178,8 +178,19 @@ 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/...`, `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 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.` @@ -188,6 +199,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: 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". @@ -76,7 +113,11 @@ def check_target(obj_path: str, kind: str) -> 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. + MuData's own groups pass here, for `validate_dimensions` to judge. """ path = norm_path(obj_path).strip("/") what = _WHAT[kind] @@ -85,6 +126,8 @@ 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 + _MUDATA_TOP_LEVEL: + raise _outside_layout(path, what) if path in DATAFRAME_PATHS: if kind != "dataframe": raise ValueError( @@ -145,11 +188,129 @@ 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 _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: + """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. + + 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: + 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 {'×'.join(map(str, data_shape)) or 'a scalar'}." + ) + frame = _member(root, frame_path) + 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." + ) + 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) @@ -157,6 +318,7 @@ def _validate_raw( 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 " @@ -165,6 +327,18 @@ def _validate_raw( ) return True + 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). 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 " + f"has {n_raw_var} variables." + ) + return True + if rest == "X": if len(data_shape) < 2: raise ValueError( @@ -183,6 +357,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 +368,98 @@ 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": + 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: + 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"Row count mismatch: input has {data_shape[0]} rows, " + f"First dimension mismatch: input has {data_shape[0]} rows, " f"but obs has {n_obs} cells." ) - return - if obj_path == "var": - if n_var is not None and data_shape[0] != n_var: + if n_var is not None and data_shape[1] != n_var: raise ValueError( - f"Row count mismatch: input has {data_shape[0]} rows, " + f"Second dimension mismatch: input has {data_shape[1]} columns, " 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)}'[/]") + 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 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. + + 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: + # 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} 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..ab5e017 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() @@ -591,6 +592,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 +618,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 +1094,331 @@ 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")) + + +@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 + 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 rows." 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 = runner.invoke(app, ["import", "array", str(store), entry, str(temp_dir / "v.npy"), "--inplace"]) + + assert result.exit_code == 1 + assert message in _out(result) + 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 = 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) + 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 = 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 _read(written).shape == (N_OBS, 3) + + +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.""" + 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(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")) + + +@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, + 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 53375f7..9863e36 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 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"), + ("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,118 @@ 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", "mod/rna/obsm/X_umap", "obsmap/rna"] +) +def test_every_name_of_the_layout_is_still_a_target(path): + """`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" + 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 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) + + +@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