Docs/Overview
More Worked Examples
On this page 4 sections
Stride tricks: a 1-D sliding window
use fnp_ufunc::UFuncArray;
use fnp_dtype::DType;
let signal = UFuncArray::new(vec![10], (0..10).map(|i| i as f64).collect(), DType::F64)?;
// Build the window-of-3 rows of the 10-sample signal. The result is shape (8, 3);
// `window_shape` is the per-axis window size, so a 1-D source takes `&[3]`.
let windows = signal.sliding_window_view(&[3])?;
// rows: [0,1,2], [1,2,3], [2,3,4], ..., [7,8,9]
let row_means = windows.reduce_mean(Some(1), false)?;
UFuncArray::sliding_window_view materializes the (8, 3) result as a new array. The zero-copy form is UFuncArrayView::sliding_window_view, which shares the source buffer, is read-only, and rejects a window larger than its axis; UFuncArrayView::as_strided refuses a view whose element span would leave the current view. The byte-span check (ShapeError::OutOfBoundsView) belongs to the SCE layouts in fnp-ndarray (NdLayout::as_strided).
Reproducible RNG with full state capture
use fnp_random::{BitGenerator, BitGeneratorKind, Generator, SeedSequence};
let mut rng_a = Generator::from_pcg64_dxsm(42)?;
let _ = rng_a.standard_normal(1000); // advance the stream
let payload = rng_a.to_pickle_payload(); // in-process snapshot (typed Rust struct)
let mut rng_b = Generator::from_pickle_payload(payload)?;
assert_eq!(rng_a.standard_normal(50), rng_b.standard_normal(50));
// `SeedSequence::spawn(n)` creates independent child streams for parallel work.
// `new` takes a u32 entropy slice; `spawn` requires `&mut self`.
let mut parent = SeedSequence::new(&[42u32])?;
let children = parent.spawn(8)?; // 8 independent, reproducible streams
let _streams: Vec<BitGenerator> = children
.iter()
.map(|ss| BitGenerator::from_seed_sequence(BitGeneratorKind::Pcg64Dxsm, ss))
.collect::<Result<_, _>>()?;
GeneratorPicklePayload is a typed in-memory struct (Debug + Clone + PartialEq + Eq); it carries the bit-generator state schema-version plus the optional SeedSequence snapshot. There is no built-in byte serialization today, so cross-process persistence requires an explicit transport layer. The structured types make adding one (or layering serde derives behind a feature flag) straightforward.
Fail-closed I/O on hostile input
use fnp_io::{load, IOError, MAX_HEADER_BYTES};
// A crafted .npy file claims a 200-MB header dict. The parser refuses without
// allocating a 200-MB buffer: MAX_HEADER_BYTES = 65,536. Header-bound and other
// schema violations surface as `IOError::HeaderSchemaInvalid` with a static-string
// reason; for this file it is "header bytes must be within bounded budget".
// `load` takes the file's bytes as `&[u8]`.
let result = load(&crafted_bytes);
assert!(matches!(result, Err(IOError::HeaderSchemaInvalid(_))));
The same fail-closed treatment applies to:
- NPZ archives claiming more than
MAX_ARCHIVE_MEMBERS = 4,096entries - NPZ archives whose declared uncompressed size exceeds
MAX_ARCHIVE_UNCOMPRESSED_BYTES = 2 GiB - Text input whose total element count would exceed
MAX_TEXT_ELEMENTS = 16,777,216 - Object-dtype
.npyfiles withoutallow_pickle=true - Unknown dtype descriptors, future format versions, and malformed header keys
Floating-point error policy via RAII
use fnp_ufunc::{errstate, FloatErrorMode, geterr};
let before = geterr(); // { divide: Warn, over: Warn, ... }
{
let _guard = errstate(Some(FloatErrorMode::Ignore), None, None, None, None);
// All FP errors silenced in this scope.
let _ = some_division_that_might_divzero();
// _guard drops at end of scope -> state restored automatically.
}
assert_eq!(geterr(), before);
errstate returns an RAII guard; dropping the guard restores the prior configuration, matching NumPy's context-manager semantics. Six modes are available per category (Ignore, Warn, Raise, Call, Print, Log); four categories (divide, over, under, invalid) are tracked independently.