Skip to main content

Block

Struct Block 

Source
pub struct Block { /* private fields */ }
Expand description

A dictionary from string keys to ndarray arrays with a consistent axis-0 length.

This Block supports heterogeneous column types (float, int, bool).

shape is optional structural metadata that lets a Block declare itself as N-dimensional (e.g. a 3D volumetric grid). Columns themselves are stored row-major, so a grid block with shape = [Nx, Ny, Nz] carries columns of axis-0 length Nx * Ny * Nzshape only tells consumers how to unflatten that index. When shape is None, the block is a plain row table and block.shape() reports vec![nrows].

Implementations§

Source§

impl Block

Source

pub fn new() -> Block

Creates an empty Block.

Source

pub fn with_capacity(cap: usize) -> Block

Creates an empty Block with the specified capacity.

Source

pub fn len(&self) -> usize

Number of keys (columns).

Source

pub fn is_empty(&self) -> bool

Returns true if there are no arrays in the block.

Source

pub fn nrows(&self) -> Option<usize>

Returns the common axis-0 length of all arrays, or None if empty.

Source

pub fn shape(&self) -> Vec<usize>

Returns the structural shape of the block.

  • For plain row tables (atoms, bonds): vec![nrows] — a single axis whose length is the row count.
  • For N-D blocks (volumetric grids): the explicitly-set shape, e.g. vec![Nx, Ny, Nz].
  • For empty blocks: vec![].

The product of the returned shape always equals nrows.unwrap_or(0). This API is uniform across atoms / bonds / grid blocks — the difference is the rank of the returned vector, not whether the accessor exists.

Source

pub fn set_shape(&mut self, shape: &[usize]) -> Result<(), BlockError>

Declare this block as N-dimensional with the given shape.

shape must have at least one axis and shape.iter().product() must equal the block’s current nrows (when the block has columns). This does not change column storage — columns remain row-major 1D buffers of length product(shape). shape is structural metadata used by consumers (e.g. the volumetric renderer) to unflatten the row index back into N-D coordinates.

Passing an empty slice clears the shape, reverting the block to plain-row-table semantics.

Source

pub fn contains_key(&self, key: &str) -> bool

Returns true if the Block contains the specified key.

Source

pub fn insert<T>( &mut self, key: impl Into<String>, arr: ArrayBase<OwnedRepr<T>, Dim<IxDynImpl>>, ) -> Result<(), BlockError>
where T: BlockDtype,

Inserts an array under key, enforcing consistent axis-0 length.

This method uses generic dispatch via the BlockDtype trait to accept any supported type (float, int, bool) without requiring users to manually construct Column enums.

§Errors
  • Returns BlockError::RankZero if the array has rank 0
  • Returns BlockError::RaggedAxis0 if the array’s axis-0 length doesn’t match the Block’s existing nrows
§Examples
use molrs_core::block::Block;
use molrs_core::types::{F, I};
use ndarray::Array1;

let mut block = Block::new();

// Insert float array
let arr_float = Array1::from_vec(vec![1.0 as F, 2.0 as F]).into_dyn();
block.insert("x", arr_float).unwrap();

// Insert int array with same nrows
let arr_int = Array1::from_vec(vec![10 as I, 20 as I]).into_dyn();
block.insert("id", arr_int).unwrap();

// This would error - different nrows
let arr_bad = Array1::from_vec(vec![1.0 as F, 2.0 as F, 3.0 as F]).into_dyn();
assert!(block.insert("bad", arr_bad).is_err());
Source

pub fn insert_column( &mut self, key: impl Into<String>, col: Column, ) -> Result<(), BlockError>

Insert a pre-built Column under key, validating axis-0 length.

This is the zero-copy insert path: the caller owns a Column (which internally holds an Arc<ArrayD<T>>) and hands it over without unwrapping the Arc. Useful when moving a column between blocks or re-inserting a clone.

Source

pub fn get(&self, key: &str) -> Option<&Column>

Gets an immutable reference to the column for key if present.

For type-safe access, prefer using get_float(), get_int(), etc.

Source

pub fn get_mut(&mut self, key: &str) -> Option<&mut Column>

Gets a mutable reference to the column for key if present.

For type-safe access, prefer using get_float_mut(), get_int_mut(), etc.

§Warning

Mutating the column’s shape through this reference is allowed but NOT revalidated. It’s the caller’s responsibility to maintain axis-0 consistency.

Source

pub fn get_float( &self, key: &str, ) -> Option<&ArrayBase<OwnedRepr<f64>, Dim<IxDynImpl>>>

Gets an immutable reference to a float array for key if present and of correct type.

Source

pub fn get_float_mut( &mut self, key: &str, ) -> Option<&mut ArrayBase<OwnedRepr<f64>, Dim<IxDynImpl>>>

Gets a mutable reference to a float array for key if present and of correct type.

Source

pub fn get_int( &self, key: &str, ) -> Option<&ArrayBase<OwnedRepr<i32>, Dim<IxDynImpl>>>

Gets an immutable reference to an int array for key if present and of correct type.

Source

pub fn get_int_mut( &mut self, key: &str, ) -> Option<&mut ArrayBase<OwnedRepr<i32>, Dim<IxDynImpl>>>

Gets a mutable reference to an int array for key if present and of correct type.

Source

pub fn get_bool( &self, key: &str, ) -> Option<&ArrayBase<OwnedRepr<bool>, Dim<IxDynImpl>>>

Gets an immutable reference to a bool array for key if present and of correct type.

Source

pub fn get_bool_mut( &mut self, key: &str, ) -> Option<&mut ArrayBase<OwnedRepr<bool>, Dim<IxDynImpl>>>

Gets a mutable reference to a bool array for key if present and of correct type.

Source

pub fn get_uint( &self, key: &str, ) -> Option<&ArrayBase<OwnedRepr<u32>, Dim<IxDynImpl>>>

Gets an immutable reference to a uint array for key if present and of correct type.

Source

pub fn get_uint_mut( &mut self, key: &str, ) -> Option<&mut ArrayBase<OwnedRepr<u32>, Dim<IxDynImpl>>>

Gets a mutable reference to a uint array for key if present and of correct type.

Source

pub fn get_u8( &self, key: &str, ) -> Option<&ArrayBase<OwnedRepr<u8>, Dim<IxDynImpl>>>

Gets an immutable reference to a u8 array for key if present and of correct type.

Source

pub fn get_u8_mut( &mut self, key: &str, ) -> Option<&mut ArrayBase<OwnedRepr<u8>, Dim<IxDynImpl>>>

Gets a mutable reference to a u8 array for key if present and of correct type.

Source

pub fn get_string( &self, key: &str, ) -> Option<&ArrayBase<OwnedRepr<String>, Dim<IxDynImpl>>>

Gets an immutable reference to a String array for key if present and of correct type.

Source

pub fn get_string_mut( &mut self, key: &str, ) -> Option<&mut ArrayBase<OwnedRepr<String>, Dim<IxDynImpl>>>

Gets a mutable reference to a String array for key if present and of correct type.

Source

pub fn remove(&mut self, key: &str) -> Option<Column>

Removes and returns the column for key, if present.

If the Block becomes empty after removal, resets nrows and shape to None.

Source

pub fn rename_column(&mut self, old_key: &str, new_key: &str) -> bool

Renames a column from old_key to new_key.

Returns true if the column was successfully renamed, false if old_key doesn’t exist or new_key already exists.

§Examples
use molrs_core::block::Block;
use molrs_core::types::F;
use ndarray::Array1;

let mut block = Block::new();
block.insert("x", Array1::from_vec(vec![1.0 as F]).into_dyn()).unwrap();

assert!(block.rename_column("x", "position_x"));
assert!(!block.contains_key("x"));
assert!(block.contains_key("position_x"));
Source

pub fn clear(&mut self)

Clears the Block, removing all keys and resetting nrows / shape.

Source

pub fn iter(&self) -> impl Iterator<Item = (&str, &Column)>

Returns an iterator over (&str, &Column).

Source

pub fn keys(&self) -> impl Iterator<Item = &str>

Returns an iterator over keys.

Source

pub fn values(&self) -> impl Iterator<Item = &Column>

Returns an iterator over column references.

Source

pub fn dtype(&self, key: &str) -> Option<DType>

Returns the data type of the column with the given key, if it exists.

Source

pub fn resize(&mut self, new_nrows: usize) -> Result<(), MolRsError>

Resize all columns along axis 0 to new_nrows.

  • Shrink (new_nrows < current): slices each column to keep the first new_nrows rows.
  • Grow (new_nrows > current): extends each column with default values (0.0 for Float, 0 for Int/UInt/U8, false for Bool, empty string for String).
  • Same size: no-op, returns Ok(()).
  • Empty block (no columns): sets nrows without touching columns.

Multi-dimensional columns (e.g. Nx3 positions) are resized only along axis 0; trailing dimensions are preserved.

§Arguments
  • new_nrows - The desired number of rows after resize.
§Returns
  • Ok(()) on success.
§Examples
use molrs_core::block::Block;
use molrs_core::types::F;
use ndarray::Array1;

let mut block = Block::new();
block.insert("x", Array1::from_vec(vec![1.0 as F, 2.0 as F]).into_dyn()).unwrap();

block.resize(4).unwrap();
assert_eq!(block.nrows(), Some(4));
let x = block.get_float("x").unwrap();
assert_eq!(x.as_slice_memory_order().unwrap(), &[1.0, 2.0, 0.0, 0.0]);
Source

pub fn merge(&mut self, other: &Block) -> Result<(), BlockError>

Merge another block into this one by concatenating columns along axis-0.

Both blocks must have the same set of column keys and matching dtypes. The resulting block will have nrows = self.nrows + other.nrows.

§Arguments
  • other - The block to merge into this one
§Returns
  • Ok(()) if merge succeeds
  • Err(BlockError) if blocks have incompatible columns
§Examples
use molrs_core::block::Block;
use molrs_core::types::F;
use ndarray::Array1;

let mut block1 = Block::new();
block1.insert("x", Array1::from_vec(vec![1.0 as F, 2.0 as F]).into_dyn()).unwrap();

let mut block2 = Block::new();
block2.insert("x", Array1::from_vec(vec![3.0 as F, 4.0 as F]).into_dyn()).unwrap();

block1.merge(&block2).unwrap();
assert_eq!(block1.nrows(), Some(4));

Trait Implementations§

Source§

impl BlockAccess for Block

Source§

fn get_float_view( &self, key: &str, ) -> Option<ArrayBase<ViewRepr<&f64>, Dim<IxDynImpl>>>

Gets a float array view for key if present and of correct type.
Source§

fn get_int_view( &self, key: &str, ) -> Option<ArrayBase<ViewRepr<&i32>, Dim<IxDynImpl>>>

Gets an int array view for key if present and of correct type.
Source§

fn get_bool_view( &self, key: &str, ) -> Option<ArrayBase<ViewRepr<&bool>, Dim<IxDynImpl>>>

Gets a bool array view for key if present and of correct type.
Source§

fn get_uint_view( &self, key: &str, ) -> Option<ArrayBase<ViewRepr<&u32>, Dim<IxDynImpl>>>

Gets a uint array view for key if present and of correct type.
Source§

fn get_u8_view( &self, key: &str, ) -> Option<ArrayBase<ViewRepr<&u8>, Dim<IxDynImpl>>>

Gets a u8 array view for key if present and of correct type.
Source§

fn get_string_view( &self, key: &str, ) -> Option<ArrayBase<ViewRepr<&String>, Dim<IxDynImpl>>>

Gets a string array view for key if present and of correct type.
Source§

fn nrows(&self) -> Option<usize>

Returns the common axis-0 length, or None if empty.
Source§

fn len(&self) -> usize

Number of columns.
Source§

fn is_empty(&self) -> bool

Returns true if there are no columns.
Source§

fn contains_key(&self, key: &str) -> bool

Returns true if the block contains the specified key.
Source§

fn column_keys(&self) -> Vec<&str>

Returns column keys as a Vec.
Source§

fn column_dtype(&self, key: &str) -> Option<DType>

Returns the data type of the column with the given key, if it exists.
Source§

fn column_shape(&self, key: &str) -> Option<Vec<usize>>

Returns the shape of the column with the given key, if it exists.
Source§

impl Clone for Block

Source§

fn clone(&self) -> Block

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Block

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Block

Source§

fn default() -> Block

Returns the “default value” for a type. Read more
Source§

impl<'a> From<&'a Block> for BlockView<'a>

Source§

fn from(block: &'a Block) -> BlockView<'a>

Converts to this type from the input type.
Source§

impl Index<&str> for Block

Source§

type Output = Column

The returned type after indexing.
Source§

fn index(&self, key: &str) -> &<Block as Index<&str>>::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl IndexMut<&str> for Block

Source§

fn index_mut(&mut self, key: &str) -> &mut <Block as Index<&str>>::Output

Performs the mutable indexing (container[index]) operation. Read more

Auto Trait Implementations§

§

impl Freeze for Block

§

impl !RefUnwindSafe for Block

§

impl Send for Block

§

impl Sync for Block

§

impl Unpin for Block

§

impl UnsafeUnpin for Block

§

impl !UnwindSafe for Block

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.