Skip to main content

XArray

Struct XArray 

Source
pub struct XArray<T> { /* private fields */ }
Expand description

Labelled N-dimensional array with named dimensions and coordinate-based indexing.

XArray wraps an NdArray or NdArrayV with per-axis names and optional coordinate labels, enabling selection by value rather than raw position. Owned data and selection views expose the same container interface.

§Construction

use minarrow::structs::ndarray::NdArray;
use minarrow::structs::xarray::{XArray, Axis};

// Name the dimensions, no coordinate labels
let data = NdArray::from_slice(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
let xa = XArray::new(data, &["station", "measurement"]);
assert_eq!(xa.dim("measurement"), 1);

§Coordinate-based selection

Assign coordinate labels to an axis, then select by value:

// 5 stations, 2 measurements each
let data = NdArray::from_slice(
    &[10.0, 20.0, 30.0, 40.0, 50.0, 1.0, 2.0, 3.0, 4.0, 5.0],
    &[5, 2],
);
let mut xa = XArray::new(data, &["station", "measurement"]);

// Label the station axis with latitude values
xa.assign_coords("station", arr_f64![-33.8, 35.7, 51.5, 40.7, -22.9]);

// Select stations between latitudes 35 and 52
let subset = xa.between("station", 35.0, 52.0);
assert_eq!(subset.shape(), vec![3, 2]); // 3 stations matched

§Positional selection

Select by axis name and index/range without coordinates:

let data = NdArray::from_slice(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
let xa = XArray::new(data, &["obs", "feat"]);

// Range on one axis - keeps the dimension
let sub = xa.select(&[("obs", &(0..2))]);
assert_eq!(sub.shape(), vec![2, 2]);

// Single index collapses the dimension
let col0 = xa.select(&[("feat", &0)]);
assert_eq!(col0.ndim(), 1);

Implementations§

Source§

impl<T: Float> XArray<T>

Source

pub fn new(data: NdArray<T>, dim_names: &[&str]) -> Self

Create with named dimensions, no coordinates.

Source

pub fn with_axes(data: NdArray<T>, axes: Vec<Axis>) -> Self

Create with fully specified axes.

Source

pub fn from_ndarray(data: NdArray<T>) -> Self

Create from NdArray with auto-generated dim names.

Source

pub fn from_view(view: NdArrayV<T>, axes: Vec<Axis>) -> Self

Wrap an NdArrayV view with axes (zero-copy).

Source

pub fn try_ax(&self, name: &str) -> Option<&Axis>

Get axis by name. Returns None if not found.

Source

pub fn ax(&self, name: &str) -> &Axis

Get axis by name. Panics if not found.

Source

pub fn try_dim(&self, name: &str) -> Option<usize>

Get the position of a named axis. Returns None if not found.

Source

pub fn dim(&self, name: &str) -> usize

Get the position of a named axis. Panics if not found.

Source

pub fn axes(&self) -> &[Axis]

All axes.

Source

pub fn dim_names(&self) -> Vec<&str>

Dim names.

Source

pub fn into_ndarray(self) -> NdArray<T>

Consume and return the inner NdArray, materialising if it is a view.

Source

pub fn to_owned(&self) -> XArray<T>

Materialise to an owned NdArray if currently a view.

Source

pub fn as_view(&self) -> NdArrayV<T>

Borrow the data as a zero-copy NdArrayV, regardless of whether this XArray currently owns its NdArray or already holds a view.

Source

pub fn is_owned(&self) -> bool

True if backed by a single owned NdArray.

Source

pub fn ndim(&self) -> usize

Source

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

Source

pub fn strides(&self) -> &[usize]

Source

pub fn len(&self) -> usize

Source

pub fn is_empty(&self) -> bool

Source

pub fn obs(&self, idx: usize) -> NdArrayV<T>

Zero-copy view of a single observation (axis-0 element).

Returns an (N-1)-dimensional NdArrayV view regardless of the inner storage mode.

Source

pub fn m(&self) -> i32

Source

pub fn n(&self) -> i32

Source

pub fn lda(&self) -> i32

Source

pub fn get(&self, indices: &[usize]) -> T

Single element access.

Source

pub fn set(&mut self, indices: &[usize], value: T)

Mutable element access. Triggers copy-on-write if the owned array is shared with views; an XArray backed by a view cannot be mutated.

Source

pub fn par_iter_obs( &self, ) -> impl ParallelIterator<Item = (usize, NdArrayV<T>)> + '_
where T: Send + Sync,

Parallel iterator over axis-0 observations. Each item is the observation index and a zero-copy NdArrayV view.

Source

pub fn apply(&self, f: impl Fn(T) -> T) -> XArray<T>

Apply a function to every logical element, returning a new labelled array with the same axes. View storage materialises to owned.

Source

pub fn apply_mut(&mut self, f: impl Fn(T) -> T)

Apply a function to every logical element in place. An XArray backed by a view cannot be mutated, matching set.

Source

pub fn rename_dim(&mut self, old: &str, new: &str)

Rename an axis.

Source

pub fn assign_coords(&mut self, dim_name: &str, coords: Array)

Assign or replace coordinates for a named axis.

Source

pub fn drop_coords(&mut self, dim_name: &str)

Remove coordinates from a named axis.

Source

pub fn select(&self, selection: &[(&str, &dyn DataSelector)]) -> XArray<T>

Select sub-arrays by named axis positions. Returns zero-copy XArray backed by NdArrayV.

Single indices collapse that dimension. Ranges keep it.

§Examples
xa.select(&[("lat", &(0..3))])                  // single axis range
xa.select(&[("lat", &(0..3)), ("lon", &2)])     // multi-axis mixed
Source

pub fn slice(&self, selection: &[&dyn DataSelector]) -> NdArrayV<T>

Slice the underlying NdArray/NdArrayV positionally and zero-copy. For named axis selection, use .select() instead.

Source

pub fn try_at( &self, dim_name: &str, value: impl Into<Scalar>, ) -> Result<XArray<T>, MinarrowError>

Select a single position on a named axis by coordinate value. Accepts numeric, string, and datetime values. Collapses that dimension. Returns an error if the value is not found. Float coordinates match by IEEE equality, so NaN never matches and derived values may miss - nearest tolerates rounding.

Source

pub fn at(&self, dim_name: &str, value: impl Into<Scalar>) -> XArray<T>

Select a single position by coordinate value. Panics if not found.

Source

pub fn try_between( &self, dim_name: &str, low: impl Into<Scalar>, high: impl Into<Scalar>, ) -> Result<XArray<T>, MinarrowError>

Select a range by coordinate value bounds (inclusive). Accepts numeric, string, and datetime bounds. Returns an error if no values fall in the range, or if the matching coordinates do not form a contiguous run i.e. the axis is not monotonic over the requested bounds - sort the axis or gather by position for unsorted coordinates.

Source

pub fn between( &self, dim_name: &str, low: impl Into<Scalar>, high: impl Into<Scalar>, ) -> XArray<T>

Select a range by coordinate value bounds. Panics if no values match, or if the axis is not monotonic over the requested bounds.

Source

pub fn try_nearest( &self, dim_name: &str, value: impl Into<Scalar>, ) -> Result<XArray<T>, MinarrowError>

Select the position whose coordinate is closest to value on a named axis. Collapses that dimension. Numeric and datetime coordinates only, since text has no distance metric. Returns an error if the axis has no comparable coordinates.

Source

pub fn nearest(&self, dim_name: &str, value: impl Into<Scalar>) -> XArray<T>

Select the position whose coordinate is closest to value. Panics if the axis has no comparable coordinates.

Source

pub fn transpose(&self, dim_order: &[&str]) -> Result<XArray<T>, MinarrowError>

Transpose (2D only). Reorders axes by name, so the result’s dimensions arrive in dim_order. Passing the current order returns the array unchanged.

Source§

impl XArray<f64>

Source

pub fn to_table(self) -> Result<Table, MinarrowError>

Convert a 2D XArray to a Table. Uses axis 1 coords as column names if available, otherwise generates names from the dim name.

Trait Implementations§

Source§

impl<T: Float> AxisSelection for XArray<T>

Available on crate features select and views only.

Positional selection across every axis at once, delegating to slice. The result is an unlabelled view. For named-axis selection with the labels carried through, use .select().

Source§

type View = NdArrayV<T>

The view type returned by axis selection e.g. NdArrayV
Source§

fn s(&self, selection: &[&dyn DataSelector]) -> NdArrayV<T>

Select along every axis at once, one DataSelector per axis Read more
Source§

fn get_axis_count(&self) -> usize

Get the axis count for selection resolution
Source§

fn select(&self, selection: &[&dyn DataSelector]) -> Self::View

Select along every axis at once, one DataSelector per axis Read more
Source§

impl<T: Float> ByteSize for XArray<T>

Available on crate feature xarray only.
Source§

fn est_bytes(&self) -> usize

Returns the estimated byte size of this object in memory. Read more
Source§

fn logical_bytes(&self) -> usize

Returns the exact logical byte size of the data. Read more
Source§

impl<T: Clone> Clone for XArray<T>

Source§

fn clone(&self) -> XArray<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: Float> Concatenate for XArray<T>

Source§

fn concat(self, other: Self) -> Result<Self, MinarrowError>

Concatenates self with other, consuming both and returning a new instance. Read more
Source§

impl<T: Float> Debug for XArray<T>

Source§

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

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

impl<T: Float + Display> Display for XArray<T>

Source§

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

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

impl From<XArray<f64>> for Value

Available on crate feature xarray only.
Source§

fn from(v: XArray<f64>) -> Self

Converts to this type from the input type.
Source§

impl From<XArray<f64>> for NdArray<f64>

Source§

fn from(value: XArray<f64>) -> Self

Drops the axis labels and keeps the contiguous payload.

Source§

impl<'a, T: Float> IntoIterator for &'a XArray<T>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = T> + 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T: Float> PartialEq for XArray<T>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<T: Float> Shape for XArray<T>

Source§

fn shape(&self) -> ShapeDim

Returns arbitrary Shape dimension for any data shape
Source§

fn shape_1d(&self) -> usize

Returns the first dimension shape Read more
Source§

fn shape_2d(&self) -> (usize, usize)

Returns the first and second dimension shapes Read more
Source§

fn shape_3d(&self) -> (usize, usize, usize)

Returns the first, second and third dimension shapes Read more
Source§

fn shape_4d(&self) -> (usize, usize, usize, usize)

Returns the first, second, third and fourth dimension shapes Read more
Source§

impl TryFrom<Table> for XArray<f64>

Source§

type Error = MinarrowError

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

fn try_from(table: Table) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<Value> for XArray<f64>

Available on crate feature xarray only.
Source§

fn try_from(v: Value) -> Result<Self, Self::Error>

Takes the XArray carried by Value::XArray, unwrapping the recursive BoxValue and ArcValue wrappers first.

Source§

type Error = MinarrowError

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

impl TryFrom<XArray<f64>> for Table

Source§

fn try_from(value: XArray<f64>) -> Result<Self, Self::Error>

Presents the labelled axes as table columns.

Source§

type Error = MinarrowError

The type returned in the event of a conversion error.

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for XArray<T>

§

impl<T> !UnwindSafe for XArray<T>

§

impl<T> Freeze for XArray<T>

§

impl<T> Send for XArray<T>
where T: Sync + Send,

§

impl<T> Sync for XArray<T>
where T: Sync + Send,

§

impl<T> Unpin for XArray<T>

§

impl<T> UnsafeUnpin for XArray<T>

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> CustomValue for T
where T: Any + Send + Sync + Clone + PartialEq + Debug,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Downcasts the type as Any
Source§

fn deep_clone(&self) -> Arc<dyn CustomValue>

Returns a deep clone of the object. Read more
Source§

fn eq_box(&self, other: &(dyn CustomValue + 'static)) -> bool

Performs semantic equality on the boxed object. Read more
Source§

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

Source§

fn __clone_box(&self, _: Private) -> *mut ()

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

fn align() -> usize

The alignment necessary for the key. Must return a power of two.
Source§

fn size(&self) -> usize

The size of the key in bytes.
Source§

unsafe fn init(&self, ptr: *mut u8)

Initialize the key in the given memory location. Read more
Source§

unsafe fn get<'a>(ptr: *const u8) -> &'a T

Get a reference to the key from the given memory location. Read more
Source§

unsafe fn drop_in_place(ptr: *mut u8)

Drop the key in place. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Print for T
where T: Display,

Source§

fn print(&self)
where Self: Display,

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToCompactString for T
where T: Display,

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.