static_math/
slices_methods.rs

1//-------------------------------------------------------------------------
2// @file slices_methods.rs
3//
4// @date 06/24/20 21:48:21
5// @author Martin Noblia
6// @email mnoblia@disroot.org
7//
8// @brief
9//
10// @detail
11//
12// Licence MIT:
13// Copyright <2020> <Martin Noblia>
14//
15// Permission is hereby granted, free of charge, to any person obtaining a copy
16// of this software and associated documentation files (the "Software"), to deal
17// in the Software without restriction, including without limitation the rights
18// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19// copies of the Software, and to permit persons to whom the Software is
20// furnished to do so, subject to the following conditions:
21//
22// The above copyright notice and this permission notice shall be included in
23// all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED
24// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
25// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
26// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
27// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
28// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30//-------------------------------------------------------------------------
31use num::{Num, Float, Signed};
32use crate::utils::nearly_equal;
33
34// TODO(elsuizo:2020-08-31): implement the Display trait for this type
35#[derive(Copy, Clone, Debug, PartialEq)]
36pub struct MaxMin<T> {
37    pub max: (T, usize),
38    pub min: (T, usize),
39}
40
41/// generic function to fin min, max values and the position in a slice
42pub fn find_max_min<T: core::cmp::PartialOrd + Copy>(slice: &[T]) -> MaxMin<T> {
43    let mut max = &slice[0];
44    let mut min = &slice[0];
45
46    let mut max_pos: usize = 0;
47    let mut min_pos: usize = 0;
48
49    for (index, element) in slice.iter().enumerate().skip(1) {
50        if element < min { min = element; min_pos = index; }
51        if element > max { max = element; max_pos = index; }
52    }
53
54    MaxMin{max: (*max, max_pos), min: (*min, min_pos)}
55}
56
57/// calculate the inf-norm of the slice
58pub fn norm_inf<T: Num + Copy + core::cmp::PartialOrd>(slice: &[T]) -> T {
59    let max_min = find_max_min(slice);
60    max_min.max.0
61}
62
63/// calculate the l-norm of the slice
64pub fn norm_l<T: Num + Copy + Signed + core::iter::Sum>(slice: &[T]) -> T {
65    slice.iter().map(|element| element.abs()).sum()
66}
67
68/// calculate the euclidean norm of the slice
69pub fn norm2<T: Float>(slice: &[T]) -> T {
70    slice.iter().fold(T::zero(), |n, &i| (i * i) + n).sqrt()
71}
72
73/// calculate the dot product of two slices
74pub fn dot<T: Num + Copy + core::iter::Sum>(slice1: &[T], slice2: &[T]) -> T {
75    slice1.iter().zip(slice2).map(|(&a, &b)| a * b).sum()
76}
77
78// NOTE(elsuizo:2021-04-15): this function assume that the slice is not zero
79// we use safely in the QR algorithm because known that the vector is not zero
80/// normalize the slice
81pub fn normalize<T: Float>(slice: &mut [T]) {
82    let n = norm2(slice);
83    slice.iter_mut().for_each(|element| {
84        *element = *element / n;
85    })
86}
87
88/// project x in the direction of y
89pub fn project_x_over_y<T: Float + core::iter::Sum>(x: &[T], y: &[T]) -> T {
90    dot(x, y) / dot(y, y)
91}
92
93pub fn check_elements<T: Float>(v: &[T], tol: T) -> bool {
94    let mut result = false;
95    for num in v.iter() {
96        result |= nearly_equal(*num, T::zero(), tol);
97    }
98    result
99}
100
101//-------------------------------------------------------------------------
102//                        tests
103//-------------------------------------------------------------------------
104#[cfg(test)]
105mod test_slides_methods {
106
107    use crate::vector3::V3;
108    use crate::slices_methods::*;
109
110    #[test]
111    fn find_max_min_test() {
112        let v = V3::new([1, 10, 37]);
113
114        let result = find_max_min(&*v);
115
116        let expected = MaxMin{max: (37, 2), min: (1, 0)};
117
118        assert_eq!(result, expected);
119
120    }
121
122    #[test]
123    fn dot_tests() {
124       let v1 = V3::new([1, 1, 1]);
125       let v2 = V3::new([1, 1, 3]);
126
127       let result = dot(&*v1, &*v2);
128       let expected = 5;
129
130       assert_eq!(result, expected);
131    }
132
133    #[test]
134    fn normalize_test() {
135        let mut v1 = V3::new([1.0, 1.0, 1.0]);
136        normalize(&mut *v1);
137
138        let expected = V3::new([0.5773502691896258, 0.5773502691896258, 0.5773502691896258]);
139
140        assert_eq!(
141            &v1[..],
142            &expected[..],
143            "\nExpected\n{:?}\nfound\n{:?}",
144            &v1[..],
145            &expected[..]
146        );
147    }
148}