Skip to main content

CausalTensor

Struct CausalTensor 

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

CausalTensor is a low-dimensional (up to ~5-25 dimensions recommended) tensor backed by a single, contiguous Vec<T>. It uses a stride-based memory layout for efficient, cache-friendly access and manipulation.

Operation Semantics: Operations on CausalTensor generally fall into two categories regarding data handling:

  1. Metadata-Only Operations (e.g., reshape, permute_axes, ravel): These operations create a new CausalTensor instance but do not physically reorder or reallocate the underlying data in memory. Instead, they create a cloned copy of the original flat data and only modify the shape and strides metadata to provide a new logical view of the data. This makes them very efficient as they avoid large data movements.

  2. Data-Copying Operations (e.g., slice, binary operations like add, sub, mul, div, reduction operations like sum_axes, mean_axes): These operations create a new CausalTensor instance with newly allocated data. The data is either a subset of the original, a transformation of the original, or a result of combining multiple tensors. These operations involve iterating through and copying/computing values into a new Vec<T>.

Implementations§

Source§

impl<T> CausalTensor<T>
where T: AddGroup + Copy + Neg<Output = T>,

Source

pub fn zero(shape: &[usize]) -> CausalTensor<T>

Creates a zero tensor with the specified shape.

Source

pub fn add(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>

Element-wise addition.

Source

pub fn sub(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>

Element-wise subtraction.

Source

pub fn neg(&self) -> CausalTensor<T>

Element-wise negation.

Source§

impl<T> CausalTensor<T>

Source

pub fn scale<S>(&self, scalar: S) -> CausalTensor<T>
where T: Module<S> + Copy, S: Ring + Copy,

Scales the tensor by a scalar value.

Source§

impl<T> CausalTensor<T>
where T: Ring + Copy,

Source

pub fn mul(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>

Element-wise multiplication (Hadamard product).

Source

pub fn one(shape: &[usize]) -> CausalTensor<T>

Creates a tensor of ones with the specified shape.

Source

pub fn ones(shape: &[usize]) -> CausalTensor<T>

Alias for one. Creates a tensor of ones with the specified shape.

Source

pub fn identity(shape: &[usize]) -> Result<CausalTensor<T>, CausalTensorError>

Creates an identity matrix (square tensor with 1s on diagonal). Typically 2D, but can be higher dim (generalized). For 2D: (N, N)

Source§

impl<T> CausalTensor<T>

Source

pub fn data(&self) -> &Vec<T>

Returns a reference to the underlying Vec<T> that stores the tensor’s data.

The data is stored in row-major order.

§Examples
use deep_causality_tensor::CausalTensor;

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
assert_eq!(tensor.data(), &vec![1, 2, 3, 4, 5, 6]);

let empty_tensor: CausalTensor<f64> = CausalTensor::new(vec![], vec![0]).unwrap();
assert!(empty_tensor.data().is_empty());
Source

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

Returns a slice representing the shape (dimensions) of the tensor.

The elements of the slice indicate the size of each dimension.

§Examples
use deep_causality_tensor::CausalTensor;

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
assert_eq!(tensor.shape(), &[2, 3]);
Source

pub fn is_empty(&self) -> bool

Returns true if the tensor contains no elements.

§Examples
use deep_causality_tensor::CausalTensor;

let empty_tensor: CausalTensor<i32> = CausalTensor::new(vec![], vec![0]).unwrap();
assert!(empty_tensor.is_empty());

let non_empty_tensor: CausalTensor<f64> = CausalTensor::new(vec![1.0], vec![1]).unwrap();
assert!(!non_empty_tensor.is_empty());
Source

pub fn num_dim(&self) -> usize

Returns the number of dimensions (rank) of the tensor.

This is equivalent to self.shape().len().

§Examples
use deep_causality_tensor::CausalTensor;

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
assert_eq!(tensor.num_dim(), 2);

let scalar = CausalTensor::new(vec![42], vec![]).   unwrap();
assert_eq!(scalar.num_dim(), 0); // A scalar has 0 dimensions
Source

pub fn len(&self) -> usize

Returns the total number of elements in the tensor.

This is equivalent to self.as_slice().len().

§Examples
use deep_causality_tensor::CausalTensor;

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
assert_eq!(tensor.len(), 6);

let empty_tensor: CausalTensor<f64> = CausalTensor::new(vec![], vec![0]).unwrap();
assert_eq!(empty_tensor.len(), 0);
Source

pub fn as_slice(&self) -> &[T]

Returns a slice to the underlying contiguous data storage of the tensor.

The data is stored in row-major order.

§Examples
use deep_causality_tensor::CausalTensor;

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
assert_eq!(tensor.as_slice(), &[1, 2, 3, 4, 5, 6]);
Source

pub fn get(&self, index: &[usize]) -> Option<&T>

Returns an optional reference to the element at the specified multi-dimensional index.

Returns None if the provided index is out of bounds or has an incorrect number of dimensions.

§Arguments
  • index - A slice representing the multi-dimensional coordinates (e.g., &[row, col]).
§Examples
use deep_causality_tensor::CausalTensor;

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();

assert_eq!(tensor.get(&[0, 0]), Some(&1));
assert_eq!(tensor.get(&[0, 1]), Some(&2));
assert_eq!(tensor.get(&[1, 2]), Some(&6));

// Out of bounds
assert_eq!(tensor.get(&[2, 0]), None);
assert_eq!(tensor.get(&[0, 3]), None);

// Incorrect number of dimensions
assert_eq!(tensor.get(&[0]), None);
assert_eq!(tensor.get(&[0, 0, 0]), None);
Source

pub fn get_mut(&mut self, index: &[usize]) -> Option<&mut T>

Returns an optional mutable reference to the element at the specified multi-dimensional index.

Returns None if the provided index is out of bounds or has an incorrect number of dimensions.

§Arguments
  • index - A slice representing the multi-dimensional coordinates (e.g., &[row, col]).
§Examples
use deep_causality_tensor::CausalTensor;

let mut tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();

if let Some(val) = tensor.get_mut(&[0, 0]) {
    *val = 10;
}
assert_eq!(tensor.as_slice(), &[10, 2, 3, 4, 5, 6]);

if let Some(val) = tensor.get_mut(&[1, 2]) {
    *val = 60;
}
assert_eq!(tensor.as_slice(), &[10, 2, 3, 4, 5, 60]);

// Out of bounds
assert_eq!(tensor.get_mut(&[2, 0]), None);
Source§

impl<T> CausalTensor<T>

Source

pub fn from_vec(data: Vec<T>, shape: &[usize]) -> CausalTensor<T>

Source

pub fn into_vec(self) -> Vec<T>

Consumes the tensor and returns the underlying data.

Source

pub fn to_vec(self) -> Vec<T>

Source§

impl<T> CausalTensor<T>

Source

pub fn new( data: Vec<T>, shape: Vec<usize>, ) -> Result<CausalTensor<T>, CausalTensorError>

This constructor validates that the total number of elements implied by the shape matches the length of the provided data vector. It also internally calculates the strides for efficient memory access based on the given shape.

§Arguments
  • data - A Vec<T> containing the tensor’s elements in row-major order.
  • shape - A Vec<usize> defining the dimensions of the tensor.
§Returns

A Result which is:

  • Ok(Self) if the data length matches the shape’s total elements.
  • Err(CausalTensorError::ShapeMismatch) if the lengths do not match.
Source

pub fn from_shape_fn<F>(shape: &[usize], f: F) -> CausalTensor<T>
where F: FnMut(&[usize]) -> T,

Creates a tensor from a function applied to each index.

§Arguments
  • shape - Dimensions of the tensor
  • f - Function mapping indices to values
Source§

impl<T> CausalTensor<T>
where T: Clone,

Source

pub fn from_slice(data: &[T], shape: &[usize]) -> CausalTensor<T>

Creates a tensor from a slice (infallible, clones data).

Source§

impl<T> CausalTensor<T>
where T: Clone + Default,

Source

pub fn zeros(shape: &[usize]) -> CausalTensor<T>

Creates a tensor of zeros with the given shape.

Trait Implementations§

Source§

impl<T> Add<&CausalTensor<T>> for CausalTensor<T>
where T: Clone + PartialOrd + Add<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the + operator.
Source§

fn add( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Add<&CausalTensor<T>>>::Output

Performs the + operation. Read more
Source§

impl<T> Add<CausalTensor<T>> for &CausalTensor<T>
where T: Clone + PartialOrd + Add<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the + operator.
Source§

fn add( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Add<CausalTensor<T>>>::Output

Performs the + operation. Read more
Source§

impl<T> Add<T> for &CausalTensor<T>
where T: Add<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: T) -> <&CausalTensor<T> as Add<T>>::Output

Performs the + operation. Read more
Source§

impl<T> Add<T> for CausalTensor<T>
where T: Add<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: T) -> <CausalTensor<T> as Add<T>>::Output

Performs the + operation. Read more
Source§

impl<T> Add for &CausalTensor<T>
where T: Clone + PartialOrd + Add<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Add>::Output

Performs the + operation. Read more
Source§

impl<T> Add for CausalTensor<T>
where T: Clone + PartialOrd + Add<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Add>::Output

Performs the + operation. Read more
Source§

impl<T> AddAssign<T> for CausalTensor<T>
where T: AddAssign + Clone,

Source§

fn add_assign(&mut self, rhs: T)

Performs the += operation. Read more
Source§

impl<T> BatchedMatMul<T> for CausalTensor<T>
where T: Field + Ring + Copy + Default + PartialOrd,

Source§

fn batched_matmul(&self, other: &Self) -> Self

Source§

impl CausalTensorMathExt<f32> for CausalTensor<f32>

Source§

fn log_nat(&self) -> Result<CausalTensor<f32>, CausalTensorError>

Computes the element-wise natural logarithm of the tensor. Read more
Source§

fn log2(&self) -> Result<CausalTensor<f32>, CausalTensorError>

Computes the element-wise base-2 logarithm of the tensor. Read more
Source§

fn log10(&self) -> Result<CausalTensor<f32>, CausalTensorError>

Computes the element-wise base-10 logarithm of the tensor. Read more
Source§

fn surd_log2(&self) -> Result<CausalTensor<f32>, CausalTensorError>

Computes the element-wise base-2 logarithm of the tensor, handling 0.0 inputs as 0.0. This replicates the behavior of Python’s mylog function for information theory calculations. Read more
Source§

fn safe_div( &self, rhs: &CausalTensor<f32>, ) -> Result<CausalTensor<f32>, CausalTensorError>

Performs element-wise division that is safe for probabilistic calculations. Read more
Source§

impl CausalTensorMathExt<f64> for CausalTensor<f64>

Source§

fn log_nat(&self) -> Result<CausalTensor<f64>, CausalTensorError>

Computes the element-wise natural logarithm of the tensor. Read more
Source§

fn log2(&self) -> Result<CausalTensor<f64>, CausalTensorError>

Computes the element-wise base-2 logarithm of the tensor. Read more
Source§

fn log10(&self) -> Result<CausalTensor<f64>, CausalTensorError>

Computes the element-wise base-10 logarithm of the tensor. Read more
Source§

fn surd_log2(&self) -> Result<CausalTensor<f64>, CausalTensorError>

Computes the element-wise base-2 logarithm of the tensor, handling 0.0 inputs as 0.0. This replicates the behavior of Python’s mylog function for information theory calculations. Read more
Source§

fn safe_div( &self, rhs: &CausalTensor<f64>, ) -> Result<CausalTensor<f64>, CausalTensorError>

Performs element-wise division that is safe for probabilistic calculations. Read more
Source§

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

Source§

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

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<T> Debug for CausalTensor<T>
where T: Debug,

Source§

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

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

impl<T> Default for CausalTensor<T>
where T: Default,

Source§

fn default() -> CausalTensor<T>

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

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

Source§

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

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

impl<T> Div<&CausalTensor<T>> for CausalTensor<T>
where T: Clone + PartialOrd + Zero + Div<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the / operator.
Source§

fn div( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Div<&CausalTensor<T>>>::Output

Performs the / operation. Read more
Source§

impl<T> Div<CausalTensor<T>> for &CausalTensor<T>
where T: Clone + PartialOrd + Zero + Div<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the / operator.
Source§

fn div( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Div<CausalTensor<T>>>::Output

Performs the / operation. Read more
Source§

impl<T> Div<T> for &CausalTensor<T>
where T: Div<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: T) -> <&CausalTensor<T> as Div<T>>::Output

Performs the / operation. Read more
Source§

impl<T> Div<T> for CausalTensor<T>
where T: Div<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: T) -> <CausalTensor<T> as Div<T>>::Output

Performs the / operation. Read more
Source§

impl<T> Div for &CausalTensor<T>
where T: Clone + PartialOrd + Zero + Div<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Div>::Output

Performs the / operation. Read more
Source§

impl<T> Div for CausalTensor<T>
where T: Clone + PartialOrd + Zero + Div<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Div>::Output

Performs the / operation. Read more
Source§

impl<T> DivAssign<T> for CausalTensor<T>
where T: DivAssign + Clone,

Source§

fn div_assign(&mut self, rhs: T)

Performs the /= operation. Read more
Source§

impl<'a, T> From<&'a CausalTensor<T>> for CausalTensor<T>
where T: Clone,

Source§

fn from(item: &'a CausalTensor<T>) -> CausalTensor<T>

Creates a new CausalTensor by cloning an existing CausalTensor reference.

Source§

impl<'a, T> From<&'a T> for CausalTensor<T>
where T: Clone,

Source§

fn from(item: &'a T) -> CausalTensor<T>

Creates a scalar tensor (0-dimensional) from a reference to a single value.

Source§

impl<T> From<T> for CausalTensor<T>
where T: Clone,

Source§

fn from(item: T) -> CausalTensor<T>

Creates a scalar tensor (0-dimensional) from a single value.

Source§

impl<T> Mul<&CausalTensor<T>> for CausalTensor<T>
where T: Clone + PartialOrd + Mul<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the * operator.
Source§

fn mul( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Mul<&CausalTensor<T>>>::Output

Performs the * operation. Read more
Source§

impl<T> Mul<CausalTensor<T>> for &CausalTensor<T>
where T: Clone + PartialOrd + Mul<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the * operator.
Source§

fn mul( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Mul<CausalTensor<T>>>::Output

Performs the * operation. Read more
Source§

impl<T> Mul<T> for &CausalTensor<T>
where T: Mul<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: T) -> <&CausalTensor<T> as Mul<T>>::Output

Performs the * operation. Read more
Source§

impl<T> Mul<T> for CausalTensor<T>
where T: Mul<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: T) -> <CausalTensor<T> as Mul<T>>::Output

Performs the * operation. Read more
Source§

impl<T> Mul for &CausalTensor<T>
where T: Clone + PartialOrd + Mul<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Mul>::Output

Performs the * operation. Read more
Source§

impl<T> Mul for CausalTensor<T>
where T: Clone + PartialOrd + Mul<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Mul>::Output

Performs the * operation. Read more
Source§

impl<T> MulAssign<T> for CausalTensor<T>
where T: MulAssign + Clone,

Source§

fn mul_assign(&mut self, rhs: T)

Performs the *= operation. Read more
Source§

impl<T> Neg for &CausalTensor<T>
where T: Neg<Output = T> + Copy + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn neg(self) -> <&CausalTensor<T> as Neg>::Output

Performs the unary - operation. Read more
Source§

impl<T> Neg for CausalTensor<T>
where T: Neg<Output = T> + Copy + Clone,

Implements Neg trait for CausalTensor.

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn neg(self) -> <CausalTensor<T> as Neg>::Output

Performs the unary - operation. Read more
Source§

impl<T> One for CausalTensor<T>
where T: One + Copy + Default + PartialOrd,

Source§

fn one() -> CausalTensor<T>

Returns the multiplicative identity element of Self, 1. Read more
Source§

fn is_one(&self) -> bool

Returns true if self is equal to the multiplicative identity.
Source§

fn set_one(&mut self)

Sets self to the multiplicative identity element of Self, 1.
Source§

impl<T> PartialEq for CausalTensor<T>
where T: PartialEq,

Source§

fn eq(&self, other: &CausalTensor<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T> Sub<&CausalTensor<T>> for CausalTensor<T>
where T: Clone + PartialOrd + Sub<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn sub( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Sub<&CausalTensor<T>>>::Output

Performs the - operation. Read more
Source§

impl<T> Sub<CausalTensor<T>> for &CausalTensor<T>
where T: Clone + PartialOrd + Sub<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn sub( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Sub<CausalTensor<T>>>::Output

Performs the - operation. Read more
Source§

impl<T> Sub<T> for &CausalTensor<T>
where T: Sub<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: T) -> <&CausalTensor<T> as Sub<T>>::Output

Performs the - operation. Read more
Source§

impl<T> Sub<T> for CausalTensor<T>
where T: Sub<Output = T> + Clone,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: T) -> <CausalTensor<T> as Sub<T>>::Output

Performs the - operation. Read more
Source§

impl<T> Sub for &CausalTensor<T>
where T: Clone + PartialOrd + Sub<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Sub>::Output

Performs the - operation. Read more
Source§

impl<T> Sub for CausalTensor<T>
where T: Clone + PartialOrd + Sub<Output = T>,

Source§

type Output = CausalTensor<T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Sub>::Output

Performs the - operation. Read more
Source§

impl<T> SubAssign<T> for CausalTensor<T>
where T: SubAssign + Clone,

Source§

fn sub_assign(&mut self, rhs: T)

Performs the -= operation. Read more
Source§

impl<T> Tensor<T> for CausalTensor<T>

Source§

fn ein_sum( ast: &ConstTree<EinSumOp<T>>, ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone + Default + PartialOrd + Add<Output = T> + Mul<Output = T>,

Public API for Einstein summation.

This method serves as the entry point for performing Einstein summation operations on CausalTensors. It takes an EinSumAST (Abstract Syntax Tree) as input, which defines the sequence of tensor operations to be executed.

§Arguments
  • ast - A reference to the EinSumAST that describes the Einstein summation operation.
§Returns

A Result which is:

  • Ok(CausalTensor<T>) containing the result of the Einstein summation.
  • Err(CausalTensorError) if any error occurs during the execution of the AST.
§Errors

Returns errors propagated from execute_ein_sum.

Source§

fn tensor_product( &self, rhs: &CausalTensor<T>, ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone + Mul<Output = T>,

Computes the tensor product (also known as the outer product) of two CausalTensors.

The tensor product combines two tensors into a new tensor whose rank is the sum of the ranks of the input tensors, and whose shape is the concatenation of their shapes. Each element of the resulting tensor is the product of an element from the left-hand side tensor and an element from the right-hand side tensor.

This operation is fundamental in linear algebra and tensor calculus, effectively creating all possible pairwise products between elements of the input tensors.

§Arguments
  • rhs - The right-hand side CausalTensor.
§Returns

A Result which is:

  • Ok(CausalTensor<T>) containing the result of the tensor product.
  • Err(CausalTensorError) if an error occurs during the operation (e.g., memory allocation).
§Errors

This method can return CausalTensorError if the underlying tensor_product_impl encounters an issue, such as a failure during new tensor creation.

§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let lhs = CausalTensor::new(vec![1.0, 2.0], vec![2]).unwrap(); // Shape [2]
let rhs = CausalTensor::new(vec![3.0, 4.0, 5.0], vec![3]).unwrap(); // Shape [3]

// Expected result:
// [[1*3, 1*4, 1*5],
//  [2*3, 2*4, 2*5]]
// which is [[3.0, 4.0, 5.0], [6.0, 8.0, 10.0]] with shape [2, 3]
let result = lhs.tensor_product(&rhs).unwrap();

assert_eq!(result.shape(), &[2, 3]);
assert_eq!(result.as_slice(), &[3.0, 4.0, 5.0, 6.0, 8.0, 10.0]);

// Tensor product with a scalar
let scalar = CausalTensor::new(vec![10.0], vec![]).unwrap(); // Shape []
let vector = CausalTensor::new(vec![1.0, 2.0], vec![2]).unwrap(); // Shape [2]
let result_scalar_vec = scalar.tensor_product(&vector).unwrap();
assert_eq!(result_scalar_vec.shape(), &[2]);
assert_eq!(result_scalar_vec.as_slice(), &[10.0, 20.0]);
Source§

fn norm_l2(&self) -> T
where T: RealField + Default + Zero + Sum + Copy,

Computes the L2 Norm (Euclidean Norm) of the tensor.

$$ ||A||_2 = \sqrt{ \sum |x_i|^2 } $$

This effectively flattens the tensor and calculates the vector magnitude. Useful for checking convergence (e.g., is the Laplacian zero?).

Source§

fn norm_sq(&self) -> T
where T: RealField + Default + Zero + Sum + Copy + Mul,

Computes the Squared L2 Norm.

$$ ||A||^2 = \sum |x_i|^2 $$

Faster than norm_l2 because it avoids the square root. Preferred for threshold checks (e.g. if norm_sq < epsilon * epsilon).

Source§

fn sum_axes(&self, axes: &[usize]) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone + Default + PartialOrd + Add<Output = T>,

Sums the elements along one or more specified axes.

The dimensions corresponding to the axes provided will be removed from the shape of the resulting tensor. If axes is empty, the sum of all elements in the tensor is returned as a 0-dimensional (scalar) tensor.

§Type Parameters
  • T: Must implement Add<T, Output = T> for summation.
§Arguments
  • axes - A slice of usize indicating the axes along which to sum. Axes are 0-indexed.
§Returns

A Result which is:

  • Ok(Self): A new CausalTensor containing the sums.
  • Err(CausalTensorError): If an invalid axis is specified.
§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
// Tensor:
// [[1, 2, 3],
//  [4, 5, 6]]

// Sum along axis 0 (columns): [1+4, 2+5, 3+6] = [5, 7, 9]
let sum_axis0 = tensor.sum_axes(&[0]).unwrap();
assert_eq!(sum_axis0.shape(), &[3]);
assert_eq!(sum_axis0.as_slice(), &[5, 7, 9]);

// Sum along axis 1 (rows): [1+2+3, 4+5+6] = [6, 15]
let sum_axis1 = tensor.sum_axes(&[1]).unwrap();
assert_eq!(sum_axis1.shape(), &[2]);
assert_eq!(sum_axis1.as_slice(), &[6, 15]);

// Sum all elements: 1+2+3+4+5+6 = 21
let sum_all = tensor.sum_axes(&[]).unwrap();
assert_eq!(sum_all.shape(), &[]); // Scalar result with shape [] still has one element.
assert_eq!(sum_all.as_slice(), &[21]);

// Invalid axis
let err = tensor.sum_axes(&[2]);
assert!(err.is_err());
Source§

fn mean_axes( &self, axes: &[usize], ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone + Default + PartialOrd + Div<Output = T> + From<u32> + Add<Output = T>,

Calculates the mean (average) of the elements along one or more specified axes.

The dimensions corresponding to the axes provided will be removed from the shape of the resulting tensor. If axes is empty, the mean of all elements in the tensor is returned as a 0-dimensional (scalar) tensor.

§Type Parameters
  • T: Must implement Div<T, Output = T> for division.
  • T: Must implement From<u32> to convert counts to the numeric type
  • T: Must implement Add<T, Output = T> for summation.
§Arguments
  • axes - A slice of usize indicating the axes along which to calculate the mean. Axes are 0-indexed.
§Returns

A Result which is:

  • Ok(Self): A new CausalTensor containing the means.
  • Err(CausalTensorError): If an invalid axis is specified.
§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let tensor = CausalTensor::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], vec![2, 3]).unwrap();
// Tensor:
// [[1.0, 2.0, 3.0],
//  [4.0, 5.0, 6.0]]

// Mean along axis 0 (columns): [(1+4)/2, (2+5)/2, (3+6)/2] = [2.5, 3.5, 4.5]
let mean_axis0 = tensor.mean_axes(&[0]).unwrap();
assert_eq!(mean_axis0.shape(), &[3]);
assert_eq!(mean_axis0.as_slice(), &[2.5, 3.5, 4.5]);

// Mean along axis 1 (rows): [(1+2+3)/3, (4+5+6)/3] = [2.0, 5.0]
let mean_axis1 = tensor.mean_axes(&[1]).unwrap();
assert_eq!(mean_axis1.shape(), &[2]);
assert_eq!(mean_axis1.as_slice(), &[2.0, 5.0]);

// Mean of all elements: (1+2+3+4+5+6)/6 = 3.5
let mean_all = tensor.mean_axes(&[]).unwrap();
assert_eq!(mean_all.shape(), &[]); // Scalar result
assert_eq!(mean_all.as_slice(), &[3.5]);
Source§

fn arg_sort(&self) -> Result<Vec<usize>, CausalTensorError>
where T: Clone + Default + PartialOrd,

Computes the indices that would sort a 1-dimensional tensor (vector).

This method is only valid for tensors with ndim() == 1. It returns a vector of indices such that applying these indices to the original tensor would yield a sorted version of the tensor. The sorting is stable.

§Returns

A Result which is:

  • Ok(Vec<usize>): A vector of indices that sort the tensor.
  • Err(CausalTensorError): If the tensor is not 1-dimensional.
§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let tensor = CausalTensor::new(vec![3, 1, 4, 1, 5, 9, 2, 6], vec![8]).unwrap();
let sorted_indices = tensor.arg_sort().unwrap();
assert_eq!(sorted_indices, vec![1, 3, 6, 0, 2, 4, 7, 5]);

// Verify sorting
let sorted_data: Vec<_> = sorted_indices.iter().map(|&i| tensor.as_slice()[i]).collect();
assert_eq!(sorted_data, vec![1, 1, 2, 3, 4, 5, 6, 9]);

// Attempting to sort a 2D tensor will result in an error
let multi_dim_tensor = CausalTensor::new(vec![1, 2, 3, 4], vec![2, 2]).unwrap();
assert!(multi_dim_tensor.arg_sort().is_err());
Source§

fn reshape( &self, new_shape: &[usize], ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone,

Returns a new tensor with the same data but a different shape.

This is a metadata-only operation; it creates a new CausalTensor with a cloned copy of the original flat data. The underlying data is not physically reordered or reallocated. Only the shape and strides are recomputed to reflect the new logical view. The total number of elements implied by the new_shape must be equal to the total number of elements in the original tensor (self.len()).

§Arguments
  • new_shape - A slice representing the desired new shape.
§Returns

A Result which is:

  • Ok(Self): A new CausalTensor with the updated shape.
  • Err(CausalTensorError): If the new_shape is incompatible (e.g., total elements don’t match).
§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();

// Reshape to 3x2
let reshaped = tensor.reshape(&[3, 2]).unwrap();
assert_eq!(reshaped.shape(), &[3, 2]);
assert_eq!(reshaped.as_slice(), &[1, 2, 3, 4, 5, 6]); // Data remains the same

// Reshape to 1D vector
let raveled = tensor.reshape(&[6]).unwrap();
assert_eq!(raveled.shape(), &[6]);

// Incompatible shape (total elements don't match)
let err = tensor.reshape(&[2, 2]);
assert!(err.is_err());
Source§

fn ravel(self) -> CausalTensor<T>
where T: Clone,

Flattens the tensor into a 1-dimensional tensor (vector).

This is a metadata-only operation; it does not copy or reallocate the underlying data. The resulting tensor will have a shape of [self.len()].

§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
let raveled_tensor = tensor.ravel();
assert_eq!(raveled_tensor.shape(), &[6]);
assert_eq!(raveled_tensor.as_slice(), &[1, 2, 3, 4, 5, 6]);
Source§

fn slice( &self, axis: usize, index: usize, ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone,

Creates a new tensor representing a slice of the original tensor along a specified axis.

This operation extracts a sub-tensor where one dimension has been fixed to a specific index. The rank (number of dimensions) of the resulting tensor will be one less than the original.

Note: This is a data-copying operation. It creates a new CausalTensor with its own allocated data. A future optimization could provide a zero-copy, lifetime-bound view.

§Arguments
  • axis - The axis to slice along (0-indexed).
  • index - The index at which to slice the axis.
§Returns

A Result containing the new, sliced CausalTensor, or a CausalTensorError if the axis or index is out of bounds.

§Examples
use deep_causality_tensor::{CausalTensor, Tensor};

let tensor = CausalTensor::new(vec![1, 2, 3, 4, 5, 6], vec![2, 3]).unwrap();
// Tensor:
// [[1, 2, 3],
//  [4, 5, 6]]

// Slice along axis 0 at index 0 (first row)
let slice_row0 = tensor.slice(0, 0).unwrap();
assert_eq!(slice_row0.shape(), &[3]);
assert_eq!(slice_row0.as_slice(), &[1, 2, 3]);

// Slice along axis 0 at index 1 (second row)
let slice_row1 = tensor.slice(0, 1).unwrap();
assert_eq!(slice_row1.shape(), &[3]);
assert_eq!(slice_row1.as_slice(), &[4, 5, 6]);

// Slice along axis 1 at index 1 (second column)
let slice_col1 = tensor.slice(1, 1).unwrap();
assert_eq!(slice_col1.shape(), &[2]);
assert_eq!(slice_col1.as_slice(), &[2, 5]);
Source§

fn permute_axes( &self, axes: &[usize], ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone,

Permutes the axes of the tensor according to the given new order.

This is a metadata-only operation; it creates a new CausalTensor with a cloned copy of the original flat data. The underlying data is not physically reordered or reallocated. Only the shape and strides are recomputed to reflect the new logical axis order.

§Arguments
  • axes - A slice of usize representing the new order of axes.

The length of the axes parameter must be equal to the number of dimensions of the tensor, and it must contain a permutation of 0..self.num_dim().

§Returns

A Result which is:

  • Ok(Self): A new CausalTensor with permuted axes.
  • Err(CausalTensorError): If the axes are invalid (e.g., wrong length, not a permutation).
Source§

fn shifted_view(&self, flat_index: usize) -> CausalTensor<T>
where T: Clone,

Creates a new tensor that is cyclically shifted (rolled) so that the element at flat_index moves to position 0.

This is essential for Comonadic extend operations, allowing a local physics function to always treat the “current” pixel/particle as the origin (index 0) of the coordinate system.

§Arguments
  • flat_index - The flat index in the data vector that should become the new origin.
§Returns

A new CausalTensor with the same shape, but rotated data.

§Physics Note

This implements Periodic Boundary Conditions (Topology of a Torus). If you shift off the edge, you wrap around to the other side.

Source§

fn inverse(&self) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone + RealField + Zero + One + Sum + PartialEq,

Computes the inverse of a square matrix using Gaussian elimination (Gauss-Jordan method).

For a square matrix $A$, its inverse $A^{-1}$ is a matrix such that when $A$ is multiplied by $A^{-1}$ (in either order), the result is the identity matrix $I$. That is, $A A^{-1} = A^{-1} A = I$.

This method uses the Gauss-Jordan elimination technique by augmenting the input matrix A with an identity matrix $I$ to form $[A | I]$. Row operations are then performed to transform the left side ($A$) into the identity matrix, resulting in the inverse matrix on the right side: $[A | I] \rightarrow [I | A^{-1}]$. Partial pivoting is used to enhance numerical stability.

§Usage

Matrix inversion is fundamental for:

  • Solving systems of linear equations: If $Ax = b$, then $x = A^{-1}b$.
  • Inverting linear transformations.
  • Various applications in optimization and numerical analysis.
§Constraints
  • The tensor must be a 2D square matrix (i.e., num_dim() == 2 and shape[0] == shape[1]).
  • The matrix must be non-singular (invertible). A singular matrix does not have an inverse.
§Returns

A Result which is:

  • Ok(Self): A new CausalTensor representing the inverse matrix.
  • Err(CausalTensorError): If the tensor is not a square matrix, is not 2-dimensional, or is singular.
§Errors
  • CausalTensorError::DimensionMismatch: If the tensor is not 2-dimensional.
  • CausalTensorError::ShapeMismatch: If the tensor is not a square matrix.
  • CausalTensorError::SingularMatrix: If the matrix is singular and cannot be inverted.
  • CausalTensorError::DivisionByZero: If a pivot element is zero during elimination.
Source§

fn cholesky_decomposition(&self) -> Result<CausalTensor<T>, CausalTensorError>
where T: Default + Clone + RealField + Zero + One + PartialEq,

Computes the Cholesky decomposition of a symmetric, positive-definite matrix.

For a symmetric, positive-definite matrix $A$, its Cholesky decomposition is $A = L L^T$, where $L$ is a lower triangular matrix with positive diagonal entries, and $L^T$ is its transpose.

The algorithm proceeds by calculating elements of $L$ column by column:

  • Diagonal elements: $L_{ii} = \sqrt{A_{ii} - \sum_{k=0}^{i-1} L_{ik}^2}$
  • Off-diagonal elements: $L_{ji} = \frac{1}{L_{ii}} (A_{ji} - \sum_{k=0}^{i-1} L_{jk} L_{ik})$ for $j > i$
§Usage

Cholesky decomposition is a cornerstone in numerical linear algebra, used for:

  • Solving systems of linear equations more efficiently than general methods (e.g., Gaussian elimination) when the matrix is symmetric positive-definite.
  • Efficiently solving Least Squares problems (as implemented in solve_least_squares_cholsky_impl).
  • Monte Carlo simulations to generate correlated random variables.
  • Kalman filtering and other state estimation problems.
§Constraints
  • The input CausalTensor must represent a 2D square matrix.
  • The matrix must be symmetric and positive-definite. If it is not positive-definite, the decomposition will fail (e.g., attempt to take the square root of a negative number, or encounter a zero on the diagonal).
§Returns

A Result which is:

  • Ok(Self): A new CausalTensor representing the lower triangular Cholesky factor $L$.
  • Err(CausalTensorError): If input dimensions are invalid, or if the matrix is not symmetric positive-definite.
§Errors
  • CausalTensorError::DimensionMismatch: If the tensor is not 2-dimensional.
  • CausalTensorError::ShapeMismatch: If the tensor is not a square matrix.
  • CausalTensorError::SingularMatrix: If the matrix is not positive-definite (e.g., a diagonal element becomes zero or negative during computation).
Source§

fn solve_least_squares_cholsky( a: &CausalTensor<T>, b: &CausalTensor<T>, ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Default + Clone + RealField + Zero + One + PartialEq,

Solves the Least Squares problem for $Ax = b$ using Cholesky decomposition.

Given a system of linear equations $Ax = b$, where $A$ is an $m \times n$ design matrix and $b$ is an $m \times 1$ observation vector, this method finds the vector $x$ (parameters) that minimizes the squared Euclidean norm of the residual $||Ax - b||^2$.

The solution $x$ is obtained by solving the normal equations: $A^T A x = A^T b$. Let $M = A^T A$ and $y = A^T b$. The normal equations become $Mx = y$.

The process involves:

  1. Computing $M = A^T A$ and $y = A^T b$.
  2. Performing Cholesky decomposition on $M$: $M = L L^T$, where $L$ is a lower triangular matrix.
  3. Solving $Lz = y$ for $z$ using forward substitution.
  4. Solving $L^T x = z$ for $x$ using backward substitution.

This method is numerically stable and efficient for well-conditioned systems.

§Usage

This solver is commonly used in:

  • Linear Regression analysis to find the best-fit parameters.
  • Data fitting and curve fitting.
  • Various optimization and statistical modeling problems.
§Arguments
  • a - The design matrix $A$ (m x n CausalTensor).
  • b - The observation vector $b$ (m x 1 CausalTensor).
§Constraints
  • The design matrix $A$ should have full column rank for a unique solution.
  • The matrix $A^T A$ must be symmetric and positive-definite for Cholesky decomposition to succeed.
  • The observation vector $b$ must be a column vector with a number of rows compatible with $A$.
§Returns

A Result which is:

  • Ok(Self): A new CausalTensor representing the solution vector $x$ (n x 1).
  • Err(CausalTensorError): If input dimensions are invalid, or if $A^T A$ is singular.
§Errors
  • CausalTensorError::DimensionMismatch: If a or b are not 2-dimensional, or b is not a column vector.
  • CausalTensorError::ShapeMismatch: If b’s rows do not match a’s rows.
  • CausalTensorError::SingularMatrix: If the $A^T A$ matrix is singular, implying no unique solution.
Source§

fn matmul( &self, rhs: &CausalTensor<T>, ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Ring + Copy + Default + PartialOrd,

Source§

fn svd( &self, ) -> Result<(CausalTensor<T>, CausalTensor<T>, CausalTensor<T>), CausalTensorError>
where T: Clone + RealField + Zero + One + Sum + PartialEq,

Source§

fn stack( tensors: &[CausalTensor<T>], axis: usize, ) -> Result<CausalTensor<T>, CausalTensorError>
where T: Clone + Default + PartialOrd + Add<Output = T> + Mul<Output = T>, CausalTensor<T>: Sized,

Source§

impl<T> Zero for CausalTensor<T>
where T: Zero + Copy + Default + PartialOrd,

Implements Zero trait for CausalTensor. Returns a scalar zero tensor (shape []). This allows broadcasting to work for addition (a + 0 = a).

Source§

fn zero() -> CausalTensor<T>

Returns the additive identity element of Self, 0. Read more
Source§

fn is_zero(&self) -> bool

Returns true if self is equal to the additive identity.
Source§

fn set_zero(&mut self)

Sets self to the additive identity element of Self, 0.
Source§

impl<T> AbelianGroup for CausalTensor<T>
where T: AbelianGroup + Copy + Default + PartialOrd + Neg<Output = T>,

Marker trait for Abelian Group. CausalTensor addition is commutative if T’s addition is commutative.

Source§

impl<T> Associative for CausalTensor<T>
where T: Associative + Copy,

Source§

impl<T> Distributive for CausalTensor<T>
where T: Distributive + Copy,

Source§

impl<T> Satisfies<TensorConstraint> for CausalTensor<T>

Source§

impl<T> StructuralPartialEq for CausalTensor<T>

Auto Trait Implementations§

§

impl<T> Freeze for CausalTensor<T>

§

impl<T> RefUnwindSafe for CausalTensor<T>
where T: RefUnwindSafe,

§

impl<T> Send for CausalTensor<T>
where T: Send,

§

impl<T> Sync for CausalTensor<T>
where T: Sync,

§

impl<T> Unpin for CausalTensor<T>
where T: Unpin,

§

impl<T> UnwindSafe for CausalTensor<T>
where T: 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> 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<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
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<V, R> Module<R> for V
where V: AbelianGroup + Mul<R, Output = V> + MulAssign<R>, R: Ring,

Source§

fn scale(&self, scalar: R) -> Self

Scales the module element by a scalar from the ring R. Read more
Source§

fn scale_mut(&mut self, scalar: R)

Scales the module element in-place by a scalar from the ring R. 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> 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.
Source§

impl<T> AddGroup for T
where T: Sub<Output = T> + Add<Output = T> + Zero + Clone,

Source§

impl<T> AddSemigroup for T
where T: Add<Output = T> + Associative + Clone,

Source§

impl<T> AssociativeRing for T
where T: Ring + Associative,

Source§

impl<T> Group for T
where T: AddGroup,

Source§

impl<T> MulMagma for T
where T: Mul<Output = T> + Clone,

Source§

impl<T> MulMonoid for T
where T: MulMagma + One + Associative,

Source§

impl<T> MulSemigroup for T
where T: Mul<Output = T> + Associative + Clone,

Source§

impl<T> Ring for T

Source§

impl<T> Satisfies<NoConstraint> for T