nalgebra/src/debug/random_orthogonal.rs

56 lines
1.6 KiB
Rust
Raw Normal View History

#[cfg(feature = "arbitrary")]
2019-03-23 21:29:07 +08:00
use crate::base::storage::Owned;
#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
2019-03-23 21:29:07 +08:00
use crate::base::allocator::Allocator;
2021-04-11 17:00:38 +08:00
use crate::base::dimension::{Dim, Dynamic};
2020-03-21 19:16:46 +08:00
use crate::base::Scalar;
2021-04-11 17:00:38 +08:00
use crate::base::{DefaultAllocator, OMatrix};
2019-03-23 21:29:07 +08:00
use crate::linalg::givens::GivensRotation;
2020-03-21 19:16:46 +08:00
use simba::scalar::ComplexField;
/// A random orthogonal matrix.
#[derive(Clone, Debug)]
2021-04-11 17:00:38 +08:00
pub struct RandomOrthogonal<T: Scalar, D: Dim = Dynamic>
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
DefaultAllocator: Allocator<T, D, D>,
2018-02-02 19:26:35 +08:00
{
2021-04-11 17:00:38 +08:00
m: OMatrix<T, D, D>,
}
2021-04-11 17:00:38 +08:00
impl<T: ComplexField, D: Dim> RandomOrthogonal<T, D>
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
DefaultAllocator: Allocator<T, D, D>,
2018-02-02 19:26:35 +08:00
{
/// Retrieve the generated matrix.
2021-04-11 17:00:38 +08:00
pub fn unwrap(self) -> OMatrix<T, D, D> {
self.m
}
/// Creates a new random orthogonal matrix from its dimension and a random reals generators.
2021-04-11 17:00:38 +08:00
pub fn new<Rand: FnMut() -> T>(dim: D, mut rand: Rand) -> Self {
let mut res = OMatrix::identity_generic(dim, dim);
// Create an orthogonal matrix by composing random Givens rotations rotations.
2018-02-02 19:26:35 +08:00
for i in 0..dim.value() - 1 {
let rot = GivensRotation::new(rand(), rand()).0;
2021-04-11 17:00:38 +08:00
rot.rotate(&mut res.fixed_rows_mut::<2>(i));
}
RandomOrthogonal { m: res }
}
}
#[cfg(feature = "arbitrary")]
2021-04-11 17:00:38 +08:00
impl<T: ComplexField + Arbitrary + Send, D: Dim> Arbitrary for RandomOrthogonal<T, D>
2018-02-02 19:26:35 +08:00
where
2021-04-11 17:00:38 +08:00
DefaultAllocator: Allocator<T, D, D>,
Owned<T, D, D>: Clone + Send,
2018-02-02 19:26:35 +08:00
{
2021-03-01 00:52:14 +08:00
fn arbitrary(g: &mut Gen) -> Self {
let dim = D::try_to_usize().unwrap_or(1 + usize::arbitrary(g) % 50);
2021-04-11 17:00:38 +08:00
Self::new(D::from_usize(dim), || T::arbitrary(g))
}
}