rust_blas/math/
vector.rs

1// Copyright 2015 Michael Yang. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5use crate::default::Default;
6use crate::math::Trans;
7use crate::vector::ops::*;
8use crate::vector::Vector;
9use num_complex::{Complex32, Complex64};
10use std::ops::{Add, Mul};
11
12impl<'a, T> Add for &'a dyn Vector<T>
13where
14    T: Axpy + Copy + Default,
15{
16    type Output = Vec<T>;
17
18    fn add(self, x: &dyn Vector<T>) -> Vec<T> {
19        let mut result: Vec<_> = self.into();
20        let scale = Default::one();
21
22        Axpy::axpy(&scale, x, &mut result);
23        result
24    }
25}
26
27impl<'a, T> Mul<&'a dyn Vector<T>> for Trans<&'a dyn Vector<T>>
28where
29    T: Sized + Copy + Dot + Dotc,
30{
31    type Output = T;
32
33    fn mul(self, x: &dyn Vector<T>) -> T {
34        match self {
35            Trans::T(v) => Dot::dot(v, x),
36            Trans::H(v) => Dotc::dotc(v, x),
37        }
38    }
39}
40
41impl<'a, T> Mul<T> for &'a dyn Vector<T>
42where
43    T: Sized + Copy + Scal,
44{
45    type Output = Vec<T>;
46
47    fn mul(self, alpha: T) -> Vec<T> {
48        let mut result: Vec<_> = self.into();
49        Scal::scal(&alpha, &mut result);
50        result
51    }
52}
53
54macro_rules! left_scale(($($t: ident), +) => (
55    $(
56        impl<'a> Mul<&'a dyn Vector<$t>> for $t
57        {
58            type Output = Vec<$t>;
59
60            fn mul(self, x: &dyn Vector<$t>) -> Vec<$t> {
61                let mut result: Vec<_> = x.into();
62                Scal::scal(&self, &mut result);
63                result
64            }
65        }
66    )+
67));
68
69left_scale!(f32, f64, Complex32, Complex64);
70
71#[cfg(test)]
72mod tests {
73    use crate::math::Marker::{H, T};
74    use crate::Vector;
75    use num_complex::Complex;
76
77    #[test]
78    fn add() {
79        let x = vec![1f32, 2f32];
80        let y = vec![3f32, 4f32];
81
82        let z = (&x as &dyn Vector<_>) + &y;
83
84        assert_eq!(&z, &vec![4f32, 6f32]);
85    }
86
87    #[test]
88    fn dot() {
89        let x = vec![1f32, 2f32];
90        let y = vec![-1f32, 2f32];
91
92        let dot = {
93            let z = &x as &dyn Vector<_>;
94            (z ^ T) * &y
95        };
96
97        assert_eq!(dot, 3.0);
98    }
99
100    #[test]
101    fn herm_dot() {
102        let x = vec![Complex::new(1f32, -1f32), Complex::new(1f32, -3f32)];
103        let y = vec![Complex::new(1f32, 2f32), Complex::new(1f32, 3f32)];
104
105        let dot = {
106            let z = &x as &dyn Vector<_>;
107            (z ^ H) * &y
108        };
109
110        assert_eq!(dot, Complex::new(-9f32, 9f32));
111    }
112
113    #[test]
114    fn scale() {
115        let x = vec![1f32, 2f32];
116        let xr = &x as &dyn Vector<_>;
117
118        let y = xr * 3.0;
119        let z = 3.0 * xr;
120        assert_eq!(y, vec![3f32, 6f32]);
121        assert_eq!(z, y);
122    }
123}