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
7 changes: 6 additions & 1 deletion docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,12 @@ of that with one choice. Elements are not re-encoded, so a store written by
anndata 0.7 keeps its legacy layout.

The input and the options are checked before anything is written; what only
the data can show, such as an index out of range, stops the copy. Either way
the data can show, such as an index out of range, stops the copy. A
pycisTopic pickle is refused if it holds anything a pycisTopic object's
pickle never does, or names a length its bytes do not hold (see
[pycisTopic pickles](formats/cistopic.md#pickles-are-trusted-input)), or if
a sample in its `path_to_fragments` holds `/` or is empty, which a store
cannot hold as a key. Either way
the output is written beside its destination (`out.adata-tmp.zarr`) and
moved into place only once complete, so a failed conversion leaves nothing
behind. An existing output is
Expand Down
45 changes: 39 additions & 6 deletions docs/reference/formats/cistopic.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,49 @@ written:
every pickle of them does, never constructed from the file's arguments;
- every sparse matrix has its indices within its shape and an `indptr`
that rises from 0 to its number of entries, every categorical's codes
lie within its categories, and every table's columns hold as many rows
as its index.
lie within its categories, and every table's blocks hold as many rows as
its index and each of its columns once. Each is checked as soon as it is
complete, before anything else in the file can take it apart, and is
given its state only in the form pandas or scipy pickles it in;
- the few builtins a pickle may call are given only what a pickle of them
holds (`set` a list, `range` integers), and nothing is hashed, as a
dict's key, a set's item, or a name, but numbers, text and tuples of
them, counted first: a tuple made of the same tuple at each level costs
a pickle a few bytes a level, and comes to twice as many values a
level;
- a length the file names rather than holds, such as a `range`, a
`RangeIndex`, or the shape of an empty array or a sparse matrix, is no
more than the bytes the file holds (inflated, for a gzipped pickle), and
is counted before anything is made for it, so a small file cannot make
the conversion take gigabytes.

Dates and times are not read; pycisTopic's objects hold none.

A pickle written by pycisTopic's pandas 1.5 reads with pandas 2 or 3, as CI
checks. Columns are written as anndata writes them: Categorical as
categorical, nullable integers and booleans as nullable, numbers held as
`object` as numbers, repeated text as categorical. Anything else on the
object is named in a warning and left out.
checks, and so does one saved again under pandas 3, whose text is held in
Arrow: that text is decoded here, every offset checked against the text it
indexes, without pyarrow. Columns are written as anndata writes them:
Categorical as categorical, nullable integers and booleans as nullable,
numbers held as `object` as numbers (integers as int64, or as uint64 past
it, as pandas reads them; as floats, with a warning, when no integer dtype
holds them, or when a missing value sits beside an integer a float cannot
hold exactly), repeated text as categorical. Anything else on the object is
named in a warning and left out.

A column label is the column's name in the store, and HDF5 and Zarr read a
`/` in a name as a path, and `""`, `.` and `..` as the group itself or its
parent: such a label is renamed (`a/b` to `a_b`, `""` to `_`) with a
warning, to a name no other column has. A sample in `path_to_fragments` is
a key in the same way, but one like that is refused instead: cell_data's
`sample_id` and the cell names, which end with it, name the sample as it
is, and a renamed key would no longer match them. Names are read from a
list, an array, an index or a Series of them, each text or a number; cell
or feature names given as anything else, such as a table, are refused.

Only text, numbers and flat lists or tuples of them are written as text:
a column holding anything else, nested deeper or not plain data, is left
out with a warning, and a label like that refused. Written out, a value
nested in itself would come to twice as much text a level.

## Memory

Expand Down
6 changes: 3 additions & 3 deletions docs/reference/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ inside every release before PyPI has it.
| `test_text.py` | Text matrices in every layout anndata's `read_text` tells apart (corner, short and comment headers, no header, no row names), each delimiter, gzip, `--transpose` CSR and dense, dtypes, refusals by line, small blocks |
| `test_hdf5.py` | One dataset of a plain HDF5 file: the listing without `--key`, `read_hdf`'s `row_names` / `col_names` and other names, `--transpose` CSR and dense, slabs of chunks, `--from hdf5` on `.h5` |
| `test_dense.py` | `conversion/dense.py`, which the loom and HDF5 importers read a dense matrix through: datasets chunked every way that changes how it reads them, on each output backend, read back by anndata |
| `test_cistopic.py` | pycisTopic pickles read through the allowlist: a CistopicObject's matrices, frames, model and projections, an imputed-features pickle, a pickle naming `os.system` refused unrun, the missing-extra hint |
| `test_pickled.py` | The restricted unpickler against crafted pickles that name only allowlisted globals, each loaded in a child process so a crash cannot take the run down |
| `test_cistopic.py` | pycisTopic pickles read through the allowlist: a CistopicObject's matrices, frames, model and projections, an imputed-features pickle, a pickle naming `os.system` refused unrun, the missing-extra hint; a pickle pandas 3 saved, its Arrow text read with pyarrow hidden; labels a store cannot hold renamed, such samples refused; integers past int64; names a pickle does not hold refused unlisted |
| `test_pickled.py` | The restricted unpickler against crafted pickles that name only allowlisted globals, each loaded in a child process so a crash cannot take the run down, then here once refused: objects refused before a `set` or a hash takes them apart, states only in the forms pandas pickles, lengths and shared parts held to the bytes the file holds, every check reached by a pickle crafted for it, Arrow text decoded (malformed layouts refused, as pyarrow's own validation refuses them), the sniff reading only a file's head |
| `test_visium.py` | Space Ranger output: standard Visium (Space Ranger 1 to 4) laid out as `squidpy.read.visium` lays it out, Visium HD bins at each size, segmented cells, Space Ranger's analysis, images, refusals |
| `test_xenium.py` | Xenium bundles (XOA 1 to 4): the cell table in or out of the matrix's order, cells the matrix lacks, Xenium's analysis with gaps |
| `test_geojson.py` | `formats/geojson.py`: Space Ranger 4's cell outlines read a feature at a time, centroids and areas against shapely |
| `test_pandas_frame.py` | Each pandas dtype written as anndata writes it, on every backend |
| `test_pandas_frame.py` | Each pandas dtype written as anndata writes it, on every backend; labels a store cannot hold as a name renamed, integers past int64 kept, past any float written as text; only text, numbers and flat lists written as text; attrs copied once |
| `test_concat_axis_elements.py` | `concat` on obsm dataframes and varm, against `anndata.concat` for each join and merge strategy |
| `test_legacy_copies.py` | anndata 0.7's dataframes (categoricals as codes with an object reference into `__categories`) copied by `subset` (h5ad and Zarr), `convert` to Zarr v2/v3 and a MuData import: written as current `categorical` groups in a 0.2.0 frame, read back by anndata with their categories |
| `test_subset_categories.py` | `subset` and `split` narrow categoricals as anndata's subsetting does: unused categories dropped (on an axis kept whole too), order and `ordered` kept, `uns["<col>_colors"]` narrowed with them; compared with anndata's own subset |
Expand Down
19 changes: 19 additions & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,25 @@ written. Drop the element from a copy first, or subset it with anndata.
`subset` with no selection would copy the store. Use `convert` to copy, or add
a selection.

### `obj.pkl: the pickle ..., which a pycisTopic object's never does, so it is not read.`

The pickle names, calls or holds something a pycisTopic object's pickle
never does: a function outside what such an object holds, an array, matrix
or table that is not well formed, or a length (of a `range`, an index, an
empty array) longer than the file itself. Nothing in it was run, and
nothing was written. A pickle that pycisTopic saved is not refused; if
yours was, please
[report it](https://github.com/cellgeni/adata-cli/issues) with the message.

### `obj.pkl: path_to_fragments names the sample 's/1', which an h5ad or Zarr store cannot hold as a key: ...`

Each sample's fragment file is written under the sample's name, and HDF5
and Zarr read `/` in a name as a path. A column label like that is renamed
with a warning, but a sample is not: cell_data's `sample_id` and the cell
names would no longer match the renamed key. Rename the sample in pycisTopic
(in `path_to_fragments`, and in `sample_id` and the cell names to keep them
matching), save the object again, and convert that.

## Visium and Xenium

These are refused before anything is written too.
Expand Down
85 changes: 70 additions & 15 deletions src/adata/conversion/cistopic.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
from adata.formats import pickled
from adata.storage import COMPRESSIONS, create_dataset, is_zarr_group, open_store, with_compression
from adata.util.markup import literal
from adata.util.names import claim, count_duplicates, make_index_unique, sanitize_label
from adata.util.names import claim, count_duplicates, make_index_unique, sanitize_label, storable

EXTENSIONS = (".pkl", ".pickle", ".pkl.gz", ".pickle.gz")

Expand Down Expand Up @@ -220,20 +220,70 @@ def _is_sparse(value: Any) -> bool:
return sp.issparse(value)


def _names(values: Any) -> List[str]:
return [str(v) for v in list(values)]
#: What a name may be: text, or a number written as text.
_NAMES = (str, bytes, int, float, np.generic, type(None))


def _names(values: Any, what: str, name: str) -> List[str]:
"""Names as text. Each must be text or a number: anything else may
share its parts with itself many times over (a tuple of the same tuple
at each level) and spell out as text far longer than it is held."""
listed = list(values)
for value in listed:
if not isinstance(value, _NAMES):
raise ValueError(f"{name}: its {what} holds a {type(value).__name__}, not a name.")
return [str(v) for v in listed]


def _count(values: Any, what: str, name: str) -> int:
"""How many names `values` holds, counted without listing them: they
are compared with the matrix before anything is made of them. Only a
sequence of names lists as many as it counts: a frame's length is its
rows, but listing it gives its columns."""
import pandas as pd

if isinstance(values, (list, tuple, range, pd.Index, pd.Series)) or (
isinstance(values, np.ndarray) and values.ndim == 1
):
return len(values)
raise ValueError(f"{name}: its {what} is a {type(values).__name__}, not a list of names.")


def _check_samples(fragments: Any, name: str) -> None:
"""`path_to_fragments`' samples, as keys a store can hold. A sample
holding `/`, or empty, is refused rather than renamed: cell_data's
`sample_id` and every cell name's suffix name it as it is, and a
renamed key would no longer match them."""
if not isinstance(fragments, dict):
return
seen = set()
for sample, path in fragments.items():
key = str(sample)
if not isinstance(path, (str, bytes)):
raise ValueError(f"{name}: path_to_fragments gives the sample {key!r} a {type(path).__name__}, not a path.")
if storable(key) != key:
raise ValueError(
f"{name}: path_to_fragments names the sample {key!r}, which an h5ad or Zarr "
"store cannot hold as a key: '/' separates its paths, and it has no empty names."
)
if key in seen:
raise ValueError(f"{name}: path_to_fragments names the sample {key!r} twice.")
seen.add(key)


def _ordered(frame: Any, names: List[str], axis: str, what: str, warnings: List[str]) -> Any:
"""`frame` with its rows (or, `axis="columns"`, columns) in `names` order."""
labels = frame.index if axis == "index" else frame.columns
if [str(v) for v in labels] == names:
from adata.formats.pandas_frame import label_text

labels = [label_text(v, f"A row of {what}" if axis == "index" else f"A column of {what}")
for v in (frame.index if axis == "index" else frame.columns)]
if labels == names:
return frame
frame = frame.copy()
if axis == "index":
frame.index = [str(v) for v in frame.index]
frame.index = labels
else:
frame.columns = [str(v) for v in frame.columns]
frame.columns = labels
missing = len(set(names) - set(frame.index if axis == "index" else frame.columns))
if missing:
warnings.append(f"{what} lacks {missing:,} of the names; they are missing values.")
Expand All @@ -244,12 +294,15 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import:
matrix = getattr(obj, "fragment_matrix", None)
if not _is_sparse(matrix):
raise ValueError(f"{name}: its CistopicObject holds no sparse fragment_matrix.")
cells, regions = _names(obj.cell_names), _names(obj.region_names)
if matrix.shape != (len(regions), len(cells)):
n_regions = _count(getattr(obj, "region_names", None), "region_names", name)
n_cells = _count(getattr(obj, "cell_names", None), "cell_names", name)
if matrix.shape != (n_regions, n_cells):
raise ValueError(
f"{name}: fragment_matrix is {matrix.shape[0]:,} x {matrix.shape[1]:,}, but "
f"the object names {len(regions):,} regions and {len(cells):,} cells."
f"the object names {n_regions:,} regions and {n_cells:,} cells."
)
_check_samples(getattr(obj, "path_to_fragments", None), name)
cells, regions = _names(obj.cell_names, "cell_names", name), _names(obj.region_names, "region_names", name)
detail = _Import("CistopicObject", obj, len(cells), len(regions), cells, regions)
if _is_frame(getattr(obj, "cell_data", None)):
detail.cell_data = _ordered(obj.cell_data, cells, "index", "cell_data", warnings)
Expand All @@ -261,7 +314,7 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import:
if isinstance(model, pickled.PycistopicObject):
cell_topic = getattr(model, "cell_topic", None)
if _is_frame(cell_topic):
detail.topics = _names(cell_topic.index)
detail.topics = _names(cell_topic.index, "model's topics", name)
frame = _ordered(cell_topic, cells, "columns", "cell_topic", warnings)
detail.arrays.append(("obsm", claim("X_topic", taken), frame.to_numpy().T))
harmony = getattr(model, "cell_topic_harmony", None)
Expand Down Expand Up @@ -296,13 +349,15 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import:

def _plan_imputed(obj: Any, name: str) -> _Import:
matrix = getattr(obj, "mtx", None)
features, cells = _names(obj.feature_names), _names(obj.cell_names)
if matrix is None or tuple(matrix.shape) != (len(features), len(cells)):
n_features = _count(getattr(obj, "feature_names", None), "feature_names", name)
n_cells = _count(getattr(obj, "cell_names", None), "cell_names", name)
if matrix is None or tuple(matrix.shape) != (n_features, n_cells):
shape = "nothing" if matrix is None else f"{matrix.shape[0]:,} x {matrix.shape[1]:,}"
raise ValueError(
f"{name}: its matrix is {shape}, but it names {len(features):,} features "
f"and {len(cells):,} cells."
f"{name}: its matrix is {shape}, but it names {n_features:,} features "
f"and {n_cells:,} cells."
)
features, cells = _names(obj.feature_names, "feature_names", name), _names(obj.cell_names, "cell_names", name)
if not _is_sparse(matrix):
if not isinstance(matrix, np.ndarray) or matrix.ndim != 2:
raise ValueError(f"{name}: its matrix is a {type(matrix).__name__}, not an array.")
Expand Down
Loading
Loading