conspire/math/tensor/
mod.rs

1// #[cfg(test)]
2pub mod test;
3
4pub mod rank_0;
5pub mod rank_1;
6pub mod rank_2;
7pub mod rank_3;
8pub mod rank_4;
9
10use super::{SquareMatrix, Vector};
11use crate::defeat_message;
12use rank_0::TensorRank0;
13use std::{
14    fmt::{self, Debug, Display, Formatter},
15    ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Sub, SubAssign},
16};
17
18/// A scalar.
19pub type Scalar = TensorRank0;
20
21/// Possible errors for tensors.
22#[derive(PartialEq)]
23pub enum TensorError {
24    NotPositiveDefinite,
25}
26
27impl Debug for TensorError {
28    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
29        let error = match self {
30            Self::NotPositiveDefinite => "\x1b[1;91mResult is not positive definite.".to_string(),
31        };
32        write!(f, "\n{error}\n\x1b[0;2;31m{}\x1b[0m\n", defeat_message())
33    }
34}
35
36impl Display for TensorError {
37    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
38        let error = match self {
39            Self::NotPositiveDefinite => "\x1b[1;91mResult is not positive definite.".to_string(),
40        };
41        write!(f, "{error}\x1b[0m")
42    }
43}
44
45/// Common methods for solutions.
46pub trait Solution
47where
48    Self: Tensor,
49{
50    /// Decrements the solution chained with a vector from another vector.
51    fn decrement_from_chained(&mut self, other: &mut Vector, vector: Vector);
52}
53
54/// Common methods for Jacobians.
55pub trait Jacobian
56where
57    Self: Tensor + Sub<Vector, Output = Self> + for<'a> Sub<&'a Vector, Output = Self>,
58{
59    /// Fills the Jacobian into a vector.
60    fn fill_into(self, vector: &mut Vector);
61    /// Fills the Jacobian chained with a vector into another vector.
62    fn fill_into_chained(self, other: Vector, vector: &mut Vector);
63}
64
65/// Common methods for Hessians.
66pub trait Hessian
67where
68    Self: Tensor,
69{
70    /// Fills the Hessian into a square matrix.
71    fn fill_into(self, square_matrix: &mut SquareMatrix);
72}
73
74/// Common methods for rank-2 tensors.
75pub trait Rank2
76where
77    Self: Sized,
78{
79    /// The type that is the transpose of the tensor.
80    type Transpose;
81    /// Returns the deviatoric component of the rank-2 tensor.
82    fn deviatoric(&self) -> Self;
83    /// Returns the deviatoric component and trace of the rank-2 tensor.
84    fn deviatoric_and_trace(&self) -> (Self, TensorRank0);
85    /// Checks whether the tensor is a diagonal tensor.
86    fn is_diagonal(&self) -> bool;
87    /// Checks whether the tensor is the identity tensor.
88    fn is_identity(&self) -> bool;
89    /// Returns the second invariant of the rank-2 tensor.
90    fn second_invariant(&self) -> TensorRank0 {
91        0.5 * (self.trace().powi(2) - self.squared_trace())
92    }
93    /// Returns the trace of the rank-2 tensor squared.
94    fn squared_trace(&self) -> TensorRank0;
95    /// Returns the trace of the rank-2 tensor.
96    fn trace(&self) -> TensorRank0;
97    /// Returns the transpose of the rank-2 tensor.
98    fn transpose(&self) -> Self::Transpose;
99}
100
101/// Common methods for tensors.
102pub trait Tensor
103where
104    for<'a> Self: Sized
105        + Debug
106        + Display
107        + Add<Self, Output = Self>
108        + Add<&'a Self, Output = Self>
109        + AddAssign
110        + AddAssign<&'a Self>
111        + Clone
112        + Div<TensorRank0, Output = Self>
113        + DivAssign<TensorRank0>
114        + Mul<TensorRank0, Output = Self>
115        + MulAssign<TensorRank0>
116        + Sub<Self, Output = Self>
117        + Sub<&'a Self, Output = Self>
118        + SubAssign
119        + SubAssign<&'a Self>,
120    Self::Item: Tensor,
121{
122    /// The type of item encountered when iterating over the tensor.
123    type Item;
124    /// Returns the full contraction with another tensor.
125    fn full_contraction(&self, tensor: &Self) -> TensorRank0 {
126        self.iter()
127            .zip(tensor.iter())
128            .map(|(self_entry, tensor_entry)| self_entry.full_contraction(tensor_entry))
129            .sum()
130    }
131    /// Checks whether the tensor is the zero tensor.
132    fn is_zero(&self) -> bool {
133        self.iter().filter(|entry| !entry.is_zero()).count() == 0
134    }
135    /// Returns an iterator.
136    ///
137    /// The iterator yields all items from start to end. [Read more](https://doc.rust-lang.org/std/iter/)
138    fn iter(&self) -> impl Iterator<Item = &Self::Item>;
139    /// Returns an iterator that allows modifying each value.
140    ///
141    /// The iterator yields all items from start to end. [Read more](https://doc.rust-lang.org/std/iter/)
142    fn iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Item>;
143    /// Returns the tensor norm.
144    fn norm(&self) -> TensorRank0 {
145        self.norm_squared().sqrt()
146    }
147    /// Returns the infinity norm.
148    fn norm_inf(&self) -> TensorRank0 {
149        unimplemented!()
150    }
151    /// Returns the tensor norm squared.
152    fn norm_squared(&self) -> TensorRank0 {
153        self.full_contraction(self)
154    }
155    /// Normalizes the tensor.
156    fn normalize(&mut self) {
157        *self /= self.norm()
158    }
159    /// Returns the tensor normalized.
160    fn normalized(self) -> Self {
161        let norm = self.norm();
162        self / norm
163    }
164    /// Returns the total number of entries.
165    fn num_entries(&self) -> usize {
166        unimplemented!()
167    }
168}
169
170/// Common methods for tensors derived from arrays.
171pub trait TensorArray {
172    /// The type of array corresponding to the tensor.
173    type Array;
174    /// The type of item encountered when iterating over the tensor.
175    type Item;
176    /// Returns the tensor as an array.
177    fn as_array(&self) -> Self::Array;
178    /// Returns the identity tensor.
179    fn identity() -> Self;
180    /// Returns a tensor given an array.
181    fn new(array: Self::Array) -> Self;
182    /// Returns the zero tensor.
183    fn zero() -> Self;
184}
185
186/// Common methods for tensors derived from Vec.
187pub trait TensorVec
188where
189    Self: FromIterator<Self::Item> + Index<usize, Output = Self::Item> + IndexMut<usize>,
190{
191    /// The type of item encountered when iterating over the tensor.
192    type Item;
193    /// The type of slice corresponding to the tensor.
194    type Slice<'a>;
195    /// Moves all the items of other into self, leaving other empty.
196    fn append(&mut self, other: &mut Self);
197    /// Returns `true` if the vector contains no items.
198    fn is_empty(&self) -> bool;
199    /// Returns the number of items in the vector, also referred to as its ‘length’.
200    fn len(&self) -> usize;
201    /// Returns a tensor given a slice.
202    fn new(slice: Self::Slice<'_>) -> Self;
203    /// Appends an item to the back of the Vec.
204    fn push(&mut self, item: Self::Item);
205    /// Returns the zero tensor.
206    fn zero(len: usize) -> Self;
207}