Skip to content
API REFERENCEUsage guides →

Native loader API ​

python
from pycellpack.loader import DataSource, OutputSchema, LoaderConfig, Loader, load, allowed

Use the native loader for explicit column maps, output schemas and NumPy batch delivery. For complete inputs and checked results, follow Native NumPy loading. For dictionaries of Tensor fields, use ScDataLoader.

Choose the result you need

Register a DataSource ​

DataSource(matrices, vocab, *, page_size=None, direct_io=None) reads metadata and registers (source, ids) pairs in order. It does not decode matrix values or infer gene names. vocab is a positive standard-ID-space size; kept IDs lie in 0 <= id < vocab.

InputContract
PathA finalized, immutable CellPack matrix stream
FileA file-backed stream or bounded embedded stream; in-memory streams are rejected
StoreA two-dimensional, row-only view; a gene-selected view is rejected
idsOne integer per stored column, mapping source column → standard ID; -1 or uint32.max drops a column; kept IDs are distinct
page_size=NoneResolve from the first stream, or 4096 for an empty source; all registered streams must agree
direct_io=NoneProbe filesystem support and select direct or buffered data reads; metadata stays buffered
direct_io=False / TrueForce buffered reads / request direct I/O; True does not promise the filesystem accepts every read

Global cell IDs number the contributed rows consecutively. A Store selecting stored rows [5, 2] contributes two global cells in that order. Accesses address these contributed rows, rather than the original file row numbers. Registration uses that Store's underlying file dtype; choose conversion on the OutputSchema rather than on a lazy Store dtype view.

OperationReturns / ownership
add(source, ids)First global cell ID of the new matrix; rebuilds this DataSource snapshot
matrix_cells(matrix)(first_global_cell, contributed_count), or None for an absent matrix
stored_cells(accesses)Original stored-row IDs for the supplied global cells
cell_pages(cell)Borrowed file descriptor, aligned offset and page count
cell_bytes(cell)Borrowed file descriptor, exact offset and byte length

Keep the source alive while using its borrowed descriptors; do not close those file descriptors. The two descriptor methods accept negative cells from the end. Run access arrays instead require nonnegative global IDs.

An existing Loader retains the native catalog and row-count snapshot from its construction. source.add(...) does not extend that Loader; construct a new Loader to use the added rows. Keep registered files immutable for all active sources, plans and runs.

Describe an OutputSchema ​

ParameterDefaultContract
out_idsRequiredNonempty, distinct standard IDs in desired output-column order; loader binding requires every ID below vocab
dtypefloat32Native-endian numeric dtype for mapped input and built-in output
id, nameNonePlan identity and batch output name; the Loader binds unset values
default0Scalar converted to dtype at construction, used for source-absent columns
processNoneNative callback; None selects built-in dense rows
row_bytesNoneFixed processed bytes per position; inferred from a declared ProcessFn layout, otherwise required for process output
out_dtypeNoneOptional process-output element view; row_bytes must be divisible by its item size; illegal for built-in output
scratch_bytes0Callback scratch per worker, in bytes

For built-in output, batch[name] has shape (batch.rows, len(out_ids)) and dtype dtype. For process output it is raw uint8 rows, or an out_dtype view of those rows. batch.region(name) always returns uint8 (batch.rows, row_bytes) storage. Field interpretation belongs to the process-function contract.

A present source column with no sparse entry contributes zero. A standard ID absent from that source contributes default; defaults do not replace existing zeros. Source and schema maps use standard IDs, rather than output positions.

allowed(source_dtype, target_dtype) tests loader conversion support. A schema dtype is checked against every source route when the Loader is built. Codec or NumPy conversion support does not imply loader support.

Bind a Loader ​

Loader(source, outputs=None, *, config=None, **settings) accepts one schema, a schema sequence, or an ordered name → schema mapping. At most 64 schemas are supported. outputs=None creates float32 full-vocabulary output named X.

Mapping keys name outputs; otherwise a schema's name is used, falling back to its assigned ID as a string. Names and IDs must be distinct. Explicit IDs are kept; unset IDs receive the smallest unused values. names preserves output order and schemas is a read-only mapping of the bound schemas.

Supply a LoaderConfig or its fields, never both. LoaderConfig is frozen; unset defaults resolve when it is constructed.

FieldDefaultUnit / behavior
workersUsable CPUs, at most 16 automaticallyNative worker threads; an explicit value is not capped at 16 by this default
backendProbe"uring" where supported, otherwise "pread"
inflight64Positions in flight per worker
claim_batch8Accesses per cursor claim, rounded to positions and bounded by slot/inflight sizes
slot_rows256Positions per output slot, shared by every schema
windowDerivedExecution lead in slots; defaults depend on the planning mode
profileNoneNone/False untimed; True all sites; site/group names select timing
cpus()Logical CPU IDs; worker i is pinned to cpus[i % len(cpus)]; empty inherits affinity

Worker, inflight, claim and slot counts must be positive, as must an explicit window. Use statistics to select profiling sites and interpret reservations and timings.

Start a run ​

loading.start(accesses, *, plan=None, ring=None, slots=None, world=None, rank=0) starts native production and returns a Run. It accepts native Accesses, AccessFn, or a one-dimensional integer array; array contents are copied natively. Values must be uint32-range global cell IDs within this Loader's source snapshot.

With S schemas, length counts accesses and must be divisible by S: access k belongs to position k // S, schema k % S. A bare [5, 1] with two schemas describes one position with different cells. Use Accesses.replicate for the same cell in each schema, or Accesses.offset for paired cells. See access sequences.

KeywordMeaning
plan=NoneNo planned cache
plan=PlanExecute a plan bound to this sequence and compatible loader
plan=PlanOptions or byte budgetCompile ahead of workers during execution
ring=NoneAllocate an output ring; slots defaults to 4 and world to 1
ring=RingUse its existing slots/world/layout; do not also supply slots or world
rank=0Rank consumed through this Run's iterator; batch b belongs to b % world

A caller-supplied ring must match output names, view dtypes, row byte sizes and slot layout. ring_layout describes memory; ring allocates it. These methods default to slots=4, world=1.

Consume batches before run.join(). A NumPy output view retains its slot lease; copy data that must outlive immediate consumption. join() returns final RunStats, and context exit closes the Run. See rings and lifecycle for precise lease release, cancellation, manual consumers and reuse rules.

start can issue a RuntimeWarning when estimated known reservations exceed available process memory. This is a diagnostic estimate, not a hard memory limit. It excludes an already allocated caller-supplied ring from the additional-memory comparison. See planning for compile, compile_stats, replay and memory_estimate.

One-shot load ​

load(source, cells=None, *, out=None, config=None, **settings) returns float32 shape (selected_rows, source.vocab), preserving row order and repetitions. cells=None selects all rows; this convenience normalizes positional selectors, including slices, masks and negative row indices.

out must be a writable, C-contiguous NumPy float32 array of the exact result shape, aligned to 8 bytes. It is returned unchanged by identity. Without out, the function allocates it. An empty selection returns a correctly shaped empty array without starting a run. The convenience sets its slot size to the entire selection, so use streaming Loader output for bounded batch memory.

Errors and result validity ​

Python type/protocol mistakes raise TypeError; invalid IDs, layouts, schema declarations or configuration generally raise ValueError. Source descriptor indexing can raise IndexError. I/O failures raise OSError; busy, cancellation and worker failures raise RuntimeError. Asynchronous failures may surface during iteration or join(). Discard incomplete output after a failed run.

Declarations ​

Complete declarations and members

DataSource ​

python
DataSource(matrices, vocab, *, page_size=None, direct_io=None)

Every input matrix, numbered by global cell id in registration order.

matrices is a sequence of (source, ids) pairs. A source is a path, a cellpack.File region or a cellpack.Store selecting cells; ids[c] is the standard id (below vocab) of the matrix's stored column c, and -1 or 0xFFFFFFFF drops the column. The ids belong to the matrix and are always given by the caller: the source infers, names and aligns nothing. A Store's cell selection defines which cells it contributes: global cell ids then number the selected cells, and runs, plans and traces translate them to stored cells natively as they read the sequence. Output schemas name the standard ids of their output dims.

Data reads use O_DIRECT unless direct_io=False; with None (the default) the source falls back to buffered reads when a file's filesystem does not support it (direct_io reports the choice). Metadata reads stay buffered. Sources pickle (in-memory streams do not). paths lists the files of the registered matrices, in registration order.

DataSource.add ​

python
DataSource.add(source, ids) -> int

Register a matrix with its column -> standard id map and return its first global cell id. Existing loaders keep the source they were built with.

DataSource.n_cells ​

n_cells: int — property.

Global cells: every stored cell, or the cells Store views select.

DataSource.vocab ​

vocab: int — property.

Size of the standard id space: ids are 0..vocab.

DataSource.n_pages ​

n_pages: int — property.

Pages of every file together, in the global page numbering plans use.

DataSource.fingerprint ​

fingerprint: int — property.

Stable identity of the page layout and cell numbering; offline plans are bound to it, and output column maps do not take part.

DataSource.mapping_fingerprint ​

mapping_fingerprint: int — property.

Identity including the standard id maps and the chunk metadata.

DataSource.matrix_cells ​

python
DataSource.matrix_cells(matrix: int)

The first global cell of a matrix and its (selected) cell count, or None for a matrix the source does not have.

DataSource.matrix_dtypes ​

matrix_dtypes — property.

Stored element type of each matrix, in registration order.

DataSource.n_matrices ​

n_matrices — property.

Matrices registered, each a contiguous range of global cell ids.

DataSource.page_size ​

page_size — property.

Page size shared by every file of the source, in bytes.

DataSource.direct_io ​

direct_io: bool — property.

Whether data reads use O_DIRECT.

DataSource.max_cell_pages ​

max_cell_pages — property.

Largest number of pages one cell spans.

DataSource.stored_cells ​

python
DataSource.stored_cells(accesses) -> np.ndarray

The stored cells of global cell ids (an array or Accesses).

DataSource.cell_pages ​

python
DataSource.cell_pages(cell)

Borrowed fd, aligned byte offset and page count of a global cell (negative cell ids count from the end); retain this source.

DataSource.cell_bytes ​

python
DataSource.cell_bytes(cell)

Borrowed fd, exact offset and byte length of a global cell (negative cell ids count from the end); retain this source.

OutputSchema ​

python
OutputSchema(out_ids, dtype: DTypeLike=np.float32, *, id=None, name=None, default=0, process=None, row_bytes=None, out_dtype: DTypeLike | None=None, scratch_bytes=0)

One output of every position: out_ids[j] is the standard id of output dim j; rows are mapped to these dims and converted to dtype (values stored as other types follow the conversion contract: the same type, lossless widening, signed to unsigned of the same width with negatives unchecked, signed to a wider unsigned, and any integer to a float).

Without process, the output is the cell's dense row. An output dim whose standard id the cell's matrix has is present: the stored value, or 0 where the record stores none (CSR drops zeros, so they are expression values). An output dim the matrix has no column for is missing and takes default; a column no output dim takes is dropped. With a ProcessFn, each cell's output is row_bytes written by the function (its row_format picks CSR or dense rows, with the same semantics), viewed in batches as out_dtype elements (default: raw bytes); scratch_bytes per worker.

name names the output in batches and statistics (a loader given a mapping of names uses those); id identifies the schema for plans (unset ids get the smallest free ones). Schemas pickle when their process function does.

OutputSchema.dense ​

python
OutputSchema.dense(out_ids, dtype: DTypeLike=np.float32, *, id=None, name=None, default=0) -> OutputSchema

The built-in output: each cell as a dense row of dtype.

OutputSchema.out_dim ​

out_dim: int — property.

Output dims: the values in every dense row.

OutputSchema.is_builtin ​

is_builtin: bool — property.

Whether the loader writes the dense row itself (no process function).

OutputSchema.view_dtype ​

view_dtype: np.dtype | None — property.

The dtype batches view this output's rows as (None: raw bytes).

allowed ​

python
allowed(source, target) -> bool

Whether the loader permits a stored source dtype to an output dtype.

LoaderConfig ​

How a loader runs: workers threads (default default_workers(cpus)), each with inflight positions in flight; I/O through backend (default io_uring where supported, else pread); claim_batch accesses claimed per cursor update; slot_rows positions per output slot; the execution window in slots (default: a plan's reuse gap, or enough slots for the in-flight accesses); cpus to pin worker i to cpus[i % len].

profile selects the timed sites: False or None runs the untimed instance, True every site, or names of sites and groups (see profile_sites() and profile_groups()); it is kept as a tuple of names, or None. Every build carries both instances.

Fields and defaults ​

python
workers: int | None = None
backend: IoBackend | str | None = None
inflight: int = 64
claim_batch: int = 8
slot_rows: int = 256
window: int | None = None
profile: bool | str | tuple[str, ...] | None = None
cpus: tuple[int, ...] = ()

IoBackend ​

How the loader issues reads. PREAD completes each read inside the call (preadv); URING queues a worker's reads on its own io_uring and harvests completions. The value is the name the native side takes, so a member compares equal to its string.

Fields and defaults ​

python
PREAD = 'pread'
URING = 'uring'

Loader ​

python
Loader(source, outputs=None, *, config=None, **settings)

One native execution frontier over a data source and named outputs.

outputs is an OutputSchema, a sequence of schemas (named by their name, else their id) or a mapping from names to schemas; without one, a dense float32 row over every standard id named "X". config is a LoaderConfig, or give its fields as keywords (workers, inflight, slot_rows, ...).

A run executes one access per output per position (in the order p0s0 p0s1 ... p1s0), each loading one cell: pass a uint32 array of the accesses' cells or an Accesses (Accesses.replicate gives every output the position's cell, Accesses.offset shifts each output's cell, e.g. to a paired matrix). Outputs land in one ring whose slots hold every output's rows of slot_rows consecutive positions. A run caches only as a plan says (an offline Plan, or PlanOptions compiled online while it runs); cached rows keep their stored type, shared by every output. Loaders pickle (to build the same loader in another process) when their source and outputs do.

source and config are what the loader was built from, schemas maps each output name to its bound OutputSchema, and names lists the names in output order.

Loader.window ​

window: int — property.

The execution window in slots of runs without a plan.

Loader.cores ​

cores: float — property.

Physical cores the workers run on (among the pinned CPUs, else the allowed ones), at most one per worker: a cost model's CPU capacity.

Loader.accesses_per_slot ​

accesses_per_slot: int — property.

Accesses a slot holds: slot_rows positions of every output.

Loader.ring_layout ​

python
Loader.ring_layout(*, slots=4, world=1) -> RingLayout

The layout of this loader's ring: slots slots of slot_rows positions shared by world consumer ranks (batch b is rank b % world's). It sizes caller-owned or shared memory and pickles to other processes.

Loader.ring ​

python
Loader.ring(*, slots=4, world=1) -> Ring

A natively allocated ring for this loader's outputs.

Loader.plan_options ​

python
Loader.plan_options(cache_bytes, *, cost='auto') -> PlanOptions

Plan options for cache_bytes of cache, with this loader's window as the reuse gap and cost: "auto" for this machine's cost model (pycellpack.loader.costs.resolve: measured records where they exist, defaults with a warning elsewhere), a CostModel, or None (every page hit counts the same).

Loader.compile ​

python
Loader.compile(accesses, options, *, online=False) -> Plan

Compiles a cache plan for a stored sequence (an array or an Accesses, materialized): offline (the whole sequence is the horizon), or as an online run would (a finite horizon, frozen and published chunk by chunk; plan.online_stats holds its statistics). options are PlanOptions or a cache budget in bytes.

Loader.compile_stats ​

python
Loader.compile_stats(accesses, options) -> OnlineStats

The statistics of compiling accesses (an array or an Accesses) online, without loading them or keeping the plan: what an online run would follow, its modeled time among them.

Loader.replay ​

python
Loader.replay(plan, accesses, *, cost: CostModel | None=None) -> PlanSummary

Replays a plan's actions serially, priced by its own cost model or cost; the plan and its stored summary are unchanged.

Loader.memory_estimate ​

python
Loader.memory_estimate(plan=None, *, slots=4, world=1) -> MemoryEstimate

Known reservations of a run with plan: a Plan, PlanOptions (with their gap, chunk and row mode), a cache budget in bytes for default page planning, or None for no plan.

Loader.start ​

python
Loader.start(accesses, *, plan=None, ring=None, slots=None, world=None, rank=0) -> Run

Starts loading accesses (a uint32 array of the accesses' cells, or an Accesses; the native side keeps its own copy of an array).

plan is an offline Plan (for the sequence it was compiled for), PlanOptions or a cache budget in bytes to compile the plan online while the run goes, or None (no cache). Outputs go to ring, or to a new ring of slots slots (default 4) shared by world ranks (default 1); this process consumes rank rank by iterating the run.

Warns (RuntimeWarning) when the run's known reservations (memory_estimate) exceed the memory still available to the process.

load ​

python
load(source, cells=None, *, out=None, config=None, **settings) -> np.ndarray

Loads a DataSource's cells (default: all) into one dense float32 array over its standard ids, through the native concurrent loader; cell order and repeats are preserved. out (C-contiguous float32, 8-byte aligned) receives them; config sets the loader, or pass its fields as keywords when config is None.