multicalc 0.10.0

Math for real-time embedded systems, in stable no_std Rust: state estimation, control, kinematics, Lie groups, autodiff, and linear algebra — from 64-bit servers to bare-metal microcontrollers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Fixed-size, stack-allocated column vector.

use core::ops::{Add, AddAssign, Div, Index, IndexMut, Mul, Neg, Sub, SubAssign};

use crate::scalar::Numeric;

/// A column vector of `N` components, stored inline on the stack.
///
/// ```
/// use multicalc::linear_algebra::Vector;
/// let a = Vector::new([1.0, 2.0, 3.0]);
/// let b = Vector::from([4.0, 5.0, 6.0]);
///
/// assert_eq!(a[0], 1.0);
/// assert_eq!(a.get(0), Some(&1.0));
/// assert_eq!(a + b, Vector::new([5.0, 7.0, 9.0]));
/// assert_eq!(b - a, Vector::new([3.0, 3.0, 3.0]));
/// assert_eq!(-a, Vector::new([-1.0, -2.0, -3.0]));
/// assert_eq!(a * 2.0, Vector::new([2.0, 4.0, 6.0]));
/// assert_eq!(a.dot(b), 32.0);
/// ```
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[must_use]
pub struct Vector<const N: usize, T = f64> {
    data: [T; N],
}

impl<const N: usize, T> Vector<N, T> {
    /// Wraps `N` components into a vector.
    #[inline]
    pub const fn new(data: [T; N]) -> Self {
        Vector { data }
    }

    /// Builds a vector by calling `f` with each index in `0..N`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let v = Vector::<4>::from_fn(|i| i as f64);
    /// assert_eq!(v.into_array(), [0.0, 1.0, 2.0, 3.0]);
    /// ```
    #[inline]
    pub fn from_fn(f: impl FnMut(usize) -> T) -> Self {
        Vector {
            data: core::array::from_fn(f),
        }
    }

    /// Borrows the components as an array.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert_eq!(Vector::new([1.0, 2.0]).as_array(), &[1.0, 2.0]);
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_array(&self) -> &[T; N] {
        &self.data
    }

    /// Borrows the components as a slice.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert_eq!(Vector::new([1.0, 2.0]).as_slice(), &[1.0, 2.0]);
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Borrows the components as a mutable slice.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let mut v = Vector::new([1.0, 2.0]);
    /// v.as_mut_slice()[0] = 9.0;
    /// assert_eq!(v[0], 9.0);
    /// ```
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.data
    }

    // Crate-internal panic path (also used by Index). Public: prefer `[]`; use `get` when fallible.
    #[inline]
    #[track_caller]
    #[must_use]
    pub(crate) fn at(&self, i: usize) -> &T {
        #[allow(clippy::indexing_slicing)]
        &self.data[i]
    }

    #[inline]
    #[track_caller]
    pub(crate) fn at_mut(&mut self, i: usize) -> &mut T {
        #[allow(clippy::indexing_slicing)]
        &mut self.data[i]
    }

    /// Returns a reference to component `i`, or `None` if `i >= N`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let v = Vector::new([1.0, 2.0]);
    /// assert_eq!(v.get(0), Some(&1.0));
    /// assert_eq!(v.get(2), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn get(&self, i: usize) -> Option<&T> {
        self.data.get(i)
    }

    /// Returns a mutable reference to component `i`, or `None` if `i >= N`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let mut v = Vector::new([1.0, 2.0]);
    /// if let Some(x) = v.get_mut(1) {
    ///     *x = 9.0;
    /// }
    /// assert_eq!(v.get(1), Some(&9.0));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
        self.data.get_mut(i)
    }

    /// Consumes the vector, returning its components.
    #[inline]
    #[must_use]
    pub fn into_array(self) -> [T; N] {
        self.data
    }

    /// Construct a new vector by applying a function to each component.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let v = Vector::new([1.0, 2.0, 3.0]);
    /// let u = v.map(|x| 2.0 * x);
    /// assert_eq!(u, Vector::new([2.0, 4.0, 6.0]));
    /// ```
    #[inline]
    pub fn map<F, U>(self, f: F) -> Vector<N, U>
    where
        F: Fn(T) -> U,
    {
        Vector::new(self.data.map(f))
    }
}

impl<const N: usize, T: Copy> Vector<N, T> {
    /// Builds a vector from a slice, or `None` if `slice.len()` is not `N`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert!(Vector::<3>::try_from_slice(&[1.0, 2.0, 3.0]).is_some());
    /// assert!(Vector::<3>::try_from_slice(&[1.0, 2.0]).is_none());
    /// ```
    #[inline]
    #[must_use]
    pub fn try_from_slice(slice: &[T]) -> Option<Self> {
        (slice.len() == N).then(|| Self::from_fn(|i| slice[i]))
    }
}

impl<const N: usize, T: Numeric> Vector<N, T> {
    /// The zero vector.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let v: Vector<3> = Vector::zeros();
    /// assert_eq!(v.into_array(), [0.0, 0.0, 0.0]);
    /// ```
    #[inline]
    pub fn zeros() -> Self {
        Vector::from_fn(|_| T::ZERO)
    }

    /// Multiplies every component by `scalar`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let v = Vector::new([1.0, 2.0]);
    /// let factor = 3.0;
    /// assert_eq!(v.scale(factor), Vector::new([3.0, 6.0]));
    /// ```
    #[inline]
    pub fn scale(self, scalar: T) -> Self {
        Vector::from_fn(|i| self.data[i] * scalar)
    }

    /// The dot product `Σ self[i] * rhs[i]`, summed left to right.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let a = Vector::new([1.0, 2.0, 3.0]);
    /// let b = Vector::new([4.0, 5.0, 6.0]);
    /// assert_eq!(a.dot(b), 32.0);
    ///
    /// // perpendicular vectors have a zero dot product
    /// let along_x = Vector::new([1.0, 0.0]);
    /// let along_y = Vector::new([0.0, 1.0]);
    /// assert_eq!(along_x.dot(along_y), 0.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn dot(self, rhs: Self) -> T {
        let mut sum = T::ZERO;
        for (&a, &b) in self.data.iter().zip(&rhs.data) {
            sum += a * b;
        }
        sum
    }

    /// The squared Euclidean norm `self · self` (no square root).
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert_eq!(Vector::new([3.0, 4.0]).norm_squared(), 25.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn norm_squared(self) -> T {
        self.dot(self)
    }

    /// The Euclidean norm `√(self · self)`.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert_eq!(Vector::new([3.0, 4.0]).norm(), 5.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn norm(self) -> T {
        self.norm_squared().sqrt()
    }

    /// Returns `true` when every component is neither infinite nor NaN.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert!(Vector::new([1.0, -2.0]).is_finite());
    /// assert!(!Vector::new([1.0, f64::NAN]).is_finite());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_finite(self) -> bool {
        self.data.iter().all(|x| x.is_finite())
    }

    /// Returns a normalized copy of the vector (i.e. one where the norm is equal to 1).
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert_eq!(Vector::new([30.0, 40.0]).normalized(), Vector::new([0.6, 0.8]));
    /// ```
    #[inline]
    pub fn normalized(self) -> Self {
        self / self.norm()
    }

    /// Attempts to return a normalized copy of the vector (i.e. one where the norm is equal to 1),
    /// returning `None` in the case of a zero vector or a vector with a `NAN` entry.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// assert_eq!(Vector::new([30.0, 40.0]).try_normalized(), Some(Vector::new([0.6, 0.8])));
    /// assert_eq!(Vector::new([0.0, 0.0]).try_normalized(), None);
    /// assert_eq!(Vector::new([f64::NAN, 0.0]).try_normalized(), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn try_normalized(self) -> Option<Self> {
        let norm = self.norm();
        if norm.is_nan() || norm == T::ZERO {
            return None;
        }
        Some(self / norm)
    }

    /// Normalize the vector in-place (i.e. after this operation the norm is equal to 1).
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let mut v = Vector::new([30.0, 40.0]);
    /// v.normalize();
    /// assert_eq!(v, Vector::new([0.6, 0.8]));
    /// ```
    #[inline]
    pub fn normalize(&mut self) {
        let norm = self.norm();
        self.do_normalize(norm);
    }

    /// Attempt to normalize the vector in-place (i.e. after this operation the norm is equal to 1).
    /// This method returns `None` and leaves the vector unchanged if the norm is zero or NAN.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let mut v = Vector::new([30.0, 40.0]);
    /// assert!(v.try_normalize().is_some());
    /// assert_eq!(v, Vector::new([0.6, 0.8]));
    ///
    /// let mut v = Vector::new([0.0, 0.0]);
    /// assert!(v.try_normalize().is_none());
    /// assert_eq!(v, Vector::new([0.0, 0.0]));
    ///
    /// let mut v = Vector::new([f64::NAN, 1.0]);
    /// assert!(v.try_normalize().is_none());
    /// ```
    #[inline]
    #[must_use]
    pub fn try_normalize(&mut self) -> Option<()> {
        let norm = self.norm();
        if norm.is_nan() || norm == T::ZERO {
            return None;
        }
        self.do_normalize(norm);
        Some(())
    }

    fn do_normalize(&mut self, norm: T) {
        for x in self.data.iter_mut() {
            *x = x.safe_div(norm);
        }
    }
}

impl<const N: usize, T> From<[T; N]> for Vector<N, T> {
    #[inline]
    fn from(data: [T; N]) -> Self {
        Vector { data }
    }
}

impl<const N: usize, T> Index<usize> for Vector<N, T> {
    type Output = T;

    /// Panics if `index >= N`. Use [`Self::get`] when the index may be invalid.
    #[inline]
    #[track_caller]
    fn index(&self, index: usize) -> &T {
        self.at(index)
    }
}

impl<const N: usize, T> IndexMut<usize> for Vector<N, T> {
    /// Panics if `index >= N`. Use [`Self::get_mut`] when the index may be invalid.
    #[inline]
    #[track_caller]
    fn index_mut(&mut self, index: usize) -> &mut T {
        self.at_mut(index)
    }
}

impl<const N: usize, T: Numeric> Add for Vector<N, T> {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self {
        Vector::from_fn(|i| self.data[i] + rhs.data[i])
    }
}

impl<const N: usize, T: Numeric> AddAssign for Vector<N, T> {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        for (a, &b) in self.data.iter_mut().zip(&rhs.data) {
            *a += b;
        }
    }
}

impl<const N: usize, T: Numeric> Sub for Vector<N, T> {
    type Output = Self;

    #[inline]
    fn sub(self, rhs: Self) -> Self {
        Vector::from_fn(|i| self.data[i] - rhs.data[i])
    }
}

impl<const N: usize, T: Numeric> SubAssign for Vector<N, T> {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        for (a, &b) in self.data.iter_mut().zip(&rhs.data) {
            *a -= b;
        }
    }
}

impl<const N: usize, T: Numeric> Neg for Vector<N, T> {
    type Output = Self;

    #[inline]
    fn neg(self) -> Self {
        Vector::from_fn(|i| -self.data[i])
    }
}

impl<const N: usize, T: Numeric> Mul<T> for Vector<N, T> {
    type Output = Self;

    #[inline]
    fn mul(self, scalar: T) -> Self {
        self.scale(scalar)
    }
}

impl<const N: usize, T: Numeric> Div<T> for Vector<N, T> {
    type Output = Self;

    #[inline]
    fn div(self, scalar: T) -> Self {
        Self::from_fn(|i| self.data[i].safe_div(scalar))
    }
}

impl<T: Numeric> Vector<3, T> {
    /// The cross product `self × rhs`, available only for 3-D vectors.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let x = Vector::new([1.0, 0.0, 0.0]);
    /// let y = Vector::new([0.0, 1.0, 0.0]);
    /// assert_eq!(x.cross(y), Vector::new([0.0, 0.0, 1.0]));
    /// ```
    #[inline]
    pub fn cross(self, rhs: Self) -> Self {
        let [ax, ay, az] = self.data;
        let [bx, by, bz] = rhs.data;
        Vector::new([ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx])
    }

    /// The scalar triple product `self · (b × c)`: the signed volume spanned by the three vectors.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let x = Vector::new([1.0, 0.0, 0.0]);
    /// let y = Vector::new([0.0, 1.0, 0.0]);
    /// let z = Vector::new([0.0, 0.0, 1.0]);
    /// assert_eq!(x.scalar_triple(y, z), 1.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn scalar_triple(self, b: Self, c: Self) -> T {
        self.dot(b.cross(c))
    }
}

impl<T: Numeric> Vector<2, T> {
    /// The 2-D cross product `self[0] * rhs[1] - self[1] * rhs[0]` — the scalar z-component of the
    /// 3-D cross, available only for 2-D vectors.
    ///
    /// ```
    /// use multicalc::linear_algebra::Vector;
    /// let x = Vector::new([1.0, 0.0]);
    /// let y = Vector::new([0.0, 1.0]);
    /// assert_eq!(x.cross(y), 1.0);
    /// assert_eq!(y.cross(x), -1.0);
    /// ```
    #[inline]
    #[must_use]
    pub fn cross(self, rhs: Self) -> T {
        let [a0, a1] = self.data;
        let [b0, b1] = rhs.data;
        a0 * b1 - a1 * b0
    }
}