nalgebra/src/linalg/balancing.rs

85 lines
2.5 KiB
Rust
Raw Normal View History

//! Functions for balancing a matrix.
2020-03-21 19:16:46 +08:00
use simba::scalar::RealField;
use std::ops::{DivAssign, MulAssign};
2019-03-23 21:29:07 +08:00
use crate::allocator::Allocator;
use crate::base::dimension::Dim;
2021-04-11 17:00:38 +08:00
use crate::base::{Const, DefaultAllocator, OMatrix, OVector};
2021-06-18 15:45:37 +08:00
/// Applies in-place a modified Parlett and Reinsch matrix balancing with 2-norm to the matrix and returns
/// the corresponding diagonal transformation.
///
2021-07-28 07:18:29 +08:00
/// See <https://arxiv.org/pdf/1401.5766.pdf>
2021-06-18 15:45:37 +08:00
pub fn balance_parlett_reinsch<T: RealField, D: Dim>(matrix: &mut OMatrix<T, D, D>) -> OVector<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>,
2020-04-06 00:49:48 +08:00
{
2021-06-18 15:45:37 +08:00
assert!(matrix.is_square(), "Unable to balance a non-square matrix.");
let dim = matrix.shape_generic().0;
2021-04-11 17:00:38 +08:00
let radix: T = crate::convert(2.0f64);
let mut d = OVector::from_element_generic(dim, Const::<1>, T::one());
let mut converged = false;
while !converged {
converged = true;
2018-02-02 19:26:35 +08:00
for i in 0..dim.value() {
2021-06-18 15:45:37 +08:00
let mut n_col = matrix.column(i).norm_squared();
let mut n_row = matrix.row(i).norm_squared();
2021-04-11 17:00:38 +08:00
let mut f = T::one();
2021-06-18 15:45:37 +08:00
let s = n_col + n_row;
n_col = n_col.sqrt();
n_row = n_row.sqrt();
2021-06-18 15:45:37 +08:00
if n_col.is_zero() || n_row.is_zero() {
continue;
}
2021-06-18 15:45:37 +08:00
while n_col < n_row / radix {
n_col *= radix;
n_row /= radix;
f *= radix;
}
2021-06-18 15:45:37 +08:00
while n_col >= n_row * radix {
n_col /= radix;
n_row *= radix;
f /= radix;
}
2021-04-11 17:00:38 +08:00
let eps: T = crate::convert(0.95);
2021-06-18 15:45:37 +08:00
#[allow(clippy::suspicious_operation_groupings)]
if n_col * n_col + n_row * n_row < eps * s {
converged = false;
d[i] *= f;
2021-06-18 15:45:37 +08:00
matrix.column_mut(i).mul_assign(f);
matrix.row_mut(i).div_assign(f);
}
}
}
d
}
/// Computes in-place `D * m * D.inverse()`, where `D` is the matrix with diagonal `d`.
2021-04-11 17:00:38 +08:00
pub fn unbalance<T: RealField, D: Dim>(m: &mut OMatrix<T, D, D>, d: &OVector<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>,
2020-04-06 00:49:48 +08:00
{
assert!(m.is_square(), "Unable to unbalance a non-square matrix.");
assert_eq!(m.nrows(), d.len(), "Unbalancing: mismatched dimensions.");
2018-02-02 19:26:35 +08:00
for j in 0..d.len() {
let mut col = m.column_mut(j);
2021-04-11 17:00:38 +08:00
let denom = T::one() / d[j];
2018-02-02 19:26:35 +08:00
for i in 0..d.len() {
col[i] *= d[i] * denom;
}
}
}