Skip to content

Storage and selection reads ​

Use cellpack::store when you want to write one matrix or synchronously read a selection into your own memory. Start with a finalized .cpk file and keep it unchanged while reading. For background batch delivery, continue to loading and ownership.

Choose your read path

Write a row stream ​

Write once, read selected rows
  1. 01
    CreateCpkWriter::create

    Declare dtype, layout and column count.

  2. 02
    Appendappend

    Add matching matrix rows in order.

  3. 03
    Finishfinish

    Publish the complete stream before reading.

  4. 04
    OpenCpkFile::open

    Read the finalized stream.

  5. 05
    Prepareprepare_read

    Bind row selection and output dimensions.

  6. 06
    Readread_dense_into

    Decode into caller-owned output.

The caller owns the output and can reuse ReadWorkspace after each read.

CpkWriter::create(path, n_cols, dtype, source_layout, options) creates or truncates a file. Calls to append need not align with chunk boundaries; the writer stages incomplete chunks. end_chunk ends a chunk early, and finish flushes the final chunk and writes the directory.

  • DenseRef borrows row-major value bytes and declares the column count.
  • CsrRef borrows u64 row offsets, column indices, and value bytes.
  • CsrView accepts row offsets in other integer types through Offsets.

CSR columns must be strictly increasing, distinct, and in range within each row. Each value occupies 1, 2, 4, or 8 little-endian bytes, interpreted by the file dtype. A writer accepts input in a different form from its declared source layout and converts that form before encoding.

The writer borrows input only for append; you can reuse that input once the call returns. Appends preserve row order. A new append adds rows to the same matrix; it does not create another named matrix or update previously written rows.

INFO

Successful finish completes encoding and file writes. It does not implement an atomic file replacement or power-loss durability protocol. Applications needing those guarantees must manage temporary paths, synchronization, and publication.

Select rows, map columns, and convert values ​

RowSelection::List(&[3, 0, 3]) preserves order and repeated rows. The storage gene_map maps each source column to an output column; UNMAPPED drops it. Mapped targets must be distinct. Output columns without a source are zero-filled. This map differs from a loader's standard-vocabulary map.

For the shared four-row fixture, the map [1, UNMAPPED, 0, UNMAPPED] keeps source columns 0 and 2, swaps their output positions, and drops the other columns:

One map, two independent orders
Source column 0Output column 1
Source column 1Dropped
Source column 2Output column 0
Source column 3Dropped
Row request[3, 0, 3]

Rows follow the request. Columns follow the map. Repeated rows remain repeated.

Source rowOutput 0
source 2
Output 1
source 0
307
000
307

Fixture from the runnable storage example. Dense output is row-major: [0, 7, 0, 0, 0, 7].

The sequence is prepare → inspect spec → allocate → read. Preparation reads chunk metadata and keeps an open file descriptor; each read loads record bytes. It is useful to prepare once when reading the same selection several times, but preparation does not preload the selected values.

read_dense_into::<f64> can convert stored f32 values into f64. Consult OutputElement for supported output types. Conversion changes numeric representation; narrowing can lose precision.

Complete runnable example ​

This program checks both dense and CSR outputs above, then writes and reads a second u16 CSR matrix. It prints selection, conversion and CSR round-trip passed when its assertions succeed.

rs
mod common;

use std::error::Error;

use cellpack::format::{Dtype, SourceLayout};
use cellpack::scans::{CsrRef, Indices, UNMAPPED};
use cellpack::store::{CpkFile, CpkWriter, ReadOptions, ReadWorkspace, RowSelection};

fn main() -> Result<(), Box<dyn Error>> {
    let path = common::fixture()?;
    let file = CpkFile::open(&path)?;
    let rows = [3, 0, 3];
    let map = [1, UNMAPPED, 0, UNMAPPED];
    let selection = file.prepare_selection(
        RowSelection::List(&rows),
        Some(&map),
        2,
        ReadOptions::default(),
    )?;
    let spec = selection.spec();
    let mut workspace = ReadWorkspace::default();
    let mut dense = vec![0.0f64; spec.dense_len()?];
    selection.read_dense_into(&mut dense, &mut workspace, 2)?;
    assert_eq!(dense, [0.0, 7.0, 0.0, 0.0, 0.0, 7.0]);

    let mut indptr = vec![0u64; spec.rows + 1];
    let mut indices = vec![0u32; spec.nnz];
    let mut values = vec![0.0f64; spec.nnz];
    let nnz = selection.read_csr_into(&mut indptr, &mut indices, &mut values, &mut workspace, 2)?;
    indices.truncate(nnz);
    values.truncate(nnz);
    assert_eq!(indptr, [0, 1, 1, 2]);
    assert_eq!(indices, [1, 1]);
    assert_eq!(values, [7.0, 7.0]);

    let csr_path = common::directory()?.join("counts.cpk");
    let indptr = [0u64, 2, 3];
    let indices = [0u32, 3, 2];
    let data: Vec<u8> = [2u16, 9, 4].iter().flat_map(|v| v.to_le_bytes()).collect();
    let mut writer = CpkWriter::create(
        &csr_path,
        4,
        Dtype::U16,
        SourceLayout::Csr,
        common::options(),
    )?;
    writer.append(CsrRef {
        n_genes: 4,
        value_width: 2,
        indptr: &indptr,
        indices: Indices::U32(&indices),
        data: &data,
    })?;
    writer.finish()?;
    let counts = CpkFile::open(csr_path)?;
    let mut out = [0u16; 8];
    counts
        .prepare_read(0..2)?
        .read_dense_into(&mut out, &mut workspace, 1)?;
    assert_eq!(out, [2, 0, 0, 9, 0, 0, 4, 0]);
    println!("selection, conversion and CSR round-trip passed");
    Ok(())
}
Shared fixture and encoding options

common::fixture() creates matrix.cpk in the supplied output directory. It uses two rows per chunk so the row request exercises multiple chunks.

rs
#![allow(dead_code)]

use std::error::Error;
use std::path::PathBuf;

use cellpack::format::{Dtype, SourceLayout};
use cellpack::scans::*;
use cellpack::store::{CpkOptions, CpkWriter};

pub const MATRIX: [[f32; 4]; 4] = [
    [0.0, 2.0, 0.0, 1.0],
    [3.0, 0.0, 4.0, 0.0],
    [0.0, 0.0, 5.0, 6.0],
    [7.0, 8.0, 0.0, 0.0],
];

pub fn options() -> CpkOptions {
    CpkOptions {
        encode: EncodeOptions {
            renumber: true,
            thresholds: Thresholds {
                indices: DEFAULT_MU_INDICES,
                values: DEFAULT_MU_VALUES,
            },
            max_lanes: DEFAULT_MAX_LANES,
            lane_min: DEFAULT_LANE_MIN,
            column_modes: Some(DEFAULT_MODE_SHARE),
            layout: LayoutChoice::Auto,
            values: ValueChoice::Auto,
        },
        chunk_rows: 2,
        page_size: 4096,
    }
}

pub fn directory() -> Result<PathBuf, Box<dyn Error>> {
    let path = PathBuf::from(
        std::env::args_os()
            .nth(1)
            .ok_or("pass an output directory")?,
    );
    std::fs::create_dir_all(&path)?;
    Ok(path)
}

pub fn fixture() -> Result<PathBuf, Box<dyn Error>> {
    let path = directory()?.join("matrix.cpk");
    let data: Vec<u8> = MATRIX
        .iter()
        .flatten()
        .flat_map(|v| v.to_le_bytes())
        .collect();
    let mut writer = CpkWriter::create(&path, 4, Dtype::F32, SourceLayout::Dense, options())?;
    writer.append(DenseRef {
        n_genes: 4,
        value_width: 4,
        data: &data,
    })?;
    writer.finish()?;
    Ok(path)
}

In the application from installation, save storage.rs as src/main.rs and common.rs as src/common.rs. Use a disposable output directory: the example recreates matrix.cpk and counts.cpk there.

sh
cargo run -- output/storage

Capacity and actual nonzero count ​

ReadSelection::spec() reports row count, output columns, stored dtype, and CSR capacity:

  • A dense output must contain exactly spec.dense_len() elements.
  • CSR indptr has exactly spec.rows + 1 entries. Indices and values each have capacity for at least spec.nnz elements.
  • spec.nnz is a capacity computed from source records. Dropping columns can reduce the actual nnz returned by read_csr_into.
  • Use indices and values only through the returned nnz. The remaining capacity has unspecified contents.

Reuse ReadWorkspace between reads; it retains scratch, not outputs. A workspace serves one read at a time. clear() releases retained scratch. A prepared selection can serve repeated reads, provided the underlying stream remains unchanged.

An I/O or codec error can leave partially written output. Discard that invocation's output when it fails.

Reuse the allocation, keep the result

After a successful read, output belongs to you and remains valid while the workspace serves another read. Concurrent reads require separate outputs and separate mutable workspaces. The selection itself owns its metadata and file descriptor, so it does not borrow the temporary row list or map passed during preparation.

Allocating convenience methods ​

CpkFile::read_dense(range) returns stored little-endian value bytes in Vec<u8>, rather than a typed Vec<f32>. read_csr(range) returns a Csr with u64indptr, u32 indices, and stored-dtype bytes in data. Use prepared reads for typed output or buffer reuse.

Read policies ​

ReadOptions controls record-range merging within a chunk:

SettingPurpose
ReadStrategy::AutoSelect ranges or the whole records region using byte and request costs
ReadStrategy::RangesRead selected record ranges
ReadStrategy::WholeChunkRead the entire records region
max_gap_bytesMaximum gap crossed while merging ranges
request_cost_bytesEquivalent byte cost assigned to one request

ReadSelection::io_summary() reports the prepared record bytes, read bytes, request count, and whole-region bytes. These describe application reads, not measured block-device traffic.

Read worker counts are clamped to at least one and at most the number of selected chunks. set_threads(n) on the writer likewise parallelizes complete chunks, defaulting to one thread; serial and parallel writes are byte-identical. Both forms of parallelism require additional scratch. Tune them after the basic workflow is correct; they are independent of the asynchronous loader's workers.

Embedded streams ​

CpkFile::open_region(path, offset, Some(length)) opens a .cpk stream inside another file. Directory offsets are relative to the stream start. The application must supply the correct region; this Rust reader does not parse HDF5 or AnnData metadata to locate it.

API: CpkWriter, CpkFile, ReadSelection.