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
//! Truncated eigenvalue decomposition
//!
use super::random;
use crate::{
lobpcg::{lobpcg, Lobpcg, LobpcgResult},
Order, Result,
};
use ndarray::prelude::*;
use ndarray::{stack, NdFloat};
use num_traits::NumCast;
use rand::Rng;
use std::iter::Sum;
#[derive(Debug, Clone)]
/// Truncated eigenproblem solver
///
/// This struct wraps the LOBPCG algorithm and provides convenient builder-pattern access to
/// parameter like maximal iteration, precision and constraint matrix. Furthermore it allows
/// conversion into a iterative solver where each iteration step yields a new eigenvalue/vector
/// pair.
///
/// # Example
///
/// ```rust
/// use ndarray::{arr1, Array2};
/// use linfa_linalg::{Order, lobpcg::TruncatedEig};
/// use rand::SeedableRng;
/// use rand_xoshiro::Xoshiro256Plus;
///
/// let diag = arr1(&[1., 2., 3., 4., 5.]);
/// let a = Array2::from_diag(&diag);
///
/// let mut eig = TruncatedEig::new_with_rng(a, Order::Largest, Xoshiro256Plus::seed_from_u64(42))
/// .precision(1e-5)
/// .maxiter(500);
///
/// let res = eig.decompose(3);
/// ```
pub struct TruncatedEig<A: NdFloat, R: Rng> {
order: Order,
problem: Array2<A>,
pub constraints: Option<Array2<A>>,
preconditioner: Option<Array2<A>>,
precision: f32,
maxiter: usize,
rng: R,
}
impl<A: NdFloat + Sum, R: Rng> TruncatedEig<A, R> {
/// Create a new truncated eigenproblem solver
///
/// # Properties
/// * `problem`: problem matrix
/// * `order`: ordering of the eigenvalues with [Order](crate::Order)
/// * `rng`: random number generator
pub fn new_with_rng(problem: Array2<A>, order: Order, rng: R) -> TruncatedEig<A, R> {
TruncatedEig {
precision: 1e-5,
maxiter: problem.len_of(Axis(0)) * 2,
preconditioner: None,
constraints: None,
order,
problem,
rng,
}
}
}
impl<A: NdFloat + Sum, R: Rng> TruncatedEig<A, R> {
/// Set desired precision
///
/// This argument specifies the desired precision, which is passed to the LOBPCG solver. It
/// controls at which point the opimization of each eigenvalue is stopped. The precision is
/// global and applied to all eigenvalues with respect to their L2 norm.
///
/// If the precision can't be reached and the maximum number of iteration is reached, then an
/// error is returned in [LobpcgResult](crate::lobpcg::LobpcgResult).
pub fn precision(mut self, precision: f32) -> Self {
self.precision = precision;
self
}
/// Set the maximal number of iterations
///
/// The LOBPCG is an iterative approach to eigenproblems and stops when this maximum
/// number of iterations are reached.
pub fn maxiter(mut self, maxiter: usize) -> Self {
self.maxiter = maxiter;
self
}
/// Construct a solution, which is orthogonal to this
///
/// If a number of eigenvectors are already known, then this function can be used to construct
/// a orthogonal subspace. Also used with an iterative approach.
pub fn orthogonal_to(mut self, constraints: Array2<A>) -> Self {
self.constraints = Some(constraints);
self
}
/// Apply a preconditioner
///
/// A preconditioning matrix can speed up the solving process by improving the spectral
/// distribution of the eigenvalues. It requires prior knowledge of the problem.
pub fn precondition_with(mut self, preconditioner: Array2<A>) -> Self {
self.preconditioner = Some(preconditioner);
self
}
/// Calculate the eigenvalue decomposition
///
/// # Parameters
///
/// * `num`: number of eigenvalues ordered by magnitude
///
/// # Example
///
/// ```rust
/// use ndarray::{arr1, Array2};
/// use linfa_linalg::{Order, lobpcg::TruncatedEig};
/// use rand::SeedableRng;
/// use rand_xoshiro::Xoshiro256Plus;
///
/// let diag = arr1(&[1., 2., 3., 4., 5.]);
/// let a = Array2::from_diag(&diag);
///
/// let mut eig = TruncatedEig::new_with_rng(a, Order::Largest, Xoshiro256Plus::seed_from_u64(42))
/// .precision(1e-5)
/// .maxiter(500);
///
/// let res = eig.decompose(3);
/// ```
pub fn decompose(&mut self, num: usize) -> LobpcgResult<A> {
if num == 0 {
// return empty solution if requested eigenvalue number is zero
return Ok(Lobpcg {
eigvals: Array1::zeros(0),
eigvecs: Array2::zeros((0, 0)),
rnorm: Vec::new(),
});
}
let x: Array2<f64> = random((self.problem.len_of(Axis(0)), num), &mut self.rng);
let x = x.mapv(|x| NumCast::from(x).unwrap());
if let Some(ref preconditioner) = self.preconditioner {
lobpcg(
|y| self.problem.dot(&y),
x,
|mut y| y.assign(&preconditioner.dot(&y)),
self.constraints.as_ref().map(|x| x.view()),
self.precision,
self.maxiter,
self.order,
)
} else {
lobpcg(
|y| self.problem.dot(&y),
x,
|_| {},
self.constraints.as_ref().map(|x| x.view()),
self.precision,
self.maxiter,
self.order,
)
}
}
}
impl<A: NdFloat + Sum, R: Rng> IntoIterator for TruncatedEig<A, R> {
type Item = (Array1<A>, Array2<A>);
type IntoIter = TruncatedEigIterator<A, R>;
fn into_iter(self) -> TruncatedEigIterator<A, R> {
TruncatedEigIterator {
step_size: 1,
remaining: self.problem.len_of(Axis(0)),
eig: self,
}
}
}
impl<A: NdFloat + Sum, R: Rng> TruncatedEig<A, R> {
pub fn into_iter_step_size(self, step_size: usize) -> Result<TruncatedEigIterator<A, R>> {
TruncatedEigIterator::new(self, step_size)
}
}
/// Truncated eigenproblem iterator
///
/// This wraps a truncated eigenproblem and provides an iterator where each step yields a new
/// eigenvalue/vector pair. Useful for generating pairs until a certain condition is met.
///
/// # Example
///
/// ```rust
/// use ndarray::{arr1, Array2};
/// use linfa_linalg::{Order, lobpcg::TruncatedEig};
/// use rand::SeedableRng;
/// use rand_xoshiro::Xoshiro256Plus;
///
/// let diag = arr1(&[1., 2., 3., 4., 5.]);
/// let a = Array2::from_diag(&diag);
///
/// let teig = TruncatedEig::new_with_rng(a, Order::Largest, Xoshiro256Plus::seed_from_u64(42))
/// .precision(1e-5)
/// .maxiter(500);
///
/// // solve eigenproblem until eigenvalues get smaller than 0.5
/// let res = teig.into_iter()
/// .take_while(|x| x.0[0] > 0.5)
/// .flat_map(|x| x.0.to_vec())
/// .collect::<Vec<_>>();
/// ```
pub struct TruncatedEigIterator<A: NdFloat, R: Rng> {
step_size: usize,
remaining: usize,
eig: TruncatedEig<A, R>,
}
impl<A: NdFloat + Sum, R: Rng> TruncatedEigIterator<A, R> {
pub fn new(obj: TruncatedEig<A, R>, step_size: usize) -> Result<TruncatedEigIterator<A, R>> {
if step_size < 1 {
panic!("Step size should be larger than zero");
}
Ok(TruncatedEigIterator {
remaining: obj.problem.len_of(Axis(0)),
eig: obj,
step_size,
})
}
}
impl<A: NdFloat + Sum, R: Rng> Iterator for TruncatedEigIterator<A, R> {
type Item = (Array1<A>, Array2<A>);
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
return None;
}
let step_size = usize::min(self.step_size, self.remaining);
let res = self.eig.decompose(step_size);
match res {
Ok(Lobpcg {
eigvals,
eigvecs,
rnorm,
})
| Err((
_,
Some(Lobpcg {
eigvals,
eigvecs,
rnorm,
}),
)) => {
// abort if any eigenproblem did not converge
for r_norm in rnorm {
if r_norm > NumCast::from(0.1).unwrap() {
return None;
}
}
// add the new eigenvector to the internal constrain matrix
let new_constraints = if let Some(ref constraints) = self.eig.constraints {
let eigvecs_arr: Vec<_> = constraints
.columns()
.into_iter()
.chain(eigvecs.columns().into_iter())
.collect();
stack(Axis(1), &eigvecs_arr).unwrap()
} else {
eigvecs.clone()
};
self.eig.constraints = Some(new_constraints);
self.remaining -= step_size;
Some((eigvals, eigvecs))
}
Err((_, _)) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::Order;
use super::TruncatedEig;
use ndarray::{arr1, Array2};
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256Plus;
#[test]
fn test_truncated_eig() {
let diag = arr1(&[
1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
20.,
]);
let a = Array2::from_diag(&diag);
let teig = TruncatedEig::new_with_rng(a, Order::Largest, Xoshiro256Plus::seed_from_u64(42))
.precision(1e-5)
.maxiter(500);
let res = teig.into_iter().take(3).flat_map(|x| x.0.to_vec());
let ground_truth = vec![20., 19., 18.];
assert!(
ground_truth
.into_iter()
.zip(res)
.map(|(x, y)| (x - y) * (x - y))
.sum::<f64>()
< 0.01
);
}
}