Appearance
Encoding, decoding, and mapping: scans
cellpack::scans operates on application-owned bytes and buffers. Use this page for capacities, units, ordering, and borrowing rules. For a complete round trip and an explanation of how the pieces fit, read Codec components. Use store when you need complete matrix files.
Select an entry point
Start at the granularity you own
- Build a model and encode selected matrix rows.Matrix selection → chunkchunk_sizes → encode_chunk; PreparedEncoder reuses a fixed borrowed input and model.
- Materialize CSR or dense output.Chunk or record → arraysdecode_csr / decode_dense for a resident chunk; Decoder for repeated records.
- Keep values encoded until mapping or casting.Record → paneldecode_parts → map_parts / map_dense; consume the borrowed view before scratch reuse.
All codec Rows selections use chunk-local row IDs. Rows::All and half-open Rows::Range preserve natural order; Rows::List(&[u32]) preserves the listed order and repetitions. Inputs and output types follow data contracts.
Encoding buffers and results
| Operation | Sizing / preparation | Result and ownership |
|---|---|---|
encode_chunk | chunk_sizes(src, rows, options) | Encoded byte count; chunk occupies out[..count] |
PreparedEncoder::encode_into | PreparedEncoder::new(source, rows, options), then sizes() | Encoded byte count; repeated calls write the same bytes for the bound input |
encode_record | record_bound(n_genes, value_width, nnz, dense) and encode_workspace_words(n_genes, max_elems) | Encoded byte count for one row under the supplied chunk model |
pack_chunk | packed_len(chunk, page_size) | Packed byte count into a separate output buffer |
ChunkSizes::output_bytes is a byte capacity; workspace_words counts u64 elements. Pass matching inputs, selection and options to sizing and encoding. The individual chunk_bound and chunk_workspace_words queries are available when only one capacity is needed. Do not treat the allocation's unused suffix as encoded data.
PreparedEncoder borrows immutable matrix input and its row selection. Construction builds the model and owns its metadata/tables; keep the borrowed inputs alive and unchanged. metadata() and metadata_bytes() describe the model before record placement. They are useful for independent encode_record calls, but do not constitute a completed chunk with record extents. encode_into completes those extents in its output.
Independent record encoding requires a row with the model's dimensions and value width, matching encoding tables, and the intended encoding options. An empty record can have length zero. Preserve the model and record identity together in your container.
pack_chunk accepts page sizes that are powers of two in [512, 65536] bytes. It can change physical record order and metadata extents, while retaining logical row order. Each nonempty record reads ceil(record_length / page_size) pages when the packed chunk is stored at a page-aligned position. Parse the resulting chunk again; old offsets do not describe the new layout.
EncodeOptions
| Field | Meaning / valid domain |
|---|---|
renumber | Build a frequency-based chunk column permutation |
thresholds | Maximum coded/raw size ratios for index and value sections, each in [0, 1]; zero retains raw sections |
max_lanes | rANS lane cap: 1, 2, 4, 8, 16, 32 |
lane_min | Minimum symbols per lane; power of two in [1, 65536] |
column_modes | Optional candidate share in [0, 1]; None disables column modes |
layout | Auto, forced sparse, or forced dense layout |
values | Automatic, raw, dictionary, or column-mode value coding |
Forced value coding ignores the value-size threshold. Forced mode coding requires column_modes: Some(...); enabling a column-mode candidate in automatic mode does not guarantee that every row uses it. CpkWriter normally suppresses column modes for nonfloating types unless modes are forced. DEFAULT_* constants expose suggested values; the generated field and enum entries below give exact variants.
Forced dense layout and explicit sparse zeros
Automatic layout selection preserves explicit sparse zeros by retaining a sparse record when needed. Forcing dense layout drops those explicit entries. Distinguish numeric equality of a dense matrix from exact recovery of a CSR representation.
Decoding buffers and results
For a resident chunk, parse its Meta, build matching DecodeTables, and pass meta.records_of(chunk) as the records region. This region differs from the full chunk, which also contains metadata and possible page-alignment padding.
Let R be selected rows, N selected nnz, C = meta.n_dims(), and W = meta.value_width() bytes.
| Call | Caller buffers | Result |
|---|---|---|
decode_csr | R + 1 row offsets, capacity for N indices and N × W value bytes | Written nnz |
decode_dense | Exactly R × C × W output bytes | Result<()> |
decode_record | Capacity for the record's nnz indices and nnz × W value bytes | Written nnz |
decode_record_dense | Exactly C × W output bytes | Result<()> |
decode_parts | Borrowed record and mutable workspace | Parts borrowing record, metadata and workspace dependencies |
All calls need decode_workspace_words(meta) u64 words. Use decode_workspace_bound(n_genes, value_width) when allocating for a maximum shape before metadata is available. This is a workspace bound, not a compressed-record or output-array bound.
selection_nnz(meta, rows) returns u64 nnz for sparse capacity sizing; Meta::cell_nnz sizes one record. dense_len(meta, rows) returns bytes. Output indices must represent the chunk's entire dimension range, even when the selected rows happen to use only small IDs. CSR offset types must hold the resulting cumulative nnz. See the IndexOut and IndptrOut implementations below.
Column order and zero filling
IdSpace::Source restores ascending source columns with their values. IdSpace::Coded produces ascending chunk-coded IDs, avoiding source-order restoration; the two spaces coincide when renumbering is disabled. This ordering promise applies to codec sparse decode, not to subsequent panel mapping.
| Fill policy | Required initial state | Behavior |
|---|---|---|
Fill::Zero | Any initialized output buffer | Clear each dense row before writing values |
Fill::AssumeZeroed | Caller guarantees the destination is already zero | Skip clearing; omitted sparse values rely on those zeros |
AssumeZeroed is not a request to merge into arbitrary existing data. Clear a reused sparse-row destination before decoding unless using Zero.
Repeated and paged records
Decoder::new(&meta, &tables) checks the binding once and retains the chunk's kernel dispatch and workspace layout. Its sparse, dense, parts, and parts_pages methods reuse that binding. It does not own an output buffer or workspace: each active operation still needs exclusive scratch.
PagedRecord { pages, page_size, start, len } supplies pages in file order. start is a byte offset inside the first page and len is the exact compressed record length. All but the last page cover page_size; the last may be shorter if the record ends inside it. Use the _pages record functions for the same output contract without assembling a contiguous application buffer. A single-page record is borrowed; a cross-page record is copied into the supplied workspace's staging region.
Parts and mapping
Parts exposes ids(), values(), nnz(), elements(), and layout(). Values distinguishes direct bytes, dictionary/rank coding, and column-mode coding. A dense record has one element per dimension, so elements() can exceed nnz(). Size materialized values for the element count. expand_values restores stored value bytes without panel mapping or numeric conversion.
Consume or copy a Parts view before reusing its workspace or changing backing record/metadata storage. The view is not an owned row. OwnedMeta owns metadata when retaining the original chunk buffer is inconvenient; it does not own records.
Mapping contracts
| Call | Selection and destination | Result |
|---|---|---|
map_parts | Map every part element, dropping UNMAPPED; columns and values need room for every element | Kept count; use only written prefixes |
map_parts_at | Select element positions in the supplied order; repeats allowed; output capacity for those positions | Result<()>; writes UNMAPPED unchanged rather than dropping it |
map_dense | Scatter mapped elements into the panel; kept target columns must fit the destination | Result<()>; honors Fill |
map[id] is an ID-to-output-column lookup in the Parts ID space. With IdSpace::Coded, compose source-to-output mapping with Meta::source_dim once per chunk. positions addresses elements within the row; it does not contain source columns, output columns, or row IDs. Mapped compact columns retain the part traversal order and are sorted only if the map is monotonic.
For Mapper<S, T> and the free mapping functions, S must describe the stored value representation and T the output element type. Provide dictionary entries converted by Dict::cast_into and, for mode-coded values, a converted chunk-mode table indexed by coded ID. Empty dictionary/mode slices are appropriate only when the representation does not use them. Reuse Mapper for repeated calls with a fixed type pair; the free functions resolve a route for each call.
UNMAPPED = u32::MAX is a drop sentinel, not a valid panel column. SIMD-addressed maps, rows, dictionaries and mode tables cannot exceed i32::MAX elements. Numeric casts follow Rust as semantics; the loader's admitted conversion pairs are a separate contract. See conversion rules.
Allocation and failure boundary
Chunk model building, table construction, and page-packing planning can allocate. Record encode/decode and mapping use supplied output and workspace memory. These per-record properties do not imply allocation-free file reading or loader runs.
Entry points check their documented capacities, table binding, options, and selected shape constraints. Record internals and per-cell metadata are trusted; parsing metadata does not establish that arbitrary record bytes are safe to decode. Keep encoder-produced records with their matching model. Invalid trusted inputs can cause undefined behavior in optimized decoding. See the validation boundary.
Complete interface index
The families below are useful when looking beyond the main workflow. Exact signatures, variants, and source links follow in the generated index.
Interface families
| Family | Interfaces |
|---|---|
| Borrowed inputs | DenseRef, CsrRef, CsrView, MatrixRef, CellRef, RowRef |
| Selection and output policies | Rows, IdSpace, Fill, IndexOut, IndptrOut |
| Tables and runtime binding | DecodeTables, EncodeTables, decode_tables, encode_tables, *_for variants |
| Numeric conversion | Element, CastInto, cast_values, Dict::cast_into, ModeDict::cast_into |
| Runtime helpers | Isa, kernel_set, prefetch |
Structs
| Interface | Responsibility |
|---|---|
CellRef | Borrowed inputs, selections and encoding options. One cell: strictly ascending gene indices and their values ( indices.len() * value_width bytes). |
ChunkSizes | Both encoding buffer sizes, queried together. Output capacity in bytes and scratch capacity in u64 words. |
CsrRef | Borrowed inputs, selections and encoding options. A canonical CSR matrix: every row’s indices strictly ascending and below n_genes ; data holds value_width little-endian bytes per element. Values are opaque bit patterns, so any 1/2/4/8-byte type round-trips. |
CsrView | Borrowed inputs, selections and encoding options. Canonical CSR with row offsets borrowed in the caller’s integer type. |
DecodeTables | The per-chunk lookup tables, bound to the runtime or to a given one. Decode-side lookup tables of one chunk. |
Decoder | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Bound metadata, tables, ISA dispatch and workspace layout for repeated records. |
DenseRef | Borrowed inputs, selections and encoding options. A row-major dense matrix: n_genes values of value_width little-endian bytes per row. A value whose bytes are all zero is a zero. |
Dict | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. A record’s dictionary: k distinct values ascending, and each element’s position in it. Debug builds check every rank against k . |
EncodeOptions | Borrowed inputs, selections and encoding options. Chunk-level encoding choices. |
EncodeTables | The per-chunk lookup tables, bound to the runtime or to a given one. Encode-side lookup tables of one chunk: an EncModel per model and the gene order records are written in. As with DecodeTables , the metadata key lets EncodeTables::check reject reuse across chunks. |
Mapper | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Maps decoded rows of element type S to outputs of T , with the kernel for every value encoding and output shape chosen once, for the kernel set the mapper was bound to. Build one per element-type pair and reuse it for every row; the methods behave as map_parts , map_parts_at and map_dense . |
ModeDict | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. A mode-coded record’s values: rank 0 is the element’s column mode (the chunk’s Meta::column_modes entry for its coded id) and rank r is dictionary entry r - 1 . Ranks::One means every value is its column mode (an empty dictionary). Debug builds check every rank against k . |
PagedRecord | Borrowed inputs, selections and encoding options. A record held in caller pages: len bytes starting start bytes into the first of pages , each page_size bytes long (the last may be shorter if the record ends inside it). |
Parts | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. A decoded record before values are materialized: ids and values in the same order, borrowed from the workspace (or the record). With IdSpace::Coded the ids ascend in the chunk’s coded numbering and no order restoration runs; with IdSpace::Source they ascend in source numbering. Callers mapping genes themselves can convert the k dictionary entries once instead of every value. Read-only access keeps the validated ids and rank lengths aligned. |
PreparedEncoder | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. A fixed, immutably borrowed input and its reusable statistical model. Construction performs model building and sizing; repeated writes preserve the same encoding decisions as encode_chunk. |
Thresholds | Borrowed inputs, selections and encoding options. Per-cell coding thresholds: a section is coded only when its coded size is at most mu times its raw size; otherwise it is stored raw. Each lies in [0, 1] ; 0 stores everything raw. |
Enums
| Interface | Responsibility |
|---|---|
Fill | Borrowed inputs, selections and encoding options. Whether dense output rows are cleared before the non-zeros are written. |
IdSpace | Borrowed inputs, selections and encoding options. Gene numbering of decoded indices. |
Indices | Borrowed inputs, selections and encoding options. Gene indices of a matrix or a cell, in their stored width. |
Isa | The bound instruction set, by name or as Isa . Instruction set of a kernel set, ordered by capability. |
LayoutChoice | Borrowed inputs, selections and encoding options. How records lay out their elements. |
MatrixRef | Borrowed inputs, selections and encoding options. An input matrix. Its form does not decide how rows are stored: every row is stored sparse or dense by its own size (see LayoutChoice ). |
Offsets | Borrowed inputs, selections and encoding options. Borrowed CSR row offsets; signed inputs are checked before indexing. |
Ranks | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Dictionary positions of a record’s values. |
RowRef | Borrowed inputs, selections and encoding options. One input row: sparse (a cell) or dense ( n_genes values). |
Rows | Borrowed inputs, selections and encoding options. Which rows of a matrix or chunk an operation covers, in the given order. |
ValueChoice | Borrowed inputs, selections and encoding options. How records code their values. |
Values | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. A record’s values, aligned with its ids. |
Constants
| Interface | Responsibility |
|---|---|
DEFAULT_LANE_MIN | Borrowed inputs, selections and encoding options. Suggested EncodeOptions::lane_min . |
DEFAULT_MAX_LANES | Borrowed inputs, selections and encoding options. Suggested EncodeOptions::max_lanes . |
DEFAULT_MODE_SHARE | Borrowed inputs, selections and encoding options. Suggested EncodeOptions::column_modes . |
DEFAULT_MU_INDICES | Borrowed inputs, selections and encoding options. Suggested threshold for Thresholds::indices . |
DEFAULT_MU_VALUES | Borrowed inputs, selections and encoding options. Suggested threshold for Thresholds::values . |
UNMAPPED | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Column-map entry for genes the caller drops. |
Traits
| Interface | Responsibility |
|---|---|
CastInto | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Conversion between element types with as semantics. |
Element | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Numeric element types values can be read as or converted to. |
IndexOut | Borrowed inputs, selections and encoding options. Integer types decoded gene indices can be written as. |
IndptrOut | Borrowed inputs, selections and encoding options. Integer types a decoded CSR indptr can be written as. |
Functions
| Interface | Responsibility |
|---|---|
cast_values | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Values of S::WIDTH little-endian bytes each, read as S and converted to T into out (at least as many entries). For converting a chunk’s Meta::column_modes once. |
chunk_bound | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. Bytes a chunk of the selected rows can take at most. |
chunk_sizes | Both encoding buffer sizes, queried together. Queries both encoding buffers using the same input and options. The underlying sizing rules are those of the individual sizing functions. |
chunk_workspace_words | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. Encode workspace in u64 words for encode_chunk on the selected rows. |
decode_csr | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decodes the selected cells of a resident chunk into CSR arrays: indptr of rows + 1 entries, indices and values of at least selection_nnz entries. Indices ascend in space within each row. Returns the nnz written. |
decode_dense | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decodes the selected cells of a resident chunk into dense rows ( rows × n_genes × value_width bytes, see dense_len ). |
decode_parts | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decodes one record (from a chunk with this metadata, read however the caller likes) into a Parts view borrowing the workspace and record. |
decode_parts_pages | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. decode_parts for a record held in pages. |
decode_record | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decodes one record into indices and values , which must hold at least its nnz entries (see Meta::cell_nnz or format::record_nnz ). Indices ascend in space . Returns the nnz. |
decode_record_dense | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decodes one record into a dense row of n_genes × value_width bytes; columns follow space . |
decode_record_dense_pages | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. decode_record_dense for a record held in pages. |
decode_record_pages | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. decode_record for a record held in pages. |
decode_tables | The per-chunk lookup tables, bound to the runtime or to a given one. Decode tables of a chunk, bound to the process kernel set ( crate::runtime::get ). |
decode_tables_for | The per-chunk lookup tables, bound to the runtime or to a given one. decode_tables bound to the kernel set of rt (ablation and equivalence checks across ISAs). |
decode_workspace_bound | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decode workspace in u64 words sufficient for every chunk with at most these parameters, without reading any metadata. |
decode_workspace_words | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Decode workspace in u64 words for any record of the chunk. |
dense_len | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Bytes of dense output for the selected cells: rows × n_genes × value width. |
encode_chunk | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. Encodes the selected rows as one chunk into out (at least chunk_bound bytes) with ws of chunk_workspace_words words. Returns the chunk length. |
encode_record | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. Encodes one row with a chunk’s metadata and tables into out (at least record_bound bytes). ws needs encode_workspace_words for the chunk’s Meta::max_elems . Returns the record length; a row without non-zeros has an empty record. The row takes the smaller of its sparse and dense layouts as opt.layout allows; a dense candidate needs max_elems == n_genes . Dictionaries beyond Meta::max_k are not used, so the record fits the chunk’s decode workspace. |
encode_tables | The per-chunk lookup tables, bound to the runtime or to a given one. Encode tables of a chunk, bound to the process kernel set. |
encode_tables_for | The per-chunk lookup tables, bound to the runtime or to a given one. encode_tables bound to the kernel set of rt . |
encode_workspace_words | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. Encode workspace in u64 words for records of at most max_elems stored elements (see crate::format::Meta::max_elems ). |
kernel_set | The bound instruction set, by name or as Isa . Name of the bound kernel set (binding the runtime from the environment if nothing has yet); "unbound" when the environment is invalid. |
map_dense | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Scatters a decoded row into a dense output row: out[map[id]] gets each element’s value, with dict and modes as in map_parts ; elements whose column is UNMAPPED are skipped. With Fill::Zero the row is cleared first. Every mapped column must lie inside out . |
map_parts | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Maps a decoded row: for each element, col = map[id] ; elements whose column is UNMAPPED are dropped, the rest are written in order to cols and vals . Values are dict[rank] for a dictionary ( dict holds its entries converted by Dict::cast_into ) or the raw values read as S and converted. For mode-coded values, modes holds the chunk’s column modes converted to T (see cast_values ), indexed by coded id; it may be empty for chunks without column modes. cols and vals need room for every element of the row; map must cover the row’s largest id. Returns the number of elements kept. Columns keep the row’s id order, so they are ascending only if the map is monotonic. |
map_parts_at | Mapping decoded rows onto a caller column panel, and the element types its conversions take. Maps the elements of a decoded row at positions (each below the row’s nnz, in any order, repeats allowed): cols[i] = map[id] and vals[i] the value of element positions[i] , with dict and modes as in map_parts . Nothing is dropped: an UNMAPPED column is written as it is. For callers that need only some elements of a row, such as a sampler choosing positions first. A position at or beyond the row’s nnz is Error::InvalidInput . |
pack_chunk | Page packing of a chunk’s records. Rewrites chunk with its records packed to page -byte pages (see the module docs) into out , which must hold packed_len bytes. Every record then reads ceil(len / page) pages once the chunk is stored at a page-aligned position. Decoding is unchanged. Returns the packed length. |
packed_len | Page packing of a chunk’s records. Bytes of chunk once packed to page -byte pages. |
prefetch | The per-chunk lookup tables, bound to the runtime or to a given one. Hints the processor to load len bytes from p into its caches. |
record_bound | Chunk and record encoding, the reusable PreparedEncoder , and the output and workspace bounds of both. Largest record a row of at most nnz stored elements can produce; dense when the row may be stored with all n_genes elements. |
selection_nnz | Record and chunk decoding: CSR arrays, dense rows and Parts views, plus the workspace sizing those calls need. Non-zeros of the selected cells. |