conspire/math/matrix/vector/
mod.rs

1#[cfg(test)]
2use crate::math::test::ErrorTensor;
3
4use crate::math::{
5    Jacobian, Matrix, Scalar, Solution, SquareMatrix, Tensor, TensorRank1Vec, TensorRank2,
6    TensorTuple, 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    slice, vec,
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 = vec::IntoIter<Self::Item>;
238    fn into_iter(self) -> Self::IntoIter {
239        self.0.into_iter()
240    }
241}
242
243impl<'a> IntoIterator for &'a Vector {
244    type Item = &'a Scalar;
245    type IntoIter = slice::Iter<'a, Scalar>;
246    fn into_iter(self) -> Self::IntoIter {
247        self.0.iter()
248    }
249}
250
251impl Extend<Scalar> for Vector {
252    fn extend<I>(&mut self, iter: I)
253    where
254        I: IntoIterator<Item = Scalar>,
255    {
256        self.0.extend(iter)
257    }
258}
259
260impl TensorVec for Vector {
261    type Item = Scalar;
262    fn append(&mut self, other: &mut Self) {
263        self.0.append(&mut other.0)
264    }
265    fn capacity(&self) -> usize {
266        self.0.capacity()
267    }
268    fn is_empty(&self) -> bool {
269        self.0.is_empty()
270    }
271    fn new() -> Self {
272        Self(Vec::new())
273    }
274    fn push(&mut self, item: Self::Item) {
275        self.0.push(item)
276    }
277    fn remove(&mut self, index: usize) -> Self::Item {
278        self.0.remove(index)
279    }
280    fn retain<F>(&mut self, f: F)
281    where
282        F: FnMut(&Self::Item) -> bool,
283    {
284        self.0.retain(f)
285    }
286    fn swap_remove(&mut self, index: usize) -> Self::Item {
287        self.0.swap_remove(index)
288    }
289}
290
291impl Sum for Vector {
292    fn sum<Ii>(iter: Ii) -> Self
293    where
294        Ii: Iterator<Item = Self>,
295    {
296        iter.reduce(|mut acc, item| {
297            acc += item;
298            acc
299        })
300        .unwrap_or_else(Self::default)
301    }
302}
303
304impl Div<Scalar> for Vector {
305    type Output = Self;
306    fn div(mut self, scalar: Scalar) -> Self::Output {
307        self /= &scalar;
308        self
309    }
310}
311
312impl Div<&Scalar> for Vector {
313    type Output = Self;
314    fn div(mut self, scalar: &Scalar) -> Self::Output {
315        self /= scalar;
316        self
317    }
318}
319
320impl DivAssign<Scalar> for Vector {
321    fn div_assign(&mut self, scalar: Scalar) {
322        self.iter_mut().for_each(|entry| *entry /= &scalar);
323    }
324}
325
326impl DivAssign<&Scalar> for Vector {
327    fn div_assign(&mut self, scalar: &Scalar) {
328        self.iter_mut().for_each(|entry| *entry /= scalar);
329    }
330}
331
332impl Mul<Scalar> for Vector {
333    type Output = Self;
334    fn mul(mut self, scalar: Scalar) -> Self::Output {
335        self *= &scalar;
336        self
337    }
338}
339
340impl Mul<&Scalar> for Vector {
341    type Output = Self;
342    fn mul(mut self, scalar: &Scalar) -> Self::Output {
343        self *= scalar;
344        self
345    }
346}
347
348impl Mul<Scalar> for &Vector {
349    type Output = Vector;
350    fn mul(self, scalar: Scalar) -> Self::Output {
351        self.iter().map(|self_i| self_i * scalar).collect()
352    }
353}
354
355impl Mul<&Scalar> for &Vector {
356    type Output = Vector;
357    fn mul(self, scalar: &Scalar) -> Self::Output {
358        self.iter().map(|self_i| self_i * scalar).collect()
359    }
360}
361
362impl MulAssign<Scalar> for Vector {
363    fn mul_assign(&mut self, scalar: Scalar) {
364        self.iter_mut().for_each(|entry| *entry *= &scalar);
365    }
366}
367
368impl MulAssign<&Scalar> for Vector {
369    fn mul_assign(&mut self, scalar: &Scalar) {
370        self.iter_mut().for_each(|entry| *entry *= scalar);
371    }
372}
373
374impl Add for Vector {
375    type Output = Self;
376    fn add(mut self, vector: Self) -> Self::Output {
377        self += vector;
378        self
379    }
380}
381
382impl Add<&Self> for Vector {
383    type Output = Self;
384    fn add(mut self, vector: &Self) -> Self::Output {
385        self += vector;
386        self
387    }
388}
389
390impl AddAssign for Vector {
391    fn add_assign(&mut self, vector: Self) {
392        self.iter_mut()
393            .zip(vector.iter())
394            .for_each(|(self_entry, scalar)| *self_entry += scalar);
395    }
396}
397
398impl AddAssign<&Self> for Vector {
399    fn add_assign(&mut self, vector: &Self) {
400        self.iter_mut()
401            .zip(vector.iter())
402            .for_each(|(self_entry, scalar)| *self_entry += scalar);
403    }
404}
405
406impl Mul for Vector {
407    type Output = Scalar;
408    fn mul(self, vector: Self) -> Self::Output {
409        self.iter()
410            .zip(vector.iter())
411            .map(|(self_i, vector_i)| self_i * vector_i)
412            .sum()
413    }
414}
415
416impl Mul<&Self> for Vector {
417    type Output = Scalar;
418    fn mul(self, vector: &Self) -> Self::Output {
419        self.iter()
420            .zip(vector.iter())
421            .map(|(self_i, vector_i)| self_i * vector_i)
422            .sum()
423    }
424}
425
426impl Mul<Vector> for &Vector {
427    type Output = Scalar;
428    fn mul(self, vector: Vector) -> Self::Output {
429        self.iter()
430            .zip(vector.iter())
431            .map(|(self_i, vector_i)| self_i * vector_i)
432            .sum()
433    }
434}
435
436impl Mul for &Vector {
437    type Output = Scalar;
438    fn mul(self, vector: Self) -> Self::Output {
439        self.iter()
440            .zip(vector.iter())
441            .map(|(self_i, vector_i)| self_i * vector_i)
442            .sum()
443    }
444}
445
446impl Sub for Vector {
447    type Output = Self;
448    fn sub(mut self, vector: Self) -> Self::Output {
449        self -= vector;
450        self
451    }
452}
453
454impl Sub<&Self> for Vector {
455    type Output = Self;
456    fn sub(mut self, vector: &Self) -> Self::Output {
457        self -= vector;
458        self
459    }
460}
461
462impl Sub<Vector> for &Vector {
463    type Output = Vector;
464    fn sub(self, mut vector: Vector) -> Self::Output {
465        vector
466            .iter_mut()
467            .zip(self.iter())
468            .for_each(|(vector_i, self_i)| *vector_i = self_i - *vector_i);
469        vector
470    }
471}
472
473impl Sub for &Vector {
474    type Output = Vector;
475    fn sub(self, vector: Self) -> Self::Output {
476        vector
477            .iter()
478            .zip(self.iter())
479            .map(|(vector_i, self_i)| self_i - vector_i)
480            .collect()
481    }
482}
483
484impl SubAssign for Vector {
485    fn sub_assign(&mut self, vector: Self) {
486        self.iter_mut()
487            .zip(vector.iter())
488            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
489    }
490}
491
492impl SubAssign<&Self> for Vector {
493    fn sub_assign(&mut self, vector: &Self) {
494        self.iter_mut()
495            .zip(vector.iter())
496            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
497    }
498}
499
500impl SubAssign<&[Scalar]> for Vector {
501    fn sub_assign(&mut self, slice: &[Scalar]) {
502        self.iter_mut()
503            .zip(slice.iter())
504            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
505    }
506}
507
508impl Mul<&Matrix> for &Vector {
509    type Output = Vector;
510    fn mul(self, matrix: &Matrix) -> Self::Output {
511        let mut output = Vector::zero(matrix.width());
512        self.iter()
513            .zip(matrix.iter())
514            .for_each(|(self_i, matrix_i)| {
515                output
516                    .iter_mut()
517                    .zip(matrix_i.iter())
518                    .for_each(|(output_j, matrix_ij)| *output_j += self_i * matrix_ij)
519            });
520        output
521    }
522}
523
524impl<const D: usize, const I: usize> Mul<&TensorRank1Vec<D, I>> for &Vector {
525    type Output = Scalar;
526    fn mul(self, tensor_rank_1_vec: &TensorRank1Vec<D, I>) -> Self::Output {
527        tensor_rank_1_vec
528            .iter()
529            .enumerate()
530            .map(|(a, entry_a)| {
531                entry_a
532                    .iter()
533                    .enumerate()
534                    .map(|(i, entry_a_i)| self[D * a + i] * entry_a_i)
535                    .sum::<Scalar>()
536            })
537            .sum()
538    }
539}
540
541impl<const D: usize, const I: usize, const J: usize> Mul<&TensorRank2<D, I, J>> for &Vector {
542    type Output = Scalar;
543    fn mul(self, tensor_rank_2: &TensorRank2<D, I, J>) -> Self::Output {
544        tensor_rank_2
545            .iter()
546            .enumerate()
547            .map(|(i, entry_i)| {
548                entry_i
549                    .iter()
550                    .enumerate()
551                    .map(|(j, entry_ij)| self[D * i + j] * entry_ij)
552                    .sum::<Scalar>()
553            })
554            .sum()
555    }
556}
557
558impl<const D: usize, const I: usize, const J: usize, const K: usize, const L: usize>
559    Mul<&TensorTuple<TensorRank2<D, I, J>, TensorRank2<D, K, L>>> for &Vector
560{
561    type Output = Scalar;
562    fn mul(
563        self,
564        tensor_tuple: &TensorTuple<TensorRank2<D, I, J>, TensorRank2<D, K, L>>,
565    ) -> Self::Output {
566        let (tensor_rank_2_a, tensor_rank_2_b) = tensor_tuple.into();
567        &self.iter().take(D * D).copied().collect::<Vector>() * tensor_rank_2_a
568            + &self.iter().skip(D * D).copied().collect::<Vector>() * tensor_rank_2_b
569    }
570}
571
572impl Div<SquareMatrix> for &Vector {
573    type Output = Vector;
574    fn div(self, _square_matrix: SquareMatrix) -> Self::Output {
575        todo!()
576    }
577}