conspire/math/matrix/vector/
mod.rs

1#[cfg(test)]
2use crate::math::test::ErrorTensor;
3
4use crate::math::{
5    Jacobian, Matrix, Scalar, Solution, Tensor, TensorRank1Vec, TensorRank2, TensorVec,
6    write_tensor_rank_0,
7};
8use std::{
9    fmt::{Display, Formatter, Result},
10    ops::{
11        Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, RangeFrom, RangeTo, Sub,
12        SubAssign,
13    },
14    vec::IntoIter,
15};
16
17/// A vector.
18#[derive(Clone, Debug, PartialEq)]
19pub struct Vector(Vec<Scalar>);
20
21impl Vector {
22    pub fn as_slice(&self) -> &[Scalar] {
23        self.0.as_slice()
24    }
25    pub fn ones(len: usize) -> Self {
26        Self(vec![1.0; len])
27    }
28}
29
30#[cfg(test)]
31impl ErrorTensor for Vector {
32    fn error(&self, comparator: &Self, tol_abs: &Scalar, tol_rel: &Scalar) -> Option<usize> {
33        let error_count = self
34            .iter()
35            .zip(comparator.iter())
36            .map(|(entry, comparator_entry)| {
37                entry
38                    .iter()
39                    .zip(comparator_entry.iter())
40                    .filter(|&(&entry_i, &comparator_entry_i)| {
41                        &(entry_i - comparator_entry_i).abs() >= tol_abs
42                            && &(entry_i / comparator_entry_i - 1.0).abs() >= tol_rel
43                    })
44                    .count()
45            })
46            .sum();
47        if error_count > 0 {
48            Some(error_count)
49        } else {
50            None
51        }
52    }
53    fn error_fd(&self, comparator: &Self, epsilon: &Scalar) -> Option<(bool, usize)> {
54        let error_count = self
55            .iter()
56            .zip(comparator.iter())
57            .map(|(entry, comparator_entry)| {
58                entry
59                    .iter()
60                    .zip(comparator_entry.iter())
61                    .filter(|&(&entry_i, &comparator_entry_i)| {
62                        &(entry_i / comparator_entry_i - 1.0).abs() >= epsilon
63                            && (&entry_i.abs() >= epsilon || &comparator_entry_i.abs() >= epsilon)
64                    })
65                    .count()
66            })
67            .sum();
68        if error_count > 0 {
69            let auxillary = self
70                .iter()
71                .zip(comparator.iter())
72                .map(|(entry, comparator_entry)| {
73                    entry
74                        .iter()
75                        .zip(comparator_entry.iter())
76                        .filter(|&(&entry_i, &comparator_entry_i)| {
77                            &(entry_i / comparator_entry_i - 1.0).abs() >= epsilon
78                                && &(entry_i - comparator_entry_i).abs() >= epsilon
79                                && (&entry_i.abs() >= epsilon
80                                    || &comparator_entry_i.abs() >= epsilon)
81                        })
82                        .count()
83                })
84                .sum::<usize>()
85                > 0;
86            Some((auxillary, error_count))
87        } else {
88            None
89        }
90    }
91}
92
93impl Display for Vector {
94    fn fmt(&self, f: &mut Formatter) -> Result {
95        write!(f, "\x1B[s")?;
96        write!(f, "[")?;
97        self.0.chunks(5).enumerate().try_for_each(|(i, chunk)| {
98            chunk
99                .iter()
100                .try_for_each(|entry| write_tensor_rank_0(f, entry))?;
101            if (i + 1) * 5 < self.len() {
102                writeln!(f, "\x1B[2D,")?;
103                write!(f, "\x1B[u")?;
104                write!(f, "\x1B[{}B ", i + 1)?;
105            }
106            Ok(())
107        })?;
108        write!(f, "\x1B[2D]")?;
109        Ok(())
110    }
111}
112
113impl<const D: usize, const I: usize> From<TensorRank1Vec<D, I>> for Vector {
114    fn from(tensor_rank_1_vec: TensorRank1Vec<D, I>) -> Self {
115        tensor_rank_1_vec.into_iter().flatten().collect()
116    }
117}
118
119impl<const D: usize, const I: usize, const J: usize> From<TensorRank2<D, I, J>> for Vector {
120    fn from(tensor_rank_2: TensorRank2<D, I, J>) -> Self {
121        tensor_rank_2.into_iter().flatten().collect()
122    }
123}
124
125impl FromIterator<Scalar> for Vector {
126    fn from_iter<Ii: IntoIterator<Item = Scalar>>(into_iterator: Ii) -> Self {
127        Self(Vec::from_iter(into_iterator))
128    }
129}
130
131impl Index<usize> for Vector {
132    type Output = Scalar;
133    fn index(&self, index: usize) -> &Self::Output {
134        &self.0[index]
135    }
136}
137
138impl Index<RangeTo<usize>> for Vector {
139    type Output = [Scalar];
140    fn index(&self, indices: RangeTo<usize>) -> &Self::Output {
141        &self.0[indices]
142    }
143}
144
145impl Index<RangeFrom<usize>> for Vector {
146    type Output = [Scalar];
147    fn index(&self, indices: RangeFrom<usize>) -> &Self::Output {
148        &self.0[indices]
149    }
150}
151
152impl IndexMut<usize> for Vector {
153    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
154        &mut self.0[index]
155    }
156}
157
158impl Tensor for Vector {
159    type Item = Scalar;
160    fn iter(&self) -> impl Iterator<Item = &Self::Item> {
161        self.0.iter()
162    }
163    fn iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Item> {
164        self.0.iter_mut()
165    }
166    fn norm_inf(&self) -> Scalar {
167        self.iter().fold(0.0, |acc, entry| entry.abs().max(acc))
168    }
169}
170
171impl Solution for Vector {
172    fn decrement_from_chained(&mut self, other: &mut Self, vector: Vector) {
173        self.iter_mut()
174            .chain(other.iter_mut())
175            .zip(vector)
176            .for_each(|(entry_i, vector_i)| *entry_i -= vector_i)
177    }
178}
179
180impl Jacobian for Vector {
181    fn fill_into(self, vector: &mut Vector) {
182        self.into_iter()
183            .zip(vector.iter_mut())
184            .for_each(|(self_i, vector_i)| *vector_i = self_i)
185    }
186    fn fill_into_chained(self, other: Self, vector: &mut Self) {
187        self.into_iter()
188            .chain(other)
189            .zip(vector.iter_mut())
190            .for_each(|(entry_i, vector_i)| *vector_i = entry_i)
191    }
192}
193
194impl IntoIterator for Vector {
195    type Item = Scalar;
196    type IntoIter = IntoIter<Self::Item>;
197    fn into_iter(self) -> Self::IntoIter {
198        self.0.into_iter()
199    }
200}
201
202impl TensorVec for Vector {
203    type Item = Scalar;
204    type Slice<'a> = &'a [Scalar];
205    fn append(&mut self, other: &mut Self) {
206        self.0.append(&mut other.0)
207    }
208    fn is_empty(&self) -> bool {
209        self.0.is_empty()
210    }
211    fn len(&self) -> usize {
212        self.0.len()
213    }
214    fn new(slice: Self::Slice<'_>) -> Self {
215        slice.iter().copied().collect()
216    }
217    fn push(&mut self, item: Self::Item) {
218        self.0.push(item)
219    }
220    fn zero(len: usize) -> Self {
221        Self(vec![0.0; len])
222    }
223}
224
225impl Div<Scalar> for Vector {
226    type Output = Self;
227    fn div(mut self, scalar: Scalar) -> Self::Output {
228        self /= &scalar;
229        self
230    }
231}
232
233impl Div<&Scalar> for Vector {
234    type Output = Self;
235    fn div(mut self, scalar: &Scalar) -> Self::Output {
236        self /= scalar;
237        self
238    }
239}
240
241impl DivAssign<Scalar> for Vector {
242    fn div_assign(&mut self, scalar: Scalar) {
243        self.iter_mut().for_each(|entry| *entry /= &scalar);
244    }
245}
246
247impl DivAssign<&Scalar> for Vector {
248    fn div_assign(&mut self, scalar: &Scalar) {
249        self.iter_mut().for_each(|entry| *entry /= scalar);
250    }
251}
252
253impl Mul<Scalar> for Vector {
254    type Output = Self;
255    fn mul(mut self, scalar: Scalar) -> Self::Output {
256        self *= &scalar;
257        self
258    }
259}
260
261impl Mul<&Scalar> for Vector {
262    type Output = Self;
263    fn mul(mut self, scalar: &Scalar) -> Self::Output {
264        self *= scalar;
265        self
266    }
267}
268
269impl Mul<Scalar> for &Vector {
270    type Output = Vector;
271    fn mul(self, scalar: Scalar) -> Self::Output {
272        self.iter().map(|self_i| self_i * scalar).collect()
273    }
274}
275
276impl Mul<&Scalar> for &Vector {
277    type Output = Vector;
278    fn mul(self, scalar: &Scalar) -> Self::Output {
279        self.iter().map(|self_i| self_i * scalar).collect()
280    }
281}
282
283impl MulAssign<Scalar> for Vector {
284    fn mul_assign(&mut self, scalar: Scalar) {
285        self.iter_mut().for_each(|entry| *entry *= &scalar);
286    }
287}
288
289impl MulAssign<&Scalar> for Vector {
290    fn mul_assign(&mut self, scalar: &Scalar) {
291        self.iter_mut().for_each(|entry| *entry *= scalar);
292    }
293}
294
295impl Add for Vector {
296    type Output = Self;
297    fn add(mut self, vector: Self) -> Self::Output {
298        self += vector;
299        self
300    }
301}
302
303impl Add<&Self> for Vector {
304    type Output = Self;
305    fn add(mut self, vector: &Self) -> Self::Output {
306        self += vector;
307        self
308    }
309}
310
311impl AddAssign for Vector {
312    fn add_assign(&mut self, vector: Self) {
313        self.iter_mut()
314            .zip(vector.iter())
315            .for_each(|(self_entry, scalar)| *self_entry += scalar);
316    }
317}
318
319impl AddAssign<&Self> for Vector {
320    fn add_assign(&mut self, vector: &Self) {
321        self.iter_mut()
322            .zip(vector.iter())
323            .for_each(|(self_entry, scalar)| *self_entry += scalar);
324    }
325}
326
327impl Mul for Vector {
328    type Output = Scalar;
329    fn mul(self, vector: Self) -> Self::Output {
330        self.iter()
331            .zip(vector.iter())
332            .map(|(self_i, vector_i)| self_i * vector_i)
333            .sum()
334    }
335}
336
337impl Mul<&Self> for Vector {
338    type Output = Scalar;
339    fn mul(self, vector: &Self) -> Self::Output {
340        self.iter()
341            .zip(vector.iter())
342            .map(|(self_i, vector_i)| self_i * vector_i)
343            .sum()
344    }
345}
346
347impl Mul<Vector> for &Vector {
348    type Output = Scalar;
349    fn mul(self, vector: Vector) -> Self::Output {
350        self.iter()
351            .zip(vector.iter())
352            .map(|(self_i, vector_i)| self_i * vector_i)
353            .sum()
354    }
355}
356
357impl Mul for &Vector {
358    type Output = Scalar;
359    fn mul(self, vector: Self) -> Self::Output {
360        self.iter()
361            .zip(vector.iter())
362            .map(|(self_i, vector_i)| self_i * vector_i)
363            .sum()
364    }
365}
366
367impl Sub for Vector {
368    type Output = Self;
369    fn sub(mut self, vector: Self) -> Self::Output {
370        self -= vector;
371        self
372    }
373}
374
375impl Sub<&Self> for Vector {
376    type Output = Self;
377    fn sub(mut self, vector: &Self) -> Self::Output {
378        self -= vector;
379        self
380    }
381}
382
383impl Sub<Vector> for &Vector {
384    type Output = Vector;
385    fn sub(self, mut vector: Vector) -> Self::Output {
386        vector
387            .iter_mut()
388            .zip(self.iter())
389            .for_each(|(vector_i, self_i)| *vector_i = self_i - *vector_i);
390        vector
391    }
392}
393
394impl SubAssign for Vector {
395    fn sub_assign(&mut self, vector: Self) {
396        self.iter_mut()
397            .zip(vector.iter())
398            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
399    }
400}
401
402impl SubAssign<&Self> for Vector {
403    fn sub_assign(&mut self, vector: &Self) {
404        self.iter_mut()
405            .zip(vector.iter())
406            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
407    }
408}
409
410impl SubAssign<&[Scalar]> for Vector {
411    fn sub_assign(&mut self, slice: &[Scalar]) {
412        self.iter_mut()
413            .zip(slice.iter())
414            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
415    }
416}
417
418impl Mul<&Matrix> for &Vector {
419    type Output = Vector;
420    fn mul(self, matrix: &Matrix) -> Self::Output {
421        let mut output = Vector::zero(matrix.width());
422        self.iter()
423            .zip(matrix.iter())
424            .for_each(|(self_i, matrix_i)| {
425                output
426                    .iter_mut()
427                    .zip(matrix_i.iter())
428                    .for_each(|(output_j, matrix_ij)| *output_j += self_i * matrix_ij)
429            });
430        output
431    }
432}
433
434impl<const D: usize, const I: usize> Mul<&TensorRank1Vec<D, I>> for &Vector {
435    type Output = Scalar;
436    fn mul(self, tensor_rank_1_vec: &TensorRank1Vec<D, I>) -> Self::Output {
437        tensor_rank_1_vec
438            .iter()
439            .enumerate()
440            .map(|(a, entry_a)| {
441                entry_a
442                    .iter()
443                    .enumerate()
444                    .map(|(i, entry_a_i)| self[D * a + i] * entry_a_i)
445                    .sum::<Scalar>()
446            })
447            .sum()
448    }
449}
450
451impl<const D: usize, const I: usize, const J: usize> Mul<&TensorRank2<D, I, J>> for &Vector {
452    type Output = Scalar;
453    fn mul(self, tensor_rank_2: &TensorRank2<D, I, J>) -> Self::Output {
454        tensor_rank_2
455            .iter()
456            .enumerate()
457            .map(|(i, entry_i)| {
458                entry_i
459                    .iter()
460                    .enumerate()
461                    .map(|(j, entry_ij)| self[D * i + j] * entry_ij)
462                    .sum::<Scalar>()
463            })
464            .sum()
465    }
466}