forked from Axect/Peroxide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.rs
99 lines (85 loc) · 2.14 KB
/
math.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use crate::structure::matrix::Matrix;
/// Mathematical Vector
///
/// # Description
/// Vector has two operations : addition, scalar multiplication.
/// And a space of the vector should closed for that operations.
pub trait Vector {
type Scalar;
fn add_vec<'a, 'b>(&'a self, rhs: &'b Self) -> Self;
fn sub_vec<'a, 'b>(&'a self, rhs: &'b Self) -> Self;
fn mul_scalar(&self, rhs: Self::Scalar) -> Self;
}
/// Kinds of Vector & Matrix norm
///
/// # Kinds of Vector norm
/// * `l1`
/// * `l2`
/// * `lp`
/// * `lInf`
///
/// # Kinds of Matrix norm
/// * `F`: Frobenius norm
/// * `lpq`: Element-wise pq norm
#[derive(Debug, Copy, Clone)]
pub enum Norm {
L1,
L2,
Lp(f64),
LInf,
F,
Lpq(f64, f64),
}
/// Normed Vector
pub trait Normed: Vector {
type UnsignedScalar;
fn norm(&self, kind: Norm) -> Self::UnsignedScalar;
fn normalize(&self, kind: Norm) -> Self
where
Self: Sized;
}
/// Inner product Vector
pub trait InnerProduct: Normed {
fn dot(&self, rhs: &Self) -> Self::Scalar;
}
/// Linear operation for Vector
pub trait LinearOp<T: Vector, S: Vector> {
fn apply(&self, rhs: &T) -> S;
}
/// Vector Products
pub trait VectorProduct: Vector {
fn cross(&self, other: &Self) -> Self;
fn outer(&self, other: &Self) -> Matrix;
}
/// Matrix Products
pub trait MatrixProduct {
fn kronecker(&self, other: &Self) -> Matrix;
fn hadamard(&self, other: &Self) -> Matrix;
}
// =============================================================================
// Implementation for primitive types
// =============================================================================
impl Vector for f64 {
type Scalar = Self;
fn add_vec<'a, 'b>(&'a self, rhs: &'b Self) -> Self {
self + rhs
}
fn sub_vec<'a, 'b>(&'a self, rhs: &'b Self) -> Self {
self - rhs
}
fn mul_scalar(&self, rhs: Self::Scalar) -> Self {
self * rhs
}
}
impl Normed for f64 {
type UnsignedScalar = f64;
fn norm(&self, _kind: Norm) -> Self::Scalar {
self.abs()
}
fn normalize(&self, _kind: Norm) -> Self
where
Self: Sized,
{
self / self.abs()
}
}