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