Skip to main content

Tensor

Struct Tensor 

Source
pub struct Tensor<St, L>
where St: Storage + StorageFor<L>, L: TensorLayout,
{ /* private fields */ }
Expand description

Tensor wrapping a TensorData bundle.

§Type Parameters

§Examples

use ariadnetor_tensor::DenseTensor;

let a = DenseTensor::<f64>::zeros(vec![2, 2]);
assert_eq!(a.shape(), &[2, 2]);

Implementations§

Source§

impl<S> Tensor<DenseStorage<S>, DenseLayout>

Source

pub fn data_slice(&self) -> &[S]

Get a reference to the underlying contiguous data buffer.

Source

pub fn data_slice_mut(&mut self) -> &mut [S]
where S: Clone,

Get a mutable reference to the underlying data buffer (CoW-aware).

Source

pub fn reshape(&self, new_shape: Vec<usize>) -> Self

Reshape to new_shape (zero-copy). Preserves the layout’s memory order. The flat data buffer is Arc-shared via DenseStorage::Clone, so the result aliases the same allocation as self.

Under non-adjacent axis fusion the logical mapping differs between row-major and column-major; callers fusing such axes must reorder the flat buffer to the appropriate order first.

§Panics

Panics if new_shape.iter().product() != self.len(), via TensorData::new’s storage.flat_len() == layout.storage_extent() assert.

Source§

impl<S: Scalar> Tensor<DenseStorage<S>, DenseLayout>

Source

pub fn order(&self) -> MemoryOrder

Memory order this tensor’s flat data is laid out in.

Source

pub fn get(&self, indices: impl AsRef<[usize]>) -> S

Get element at the given indices.

indices accepts any AsRef<[usize]>, so an array literal can be passed without a borrow: t.get([i, j]) as well as t.get(&coords).

§Panics

Panics if indices.len() != rank or any index exceeds the corresponding axis dimension.

Source

pub fn set(&mut self, indices: impl AsRef<[usize]>, value: S)

Set element at the given indices.

indices accepts any AsRef<[usize]>, so an array literal can be passed without a borrow: t.set([i, j], v) as well as t.set(&coords, v).

§Panics

Panics if indices.len() != rank or any index exceeds the corresponding axis dimension.

Source

pub fn fill(&mut self, value: S)

Fill the tensor with a constant value.

Source§

impl<S: Clone> Tensor<DenseStorage<S>, DenseLayout>

Source

pub fn scale<F>(&mut self, factor: F)
where S: Mul<F, Output = S>, F: Clone,

Scale every element by a factor (in-place).

Source

pub fn scaled<F>(&self, factor: F) -> Self
where S: Mul<F, Output = S>, F: Clone,

Scale every element by a factor (out-of-place).

Source§

impl<S> Tensor<DenseStorage<S>, DenseLayout>
where S: Scalar,

Source

pub fn norm(&self) -> S::Real

Frobenius norm.

Source

pub fn normalize(&mut self) -> S::Real

Normalize to unit norm (in-place). Returns the original norm.

§Panics

Panics if the tensor has zero norm.

Source

pub fn normalized(&self) -> (Self, S::Real)

Normalize and return a new tensor (out-of-place).

Source

pub fn conj(&self) -> Self

Element-wise complex conjugate. Symmetric with [BlockSparseTensor::conj].

Source

pub fn reordered(&self, to: MemoryOrder) -> Self

Return a tensor with flat data reordered to to. When self.data().order() == to, the underlying buffer is shared via Arc rather than copied.

This is a workspace-internal escape hatch, not a user entry point. The public Tensor surface hides memory layout: constructors take no order, and the linalg / algorithm layers normalize to the backend’s preferred order internally. The only in-tree callers are that internal plumbing (and the order-mismatch rejection tests). End users should never need to choose a MemoryOrder; as an inherent method on a re-exported type it cannot be hidden from umbrella users, hence this note.

Source

pub fn reshape_logical(&self, new_shape: Vec<usize>) -> Self

General logical (C-order) reshape to an arbitrary target shape, preserving the tensor’s memory order. The buffer is routed through row-major so the logical axis grouping is independent of the physical layout, then restored to the original order; for a row-major tensor each step is a zero-copy Arc share, for a column-major tensor it costs one round-trip transpose.

This is the low-level escape hatch for multi-leg regroupings that fuse_legs / split_leg cannot express in a single operation — e.g. fusing two disjoint leg groups at once. Prefer fuse_legs / split_leg for single-leg fuse / split: they constrain which axis changes and read as intent. Like reshape, only the total element count is validated.

§Panics

Panics if new_shape’s total element count differs from the tensor’s, via reshape.

Source

pub fn fuse_legs(&self, range: Range<usize>) -> Self

Fuse a contiguous range of axes into a single leg, grouping them in row-major (C-order) logical order regardless of the tensor’s physical memory order.

The fused leg’s extent is the product of the fused axes’ extents and its logical index runs fastest over the last fused axis. The result keeps self’s memory order. Use reshape instead when a raw, order-preserving buffer reinterpretation is wanted. Inverse of split_leg over the same range. Convenience over reshape_logical for the single-leg case; for multi-group regroupings call reshape_logical directly.

§Panics

Panics unless range.start < range.end <= rank.

Source

pub fn split_leg(&self, axis: usize, into: &[usize]) -> Self

Split one axis into multiple axes, distributing the extent in row-major (C-order) logical order regardless of the tensor’s physical memory order.

into lists the resulting extents from slowest- to fastest-varying. The result keeps self’s memory order. Inverse of fuse_legs for a contiguous range. Convenience over reshape_logical for the single-leg case; for multi-group regroupings call reshape_logical directly.

§Panics

Panics unless axis < rank, into is non-empty, and into.iter().product() == shape[axis].

Source§

impl<T, S> Tensor<BlockSparseStorage<T>, BlockSparseLayout<S>>
where S: Sector,

Source

pub fn order(&self) -> MemoryOrder

Memory order this tensor’s flat block data is laid out in.

Mirror of DenseTensor::order — saves block-sparse callers from reaching through .data().layout().order() for a basic layout property.

Source

pub fn indices(&self) -> &[QNIndex<S>]

Per-leg QNIndex metadata (one entry per axis).

Source

pub fn flux(&self) -> &S

Overall flux label of the tensor.

Source

pub fn num_blocks(&self) -> usize

Number of flux-allowed blocks.

Source

pub fn block_metas(&self) -> &[BlockMeta]

Block metadata table (one entry per flux-allowed block).

Source

pub fn block_shape(&self, coord: &BlockCoord) -> Option<Vec<usize>>

Per-leg block shape for a stored block coordinate.

Returns None if the coord is outside the layout’s enumerated block set.

Source

pub fn block_data(&self, coord: &BlockCoord) -> Option<&[T]>

Data slice for a block identified by coordinate.

Returns None if the block is not stored (zero by symmetry).

Source

pub fn block_data_mut(&mut self, coord: &BlockCoord) -> Option<&mut [T]>
where T: Clone,

Mutable data slice for a block identified by coordinate (CoW-aware).

Source§

impl<T, S> Tensor<BlockSparseStorage<T>, BlockSparseLayout<S>>
where T: Scalar, S: Sector,

Source

pub fn norm(&self) -> T::Real

Frobenius norm: sqrt(Σ |x|^2) over the packed flat buffer.

Source

pub fn dagger(&self) -> Self

Hermitian adjoint: element-wise conjugation, leg-direction flip, and flux dualization.

Source

pub fn conj(&self) -> Self

Element-wise complex conjugate.

Source§

impl<T, S> Tensor<BlockSparseStorage<T>, BlockSparseLayout<S>>
where T: Clone, S: Sector,

Source

pub fn scale<F>(&mut self, factor: F)
where T: Mul<F, Output = T>, F: Clone,

Scale every stored element by a factor (in-place).

Source

pub fn scaled<F>(&self, factor: F) -> Self
where T: Mul<F, Output = T>, F: Clone,

Scale every stored element by a factor (out-of-place).

Source§

impl<St, L> Tensor<St, L>
where St: Storage + StorageFor<L>, L: TensorLayout,

Source

pub fn from_data(data: TensorData<St, L>) -> Self

Build a tensor from a pre-bundled TensorData.

Source

pub fn data(&self) -> &TensorData<St, L>

Internal escape hatch: reference to the joined TensorData bundle.

Intended for cross-crate kernel-access paths inside ariadnetor-linalg and ariadnetor-mps; user code should reach for the inherent methods on DenseTensor / BlockSparseTensor instead.

Source

pub fn data_mut(&mut self) -> &mut TensorData<St, L>

Internal escape hatch: mutable reference to the joined TensorData bundle.

Same audience as Tensor::data — cross-crate kernel paths that need to mutate raw storage / layout state.

Source

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

Logical shape (delegates to the layout).

Source

pub fn rank(&self) -> usize

Rank (number of dimensions).

Source

pub fn len(&self) -> usize

Total number of logical elements (product(shape)).

Source

pub fn is_empty(&self) -> bool

Whether the tensor has zero logical elements.

Source§

impl<S: Scalar> Tensor<DenseStorage<S>, DenseLayout>

Source

pub fn zeros(shape: Vec<usize>) -> Self

Create a Dense tensor filled with zeros.

Source

pub fn ones(shape: Vec<usize>) -> Self

Create a Dense tensor filled with ones.

Source

pub fn filled(shape: Vec<usize>, value: S) -> Self

Create a Dense tensor filled with value.

Source

pub fn eye(n: usize) -> Self

Create an n×n identity matrix.

Source

pub fn random<R: Rng>(shape: Vec<usize>, rng: &mut R) -> Self

Create a Dense tensor filled with values drawn from the standard distribution via the supplied RNG.

Source§

impl<T, S> Tensor<BlockSparseStorage<T>, BlockSparseLayout<S>>
where T: Clone + Zero, S: Sector,

Source

pub fn zeros(indices: Vec<QNIndex<S>>, flux: S) -> Self

Create a zero-filled BlockSparseTensor enumerating every flux-allowed block of the supplied QNIndex legs.

Source§

impl<T, S> Tensor<BlockSparseStorage<T>, BlockSparseLayout<S>>

Source

pub fn random<R: Rng>(indices: Vec<QNIndex<S>>, flux: S, rng: &mut R) -> Self

Create a BlockSparseTensor whose flux-allowed blocks are filled with values drawn from the standard distribution via the supplied RNG.

Source§

impl<T, S> Tensor<BlockSparseStorage<T>, BlockSparseLayout<S>>
where T: Clone + Zero, S: Sector,

Source

pub fn from_block_fn<F>(indices: Vec<QNIndex<S>>, flux: S, f: F) -> Self
where F: FnMut(&BlockCoord, &[usize]) -> Vec<T>,

Construct a BlockSparseTensor by populating each flux-allowed block from a closure receiving the block coordinate and its dense block shape.

Trait Implementations§

Source§

impl<St, L> Clone for Tensor<St, L>
where St: Storage + StorageFor<L> + Clone, L: TensorLayout + Clone,

Source§

fn clone(&self) -> Self

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<St, L> Debug for Tensor<St, L>
where St: Storage + StorageFor<L>, L: TensorLayout,

Source§

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

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

impl<S> Mul<S> for Tensor<DenseStorage<S>, DenseLayout>
where S: Clone + Mul<Output = S>,

Source§

fn mul(self, rhs: S) -> Self::Output

Scale by rhs, consuming self. Reuses the owned buffer in place (no extra allocation when the storage is uniquely owned; a buffer still shared via copy-on-write is cloned first).

Source§

type Output = Tensor<DenseStorage<S>, DenseLayout>

The resulting type after applying the * operator.
Source§

impl<S> Mul<S> for &Tensor<DenseStorage<S>, DenseLayout>
where S: Clone + Mul<Output = S>,

Source§

fn mul(self, rhs: S) -> Self::Output

Scale by rhs, leaving self untouched (out-of-place).

Source§

type Output = Tensor<DenseStorage<S>, DenseLayout>

The resulting type after applying the * operator.
Source§

impl<S> MulAssign<S> for Tensor<DenseStorage<S>, DenseLayout>
where S: Clone + Mul<Output = S>,

Source§

fn mul_assign(&mut self, rhs: S)

Scale every element by rhs in place.

Auto Trait Implementations§

§

impl<St, L> Freeze for Tensor<St, L>
where St: Freeze, L: Freeze,

§

impl<St, L> RefUnwindSafe for Tensor<St, L>

§

impl<St, L> Send for Tensor<St, L>
where St: Send, L: Send,

§

impl<St, L> Sync for Tensor<St, L>
where St: Sync, L: Sync,

§

impl<St, L> Unpin for Tensor<St, L>
where St: Unpin, L: Unpin,

§

impl<St, L> UnsafeUnpin for Tensor<St, L>
where St: UnsafeUnpin, L: UnsafeUnpin,

§

impl<St, L> UnwindSafe for Tensor<St, L>
where St: UnwindSafe, L: UnwindSafe,

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

Source§

fn by_ref(&self) -> &T

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> DistributionExt for T
where T: ?Sized,

Source§

fn rand<T>(&self, rng: &mut (impl Rng + ?Sized)) -> T
where Self: Distribution<T>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Imply<T> for U
where T: ?Sized, U: ?Sized,

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> 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> 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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V