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:
-
Metadata-Only Operations (e.g.,
reshape,permute_axes,ravel): These operations create a newCausalTensorinstance 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 theshapeandstridesmetadata to provide a new logical view of the data. This makes them very efficient as they avoid large data movements. -
Data-Copying Operations (e.g.,
slice, binary operations likeadd,sub,mul,div, reduction operations likesum_axes,mean_axes): These operations create a newCausalTensorinstance 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 newVec<T>.
Implementations§
Source§impl<T> CausalTensor<T>
impl<T> CausalTensor<T>
Sourcepub fn zero(shape: &[usize]) -> CausalTensor<T>
pub fn zero(shape: &[usize]) -> CausalTensor<T>
Creates a zero tensor with the specified shape.
Sourcepub fn add(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>
pub fn add(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>
Element-wise addition.
Sourcepub fn sub(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>
pub fn sub(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>
Element-wise subtraction.
Sourcepub fn neg(&self) -> CausalTensor<T>
pub fn neg(&self) -> CausalTensor<T>
Element-wise negation.
Source§impl<T> CausalTensor<T>
impl<T> CausalTensor<T>
Source§impl<T> CausalTensor<T>
impl<T> CausalTensor<T>
Sourcepub fn mul(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>
pub fn mul(&self, rhs: &CausalTensor<T>) -> CausalTensor<T>
Element-wise multiplication (Hadamard product).
Sourcepub fn one(shape: &[usize]) -> CausalTensor<T>
pub fn one(shape: &[usize]) -> CausalTensor<T>
Creates a tensor of ones with the specified shape.
Sourcepub fn ones(shape: &[usize]) -> CausalTensor<T>
pub fn ones(shape: &[usize]) -> CausalTensor<T>
Alias for one. Creates a tensor of ones with the specified shape.
Sourcepub fn identity(shape: &[usize]) -> Result<CausalTensor<T>, CausalTensorError>
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>
impl<T> CausalTensor<T>
Sourcepub fn data(&self) -> &Vec<T>
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());Sourcepub fn shape(&self) -> &[usize]
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]);Sourcepub fn is_empty(&self) -> bool
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());Sourcepub fn num_dim(&self) -> usize
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 dimensionsSourcepub fn len(&self) -> usize
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);Sourcepub fn as_slice(&self) -> &[T]
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]);Sourcepub fn get(&self, index: &[usize]) -> Option<&T>
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);Sourcepub fn get_mut(&mut self, index: &[usize]) -> Option<&mut T>
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>
impl<T> CausalTensor<T>
Source§impl<T> CausalTensor<T>
impl<T> CausalTensor<T>
Sourcepub fn new(
data: Vec<T>,
shape: Vec<usize>,
) -> Result<CausalTensor<T>, CausalTensorError>
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- AVec<T>containing the tensor’s elements in row-major order.shape- AVec<usize>defining the dimensions of the tensor.
§Returns
A Result which is:
Ok(Self)if thedatalength matches theshape’s total elements.Err(CausalTensorError::ShapeMismatch)if the lengths do not match.
Sourcepub fn from_shape_fn<F>(shape: &[usize], f: F) -> CausalTensor<T>
pub fn from_shape_fn<F>(shape: &[usize], f: F) -> CausalTensor<T>
Creates a tensor from a function applied to each index.
§Arguments
shape- Dimensions of the tensorf- Function mapping indices to values
Source§impl<T> CausalTensor<T>where
T: Clone,
impl<T> CausalTensor<T>where
T: Clone,
Sourcepub fn from_slice(data: &[T], shape: &[usize]) -> CausalTensor<T>
pub fn from_slice(data: &[T], shape: &[usize]) -> CausalTensor<T>
Creates a tensor from a slice (infallible, clones data).
Source§impl<T> CausalTensor<T>
impl<T> CausalTensor<T>
Sourcepub fn zeros(shape: &[usize]) -> CausalTensor<T>
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>
impl<T> Add<&CausalTensor<T>> for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
+ operator.Source§fn add(
self,
rhs: &CausalTensor<T>,
) -> <CausalTensor<T> as Add<&CausalTensor<T>>>::Output
fn add( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Add<&CausalTensor<T>>>::Output
+ operation. Read moreSource§impl<T> Add<CausalTensor<T>> for &CausalTensor<T>
impl<T> Add<CausalTensor<T>> for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
+ operator.Source§fn add(
self,
rhs: CausalTensor<T>,
) -> <&CausalTensor<T> as Add<CausalTensor<T>>>::Output
fn add( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Add<CausalTensor<T>>>::Output
+ operation. Read moreSource§impl<T> Add<T> for &CausalTensor<T>
impl<T> Add<T> for &CausalTensor<T>
Source§impl<T> Add<T> for CausalTensor<T>
impl<T> Add<T> for CausalTensor<T>
Source§impl<T> Add for &CausalTensor<T>
impl<T> Add for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
+ operator.Source§fn add(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Add>::Output
fn add(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Add>::Output
+ operation. Read moreSource§impl<T> Add for CausalTensor<T>
impl<T> Add for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
+ operator.Source§fn add(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Add>::Output
fn add(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Add>::Output
+ operation. Read moreSource§impl<T> AddAssign<T> for CausalTensor<T>
impl<T> AddAssign<T> for CausalTensor<T>
Source§fn add_assign(&mut self, rhs: T)
fn add_assign(&mut self, rhs: T)
+= operation. Read moreSource§impl<T> BatchedMatMul<T> for CausalTensor<T>
impl<T> BatchedMatMul<T> for CausalTensor<T>
fn batched_matmul(&self, other: &Self) -> Self
Source§impl CausalTensorMathExt<f32> for CausalTensor<f32>
impl CausalTensorMathExt<f32> for CausalTensor<f32>
Source§fn log_nat(&self) -> Result<CausalTensor<f32>, CausalTensorError>
fn log_nat(&self) -> Result<CausalTensor<f32>, CausalTensorError>
Source§fn log2(&self) -> Result<CausalTensor<f32>, CausalTensorError>
fn log2(&self) -> Result<CausalTensor<f32>, CausalTensorError>
Source§fn log10(&self) -> Result<CausalTensor<f32>, CausalTensorError>
fn log10(&self) -> Result<CausalTensor<f32>, CausalTensorError>
Source§fn surd_log2(&self) -> Result<CausalTensor<f32>, CausalTensorError>
fn surd_log2(&self) -> Result<CausalTensor<f32>, CausalTensorError>
mylog function for information theory calculations. Read moreSource§fn safe_div(
&self,
rhs: &CausalTensor<f32>,
) -> Result<CausalTensor<f32>, CausalTensorError>
fn safe_div( &self, rhs: &CausalTensor<f32>, ) -> Result<CausalTensor<f32>, CausalTensorError>
Source§impl CausalTensorMathExt<f64> for CausalTensor<f64>
impl CausalTensorMathExt<f64> for CausalTensor<f64>
Source§fn log_nat(&self) -> Result<CausalTensor<f64>, CausalTensorError>
fn log_nat(&self) -> Result<CausalTensor<f64>, CausalTensorError>
Source§fn log2(&self) -> Result<CausalTensor<f64>, CausalTensorError>
fn log2(&self) -> Result<CausalTensor<f64>, CausalTensorError>
Source§fn log10(&self) -> Result<CausalTensor<f64>, CausalTensorError>
fn log10(&self) -> Result<CausalTensor<f64>, CausalTensorError>
Source§fn surd_log2(&self) -> Result<CausalTensor<f64>, CausalTensorError>
fn surd_log2(&self) -> Result<CausalTensor<f64>, CausalTensorError>
mylog function for information theory calculations. Read moreSource§fn safe_div(
&self,
rhs: &CausalTensor<f64>,
) -> Result<CausalTensor<f64>, CausalTensorError>
fn safe_div( &self, rhs: &CausalTensor<f64>, ) -> Result<CausalTensor<f64>, CausalTensorError>
Source§impl<T> Clone for CausalTensor<T>where
T: Clone,
impl<T> Clone for CausalTensor<T>where
T: Clone,
Source§fn clone(&self) -> CausalTensor<T>
fn clone(&self) -> CausalTensor<T>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl<T> Debug for CausalTensor<T>where
T: Debug,
impl<T> Debug for CausalTensor<T>where
T: Debug,
Source§impl<T> Default for CausalTensor<T>where
T: Default,
impl<T> Default for CausalTensor<T>where
T: Default,
Source§fn default() -> CausalTensor<T>
fn default() -> CausalTensor<T>
Source§impl<T> Display for CausalTensor<T>where
T: Display,
impl<T> Display for CausalTensor<T>where
T: Display,
Source§impl<T> Div<&CausalTensor<T>> for CausalTensor<T>
impl<T> Div<&CausalTensor<T>> for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
/ operator.Source§fn div(
self,
rhs: &CausalTensor<T>,
) -> <CausalTensor<T> as Div<&CausalTensor<T>>>::Output
fn div( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Div<&CausalTensor<T>>>::Output
/ operation. Read moreSource§impl<T> Div<CausalTensor<T>> for &CausalTensor<T>
impl<T> Div<CausalTensor<T>> for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
/ operator.Source§fn div(
self,
rhs: CausalTensor<T>,
) -> <&CausalTensor<T> as Div<CausalTensor<T>>>::Output
fn div( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Div<CausalTensor<T>>>::Output
/ operation. Read moreSource§impl<T> Div<T> for &CausalTensor<T>
impl<T> Div<T> for &CausalTensor<T>
Source§impl<T> Div<T> for CausalTensor<T>
impl<T> Div<T> for CausalTensor<T>
Source§impl<T> Div for &CausalTensor<T>
impl<T> Div for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
/ operator.Source§fn div(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Div>::Output
fn div(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Div>::Output
/ operation. Read moreSource§impl<T> Div for CausalTensor<T>
impl<T> Div for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
/ operator.Source§fn div(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Div>::Output
fn div(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Div>::Output
/ operation. Read moreSource§impl<T> DivAssign<T> for CausalTensor<T>
impl<T> DivAssign<T> for CausalTensor<T>
Source§fn div_assign(&mut self, rhs: T)
fn div_assign(&mut self, rhs: T)
/= operation. Read moreSource§impl<'a, T> From<&'a CausalTensor<T>> for CausalTensor<T>where
T: Clone,
impl<'a, T> From<&'a CausalTensor<T>> for CausalTensor<T>where
T: Clone,
Source§fn from(item: &'a CausalTensor<T>) -> CausalTensor<T>
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,
impl<'a, T> From<&'a T> for CausalTensor<T>where
T: Clone,
Source§fn from(item: &'a T) -> CausalTensor<T>
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,
impl<T> From<T> for CausalTensor<T>where
T: Clone,
Source§fn from(item: T) -> CausalTensor<T>
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>
impl<T> Mul<&CausalTensor<T>> for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
* operator.Source§fn mul(
self,
rhs: &CausalTensor<T>,
) -> <CausalTensor<T> as Mul<&CausalTensor<T>>>::Output
fn mul( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Mul<&CausalTensor<T>>>::Output
* operation. Read moreSource§impl<T> Mul<CausalTensor<T>> for &CausalTensor<T>
impl<T> Mul<CausalTensor<T>> for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
* operator.Source§fn mul(
self,
rhs: CausalTensor<T>,
) -> <&CausalTensor<T> as Mul<CausalTensor<T>>>::Output
fn mul( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Mul<CausalTensor<T>>>::Output
* operation. Read moreSource§impl<T> Mul<T> for &CausalTensor<T>
impl<T> Mul<T> for &CausalTensor<T>
Source§impl<T> Mul<T> for CausalTensor<T>
impl<T> Mul<T> for CausalTensor<T>
Source§impl<T> Mul for &CausalTensor<T>
impl<T> Mul for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
* operator.Source§fn mul(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Mul>::Output
fn mul(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Mul>::Output
* operation. Read moreSource§impl<T> Mul for CausalTensor<T>
impl<T> Mul for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
* operator.Source§fn mul(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Mul>::Output
fn mul(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Mul>::Output
* operation. Read moreSource§impl<T> MulAssign<T> for CausalTensor<T>
impl<T> MulAssign<T> for CausalTensor<T>
Source§fn mul_assign(&mut self, rhs: T)
fn mul_assign(&mut self, rhs: T)
*= operation. Read moreSource§impl<T> Neg for &CausalTensor<T>
impl<T> Neg for &CausalTensor<T>
Source§impl<T> Neg for CausalTensor<T>
Implements Neg trait for CausalTensor.
impl<T> Neg for CausalTensor<T>
Implements Neg trait for CausalTensor.
Source§impl<T> One for CausalTensor<T>
impl<T> One for CausalTensor<T>
Source§impl<T> PartialEq for CausalTensor<T>where
T: PartialEq,
impl<T> PartialEq for CausalTensor<T>where
T: PartialEq,
Source§impl<T> Sub<&CausalTensor<T>> for CausalTensor<T>
impl<T> Sub<&CausalTensor<T>> for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
- operator.Source§fn sub(
self,
rhs: &CausalTensor<T>,
) -> <CausalTensor<T> as Sub<&CausalTensor<T>>>::Output
fn sub( self, rhs: &CausalTensor<T>, ) -> <CausalTensor<T> as Sub<&CausalTensor<T>>>::Output
- operation. Read moreSource§impl<T> Sub<CausalTensor<T>> for &CausalTensor<T>
impl<T> Sub<CausalTensor<T>> for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
- operator.Source§fn sub(
self,
rhs: CausalTensor<T>,
) -> <&CausalTensor<T> as Sub<CausalTensor<T>>>::Output
fn sub( self, rhs: CausalTensor<T>, ) -> <&CausalTensor<T> as Sub<CausalTensor<T>>>::Output
- operation. Read moreSource§impl<T> Sub<T> for &CausalTensor<T>
impl<T> Sub<T> for &CausalTensor<T>
Source§impl<T> Sub<T> for CausalTensor<T>
impl<T> Sub<T> for CausalTensor<T>
Source§impl<T> Sub for &CausalTensor<T>
impl<T> Sub for &CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
- operator.Source§fn sub(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Sub>::Output
fn sub(self, rhs: &CausalTensor<T>) -> <&CausalTensor<T> as Sub>::Output
- operation. Read moreSource§impl<T> Sub for CausalTensor<T>
impl<T> Sub for CausalTensor<T>
Source§type Output = CausalTensor<T>
type Output = CausalTensor<T>
- operator.Source§fn sub(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Sub>::Output
fn sub(self, rhs: CausalTensor<T>) -> <CausalTensor<T> as Sub>::Output
- operation. Read moreSource§impl<T> SubAssign<T> for CausalTensor<T>
impl<T> SubAssign<T> for CausalTensor<T>
Source§fn sub_assign(&mut self, rhs: T)
fn sub_assign(&mut self, rhs: T)
-= operation. Read moreSource§impl<T> Tensor<T> for CausalTensor<T>
impl<T> Tensor<T> for CausalTensor<T>
Source§fn ein_sum(
ast: &ConstTree<EinSumOp<T>>,
) -> Result<CausalTensor<T>, CausalTensorError>
fn ein_sum( ast: &ConstTree<EinSumOp<T>>, ) -> Result<CausalTensor<T>, CausalTensorError>
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 theEinSumASTthat 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>
fn tensor_product( &self, rhs: &CausalTensor<T>, ) -> Result<CausalTensor<T>, CausalTensorError>
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 sideCausalTensor.
§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
fn norm_l2(&self) -> T
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
fn norm_sq(&self) -> T
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>
fn sum_axes(&self, axes: &[usize]) -> Result<CausalTensor<T>, CausalTensorError>
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 implementAdd<T, Output = T>for summation.
§Arguments
axes- A slice ofusizeindicating the axes along which to sum. Axes are 0-indexed.
§Returns
A Result which is:
Ok(Self): A newCausalTensorcontaining 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>
fn mean_axes( &self, axes: &[usize], ) -> Result<CausalTensor<T>, CausalTensorError>
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 implementDiv<T, Output = T>for division.T: Must implementFrom<u32>to convert counts to the numeric typeT: Must implementAdd<T, Output = T>for summation.
§Arguments
axes- A slice ofusizeindicating the axes along which to calculate the mean. Axes are 0-indexed.
§Returns
A Result which is:
Ok(Self): A newCausalTensorcontaining 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>
fn arg_sort(&self) -> Result<Vec<usize>, CausalTensorError>
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,
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 newCausalTensorwith the updated shape.Err(CausalTensorError): If thenew_shapeis 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,
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,
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,
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 ofusizerepresenting 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 newCausalTensorwith permuted axes.Err(CausalTensorError): If theaxesare invalid (e.g., wrong length, not a permutation).
Source§fn shifted_view(&self, flat_index: usize) -> CausalTensor<T>where
T: Clone,
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>
fn inverse(&self) -> Result<CausalTensor<T>, CausalTensorError>
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() == 2andshape[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 newCausalTensorrepresenting 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>
fn cholesky_decomposition(&self) -> Result<CausalTensor<T>, CausalTensorError>
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
CausalTensormust 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 newCausalTensorrepresenting 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>
fn solve_least_squares_cholsky( a: &CausalTensor<T>, b: &CausalTensor<T>, ) -> Result<CausalTensor<T>, CausalTensorError>
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:
- Computing $M = A^T A$ and $y = A^T b$.
- Performing Cholesky decomposition on $M$: $M = L L^T$, where $L$ is a lower triangular matrix.
- Solving $Lz = y$ for $z$ using forward substitution.
- 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 nCausalTensor).b- The observation vector $b$ (m x 1CausalTensor).
§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 newCausalTensorrepresenting the solution vector $x$ (n x 1).Err(CausalTensorError): If input dimensions are invalid, or if $A^T A$ is singular.
§Errors
CausalTensorError::DimensionMismatch: Ifaorbare not 2-dimensional, orbis not a column vector.CausalTensorError::ShapeMismatch: Ifb’s rows do not matcha’s rows.CausalTensorError::SingularMatrix: If the $A^T A$ matrix is singular, implying no unique solution.
fn matmul( &self, rhs: &CausalTensor<T>, ) -> Result<CausalTensor<T>, CausalTensorError>
fn svd( &self, ) -> Result<(CausalTensor<T>, CausalTensor<T>, CausalTensor<T>), CausalTensorError>
fn stack( tensors: &[CausalTensor<T>], axis: usize, ) -> Result<CausalTensor<T>, CausalTensorError>
Source§impl<T> Zero for CausalTensor<T>
Implements Zero trait for CausalTensor.
Returns a scalar zero tensor (shape []).
This allows broadcasting to work for addition (a + 0 = a).
impl<T> Zero for CausalTensor<T>
Implements Zero trait for CausalTensor. Returns a scalar zero tensor (shape []). This allows broadcasting to work for addition (a + 0 = a).
impl<T> AbelianGroup for CausalTensor<T>
Marker trait for Abelian Group. CausalTensor addition is commutative if T’s addition is commutative.