Skip to content
API REFERENCEUsage guides →

Storage API ​

Use Store for lazy matrix access, Writer for incremental encoding, and File when you need embedded regions or chunk metadata. For an executable selection and streaming-write workflow, see matrix access.

python
from pycellpack import CSR, File, Store, Writer, read, write, compress
from pycellpack.cellpack import GeneMap, ReadOptions, ReadSelection, ReadWorkspace
from pycellpack import io

Select an interface

Entry points and results ​

InterfaceInputResult
Store(source, *, shape=None, dtype=None)Path, File or StoreImmutable lazy matrix view
File(path, *, offset=0, length=None)Path and optional bounded stream regionStream handle; no matrix decoding
File.from_bytes(buffer)Encoded stream bytesFile backed by an owned anonymous copy
read(path, cells=None, genes=None, ...)Path/File and positional selectorsNumPy ndarray or CSR
write(path, matrix, ...)NumPy, SciPy sparse, CSR or SparseRowFile-backed Store
compress(matrix, ...)Same matrix inputsStore over an anonymous in-memory stream
Writer(path, n_cols, dtype, ...)Declared width/type, then append callsIncremental writer; finish() returns None
io.open_cpk(source, ...)Path, File, Store or encoded bytesStore; an existing Store is returned unchanged
io.read_cpk / io.iter_cpkStream or Store and selectorsOne decoded result / successive decoded row batches
io.write_cpk(path, matrix, ...)Whole matrix, 2-D Store or iterable of batchesFile-backed Store; streamed inputs need at least one batch
io.cpk_info(source, ...)Stream sourceCpkInfo: stream shape, dtype, format, sizes and chunk count

cpk_info describes the underlying stream, even when passed a selected Store; it does not describe that view's selected dimensions. CpkInfo.bytes_per_cell includes metadata and returns zero for an empty matrix. Stream inspection does not decode record values.

Views and selections ​

OperationContract
store[cells, genes]Orthogonal, axis-preserving selection; both axes support slices, integers, integer arrays and boolean masks
store.astype(dtype)Choose decode dtype without decoding; copy does not force materialization
store.copy()Return the same immutable view
store.map_genes(gene_map, n_genes=None)Map each current column to a distinct output position; unfilled output positions read as zero
store.prepare(read_options=None)Prepare reusable metadata; repeated columns are rejected
store.read(format=None, ...)Decode in stored format by default; "dense" returns ndarray, "csr" returns CSR
store.iter_batches(batch_size=4096, ...)Decode successive view rows; batch size must be positive

Order and repeated positions are preserved. Negative integer positions and negative-step slices follow positional indexing. Boolean mask lengths must match their current axis. Selection arrays exposed by cells and genes are read-only; genes=None means every source column in order. Strings are not gene or cell selectors: the stream stores no names.

For gene mapping, GeneMap owns the validated source-to-output map. cellpack.selection.as_gene_map also accepts an integer vector or a dict from current source positions to targets. The map covers every current column; -1 or scans.UNMAPPED drops a column, kept targets are distinct and below n_genes. This map assigns output positions, whereas a DataSource map assigns standard vocabulary IDs; see gene alignment. normalize_rows(rows, size) produces contiguous uint64 positional IDs.

Store(file, shape=...) requires its first dimension to equal stream rows and the product of trailing dimensions to equal stream columns. Only dense streams support more than two dimensions; those views allow row selection and dense reads only. Stores are read-only: materialize before assigning values.

Dtypes and materialized results ​

Supported value dtypes are uint8/16/32/64, int8/16/32/64, float32 and float64 in native byte order. A view/selection dtype requests conversion during decoding; compression alone preserves stored value bits. Conversion can lose precision.

read_dense, toarray and np.asarray(store) produce dense NumPy arrays. read_csr produces the package's NumPy-backed CSR without requiring SciPy. to_memory converts sparse output to a SciPy csr_array; tocsr always returns that SciPy type. CSR.to_scipy() requests shared storage, so later mutation of shared buffers can affect both representations.

Prepared reads and buffer extents ​

File.prepare_read(rows=None, *, gene_map=None, n_genes=None, dtype=None, read_options=None) reads selection metadata and returns ReadSelection. shape, dtype, capacity_nnz and io_summary describe the prepared result. Omitting output storage allocates arrays; supplied buffers follow these rules:

ReadRequired outputReturned storage
selection.read_dense(out=...)ndarray with exact selection.shape and selection.dtypeThe supplied array itself
selection.read_csr(out=...)CSR with matching shape, or (indptr, indices, data)CSR sharing supplied buffers; indices/data trimmed to actual entries
CSR indptrExactly rows + 1 elementsFinal value gives actual stored-entry count
CSR indices, dataCapacity for selection.capacity_nnz; data dtype matches selectionUnused trailing capacity is not output data

capacity_nnz is source-based capacity, not an exact mapped count: column filtering can reduce the returned CSR.nnz. Explicit sparse zeros remain stored entries. Allocated CSR indices/offsets use index_dtype=np.int64; int32, uint32 and uint64 are also supported. Caller-supplied indices additionally accept uint16, while row offsets require one of the four allocation types. The chosen integer widths must hold the resulting indices and offsets.

Outputs must be native-endian, aligned, writable and C-contiguous. Inputs, outputs and scratch must not overlap where native calls reject overlapping regions. Do not mutate or resize arrays borrowed by a native call, or read an output concurrently with its write. A ReadWorkspace retains scratch and permits one active read; use separate workspaces concurrently. After any failed read, discard potentially partial output.

Allocating Store reads can expand repeated selected columns. Such a view cannot prepare() or write CSR into caller-supplied buffers; dense out= remains supported. See the worked buffer example.

Payload read policy ​

ReadOptions fieldDefaultMeaning
strategy"auto"Compare range/whole-region read costs; "ranges" or "whole" forces a policy
max_gap_bytes0Maximum gap joined while merging selected ranges
request_cost_bytes4096Per-request byte-equivalent cost in the auto heuristic

ReadSummary reports record_bytes, read_bytes, requests and whole_chunk_bytes for one payload execution, excluding metadata preparation. These are application read estimates, not physical device traffic or calibration.

Writing and publication ​

Writer defaults are format="csr", chunk_rows=4096, page_size=4096, options=None, workers=None, atomic=False. write, compress and io.write_cpk instead default stored format to their input layout. Page size is a power of two from 512 through 65536 bytes; chunk_rows counts encoding rows. options accepts scans.EncodeOptions.

Every append(matrix) must match declared dtype and width. Dense or sparse batches can feed either stored layout. NumPy buffers are normalized; SciPy sparse inputs are canonicalized by sorting and summing duplicates. Package CSR/SparseRow inputs must already have sorted, distinct column indices per row. Explicit masked values must be filled before encoding.

ActionLifecycle
appendEncode more rows in order; stream is unfinished
end_chunkEnd the current encoding chunk early
finish / successful context exitFlush/finalize, then publish an atomic destination; returns None
abort / exceptional context exitClose unfinished work and discard atomic staging

Writers belong to their creating process. Without atomic mode an existing path can be truncated. atomic=True stages beside a regular destination and replaces it only after success; abort preserves the destination. Existing permission bits are preserved; a new atomic file uses mode 0600. Atomic publication does not promise persistence across power loss. Keep a completed stream immutable while readers or loaders use it.

Encoding and decoding release the GIL and use native worker threads. workers=None uses available CPUs, capped at 32 by default; the nonempty PYCELLPACK_WORKERS environment value overrides that default. Explicit counts and environment overrides must be positive and are capped by available CPU capacity, including affinity/cgroup quota. They are not fixed to the default 32-worker ceiling.

File regions, chunk access and identity ​

offset and length bound an embedded encoded stream. File.chunks returns its directory. read_chunk(chunk, out=None, metadata_only=False) reads encoded bytes, accepting negative chunk indices; chunk_meta(chunk) parses metadata using the stream dtype. Chunk APIs expose encoded components rather than materialized matrices; see codecs for record operations.

A File retains the opened descriptor and recorded device/inode identity. After path replacement, existing native reads use the original file; is_current reports whether the path still names it. to_bytes() rejects a replacement, and unpickling rejects a changed identity. File.from_bytes copies into anonymous storage; such Files pickle by copying their encoded bytes. Stores pickle their file and composed view. Exporting the whole region can require a large buffer.

Invalid types/selectors/buffer declarations raise TypeError, IndexError or ValueError as appropriate; file failures raise OSError. Those checked errors do not validate arbitrary trusted record bytes. Keep encoded data paired with its metadata, and do not modify files in place during reads.

Complete declarations ​

Complete declarations and members

Store ​

python
Store(source: File | Store | str | PathLike, *, shape: tuple[int, ...] | None=None, dtype=None)

An immutable, lazily indexed view of one CellPack stream.

Rows are cells. Each output column is a stored column or an absent one, which reads as zeros, so a Store can present a stream in a panel the caller lays out. Columns are addressed by position only. Views come from:

  • store[cells, genes]: orthogonal selection, as in AnnData or h5py. Integers keep their axis. Both axes take slices, integers, integer arrays (any order, repeats) and boolean masks.
  • map_genes: place columns by a caller-given column → panel map.
  • astype: convert values while decoding.

None of these read data. read, read_dense and read_csr decode into NumPy / ~pycellpack.cellpack.CSR (into caller buffers with out=); prepare returns a ReadSelection for repeated reads; to_memory, toarray, tocsr and np.asarray return NumPy / SciPy objects. Higher-rank dense arrays stored with flattened trailing axes take their logical shape and select cells only.

Store.file ​

file: File — property.

The underlying stream; views never modify it.

Store.shape ​

shape: tuple[int, ...] — property.

Store.ndim ​

ndim: int — property.

Store.size ​

size: int — property.

Store.dtype ​

dtype: np.dtype — property.

Store.format ​

format: str — property.

Natural output format of the stream: "dense" or "csr".

Store.cells ​

cells: np.ndarray — property.

Read-only source cell ids in output order.

Store.genes ​

genes: np.ndarray | None — property.

Read-only source ids per output column (-1 absent), or None for all.

Store.selects_all_cells ​

selects_all_cells: bool — property.

True when the view shows every stored cell once, in order.

Store.is_identity ​

is_identity: bool — property.

True when the view is the whole stream in its stored dtype.

Store.map_genes ​

python
Store.map_genes(gene_map, n_genes: int | None=None) -> Store

Place this view's columns into a panel of width n_genes.

gene_map gives each current column's panel position: a GeneMap, an integer array with -1 or UNMAPPED for dropped columns, or a mapping from column positions to panel positions. Positions must be distinct; unfilled panel positions read as zeros.

Store.astype ​

python
Store.astype(dtype, copy: bool=True) -> Store

Convert values to another CellPack numeric dtype while decoding.

Store.copy ​

python
Store.copy() -> Self

Return this view; Stores are immutable, so sharing is a copy.

Store.prepare ​

python
Store.prepare(*, read_options: ReadOptions | None=None) -> ReadSelection

Prepare reusable read metadata (views without repeated genes).

Store.read ​

python
Store.read(format: str | None=None, *, out=None, index_dtype=np.int64, workspace: ReadWorkspace | None=None, read_options: ReadOptions | None=None, workers: int | None=None)

Decode as NumPy (logical shape) or CSR.

format defaults to the stream's own. Dense out must be C-contiguous with the view's size and dtype; CSR out follows ReadSelection.read_csr. Chunks decode on workers threads (default: one per CPU, at most 32).

Store.read_dense ​

python
Store.read_dense(*, out=None, workspace=None, read_options=None, workers=None) -> np.ndarray

Decode this view into a NumPy array. out must match the view shape/dtype and is returned when supplied.

Store.read_csr ​

python
Store.read_csr(*, out=None, index_dtype=np.int64, workspace=None, read_options=None, workers=None) -> CSR

Decode this view into a NumPy-backed CSR. out accepts CSR or (indptr, indices, data) with sufficient capacity.

Store.to_memory ​

python
Store.to_memory()

Decode in the stream's format: NumPy, or a SciPy csr_array.

Store.toarray ​

python
Store.toarray() -> np.ndarray

Store.tocsr ​

python
Store.tocsr()

Decode as a SciPy csr_array.

Store.iter_batches ​

python
Store.iter_batches(batch_size: int=4096, *, format: str | None=None, **kwargs)

Yield read() results for consecutive cell batches of this view.

read ​

python
read(path: str | PathLike | File, cells=None, genes=None, *, format: str | None=None, dtype=None, **kwargs)

Decode selected cells and genes of a stream; see Store.read.

write ​

python
write(path: str | PathLike, matrix, *, format: str | None=None, workers: int | None=None, chunk_rows: int=4096, page_size: int=4096, options: EncodeOptions | None=None, atomic: bool=False) -> Store

Write a matrix to one .cpk stream and return a Store over it.

matrix may be NumPy (any layout), SciPy sparse (any format), CSR or SparseRow; sparse input is canonicalized. format picks the stored layout ("dense" or "csr") and defaults to the input's own. Chunks are encoded by workers threads (default: one per CPU, at most 32). atomic=True preserves the destination on failure; see Writer.

compress ​

python
compress(matrix, *, format: str | None=None, workers: int | None=None, chunk_rows: int=4096, page_size: int=4096, options: EncodeOptions | None=None) -> Store

Encode a matrix into an in-memory stream and return a Store over it.

Arguments follow write. The encoded bytes stay in this process (pickling copies them); reads decode only what they select.

File ​

python
File(path: str | PathLike, *, offset: int=0, length: int | None=None, _memory: _Memory | None=None)

The low-level handle of one matrix stream: a .cpk file, a bounded region of another file (such as an H5CP dataset), or an in-memory stream (from_bytes).

A File exposes the stream's layout, chunk I/O and prepared reads (prepare_read); ~pycellpack.cellpack.Store is the array API over it. A stream holds the matrix only; columns are selected by position and cellpack keeps no names.

File.from_bytes ​

python
File.from_bytes(buffer) -> File

Open an encoded stream held in memory (copied into an anonymous file).

File.identity ​

identity: tuple[int, int] — property.

Device and inode of the opened descriptor, fixed at opening.

File.in_memory ​

in_memory: bool — property.

True for streams held in anonymous memory rather than on disk.

File.to_bytes ​

python
File.to_bytes() -> bytes

Return the whole region; reject a path replaced since opening.

File.is_current ​

python
File.is_current() -> bool

Whether path still names the file this stream was opened from.

Reads always use the opened file; a path replaced since then (for example by an atomic rewrite) no longer refers to the same bytes.

File.shape ​

shape: tuple[int, int] — property.

File.dtype ​

dtype: np.dtype — property.

File.format ​

format: str — property.

Stored layout the matrix was written from: "dense" or "csr".

File.page_size ​

page_size: int — property.

File.prepare_read ​

python
File.prepare_read(rows=None, *, gene_map: GeneMap | np.ndarray | dict | None=None, n_genes: int | None=None, dtype=None, read_options: ReadOptions | None=None) -> ReadSelection

Prepare a reusable read of rows (a slice, integer ids in any order with repeats, or a boolean mask; default all cells).

gene_map places source columns into a panel of n_genes columns (see ~pycellpack.cellpack.GeneMap); dtype is the output dtype (default: stored). Only metadata is read here.

File.chunks ​

chunks: list[ChunkEntry] — property.

The chunk directory, one entry per chunk in row order.

File.read_chunk ​

python
File.read_chunk(chunk: int, *, out: np.ndarray | None=None, metadata_only: bool=False) -> np.ndarray

Read one chunk's bytes (or only its metadata) into out.

File.chunk_meta ​

python
File.chunk_meta(chunk: int) -> Meta

Parsed metadata of one chunk, read in the stored dtype.

Writer ​

python
Writer(path: str | PathLike, n_cols: int, dtype, *, format: str='csr', chunk_rows: int=4096, page_size: int=4096, options: EncodeOptions | None=None, workers: int | None=None, atomic: bool=False)

Streaming stream writer. A stream becomes readable after finish().

append takes dense or sparse rows whatever the stored format; the native writer converts them. Whole chunks within one append are encoded by workers threads (default: one per CPU, at most 32); the file is identical to a serial write. Append many rows at a time to let chunks encode concurrently.

With atomic=True, a sibling temporary file is published only after finish succeeds; abort leaves the destination untouched. This requires a regular filesystem path and does not guarantee power-loss durability. New atomic files are private (mode 0600); existing permission bits are kept.

Writer.append ​

python
Writer.append(matrix) -> None

Append rows from NumPy, SciPy sparse, CSR or SparseRow input.

The dtype and column count must match the writer's.

Writer.end_chunk ​

python
Writer.end_chunk() -> None

End the current chunk early; the next row starts a new one.

Writer.finish ​

python
Writer.finish() -> None

Finalize the stream and publish an atomic destination. Returns None; reopen the path as Store to read it.

Writer.abort ​

python
Writer.abort() -> None

Close unfinished output and discard an atomic staging file. Returns None.

ReadOptions ​

Physical read policy; request_cost_bytes is an explicit Auto heuristic.

Fields and defaults ​

python
strategy: str = 'auto'
max_gap_bytes: int = 0
request_cost_bytes: int = 4096

ReadSummary ​

Payload I/O planned for one execution, excluding metadata preparation.

Fields and defaults ​

python
record_bytes: int
read_bytes: int
requests: int
whole_chunk_bytes: int

ReadSelection ​

Read metadata of a cell selection, reusable across output arrays.

dtype is the output dtype values are converted to. capacity_nnz sizes CSR outputs; dropped genes can reduce the nnz a read returns. Reads split the selected chunks over workers threads (default: one per CPU, at most 32); a workspace keeps their scratch between reads.

ReadSelection.io_summary ​

io_summary: ReadSummary — property.

ReadSelection.shape ​

shape: tuple[int, int] — property.

ReadSelection.dtype ​

dtype: np.dtype — property.

ReadSelection.capacity_nnz ​

capacity_nnz: int — property.

ReadSelection.read_dense ​

python
ReadSelection.read_dense(*, out: np.ndarray | None=None, workspace: ReadWorkspace | None=None, workers: int | None=None) -> np.ndarray

ReadSelection.read_csr ​

python
ReadSelection.read_csr(*, out: CSR | tuple[np.ndarray, np.ndarray, np.ndarray] | None=None, index_dtype=np.int64, workspace: ReadWorkspace | None=None, workers: int | None=None) -> CSR

Canonical CSR; caller out buffers need capacity_nnz entries.

indptr may be int32/int64/uint32/uint64 and indices also uint16.

CSR ​

Canonical CSR arrays, all sharing one decoded dtype.

indptr holds shape[0] + 1 row starts, indices and data are parallel and column ids ascend within each row. data may be longer than nnz: callers that reserve a capacity slice the views they export.

Fields and defaults ​

python
indptr: np.ndarray
indices: np.ndarray
data: np.ndarray
shape: tuple[int, int]

CSR.nnz ​

nnz: int — property.

Stored element count: the last indptr entry.

CSR.to_scipy ​

python
CSR.to_scipy()

Build a scipy.sparse.csr_array over these arrays, asking for no copy.

SciPy normally shares the buffers, so mutating them later changes the matrix too; indices must already be canonical for SciPy's own operations.

GeneMap ​

python
GeneMap(targets: Any, n_genes: int | None=None) -> None

GeneMap.n_genes ​

n_genes: int — property.

GeneMap.targets ​

targets: np.ndarray — property.

GeneMap.is_identity ​

is_identity: bool — property.

ReadWorkspace ​

python
ReadWorkspace() -> None

ReadWorkspace.clear ​

python
ReadWorkspace.clear() -> None

open_cpk ​

python
open_cpk(source, *, offset: int=0, length: int | None=None) -> Store

A lazy ~pycellpack.cellpack.Store over a stream.

source is a path (offset/length bound a stream embedded in a larger file), a ~pycellpack.cellpack.File, a Store (returned as is) or encoded bytes. Nothing is decoded until the Store is read.

read_cpk ​

python
read_cpk(source, cells=None, genes=None, *, format: str | None=None, dtype=None, **kwargs)

Decode selected cells and genes of a stream.

cells and genes take what Store indexing takes (slices, integer arrays with repeats, boolean masks; None for all). format is "dense" (a NumPy array), "csr" (a ~pycellpack.cellpack.CSR) or None for the stored layout; dtype converts values. Other keywords go to Store.read (workers, out, workspace, ...).

iter_cpk ​

python
iter_cpk(source, batch_size: int=4096, *, format: str | None=None, cells=None, dtype=None, **kwargs) -> Iterator[Any]

Decode successive batches of batch_size cells (of cells when given), each as read_cpk returns them.

write_cpk ​

python
write_cpk(path: str | PathLike, matrix, *, format: str | None=None, workers: int | None=None, chunk_rows: int=4096, page_size: int=4096, options: EncodeOptions | None=None, atomic: bool=False) -> Store

Write one .cpk stream and return a Store over it.

matrix is a whole matrix (NumPy, SciPy sparse, CSR or SparseRow), a Store (re-encoded batch by batch, so it may be larger than memory, and may read the file being replaced when atomic=True) or an iterable of row batches with one column count and dtype (streamed; nothing but the current batch is held). format is the stored layout, "dense" or "csr", by default the input's own (a Store's stored layout, the first batch's). The remaining arguments are ~pycellpack.cellpack.Writer's.

cpk_info ​

python
cpk_info(source, *, offset: int=0, length: int | None=None) -> CpkInfo

Shape, dtype, layout, page and chunk sizes of a stream, without decoding any record.

CpkInfo ​

A stream's layout, read from its superblock and directory alone.

Fields and defaults ​

python
path: Path | None
offset: int
shape: tuple[int, int]
dtype: np.dtype
format: str
page_size: int
chunk_rows: int
n_chunks: int
nbytes: int

CpkInfo.bytes_per_cell ​

bytes_per_cell: float — property.

Encoded bytes per stored cell (the whole stream, metadata included).