Skip to content
API REFERENCEUsage guides →

Runnable API examples ​

Each example uses a tiny matrix generated inside its own temporary directory. Read the highlighted source and expected output, then choose Run example. Only fixed examples can run; the server accepts an example ID, never source code or arguments. Both source files are read-only and available to download.

Enable LSP for rust-analyzer hover information and F12 / Ctrl/⌘ click definition lookup. Navigation stays in the selected file. Definitions in other files or libraries do not open another page or file. The server enforces the same restriction and rejects document changes.

Write and reopen ​

Inspect the decoded dense matrix and its CSR structure. The writer must be finished before the file is read.

FIXED EXAMPLE RUST / CPU

Write and reopen a matrix

Write a small matrix and inspect the decoded dense rows and CSR structure. The file becomes readable after finish succeeds.

mod common;

use std::error::Error;
use cellpack::format::{Dtype, SourceLayout};
use cellpack::scans::DenseRef;
use cellpack::store::{CpkFile, CpkWriter, ReadWorkspace};

fn main() -> Result<(), Box<dyn Error>> {
    let path = common::directory()?.join("example.cpk");
    let values = [0.0f32, 2.0, 0.0, 1.0, 0.0, 3.0];
    let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
    let mut writer = CpkWriter::create(
        &path, 3, Dtype::F32, SourceLayout::Dense, common::options(),
    )?;
    writer.append(DenseRef { n_genes: 3, value_width: 4, data: &bytes })?;
    writer.finish()?;

    let file = CpkFile::open(&path)?;
    let selection = file.prepare_read(0..2)?;
    let mut out = vec![0.0f32; selection.spec().dense_len()?];
    selection.read_dense_into(&mut out, &mut ReadWorkspace::default(), 1)?;
    let csr = file.read_csr(0..2)?;
    println!("shape: {} × {}", file.n_rows(), file.n_cols());
    println!("dense: {out:?}");
    println!("CSR offsets: {:?}", csr.indptr);
    println!("CSR columns: {:?}", csr.indices);
    Ok(())
}
OUTPUTExpected result
shape: 2 × 3
dense: [0.0, 2.0, 0.0, 1.0, 0.0, 3.0]
CSR offsets: [0, 1, 3]
CSR columns: [1, 0, 2]

Gather and map ​

The fixture is a four-row, four-column matrix:

Shared example fixture · 4 rows × 4 columns
RowCol 0Col 1Col 2Col 3
00201
13040
20056
37800

The example gathers rows [3, 0, 3]. The map [1, UNMAPPED, 0, UNMAPPED] keeps source column 2 at output position 0 and source column 0 at output position 1. spec.nnz reserves capacity; the CSR read returns the actual count after mapping.

FIXED EXAMPLE RUST / CPU

Gather rows and map columns

Rows [3, 0, 3] preserve order and repetition. The source → output map keeps source column 2 first and column 0 second.

mod common;

use std::error::Error;
use cellpack::scans::UNMAPPED;
use cellpack::store::{CpkFile, ReadOptions, ReadWorkspace, RowSelection};

fn main() -> Result<(), Box<dyn Error>> {
    let file = CpkFile::open(common::fixture()?)?;
    let rows = [3, 0, 3];
    // Each entry maps a source column to its output position.
    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 out = vec![0.0f64; spec.dense_len()?];
    selection.read_dense_into(&mut out, &mut workspace, 1)?;
    let mut offsets = vec![0u64; spec.rows + 1];
    let mut columns = vec![0u32; spec.nnz];
    let mut values = vec![0.0f64; spec.nnz];
    let nnz = selection.read_csr_into(
        &mut offsets, &mut columns, &mut values, &mut workspace, 1,
    )?;
    println!("rows: {rows:?}");
    println!("output: {out:?}");
    println!("CSR offsets: {offsets:?}");
    println!("actual nnz: {nnz}");
    Ok(())
}
OUTPUTExpected result
rows: [3, 0, 3]
output: [0.0, 7.0, 0.0, 0.0, 0.0, 7.0]
CSR offsets: [0, 1, 1, 2]
actual nnz: 2
Explore how row and column selection works
Explore the selectionInstant illustration in your browser
Keep source columns (click order = output order)
Output · 3 rows × 2 columns
Source rowSource col 2Source col 0
307
000
307

source → output: [1, UNMAPPED, 0, UNMAPPED]

This illustration runs in the browser. The fixed server example always uses rows [3, 0, 3].

Ordered batch delivery ​

Five positions use the cell order [3, 0, 2, 3, 1]. Each position has two schemas, so it accounts for two accesses. With two positions per slot, the final batch has one row. Standard column 4 is absent from this source and receives NaN; existing columns with sparse zero values still return zero.

FIXED EXAMPLE RUST / CPU

Deliver ordered batches

Two output schemas share each requested position. Missing dimensions use the schema default; present sparse zeros stay zero.

mod common;

use std::error::Error;
use std::sync::Arc;
use cellpack::loader::{
    DataSourceBuilder, Dtype, IoBackend, Loader, LoaderConfig,
    OutputSchema, Planning, Replicate, Ring,
};

fn main() -> Result<(), Box<dyn Error>> {
    let mut builder = DataSourceBuilder::new(5, 4096)?.direct_io(false);
    builder.add_cpk(common::fixture()?, &[0, 1, 2, 3])?;
    let source = Arc::new(builder.build()?);
    let schemas = vec![
        OutputSchema::dense(1, vec![3, 1, 4], Dtype::F32)?.with_default(f64::NAN),
        OutputSchema::dense(2, vec![0, 2], Dtype::F64)?,
    ];
    let loader = Loader::new(source, schemas, LoaderConfig {
        workers: 2, backend: IoBackend::Pread, slot_cells: 2,
        ..LoaderConfig::default()
    })?;
    let cells = [3u32, 0, 2, 3, 1];
    let accesses = Replicate::new(cells, 2)?;
    let ring = Arc::new(Ring::allocate(loader.ring_layout(2, 1))?);
    let run = loader.prepare(&accesses, ring, Planning::None)?;
    let stats = run.for_each_batch(|batch| {
        let panel: Vec<f32> = batch.region(0).chunks_exact(4)
            .map(|v| f32::from_ne_bytes(v.try_into().unwrap())).collect();
        println!("positions {}..{}: panel {panel:?}",
            batch.first_position(), batch.first_position() + batch.rows() as u64);
        Ok(())
    })?;
    println!("delivered: {} positions, {} accesses", cells.len(), stats.counters.accesses);
    Ok(())
}
OUTPUTExpected result
positions 0..2: panel [0.0, 8.0, NaN, 1.0, 2.0, NaN]
positions 2..4: panel [6.0, 0.0, NaN, 0.0, 8.0, NaN]
positions 4..5: panel [0.0, 0.0, NaN]
delivered: 5 positions, 10 accesses

Run locally ​

Download main.rs and common.rs from the same example and put both in the src/ directory of a Rust package. Add the published crate from crates.io:

sh
cargo add cellpack@0.1.0

Use Rust 1.96.0 and edition 2024. No CellPack checkout is needed. The helper takes an output directory as its first argument:

sh
cargo run -- /path/to/example-output

Examples keep inputs small and use buffered Pread reads. They demonstrate API behavior and are not throughput measurements. If the run service is offline, the highlighted code, expected output, downloads, and normal API navigation remain available.

For server configuration, see the playground operator guide.

Definition