Debian Codegraph @

debian/missing-sources/nalgebra/src/third_party/alga/alga_matrix.rs

raw
1 #[cfg(all(feature = "alloc", not(feature = "std")))]
2 use alloc::vec::Vec;
3
4 use num::{One, Zero};
5
6 use alga::general::{
7 AbstractGroup, AbstractGroupAbelian, AbstractLoop, AbstractMagma, AbstractModule,
8 AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, Additive, ClosedAdd, ClosedMul,
9 ClosedNeg, ComplexField, Field, Identity, JoinSemilattice, Lattice, MeetSemilattice, Module,
10 Multiplicative, RingCommutative, TwoSidedInverse,
11 };
12 use alga::linear::{
13 FiniteDimInnerSpace, FiniteDimVectorSpace, InnerSpace, NormedSpace, VectorSpace,
14 };
15
16 use crate::base::allocator::Allocator;
17 use crate::base::dimension::{Dim, DimName};
18 use crate::base::storage::{RawStorage, RawStorageMut};
19 use crate::base::{DefaultAllocator, Matrix, OMatrix, Scalar};
20 use std::mem::MaybeUninit;
21
22 /*
23 *
24 * Additive structures.
25 *
26 */
27 impl<T, R: DimName, C: DimName> Identity<Additive> for OMatrix<T, R, C>
28 where
29 T: Scalar + Zero,
30 DefaultAllocator: Allocator<R, C>,
31 {
32 #[inline]
33 fn identity() -> Self {
34 Self::from_element(T::zero())
35 }
36 }
37
38 impl<T, R: DimName, C: DimName> AbstractMagma<Additive> for OMatrix<T, R, C>
39 where
40 T: Scalar + ClosedAdd,
41 DefaultAllocator: Allocator<R, C>,
42 {
43 #[inline]
44 fn operate(&self, other: &Self) -> Self {
45 self + other
46 }
47 }
48
49 impl<T, R: DimName, C: DimName> TwoSidedInverse<Additive> for OMatrix<T, R, C>
50 where
51 T: Scalar + ClosedNeg,
52 DefaultAllocator: Allocator<R, C>,
53 {
54 #[inline]
55 fn two_sided_inverse(&self) -> Self {
56 -self
57 }
58
59 #[inline]
60 fn two_sided_inverse_mut(&mut self) {
61 *self = -self.clone()
62 }
63 }
64
65 macro_rules! inherit_additive_structure(
66 ($($marker: ident<$operator: ident> $(+ $bounds: ident)*),* $(,)*) => {$(
67 impl<T, R: DimName, C: DimName> $marker<$operator> for OMatrix<T, R, C>
68 where T: Scalar + $marker<$operator> $(+ $bounds)*,
69 DefaultAllocator: Allocator<R, C> { }
70 )*}
71 );
72
73 inherit_additive_structure!(
74 AbstractSemigroup<Additive> + ClosedAdd,
75 AbstractMonoid<Additive> + Zero + ClosedAdd,
76 AbstractQuasigroup<Additive> + ClosedAdd + ClosedNeg,
77 AbstractLoop<Additive> + Zero + ClosedAdd + ClosedNeg,
78 AbstractGroup<Additive> + Zero + ClosedAdd + ClosedNeg,
79 AbstractGroupAbelian<Additive> + Zero + ClosedAdd + ClosedNeg
80 );
81
82 impl<T, R: DimName, C: DimName> AbstractModule for OMatrix<T, R, C>
83 where
84 T: Scalar + RingCommutative,
85 DefaultAllocator: Allocator<R, C>,
86 {
87 type AbstractRing = T;
88
89 #[inline]
90 fn multiply_by(&self, n: T) -> Self {
91 self * n
92 }
93 }
94
95 impl<T, R: DimName, C: DimName> Module for OMatrix<T, R, C>
96 where
97 T: Scalar + RingCommutative,
98 DefaultAllocator: Allocator<R, C>,
99 {
100 type Ring = T;
101 }
102
103 impl<T, R: DimName, C: DimName> VectorSpace for OMatrix<T, R, C>
104 where
105 T: Scalar + Field,
106 DefaultAllocator: Allocator<R, C>,
107 {
108 type Field = T;
109 }
110
111 impl<T, R: DimName, C: DimName> FiniteDimVectorSpace for OMatrix<T, R, C>
112 where
113 T: Scalar + Field,
114 DefaultAllocator: Allocator<R, C>,
115 {
116 #[inline]
117 fn dimension() -> usize {
118 R::DIM * C::DIM
119 }
120
121 #[inline]
122 fn canonical_basis_element(i: usize) -> Self {
123 assert!(i < Self::dimension(), "Index out of bound.");
124
125 let mut res = Self::zero();
126 unsafe {
127 *res.data.get_unchecked_linear_mut(i) = T::one();
128 }
129
130 res
131 }
132
133 #[inline]
134 fn dot(&self, other: &Self) -> T {
135 self.dot(other)
136 }
137
138 #[inline]
139 unsafe fn component_unchecked(&self, i: usize) -> &T {
140 unsafe { self.data.get_unchecked_linear(i) }
141 }
142
143 #[inline]
144 unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut T {
145 unsafe { self.data.get_unchecked_linear_mut(i) }
146 }
147 }
148
149 impl<
150 T: ComplexField + simba::scalar::ComplexField<RealField = <T as ComplexField>::RealField>,
151 R: DimName,
152 C: DimName,
153 > NormedSpace for OMatrix<T, R, C>
154 where
155 <T as ComplexField>::RealField: simba::scalar::RealField,
156 DefaultAllocator: Allocator<R, C>,
157 {
158 type RealField = <T as ComplexField>::RealField;
159 type ComplexField = T;
160
161 #[inline]
162 fn norm_squared(&self) -> <T as ComplexField>::RealField {
163 self.norm_squared()
164 }
165
166 #[inline]
167 fn norm(&self) -> <T as ComplexField>::RealField {
168 self.norm()
169 }
170
171 #[inline]
172 fn normalize(&self) -> Self {
173 self.normalize()
174 }
175
176 #[inline]
177 fn normalize_mut(&mut self) -> <T as ComplexField>::RealField {
178 self.normalize_mut()
179 }
180
181 #[inline]
182 fn try_normalize(&self, min_norm: <T as ComplexField>::RealField) -> Option<Self> {
183 self.try_normalize(min_norm)
184 }
185
186 #[inline]
187 fn try_normalize_mut(
188 &mut self,
189 min_norm: <T as ComplexField>::RealField,
190 ) -> Option<<T as ComplexField>::RealField> {
191 self.try_normalize_mut(min_norm)
192 }
193 }
194
195 impl<
196 T: ComplexField + simba::scalar::ComplexField<RealField = <T as ComplexField>::RealField>,
197 R: DimName,
198 C: DimName,
199 > InnerSpace for OMatrix<T, R, C>
200 where
201 <T as ComplexField>::RealField: simba::scalar::RealField,
202 DefaultAllocator: Allocator<R, C>,
203 {
204 #[inline]
205 fn angle(&self, other: &Self) -> <T as ComplexField>::RealField {
206 self.angle(other)
207 }
208
209 #[inline]
210 fn inner_product(&self, other: &Self) -> T {
211 self.dotc(other)
212 }
213 }
214
215 // TODO: specialization will greatly simplify this implementation in the future.
216 // In particular:
217 // − use `x()` instead of `::canonical_basis_element`
218 // − use `::new(x, y, z)` instead of `::from_slice`
219 impl<
220 T: ComplexField + simba::scalar::ComplexField<RealField = <T as ComplexField>::RealField>,
221 R: DimName,
222 C: DimName,
223 > FiniteDimInnerSpace for OMatrix<T, R, C>
224 where
225 <T as ComplexField>::RealField: simba::scalar::RealField,
226 DefaultAllocator: Allocator<R, C>,
227 {
228 #[inline]
229 fn orthonormalize(vs: &mut [Self]) -> usize {
230 let mut nbasis_elements = 0;
231
232 for i in 0..vs.len() {
233 {
234 let (elt, basis) = vs[..i + 1].split_last_mut().unwrap();
235
236 for basis_element in &basis[..nbasis_elements] {
237 *elt -= &*basis_element * elt.dot(basis_element)
238 }
239 }
240
241 if vs[i]
242 .try_normalize_mut(<T as ComplexField>::RealField::zero())
243 .is_some()
244 {
245 // TODO: this will be efficient on dynamically-allocated vectors but for
246 // statically-allocated ones, `.clone_from` would be better.
247 vs.swap(nbasis_elements, i);
248 nbasis_elements += 1;
249
250 // All the other vectors will be dependent.
251 if nbasis_elements == Self::dimension() {
252 break;
253 }
254 }
255 }
256
257 nbasis_elements
258 }
259
260 #[inline]
261 fn orthonormal_subspace_basis<F>(vs: &[Self], mut f: F)
262 where
263 F: FnMut(&Self) -> bool,
264 {
265 // TODO: is this necessary?
266 assert!(
267 vs.len() <= Self::dimension(),
268 "The given set of vectors has no chance of being a free family."
269 );
270
271 match Self::dimension() {
272 1 => {
273 if vs.is_empty() {
274 let _ = f(&Self::canonical_basis_element(0));
275 }
276 }
277 2 => {
278 if vs.is_empty() {
279 let _ = f(&Self::canonical_basis_element(0))
280 && f(&Self::canonical_basis_element(1));
281 } else if vs.len() == 1 {
282 let v = &vs[0];
283 let res = Self::from_column_slice(&[-v[1], v[0]]);
284
285 let _ = f(&res.normalize());
286 }
287
288 // Otherwise, nothing.
289 }
290 3 => {
291 if vs.is_empty() {
292 let _ = f(&Self::canonical_basis_element(0))
293 && f(&Self::canonical_basis_element(1))
294 && f(&Self::canonical_basis_element(2));
295 } else if vs.len() == 1 {
296 let v = &vs[0];
297 let mut a;
298
299 if ComplexField::norm1(v[0]) > ComplexField::norm1(v[1]) {
300 a = Self::from_column_slice(&[v[2], T::zero(), -v[0]]);
301 } else {
302 a = Self::from_column_slice(&[T::zero(), -v[2], v[1]]);
303 };
304
305 let _ = a.normalize_mut();
306
307 if f(&a.cross(v)) {
308 let _ = f(&a);
309 }
310 } else if vs.len() == 2 {
311 let _ = f(&vs[0].cross(&vs[1]).normalize());
312 }
313 }
314 _ => {
315 #[cfg(any(feature = "std", feature = "alloc"))]
316 {
317 // XXX: use a GenericArray instead.
318 let mut known_basis = Vec::new();
319
320 for v in vs.iter() {
321 known_basis.push(v.normalize())
322 }
323
324 for i in 0..Self::dimension() - vs.len() {
325 let mut elt = Self::canonical_basis_element(i);
326
327 for v in &known_basis {
328 elt -= v * elt.dot(v)
329 }
330
331 if let Some(subsp_elt) =
332 elt.try_normalize(<T as ComplexField>::RealField::zero())
333 {
334 if !f(&subsp_elt) {
335 return;
336 };
337
338 known_basis.push(subsp_elt);
339 }
340 }
341 }
342 #[cfg(all(not(feature = "std"), not(feature = "alloc")))]
343 {
344 panic!(
345 "Cannot compute the orthogonal subspace basis of a vector with a dimension greater than 3 \
346 if #![no_std] is enabled and the 'alloc' feature is not enabled."
347 )
348 }
349 }
350 }
351 }
352 }
353
354 /*
355 *
356 *
357 * Multiplicative structures.
358 *
359 *
360 */
361 impl<T, D: DimName> Identity<Multiplicative> for OMatrix<T, D, D>
362 where
363 T: Scalar + Zero + One,
364 DefaultAllocator: Allocator<D, D>,
365 {
366 #[inline]
367 fn identity() -> Self {
368 Self::identity()
369 }
370 }
371
372 impl<T, D: DimName> AbstractMagma<Multiplicative> for OMatrix<T, D, D>
373 where
374 T: Scalar + Zero + One + ClosedAdd + ClosedMul,
375 DefaultAllocator: Allocator<D, D>,
376 {
377 #[inline]
378 fn operate(&self, other: &Self) -> Self {
379 self * other
380 }
381 }
382
383 macro_rules! impl_multiplicative_structure(
384 ($($marker: ident<$operator: ident> $(+ $bounds: ident)*),* $(,)*) => {$(
385 impl<T, D: DimName> $marker<$operator> for OMatrix<T, D, D>
386 where T: Scalar + Zero + One + ClosedAdd + ClosedMul + $marker<$operator> $(+ $bounds)*,
387 DefaultAllocator: Allocator<D, D> { }
388 )*}
389 );
390
391 impl_multiplicative_structure!(
392 AbstractSemigroup<Multiplicative>,
393 AbstractMonoid<Multiplicative> + One
394 );
395
396 /*
397 *
398 * Ordering
399 *
400 */
401 impl<T, R: Dim, C: Dim> MeetSemilattice for OMatrix<T, R, C>
402 where
403 T: Scalar + MeetSemilattice,
404 DefaultAllocator: Allocator<R, C>,
405 {
406 #[inline]
407 fn meet(&self, other: &Self) -> Self {
408 self.zip_map(other, |a, b| a.meet(&b))
409 }
410 }
411
412 impl<T, R: Dim, C: Dim> JoinSemilattice for OMatrix<T, R, C>
413 where
414 T: Scalar + JoinSemilattice,
415 DefaultAllocator: Allocator<R, C>,
416 {
417 #[inline]
418 fn join(&self, other: &Self) -> Self {
419 self.zip_map(other, |a, b| a.join(&b))
420 }
421 }
422
423 impl<T, R: Dim, C: Dim> Lattice for OMatrix<T, R, C>
424 where
425 T: Scalar + Lattice,
426 DefaultAllocator: Allocator<R, C>,
427 {
428 #[inline]
429 fn meet_join(&self, other: &Self) -> (Self, Self) {
430 let shape = self.shape_generic();
431 assert!(
432 shape == other.shape_generic(),
433 "Matrix meet/join error: mismatched dimensions."
434 );
435
436 let mut mres = Matrix::uninit(shape.0, shape.1);
437 let mut jres = Matrix::uninit(shape.0, shape.1);
438
439 for i in 0..shape.0.value() * shape.1.value() {
440 unsafe {
441 let mj = self
442 .data
443 .get_unchecked_linear(i)
444 .meet_join(other.data.get_unchecked_linear(i));
445 *mres.data.get_unchecked_linear_mut(i) = MaybeUninit::new(mj.0);
446 *jres.data.get_unchecked_linear_mut(i) = MaybeUninit::new(mj.1);
447 }
448 }
449
450 // Safety: both mres and jres are now completely initialized.
451 unsafe { (mres.assume_init(), jres.assume_init()) }
452 }
453 }