FrankenNumPy

Docs/Guarantees and recipes

Cookbook

On this page 5 sections

Recipes for common Rust-side tasks. These complement the Quick Example and More Worked Examples sections, focusing on idiomatic patterns rather than feature demos. There is no top-level examples/ directory today — the recipes below are paste-into-your-project snippets, not runnable Cargo examples. (If a workspace examples/ tree becomes useful, mirror cargo's standard layout under each crate.)

Recipe 1: load an .npy, do work, save the result

use fnp_io::{load, save, IOSupportedDType};
use fnp_ufunc::UFuncArray;
use fnp_dtype::DType;

let bytes = std::fs::read("input.npy")?;
let (shape, values, _dtype) = load(&bytes)?;          // bounded parser, fail-closed

let array = UFuncArray::new(shape, values, DType::F64)?;
let result = array.reduce_mean(Some(0), false)?;     // axis-0 mean

let out_bytes = save(
    result.shape(),                                  // &[usize], borrows from result
    result.values(),                                 // &[f64], borrows from result
    IOSupportedDType::F64,
)?;
std::fs::write("output.npy", out_bytes)?;

load enforces every bound (MAX_HEADER_BYTES, dtype-descriptor validation, payload completeness) before allocating; save produces NumPy-compatible bytes that round-trip exactly.

Recipe 2: parallel RNG with reproducible per-worker streams

use fnp_random::{BitGenerator, BitGeneratorKind, Generator, SeedSequence};
use std::thread;

// The workers' error type is `Send + Sync` so it can cross the thread boundary;
// the enclosing function returns that same type, so the `?` after `join()` needs
// no conversion into a plain `Box<dyn Error>`.
fn run_workers() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let n_workers = 8;
    let mut root = SeedSequence::new(&[42u32])?;
    let child_seqs = root.spawn(n_workers)?;

    let handles: Vec<_> = child_seqs
        .into_iter()
        .enumerate()
        .map(|(worker_id, ss)| {
            thread::spawn(move || -> Result<_, Box<dyn std::error::Error + Send + Sync>> {
                let bg = BitGenerator::from_seed_sequence(BitGeneratorKind::Pcg64Dxsm, &ss)?;
                let mut rng = Generator::from_bit_generator(bg);
                let samples = rng.standard_normal(10_000);
                Ok((worker_id, samples))
            })
        })
        .collect();

    for h in handles {
        let (worker_id, samples) = h.join().unwrap()?;
        println!("worker {worker_id}: first sample = {}", samples[0]);
    }
    Ok(())
}

Each worker stream is statistically independent and individually reproducible; re-running with the same root seed produces the same per-worker draw sequences. This is how NumPy itself recommends parallelizing RNG-driven work.

Recipe 3: an FFT round-trip test (a metamorphic check; NumPy is not involved)

use fnp_ufunc::UFuncArray;
use fnp_dtype::DType;

#[test]
fn fft_then_ifft_recovers_the_signal() -> Result<(), Box<dyn std::error::Error>> {
    // Build a fixture deterministically.
    let signal_values: Vec<f64> = (0..256).map(|i| (i as f64 * 0.1).sin()).collect();
    let signal = UFuncArray::new(vec![256], signal_values, DType::F64)?;

    // Forward then inverse FFT, should match the original to within FP tolerance.
    let spectrum = signal.fft(None)?;
    let recovered = spectrum.ifft()?;

    for (i, (got, want)) in recovered
        .values()
        .chunks_exact(2)
        .map(|c| c[0])
        .zip(signal.values().iter().copied())
        .enumerate()
    {
        let err = (got - want).abs();
        assert!(err < 1e-12, "fft/ifft round-trip diverged at index {i}: |Δ| = {err:.3e}");
    }
    Ok(())
}

The same pattern (build fixture → run kernel → run inverse → compare to original) is the basis for the metamorphic-test layer described in Conformance Methodology Deep-Dive.

Recipe 4: call FrankenNumPy from Python (mixed Rust fast-paths + numpy fallback)

import fnp_python as np

# A float64 sort this small runs numpy.sort (fnp's native float64 flat sort starts
# at 2**20 elements); np.ma is fnp's overlay of numpy.ma.
data = np.array([3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0])
sorted_view = np.sort(data)                # numpy.sort at 8 elements
masked = np.ma.masked_greater(data, 4.0)   # fnp's masked_greater (the overlay replaces numpy's)

# Save and round-trip via .npy (byte-identical to numpy.save for the tested dtypes, incl. float64).
np.save("data.npy", data)
restored = np.load("data.npy")             # a plain .npy path decodes through fnp-io
assert (data == restored).all()

Native routes take the calls they cover (by dtype, layout and size); everything else runs the same NumPy code you would have called directly. The boundary is invisible to your code.

Recipe 5: capture a generator's state mid-stream and resume it later

use fnp_random::Generator;

let mut rng = Generator::from_pcg64_dxsm(2026)?;
let _first_batch = rng.standard_normal(100);

// Snapshot the exact state into an in-memory payload.
let snapshot = rng.to_pickle_payload();

// Hand the snapshot to another part of your program (or persist it via your
// own transport; fnp-random does not ship a bytes serializer today, but the
// `GeneratorPicklePayload` struct exposes its fields so you can layer one
// on top, or feed it through a serde derive behind your own feature flag).
let mut rng_resumed = Generator::from_pickle_payload(snapshot)?;

let next_from_original = rng.standard_normal(50);
let next_from_resumed  = rng_resumed.standard_normal(50);
assert_eq!(next_from_original, next_from_resumed);

The payload carries the bit-generator state plus the (optional) SeedSequence snapshot for spawn-lineage tracking. The bit-generator state includes a schema version, so a future generator change that preserves the underlying algorithm can still rehydrate older payloads.


This section in the README on GitHub