nalgebra/nalgebra-lapack/src/eigen.rs

493 lines
15 KiB
Rust
Raw Normal View History

#[cfg(feature = "serde-serialize")]
2018-10-22 13:00:10 +08:00
use serde::{Deserialize, Serialize};
use num::Zero;
use num_complex::Complex;
2020-03-21 19:16:46 +08:00
use simba::scalar::RealField;
2020-03-21 19:16:46 +08:00
use crate::ComplexHelper;
use na::allocator::Allocator;
2021-04-12 16:34:44 +08:00
use na::dimension::{Const, Dim};
2021-04-11 17:00:38 +08:00
use na::{DefaultAllocator, Matrix, OMatrix, OVector, Scalar};
use lapack;
/// Eigendecomposition of a real square matrix with real eigenvalues.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde-serialize",
2020-03-21 19:16:46 +08:00
serde(
2021-04-11 17:00:38 +08:00
bound(serialize = "DefaultAllocator: Allocator<T, D, D> + Allocator<T, D>,
OVector<T, D>: Serialize,
OMatrix<T, D, D>: Serialize")
2020-03-21 19:16:46 +08:00
)
)]
#[cfg_attr(
feature = "serde-serialize",
2020-03-21 19:16:46 +08:00
serde(
2021-04-11 17:00:38 +08:00
bound(deserialize = "DefaultAllocator: Allocator<T, D, D> + Allocator<T, D>,
OVector<T, D>: Serialize,
OMatrix<T, D, D>: Deserialize<'de>")
2020-03-21 19:16:46 +08:00
)
)]
#[derive(Clone, Debug)]
pub struct Eigen<T: Scalar, D: Dim>
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
DefaultAllocator: Allocator<T, D> + Allocator<T, D, D>,
2018-02-02 19:26:35 +08:00
{
/// The eigenvalues of the decomposed matrix.
2021-04-11 17:00:38 +08:00
pub eigenvalues: OVector<T, D>,
/// The (right) eigenvectors of the decomposed matrix.
2021-04-11 17:00:38 +08:00
pub eigenvectors: Option<OMatrix<T, D, D>>,
/// The left eigenvectors of the decomposed matrix.
2021-04-11 17:00:38 +08:00
pub left_eigenvectors: Option<OMatrix<T, D, D>>,
}
impl<T: Scalar + Copy, D: Dim> Copy for Eigen<T, D>
2018-02-02 19:26:35 +08:00
where
2021-04-11 17:00:38 +08:00
DefaultAllocator: Allocator<T, D> + Allocator<T, D, D>,
OVector<T, D>: Copy,
OMatrix<T, D, D>: Copy,
2020-03-21 19:16:46 +08:00
{
}
2021-04-11 17:00:38 +08:00
impl<T: EigenScalar + RealField, D: Dim> Eigen<T, D>
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
DefaultAllocator: Allocator<T, D, D> + Allocator<T, D>,
2018-02-02 19:26:35 +08:00
{
/// Computes the eigenvalues and eigenvectors of the square matrix `m`.
///
/// If `eigenvectors` is `false` then, the eigenvectors are not computed explicitly.
2018-02-02 19:26:35 +08:00
pub fn new(
2021-04-11 17:00:38 +08:00
mut m: OMatrix<T, D, D>,
2018-02-02 19:26:35 +08:00
left_eigenvectors: bool,
eigenvectors: bool,
2021-04-11 17:00:38 +08:00
) -> Option<Eigen<T, D>> {
2018-02-02 19:26:35 +08:00
assert!(
m.is_square(),
"Unable to compute the eigenvalue decomposition of a non-square matrix."
);
2022-05-03 03:55:51 +08:00
let ljob = if left_eigenvectors { b'V' } else { b'N' };
let rjob = if eigenvectors { b'V' } else { b'N' };
let (nrows, ncols) = m.shape_generic();
let n = nrows.value();
let lda = n as i32;
2021-08-03 23:39:45 +08:00
// TODO: avoid the initialization?
let mut wr = Matrix::zeros_generic(nrows, Const::<1>);
2020-11-15 23:57:49 +08:00
// TODO: Tap into the workspace.
2021-08-03 23:39:45 +08:00
let mut wi = Matrix::zeros_generic(nrows, Const::<1>);
let mut info = 0;
2021-04-11 17:00:38 +08:00
let mut placeholder1 = [T::zero()];
let mut placeholder2 = [T::zero()];
2018-02-02 19:26:35 +08:00
2021-04-11 17:00:38 +08:00
let lwork = T::xgeev_work_size(
2018-02-02 19:26:35 +08:00
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut placeholder1,
n as i32,
&mut placeholder2,
n as i32,
&mut info,
);
lapack_check!(info);
2021-08-03 23:39:45 +08:00
let mut work = vec![T::zero(); lwork as usize];
match (left_eigenvectors, eigenvectors) {
(true, true) => {
2021-08-03 23:39:45 +08:00
// TODO: avoid the initializations?
let mut vl = Matrix::zeros_generic(nrows, ncols);
let mut vr = Matrix::zeros_generic(nrows, ncols);
2021-04-11 17:00:38 +08:00
T::xgeev(
2018-02-02 19:26:35 +08:00
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut vl.as_mut_slice(),
n as i32,
&mut vr.as_mut_slice(),
n as i32,
&mut work,
lwork,
&mut info,
);
lapack_check!(info);
if wi.iter().all(|e| e.is_zero()) {
return Some(Self {
2018-02-02 19:26:35 +08:00
eigenvalues: wr,
left_eigenvectors: Some(vl),
eigenvectors: Some(vr),
});
}
2018-02-02 19:26:35 +08:00
}
(true, false) => {
2021-08-03 23:39:45 +08:00
// TODO: avoid the initialization?
let mut vl = Matrix::zeros_generic(nrows, ncols);
2021-04-11 17:00:38 +08:00
T::xgeev(
2018-02-02 19:26:35 +08:00
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut vl.as_mut_slice(),
n as i32,
&mut placeholder2,
1 as i32,
&mut work,
lwork,
&mut info,
);
lapack_check!(info);
if wi.iter().all(|e| e.is_zero()) {
return Some(Self {
2018-02-02 19:26:35 +08:00
eigenvalues: wr,
left_eigenvectors: Some(vl),
eigenvectors: None,
});
}
2018-02-02 19:26:35 +08:00
}
(false, true) => {
2021-08-03 23:39:45 +08:00
// TODO: avoid the initialization?
let mut vr = Matrix::zeros_generic(nrows, ncols);
2021-04-11 17:00:38 +08:00
T::xgeev(
2018-02-02 19:26:35 +08:00
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut placeholder1,
1 as i32,
&mut vr.as_mut_slice(),
n as i32,
&mut work,
lwork,
&mut info,
);
lapack_check!(info);
if wi.iter().all(|e| e.is_zero()) {
return Some(Self {
2018-02-02 19:26:35 +08:00
eigenvalues: wr,
left_eigenvectors: None,
eigenvectors: Some(vr),
});
}
2018-02-02 19:26:35 +08:00
}
(false, false) => {
2021-04-11 17:00:38 +08:00
T::xgeev(
2018-02-02 19:26:35 +08:00
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut placeholder1,
1 as i32,
&mut placeholder2,
1 as i32,
&mut work,
lwork,
&mut info,
);
lapack_check!(info);
if wi.iter().all(|e| e.is_zero()) {
return Some(Self {
2018-02-02 19:26:35 +08:00
eigenvalues: wr,
left_eigenvectors: None,
eigenvectors: None,
});
}
}
}
None
}
2022-09-14 01:09:27 +08:00
/// The complex eigen decomposition of the given matrix.
///
/// Panics if the eigenvalue computation does not converge.
2022-09-15 01:07:38 +08:00
pub fn complex_eigen_decomposition(
mut m: OMatrix<T, D, D>,
left_eigenvectors: bool,
eigenvectors: bool,
) -> (
OVector<Complex<T>, D>,
Option<OMatrix<T, D, D>>,
Option<OMatrix<T, D, D>>,
)
2020-04-06 00:49:48 +08:00
where
2022-05-03 03:55:51 +08:00
DefaultAllocator: Allocator<Complex<T>, D> + Allocator<Complex<T>, D, D>,
2020-04-06 00:49:48 +08:00
{
2018-02-02 19:26:35 +08:00
assert!(
m.is_square(),
"Unable to compute the eigenvalue decomposition of a non-square matrix."
);
2022-05-03 03:55:51 +08:00
let ljob = if left_eigenvectors { b'V' } else { b'N' };
let rjob = if eigenvectors { b'V' } else { b'N' };
let (nrows, ncols) = m.shape_generic();
let n = nrows.value();
let lda = n as i32;
2021-08-03 23:39:45 +08:00
// TODO: avoid the initialization?
let mut wr = Matrix::zeros_generic(nrows, Const::<1>);
2022-05-03 03:55:51 +08:00
// TODO: Tap into the workspace.
2021-08-03 23:39:45 +08:00
let mut wi = Matrix::zeros_generic(nrows, Const::<1>);
let mut info = 0;
2021-04-11 17:00:38 +08:00
let mut placeholder1 = [T::zero()];
let mut placeholder2 = [T::zero()];
2018-02-02 19:26:35 +08:00
2021-04-11 17:00:38 +08:00
let lwork = T::xgeev_work_size(
2022-05-03 03:55:51 +08:00
ljob,
rjob,
2018-02-02 19:26:35 +08:00
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut placeholder1,
n as i32,
&mut placeholder2,
n as i32,
&mut info,
);
lapack_panic!(info);
2021-08-03 23:39:45 +08:00
let mut work = vec![T::zero(); lwork as usize];
2022-05-03 03:55:51 +08:00
match (left_eigenvectors, eigenvectors) {
(true, true) => {
// TODO: avoid the initializations?
let mut vl = Matrix::zeros_generic(nrows, ncols);
let mut vr = Matrix::zeros_generic(nrows, ncols);
T::xgeev(
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut vl.as_mut_slice(),
n as i32,
&mut vr.as_mut_slice(),
n as i32,
&mut work,
lwork,
&mut info,
);
lapack_panic!(info);
let mut res = Matrix::zeros_generic(nrows, Const::<1>);
for i in 0..res.len() {
res[i] = Complex::new(wr[i].clone(), wi[i].clone());
}
2022-05-03 04:49:07 +08:00
(res, Some(vl), Some(vr))
2022-05-03 03:55:51 +08:00
}
(true, false) => {
// TODO: avoid the initialization?
let mut vl = Matrix::zeros_generic(nrows, ncols);
T::xgeev(
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut vl.as_mut_slice(),
n as i32,
&mut placeholder2,
1 as i32,
&mut work,
lwork,
&mut info,
);
lapack_panic!(info);
let mut res = Matrix::zeros_generic(nrows, Const::<1>);
for i in 0..res.len() {
res[i] = Complex::new(wr[i].clone(), wi[i].clone());
}
2022-05-03 04:49:07 +08:00
(res, Some(vl), None)
2022-05-03 03:55:51 +08:00
}
(false, true) => {
// TODO: avoid the initialization?
let mut vr = Matrix::zeros_generic(nrows, ncols);
T::xgeev(
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut placeholder1,
1 as i32,
&mut vr.as_mut_slice(),
n as i32,
&mut work,
lwork,
&mut info,
);
lapack_panic!(info);
2022-05-03 03:55:51 +08:00
let mut res = Matrix::zeros_generic(nrows, Const::<1>);
2022-05-03 03:55:51 +08:00
for i in 0..res.len() {
res[i] = Complex::new(wr[i].clone(), wi[i].clone());
}
2022-05-03 04:49:07 +08:00
(res, None, Some(vr))
2022-05-03 03:55:51 +08:00
}
(false, false) => {
T::xgeev(
ljob,
rjob,
n as i32,
m.as_mut_slice(),
lda,
wr.as_mut_slice(),
wi.as_mut_slice(),
&mut placeholder1,
1 as i32,
&mut placeholder2,
1 as i32,
&mut work,
lwork,
&mut info,
);
lapack_panic!(info);
let mut res = Matrix::zeros_generic(nrows, Const::<1>);
for i in 0..res.len() {
res[i] = Complex::new(wr[i].clone(), wi[i].clone());
}
2022-05-03 04:49:07 +08:00
(res, None, None)
2022-05-03 03:55:51 +08:00
}
}
}
/// The determinant of the decomposed matrix.
#[inline]
#[must_use]
2021-04-11 17:00:38 +08:00
pub fn determinant(&self) -> T {
let mut det = T::one();
for e in self.eigenvalues.iter() {
2022-01-02 22:30:05 +08:00
det *= e.clone();
}
det
}
}
/*
*
* Lapack functions dispatch.
*
*/
2018-09-24 12:48:42 +08:00
/// Trait implemented by scalar type for which Lapack function exist to compute the
/// eigendecomposition.
pub trait EigenScalar: Scalar {
#[allow(missing_docs)]
2018-02-02 19:26:35 +08:00
fn xgeev(
jobvl: u8,
jobvr: u8,
n: i32,
a: &mut [Self],
lda: i32,
wr: &mut [Self],
wi: &mut [Self],
vl: &mut [Self],
ldvl: i32,
vr: &mut [Self],
ldvr: i32,
work: &mut [Self],
lwork: i32,
info: &mut i32,
);
#[allow(missing_docs)]
2018-02-02 19:26:35 +08:00
fn xgeev_work_size(
jobvl: u8,
jobvr: u8,
n: i32,
a: &mut [Self],
lda: i32,
wr: &mut [Self],
wi: &mut [Self],
vl: &mut [Self],
ldvl: i32,
vr: &mut [Self],
ldvr: i32,
info: &mut i32,
) -> i32;
}
macro_rules! real_eigensystem_scalar_impl (
($N: ty, $xgeev: path) => (
impl EigenScalar for $N {
#[inline]
fn xgeev(jobvl: u8, jobvr: u8, n: i32, a: &mut [Self], lda: i32,
wr: &mut [Self], wi: &mut [Self],
vl: &mut [Self], ldvl: i32, vr: &mut [Self], ldvr: i32,
work: &mut [Self], lwork: i32, info: &mut i32) {
unsafe { $xgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info) }
}
#[inline]
fn xgeev_work_size(jobvl: u8, jobvr: u8, n: i32, a: &mut [Self], lda: i32,
wr: &mut [Self], wi: &mut [Self], vl: &mut [Self], ldvl: i32,
vr: &mut [Self], ldvr: i32, info: &mut i32) -> i32 {
let mut work = [ Zero::zero() ];
let lwork = -1 as i32;
unsafe { $xgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, &mut work, lwork, info) };
ComplexHelper::real_part(work[0]) as i32
}
}
)
);
real_eigensystem_scalar_impl!(f32, lapack::sgeev);
real_eigensystem_scalar_impl!(f64, lapack::dgeev);
2020-11-15 23:57:49 +08:00
//// TODO: decomposition of complex matrix and matrices with complex eigenvalues.
// eigensystem_complex_impl!(f32, lapack::cgeev);
// eigensystem_complex_impl!(f64, lapack::zgeev);