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