Skip to main content

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 reserve(&mut self, additional: usize) {
281        self.0.reserve(additional)
282    }
283    fn retain<F>(&mut self, f: F)
284    where
285        F: FnMut(&Self::Item) -> bool,
286    {
287        self.0.retain(f)
288    }
289    fn swap_remove(&mut self, index: usize) -> Self::Item {
290        self.0.swap_remove(index)
291    }
292    fn with_capacity(capacity: usize) -> Self {
293        Self(Vec::with_capacity(capacity))
294    }
295}
296
297impl Sum for Vector {
298    fn sum<Ii>(iter: Ii) -> Self
299    where
300        Ii: Iterator<Item = Self>,
301    {
302        iter.reduce(|mut acc, item| {
303            acc += item;
304            acc
305        })
306        .unwrap_or_else(Self::default)
307    }
308}
309
310impl Div<Scalar> for Vector {
311    type Output = Self;
312    fn div(mut self, scalar: Scalar) -> Self::Output {
313        self /= &scalar;
314        self
315    }
316}
317
318impl Div<&Scalar> for Vector {
319    type Output = Self;
320    fn div(mut self, scalar: &Scalar) -> Self::Output {
321        self /= scalar;
322        self
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 DivAssign<&Scalar> for Vector {
333    fn div_assign(&mut self, scalar: &Scalar) {
334        self.iter_mut().for_each(|entry| *entry /= scalar);
335    }
336}
337
338impl Mul<Scalar> for Vector {
339    type Output = Self;
340    fn mul(mut self, scalar: Scalar) -> Self::Output {
341        self *= &scalar;
342        self
343    }
344}
345
346impl Mul<&Scalar> for Vector {
347    type Output = Self;
348    fn mul(mut self, scalar: &Scalar) -> Self::Output {
349        self *= scalar;
350        self
351    }
352}
353
354impl Mul<Scalar> for &Vector {
355    type Output = Vector;
356    fn mul(self, scalar: Scalar) -> Self::Output {
357        self.iter().map(|self_i| self_i * scalar).collect()
358    }
359}
360
361impl Mul<&Scalar> for &Vector {
362    type Output = Vector;
363    fn mul(self, scalar: &Scalar) -> Self::Output {
364        self.iter().map(|self_i| self_i * scalar).collect()
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 MulAssign<&Scalar> for Vector {
375    fn mul_assign(&mut self, scalar: &Scalar) {
376        self.iter_mut().for_each(|entry| *entry *= scalar);
377    }
378}
379
380impl Add for Vector {
381    type Output = Self;
382    fn add(mut self, vector: Self) -> Self::Output {
383        self += vector;
384        self
385    }
386}
387
388impl Add<&Self> for Vector {
389    type Output = Self;
390    fn add(mut self, vector: &Self) -> Self::Output {
391        self += vector;
392        self
393    }
394}
395
396impl AddAssign for Vector {
397    fn add_assign(&mut self, vector: Self) {
398        self.iter_mut()
399            .zip(vector.iter())
400            .for_each(|(self_entry, scalar)| *self_entry += scalar);
401    }
402}
403
404impl AddAssign<&Self> for Vector {
405    fn add_assign(&mut self, vector: &Self) {
406        self.iter_mut()
407            .zip(vector.iter())
408            .for_each(|(self_entry, scalar)| *self_entry += scalar);
409    }
410}
411
412impl Mul for Vector {
413    type Output = Scalar;
414    fn mul(self, vector: Self) -> Self::Output {
415        self.iter()
416            .zip(vector.iter())
417            .map(|(self_i, vector_i)| self_i * vector_i)
418            .sum()
419    }
420}
421
422impl Mul<&Self> for Vector {
423    type Output = Scalar;
424    fn mul(self, vector: &Self) -> Self::Output {
425        self.iter()
426            .zip(vector.iter())
427            .map(|(self_i, vector_i)| self_i * vector_i)
428            .sum()
429    }
430}
431
432impl Mul<Vector> for &Vector {
433    type Output = Scalar;
434    fn mul(self, vector: Vector) -> Self::Output {
435        self.iter()
436            .zip(vector.iter())
437            .map(|(self_i, vector_i)| self_i * vector_i)
438            .sum()
439    }
440}
441
442impl Mul for &Vector {
443    type Output = Scalar;
444    fn mul(self, vector: Self) -> Self::Output {
445        self.iter()
446            .zip(vector.iter())
447            .map(|(self_i, vector_i)| self_i * vector_i)
448            .sum()
449    }
450}
451
452impl Sub for Vector {
453    type Output = Self;
454    fn sub(mut self, vector: Self) -> Self::Output {
455        self -= vector;
456        self
457    }
458}
459
460impl Sub<&Self> for Vector {
461    type Output = Self;
462    fn sub(mut self, vector: &Self) -> Self::Output {
463        self -= vector;
464        self
465    }
466}
467
468impl Sub<Vector> for &Vector {
469    type Output = Vector;
470    fn sub(self, mut vector: Vector) -> Self::Output {
471        vector
472            .iter_mut()
473            .zip(self.iter())
474            .for_each(|(vector_i, self_i)| *vector_i = self_i - *vector_i);
475        vector
476    }
477}
478
479impl Sub for &Vector {
480    type Output = Vector;
481    fn sub(self, vector: Self) -> Self::Output {
482        vector
483            .iter()
484            .zip(self.iter())
485            .map(|(vector_i, self_i)| self_i - vector_i)
486            .collect()
487    }
488}
489
490impl SubAssign for Vector {
491    fn sub_assign(&mut self, vector: Self) {
492        self.iter_mut()
493            .zip(vector.iter())
494            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
495    }
496}
497
498impl SubAssign<&Self> for Vector {
499    fn sub_assign(&mut self, vector: &Self) {
500        self.iter_mut()
501            .zip(vector.iter())
502            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
503    }
504}
505
506impl SubAssign<&[Scalar]> for Vector {
507    fn sub_assign(&mut self, slice: &[Scalar]) {
508        self.iter_mut()
509            .zip(slice.iter())
510            .for_each(|(self_entry, tensor_rank_1)| *self_entry -= tensor_rank_1);
511    }
512}
513
514impl Mul<&Matrix> for &Vector {
515    type Output = Vector;
516    fn mul(self, matrix: &Matrix) -> Self::Output {
517        let mut output = Vector::zero(matrix.width());
518        self.iter()
519            .zip(matrix.iter())
520            .for_each(|(self_i, matrix_i)| {
521                output
522                    .iter_mut()
523                    .zip(matrix_i.iter())
524                    .for_each(|(output_j, matrix_ij)| *output_j += self_i * matrix_ij)
525            });
526        output
527    }
528}
529
530impl<const D: usize, const I: usize> Mul<&TensorRank1Vec<D, I>> for &Vector {
531    type Output = Scalar;
532    fn mul(self, tensor_rank_1_vec: &TensorRank1Vec<D, I>) -> Self::Output {
533        tensor_rank_1_vec
534            .iter()
535            .enumerate()
536            .map(|(a, entry_a)| {
537                entry_a
538                    .iter()
539                    .enumerate()
540                    .map(|(i, entry_a_i)| self[D * a + i] * entry_a_i)
541                    .sum::<Scalar>()
542            })
543            .sum()
544    }
545}
546
547impl<const D: usize, const I: usize, const J: usize> Mul<&TensorRank2<D, I, J>> for &Vector {
548    type Output = Scalar;
549    fn mul(self, tensor_rank_2: &TensorRank2<D, I, J>) -> Self::Output {
550        tensor_rank_2
551            .iter()
552            .enumerate()
553            .map(|(i, entry_i)| {
554                entry_i
555                    .iter()
556                    .enumerate()
557                    .map(|(j, entry_ij)| self[D * i + j] * entry_ij)
558                    .sum::<Scalar>()
559            })
560            .sum()
561    }
562}
563
564impl<const D: usize, const I: usize, const J: usize, const K: usize, const L: usize>
565    Mul<&TensorTuple<TensorRank2<D, I, J>, TensorRank2<D, K, L>>> for &Vector
566{
567    type Output = Scalar;
568    fn mul(
569        self,
570        tensor_tuple: &TensorTuple<TensorRank2<D, I, J>, TensorRank2<D, K, L>>,
571    ) -> Self::Output {
572        let (tensor_rank_2_a, tensor_rank_2_b) = tensor_tuple.into();
573        &self.iter().take(D * D).copied().collect::<Vector>() * tensor_rank_2_a
574            + &self.iter().skip(D * D).copied().collect::<Vector>() * tensor_rank_2_b
575    }
576}
577
578impl Div<SquareMatrix> for &Vector {
579    type Output = Vector;
580    fn div(self, _square_matrix: SquareMatrix) -> Self::Output {
581        todo!()
582    }
583}