Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 27 additions & 10 deletions docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
21 changes: 19 additions & 2 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.`

Expand All @@ -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
Expand Down
26 changes: 24 additions & 2 deletions src/adata/formats/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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 (`<U` or `S`) is written as a string array.
Text (`<U` or `S`) is written as a string array. Into a dataframe
(`obs/score`) the array is a column, listed in the frame's
`column-order` so that anndata reads it.
"""
obj = check_target(obj, "array")
if _holds_objects(input_file):
Expand Down Expand Up @@ -256,5 +275,8 @@ def import_npy(
block = decode_str_array(block).astype(object)
target[start:end] = block

if spec.encoding_type(parent) == spec.DATAFRAME:
_list_column(parent, name)

shape_str = "×".join(str(d) for d in arr.shape)
console.print(f"[green]Imported[/] {shape_str} array into '{literal(obj)}'")
Loading
Loading