Skip to main content

TensorLike

Trait TensorLike 

Source
pub trait TensorLike:
    TensorVectorSpace
    + TensorFactorizationLike
    + TensorConstructionLike { }
Expand description

Trait for tensor-like objects that expose external indices and support contraction.

This trait is fully generic (monomorphic), meaning it does not support trait objects (dyn TensorLike). For heterogeneous tensor collections, use an enum wrapper instead.

§Design Principles

  • Capability composition: combines vector-space, factorization, construction, and contraction traits
  • Fully generic: Uses associated type for Index, returns Self
  • Stable ordering: external_indices() returns indices in deterministic order
  • No trait objects: Requires Sized, cannot use dyn TensorLike

§Example

use tensor4all_core::{DynIndex, TensorContractionLike, TensorDynLen};

fn contract_pair(a: &TensorDynLen, b: &TensorDynLen) -> anyhow::Result<TensorDynLen> {
    Ok(<TensorDynLen as TensorContractionLike>::contract(&[a, b])?)
}

let i = DynIndex::new_dyn(2);
let j = DynIndex::new_dyn(2);
let a = TensorDynLen::from_dense(
    vec![i.clone(), j.clone()],
    vec![1.0, 0.0, 0.0, 1.0],
)?;
let b = TensorDynLen::from_dense(vec![j.clone()], vec![2.0, 3.0])?;

let result = contract_pair(&a, &b)?;
assert_eq!(result.to_vec::<f64>()?, vec![2.0, 3.0]);

§Heterogeneous Collections

For mixing different tensor types, define an enum:

use tensor4all_core::{block_tensor::BlockTensor, DynIndex, TensorDynLen};

let i = DynIndex::new_dyn(2);
let dense = TensorDynLen::from_dense(vec![i.clone()], vec![1.0, 2.0]).unwrap();
let block = BlockTensor::new(vec![dense.clone()], (1, 1)).unwrap();

enum TensorNetwork {
    Dense(TensorDynLen),
    Block(BlockTensor<TensorDynLen>),
}

let network = TensorNetwork::Block(block);
assert!(matches!(network, TensorNetwork::Block(_)));

§Supertrait

TensorLike extends several capability traits. Through those traits it provides:

  • external_indices() - Get all external indices
  • num_external_indices() - Count external indices
  • replaceind() / replaceinds() - Replace indices
  • vector-space operations such as axpby, inner_product, and norm
  • tensor-network operations such as contraction, construction, and factorization

Use narrower traits such as TensorVectorSpace or TensorContractionLike when an algorithm does not need the full surface.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§