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