| 1 |
#[cfg(feature = "arbitrary")] |
| 2 |
use crate::base::storage::Owned; |
| 3 |
#[cfg(feature = "arbitrary")] |
| 4 |
use quickcheck::{Arbitrary, Gen}; |
| 5 |
|
| 6 |
use crate::base::Scalar; |
| 7 |
use crate::base::allocator::Allocator; |
| 8 |
use crate::base::dimension::{Dim, Dyn}; |
| 9 |
use crate::base::{DefaultAllocator, OMatrix}; |
| 10 |
use crate::linalg::givens::GivensRotation; |
| 11 |
use simba::scalar::ComplexField; |
| 12 |
|
| 13 |
/// A random orthogonal matrix. |
| 14 |
#[derive(Clone, Debug)] |
| 15 |
pub struct RandomOrthogonal<T: Scalar, D: Dim = Dyn> |
| 16 |
where |
| 17 |
DefaultAllocator: Allocator<D, D>, |
| 18 |
{ |
| 19 |
m: OMatrix<T, D, D>, |
| 20 |
} |
| 21 |
|
| 22 |
impl<T: ComplexField, D: Dim> RandomOrthogonal<T, D> |
| 23 |
where |
| 24 |
DefaultAllocator: Allocator<D, D>, |
| 25 |
{ |
| 26 |
/// Retrieve the generated matrix. |
| 27 |
pub fn unwrap(self) -> OMatrix<T, D, D> { |
| 28 |
self.m |
| 29 |
} |
| 30 |
|
| 31 |
/// Creates a new random orthogonal matrix from its dimension and a random reals generators. |
| 32 |
pub fn new<Rand: FnMut() -> T>(dim: D, mut rand: Rand) -> Self { |
| 33 |
let mut res = OMatrix::identity_generic(dim, dim); |
| 34 |
|
| 35 |
// Create an orthogonal matrix by composing random Givens rotations rotations. |
| 36 |
for i in 0..dim.value() - 1 { |
| 37 |
let rot = GivensRotation::new(rand(), rand()).0; |
| 38 |
rot.rotate(&mut res.fixed_rows_mut::<2>(i)); |
| 39 |
} |
| 40 |
|
| 41 |
RandomOrthogonal { m: res } |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
#[cfg(feature = "arbitrary")] |
| 46 |
impl<T: ComplexField + Arbitrary + Send, D: Dim> Arbitrary for RandomOrthogonal<T, D> |
| 47 |
where |
| 48 |
DefaultAllocator: Allocator<D, D>, |
| 49 |
Owned<T, D, D>: Clone + Send, |
| 50 |
{ |
| 51 |
fn arbitrary(g: &mut Gen) -> Self { |
| 52 |
let dim = D::try_to_usize().unwrap_or(1 + usize::arbitrary(g) % 50); |
| 53 |
Self::new(D::from_usize(dim), || T::arbitrary(g)) |
| 54 |
} |
| 55 |
} |