Skip to content
API REFERENCEUsage guides →

Codec components API ​

pycellpack.cellpack.scans encodes chunks and decodes records over NumPy buffers. Use it when your application owns the container or record-read strategy. Use Store for ordinary matrix files, or follow the codec guide for a complete round trip.

python
from pycellpack.cellpack import scans

Choose the interface you need

Numeric interpretation and metadata ​

Raw chunks store value width, not signedness or floating-point type. Meta(buffer, source_dtype=...) declares how those bits are read; its dtype must be a supported native numeric dtype of that width. Omitting it on Meta selects an unsigned integer dtype, which is usually wrong for float or signed input.

decode_chunk(raw_bytes, source_dtype=...) requires that argument explicitly. decode_chunk(meta) reuses the parsed interpretation; supplying a conflicting source_dtype raises ValueError. dtype= instead requests a numeric output conversion. It does not repair an incorrectly interpreted source. File.chunk_meta already supplies the stream's stored dtype.

Object / methodMeaning and ownership
MetaValidated private metadata snapshot; buffer retains the supplied bytes
shape, dtype, value_widthChunk rows/columns and declared stored interpretation
records()View of the complete records region in buffer; raises if it is absent
record_range(cell)A slice relative to the records region, not the chunk start
record(cell, records=...)View of that record; supplied records is already the records region
DecodeTables(meta) / EncodeTables(meta)Lookup tables bound to that metadata model
column_modes, table permutation arraysRead-only NumPy snapshots; no permutation array means identity order

Metadata-only bytes are sufficient for model inspection and table construction. Pass records= to chunk decoders when records are held separately. Derive metadata, tables and records from the same encoded chunk. After pack_chunk, parse its returned buffer again: packing changes offsets and byte extents.

Chunk and record operations ​

A chunk’s round trip
  1. 01
    Encodescans.encode_chunk

    Normalize matrix input and produce encoded chunk bytes.

  2. 02
    Inspect metadatascans.Meta

    Bind metadata to its matching encoded records.

  3. 03
    Decodescans.decode_dense / decode_csr

    Restore selected rows into NumPy or CSR output.

Python Parts objects own immutable snapshots. Outputs and scratch supplied by callers must satisfy the documented array and capacity requirements.

OperationInputResult
chunk_sizesMatrix, rows and encoding optionsChunkSizes(output_bytes, workspace_words)
encode_chunkSame input; optional out and workspaceWritten uint8 prefix, which can share out
decode_chunkRaw bytes plus source dtype, or Meta; format="dense" / "csr"NumPy ndarray / package CSR
decode_dense / decode_csrMeta and optional rows, records, tables, buffers or mappingSelected dense rows / CSR, in requested row order
encode_recordOne row and matching Meta/EncodeTables/optionsEncoded uint8 prefix under that chunk model
decode_recordMeta plus record bytes, PagedRecord or cell=SparseRow with trimmed indices and values
decode_record_denseSame record inputsOne dense row of shape (meta.n_dims,)
decode_partsSame record inputs; coded space by defaultOwned Parts
packed_len / pack_chunkEncoded chunk; page size default 4096 bytesPacked byte count / packed uint8 prefix
record_nnzRecord bytes or PagedRecordDeclared header count, not record integrity validation

rows addresses chunk-local rows. None selects all; integers, slices, masks and integer lists preserve the selected order and repetitions. Record calls accept either record or cell, never both. cell indexes the metadata's own record buffer. It is not a loader global cell ID.

encode_record requires one row with the model's dimensions and dtype, matching encoding tables and compatible encoding options. It does not rebuild a model for an unrelated row population. Chunk encoders accept NumPy, SciPy sparse, CSR and SparseRow inputs; package CSR must already have ascending distinct column indices per row. SciPy inputs are canonicalized before encoding.

Encoding options ​

EncodeOptions() defaults to renumbering, thresholds of 0.6, max_lanes=32, lane_min=32, column_modes=0.5, and automatic layout/value coding. Thresholds and column-mode share are in [0, 1]; None disables column modes. Lane caps are 1, 2, 4, 8, 16, 32; lane minimum is a power of two through 65536. Forced dense layout can remove explicit sparse-zero entries, even when the dense numeric matrix is unchanged. Keep automatic/sparse layout when CSR structure itself must round-trip.

Buffers, capacities, and fill ​

Buffer / sizing queryUnit and required extent
Encoding out, record_bound, packed_lenuint8 storage / bytes; only the returned prefix is meaningful
Encoding or decoding workspaceWritable contiguous uint64 words, not bytes
meta.decode_workspace_words, decode_workspace_boundScratch word count for one active decode
dense_bytes(meta, rows)Dense selection bytes in the stored dtype, before panel/dtype changes
Dense chunk outputExact (selected_rows, columns) shape and requested dtype
Dense record outputExact one-dimensional row width and dtype
CSR outputrows + 1 offsets and capacity for selection_nnz(meta, rows) indices/values

Output arrays must be writable, aligned, native-endian and C-contiguous. CSR accepts the package CSR or (indptr, indices, data); allocating calls default to int64 indices. Mapped CSR can return fewer entries than its source-based capacity: use the returned trimmed arrays and final row offset.

Fill.ZERO / "zero" initializes absent dense values. With a supplied output, Fill.ASSUME_ZEROED / "assume_zeroed" promises it is already all zero. It does not preserve arbitrary previous content correctly; clear a reused row before relying on that promise. Allocating calls provide zeroed storage for it.

Chunk decoders may split rows over workers threads. On the direct decode path, caller workspace serves the first thread; other threads allocate their own. Supplying gene_map, n_genes or dtype selects the Decoder panel path, whose tables and scratch are managed internally rather than reusing those standalone arguments. Construct a Decoder explicitly to reuse that state across calls.

Keep input/output/scratch regions disjoint as required by the call. Do not resize or mutate borrowed inputs while native work is active, and do not share one output or workspace between concurrent calls. Discard potentially partial output after a failed operation.

Column spaces and Parts ​

SpaceMeaningMapping rule
SourceOriginal input column positionChunk decode gene_map uses source → output
CodedThis chunk's compression permutationCompose the source map with compose_mapping(tables, map)
OutputDesired panel positionn_genes is panel width; unfilled positions are zero

Most decoders default to IdSpace.SOURCE; decode_parts defaults to CODED. For chunk decoding, gene_map, n_genes or dtype require source space. For Parts mapping, the map is indexed by that Parts object's space. -1 or UNMAPPED drops a source dimension; kept targets must be distinct and inside the output panel. A source-to-output map is not a loader vocabulary map.

OperationResult and ordering
compose_mappingCoded → output GeneMap composed from DecodeTables and a source → output map
map_denseDense panel row, with optional dtype conversion and fill policy
map_partsSparseRow, dropping unmapped genes; columns follow input element order and need not be sorted
map_parts_atOne entry per selected element position, preserving order/repeats; dropped dimensions keep UNMAPPED
cast_values / Dict.cast_intoConverted values / dictionary; supplied out must agree with explicit dtype

Filter UNMAPPED entries from map_parts_at before treating the result as a normal sparse row. Element positions address parts.elements, not gene IDs. Dense-layout Parts can have more elements than nonzeros. map_parts omits dense zero values; mapping selected positions retains the selected entries. Optional converted dictionary and modes arrays must match this row's components and target dtype; a mode vector addresses coded dimensions.

Python Parts owns private metadata, copied record/page bytes and scratch. Its ids, values, dictionary and rank properties expose read-only snapshots; mapping reads the stable private representation. expand_values(out=...) materializes all elements. These are owned Python objects, unlike Rust's borrowed Parts, and can outlive the original caller buffers.

Reusable objects and concurrency ​

PreparedEncoder(matrix, rows=None, options=...) snapshots input arrays and selection, then builds the model once. encode(out=..., workspace=...) can be called concurrently with independent output/scratch. Its meta describes the model before record placement: use it for encoding tables or independent record encoding, not cell-indexed decoding. Parse the encoded result for that.

Decoder(meta, gene_map=..., n_genes=..., dtype=...) composes the mapping and retains reusable native tables/scratch. It serves one call at a time, even when that call uses several workers; concurrent use raises RuntimeError. Give independent consumers separate Decoders. Its decode_record returns a dense panel row, whereas the standalone function returns SparseRow.

PagedRecord(pages, page_size, start, length) describes separately read pages in file order and the record's offset within the first page. Record/Parts decoders accept it. Pages must cover the declared record; all preceding pages are full-size. Cross-page decoding may stage bytes in scratch, so this does not promise zero-copy decoding.

kernel_set() reports the process binding; supported_kernel_sets() lists CPU capabilities. A supported ISA need not be the bound one. The Python extension binds the runtime when imported; set CELLPACK_KERNELS before importing PyCellPack, preferably in the environment used to launch the interpreter.

Errors and trusted records ​

Invalid dtype/buffer declarations, incompatible tables, out-of-range selectors or insufficient capacities raise TypeError, IndexError or ValueError as appropriate. Decoder concurrent use raises RuntimeError. Metadata checks and a successful record_nnz do not validate arbitrary compressed record internals. Only decode records produced for their matching chunk model; violating that trusted-record contract can cause undefined behavior in optimized native paths.

Declarations ​

Complete declarations and members

Meta ​

python
Meta(buffer: Bytes, *, source_dtype: DTypeLike | None=None)

Validated metadata snapshot; records remain byte views over caller input.

Chunk metadata stores value width, not signedness: source_dtype says how stored values read (default: unsigned integers of the width) and becomes dtype, the dtype decoding yields by default.

Meta.n_cells ​

n_cells: int — property.

Meta.n_dims ​

n_dims: int — property.

Meta.value_width ​

value_width: int — property.

Meta.index_width ​

index_width: int — property.

Meta.renumbered ​

renumbered: bool — property.

Meta.max_nnz ​

max_nnz: int — property.

Meta.max_elems ​

max_elems: int — property.

Meta.max_k ​

max_k: int — property.

Meta.nnz_total ​

nnz_total: int — property.

Meta.meta_len ​

meta_len: int — property.

Meta.records_start ​

records_start: int — property.

Meta.records_len ​

records_len: int — property.

Meta.chunk_len ​

chunk_len: int — property.

Meta.page_size ​

page_size: int — property.

Meta.decode_workspace_words ​

decode_workspace_words: int — property.

uint64 workspace words decoding any record of this chunk needs.

Meta.has_modes ​

has_modes: bool — property.

Meta.shape ​

shape: tuple[int, int] — property.

Meta.cell_nnz ​

python
Meta.cell_nnz(cell) -> int

Meta.cell_layout ​

python
Meta.cell_layout(cell) -> RecordLayout

Meta.cell_kind ​

python
Meta.cell_kind(cell) -> int

Meta.record_range ​

python
Meta.record_range(cell) -> slice

Meta.records ​

python
Meta.records(buffer: Bytes | None=None) -> np.ndarray

Meta.record ​

python
Meta.record(cell, *, records=None) -> np.ndarray

Meta.column_modes ​

python
Meta.column_modes() -> np.ndarray | None

EncodeOptions ​

Fields and defaults ​

python
renumber: bool = True
thresholds: Thresholds = field(default_factory=Thresholds)
max_lanes: int = DEFAULT_MAX_LANES
lane_min: int = DEFAULT_LANE_MIN
column_modes: float | None = DEFAULT_MODE_SHARE
layout: LayoutChoice | str = LayoutChoice.AUTO
values: ValueChoice | str = ValueChoice.AUTO

Thresholds ​

Fields and defaults ​

python
indices: float = DEFAULT_MU_INDICES
values: float = DEFAULT_MU_VALUES

EncodeTables ​

python
EncodeTables(meta: Meta)

Encoding lookup tables for one metadata model.

EncodeTables.coded_of_source ​

python
EncodeTables.coded_of_source() -> np.ndarray | None

DecodeTables ​

python
DecodeTables(meta: Meta)

Decoding lookup tables for one metadata model.

DecodeTables.source_of_coded ​

source_of_coded: np.ndarray | None — property.

DecodeTables.coded_of_source ​

coded_of_source: np.ndarray | None — property.

IdSpace ​

Fields and defaults ​

python
SOURCE = 'source'
CODED = 'coded'

Fill ​

Fields and defaults ​

python
ZERO = 'zero'
ASSUME_ZEROED = 'assume_zeroed'

RecordLayout ​

Fields and defaults ​

python
SPARSE = 'sparse'
DENSE = 'dense'

LayoutChoice ​

Fields and defaults ​

python
AUTO = 'auto'
SPARSE = 'sparse'
DENSE = 'dense'

ValueChoice ​

Fields and defaults ​

python
AUTO = 'auto'
RAW = 'raw'
DICT = 'dict'
MODES = 'modes'

PagedRecord ​

Fields and defaults ​

python
pages: list[np.ndarray]
page_size: int
start: int
length: int

Parts ​

An owned decoded object with stable private record and scratch storage.

Component properties return read-only NumPy snapshots. Mapping reads the private native data. expand_values(out=) writes into caller-owned storage.

Parts.nnz ​

nnz: int — property.

Parts.elements ​

elements: int — property.

Parts.layout ​

layout: RecordLayout — property.

Parts.ids ​

python
Parts.ids() -> np.ndarray

Parts.values ​

python
Parts.values() -> Values

Parts.expand_values ​

python
Parts.expand_values(*, out=None) -> np.ndarray

Dict ​

python
Dict(parts: Parts)

Dict.entries ​

python
Dict.entries() -> np.ndarray

Dict.ranks ​

python
Dict.ranks() -> Ranks

Dict.cast_into ​

python
Dict.cast_into(dtype: DTypeLike | None=None, *, out: np.ndarray | None=None) -> np.ndarray

ModeDict ​

ModeDict.modes ​

modes: np.ndarray | None — property.

Ranks ​

Fields and defaults ​

python
kind: str
data: np.ndarray | None

Values ​

Fields and defaults ​

python
kind: str
raw: np.ndarray | None = None
dictionary: Dict | None = None

ChunkSizes ​

Capacities one chunk encoding needs.

Fields and defaults ​

python
output_bytes: int
workspace_words: int

chunk_sizes ​

python
chunk_sizes(matrix, rows: RowSelector=None, *, options: EncodeOptions | None=None) -> ChunkSizes

Output bytes and uint64 workspace words encode_chunk needs.

encode_chunk ​

python
encode_chunk(matrix, rows: RowSelector=None, *, options: EncodeOptions | None=None, out: np.ndarray | None=None, workspace: np.ndarray | None=None) -> np.ndarray

Encode selected rows as one chunk; missing buffers are sized first.

encode_record ​

python
encode_record(meta: Meta, row, *, tables: EncodeTables | None=None, options: EncodeOptions | None=None, out: np.ndarray | None=None, workspace: np.ndarray | None=None) -> np.ndarray

Encode one row against an existing chunk model.

decode_chunk ​

python
decode_chunk(buffer, *, source_dtype=None, format='dense', rows=None, out=None, workspace=None, tables=None, space: IdSpace | str=IdSpace.SOURCE, workers=None, gene_map=None, n_genes=None, dtype=None)

Decode an encoded chunk: bytes read as source_dtype, or a parsed Meta, into format ("dense" or "csr").

Chunks record value width but not signedness or float-ness, so raw bytes need the source_dtype they were encoded from. dtype and the gene map arguments select the output as in decode_dense.

decode_dense ​

python
decode_dense(meta: Meta, *, records: Bytes | None=None, rows: RowSelector=None, tables: DecodeTables | None=None, out: np.ndarray | None=None, workspace: np.ndarray | None=None, space: IdSpace | str=IdSpace.SOURCE, fill: Fill | str=Fill.ZERO, workers: int | None=None, gene_map=None, n_genes: int | None=None, dtype: DTypeLike | None=None) -> np.ndarray

Decode selected cells densely; many rows decode on workers threads.

gene_map (a ~pycellpack.cellpack.GeneMap, an integer vector or a mapping of source genes to panel columns), n_genes and dtype decode straight into a panel through Decoder. workspace serves the first thread; others allocate their own.

decode_csr ​

python
decode_csr(meta: Meta, *, records: Bytes | None=None, rows: RowSelector=None, tables: DecodeTables | None=None, out: _CSROut=None, workspace: np.ndarray | None=None, space: IdSpace | str=IdSpace.SOURCE, index_dtype: DTypeLike=np.int64, workers: int | None=None, gene_map=None, n_genes: int | None=None, dtype: DTypeLike | None=None) -> CSR

Decode selected cells as CSR; many rows decode on workers threads.

With gene_map/n_genes/dtype the result is in the panel: dropped genes are removed and each row's columns ascend. out buffers need selection_nnz entries.

decode_record ​

python
decode_record(meta: Meta, record: Bytes | PagedRecord | None=None, *, cell: int | None=None, tables: DecodeTables | None=None, out: _SparseOut=None, workspace: np.ndarray | None=None, space: IdSpace | str=IdSpace.SOURCE, index_dtype: DTypeLike=np.int64) -> SparseRow

Decode one record (bytes, pages or cell=) as a sparse row.

decode_record_dense ​

python
decode_record_dense(meta: Meta, record: Bytes | PagedRecord | None=None, *, cell: int | None=None, tables: DecodeTables | None=None, out: np.ndarray | None=None, workspace: np.ndarray | None=None, space: IdSpace | str=IdSpace.SOURCE, fill: Fill | str=Fill.ZERO) -> np.ndarray

Decode one record (bytes, pages or cell=) as a dense row.

decode_parts ​

python
decode_parts(meta: Meta, record: Bytes | PagedRecord | None=None, *, cell: int | None=None, tables: DecodeTables | None=None, space: IdSpace | str=IdSpace.CODED) -> Parts

Decode one record (bytes, pages or cell=) into owned parts.

pack_chunk ​

python
pack_chunk(chunk: Bytes, page_size: int=4096, *, out: np.ndarray | None=None) -> np.ndarray

Place a chunk's records so each reads its minimum number of pages.

packed_len ​

python
packed_len(chunk: Bytes, page_size: int=4096) -> int

Bytes of the chunk packed to page_size pages.

record_nnz ​

python
record_nnz(record: Bytes | PagedRecord) -> int

The non-zero count a record declares.

selection_nnz ​

python
selection_nnz(meta: Meta, rows: RowSelector=None) -> int

Stored entries of the selected cells (the CSR capacity).

dense_bytes ​

python
dense_bytes(meta: Meta, rows: RowSelector=None) -> int

Bytes of the selected cells' dense rows in the stored dtype.

record_bound ​

python
record_bound(n_genes: int, value_width: int, nnz: int, dense: bool=False) -> int

Upper bound of one encoded record's bytes.

encode_workspace_words ​

python
encode_workspace_words(n_genes: int, max_elems: int) -> int

Workspace words encode_record needs for rows of this size.

decode_workspace_bound ​

python
decode_workspace_bound(n_genes: int, value_width: int) -> int

Decode workspace words sufficient for any chunk of these dimensions.

PreparedEncoder ​

python
PreparedEncoder(matrix, rows: RowSelector=None, *, options: EncodeOptions | None=None)

Snapshot an input and build its statistical model once.

Rust PreparedEncoder borrows immutable input; this Python adapter takes private copies so edits to caller arrays cannot invalidate the model. Each encode owns its output/workspace and may run concurrently.

PreparedEncoder.meta ​

python
PreparedEncoder.meta() -> Meta

Model metadata for independent record encoding, before record placement.

PreparedEncoder.encode ​

python
PreparedEncoder.encode(*, out: np.ndarray | None=None, workspace: np.ndarray | None=None) -> np.ndarray

Decoder ​

python
Decoder(meta: Meta, *, gene_map=None, n_genes: int | None=None, dtype: DTypeLike | None=None)

Decode records of one chunk straight into a panel of dtype.

gene_map (a ~pycellpack.cellpack.GeneMap, integer vector or mapping over the chunk's source genes; default every gene in place) is composed with the chunk's gene order once. Tables and scratch are reused; no owned Parts is created. One decoder serves one call at a time (which may use workers threads); concurrent consumers use separate decoders.

Decoder.decode_dense ​

python
Decoder.decode_dense(*, records: Bytes | None=None, rows: RowSelector=None, out: np.ndarray | None=None, fill: Fill | str=Fill.ZERO, workers: int | None=None) -> np.ndarray

Decoder.decode_csr ​

python
Decoder.decode_csr(*, records: Bytes | None=None, rows: RowSelector=None, out: CSR | tuple[np.ndarray, np.ndarray, np.ndarray] | None=None, index_dtype: DTypeLike=np.int64, workers: int | None=None) -> CSR

Canonical CSR in panel columns; out buffers need selection_nnz entries (dropped genes reduce the result).

Decoder.decode_record ​

python
Decoder.decode_record(record: Bytes | None=None, *, cell: int | None=None, out: np.ndarray | None=None, fill: Fill | str=Fill.ZERO) -> np.ndarray

compose_mapping ​

python
compose_mapping(tables: DecodeTables, gene_map, *, n_genes: int | None=None) -> GeneMap

Compose a source gene → panel map with the chunk's coded gene order, giving the coded gene → panel map that coded-space parts use.

cast_values ​

python
cast_values(values: np.ndarray, dtype: DTypeLike | None=None, *, source_dtype: DTypeLike | None=None, out: np.ndarray | None=None) -> np.ndarray

Convert values (or raw bytes read as source_dtype) natively.

map_parts ​

python
map_parts(parts: Parts, gene_map, *, dtype: DTypeLike | None=None, out: _SparseOut=None, dictionary: np.ndarray | None=None, modes: np.ndarray | None=None, n_genes: int | None=None) -> SparseRow

Map a row's elements to panel columns, dropping unmapped genes.

Columns keep the row's id order. Dense-layout records keep their non-zero values. dictionary and modes reuse converted components.

map_parts_at ​

python
map_parts_at(parts: Parts, positions: RowSelector, gene_map, *, dtype: DTypeLike | None=None, out: _SparseOut=None, dictionary: np.ndarray | None=None, modes: np.ndarray | None=None, n_genes: int | None=None) -> SparseRow

Map the elements at positions, one output entry per position.

Entries stay aligned with positions: an element whose gene is dropped by gene_map keeps index UNMAPPED, so filter on it before treating the result as a sparse row.

map_dense ​

python
map_dense(parts: Parts, gene_map, *, dtype: DTypeLike | None=None, out: np.ndarray | None=None, dictionary: np.ndarray | None=None, modes: np.ndarray | None=None, n_genes: int | None=None, fill: Fill | str=Fill.ZERO) -> np.ndarray

Scatter a row into a dense panel row of n_genes columns.

SparseRow ​

One row of stored elements over n_genes columns.

indices are gene ids in the row's id space (source genes, or coded genes for "coded" decodes) and data holds the matching values. A dense record expands to one entry per gene, zeros included.

Fields and defaults ​

python
indices: np.ndarray
data: np.ndarray
n_genes: int

SparseRow.nnz ​

nnz: int — property.

Number of entries, i.e. len(data).

SparseRow.shape ​

shape: tuple[int] — property.

Row shape as a tuple, as NumPy-style consumers expect.

SparseRow.to_csr ​

python
SparseRow.to_csr() -> CSR

Wrap the row as a one-row CSR matrix; indices and data are shared.

kernel_set ​

python
kernel_set() -> str

The kernel set bound at import.

supported_kernel_sets ​

python
supported_kernel_sets() -> list[str]

Kernel sets this machine supports.