use num_traits::Zero;
use nalgebra::ComplexField;
use nalgebra::allocator::Allocator;
use nalgebra::base::{Const, DefaultAllocator, Matrix, OMatrix, OVector, Unit};
use nalgebra::dimension::{Dim, DimMin, DimMinimum};
use nalgebra::geometry::Reflection;
use nalgebra::linalg::{PermutationSequence, householder};
use std::mem::MaybeUninit;
#[derive(Clone, Debug)]
pub struct ColPivQR<T: ComplexField, R: DimMin<C>, C: Dim>
where
DefaultAllocator: Allocator<R, C> + Allocator<DimMinimum<R, C>>,
{
col_piv_qr: OMatrix<T, R, C>,
p: PermutationSequence<DimMinimum<R, C>>,
diag: OVector<T, DimMinimum<R, C>>,
}
impl<T: ComplexField, R: DimMin<C>, C: Dim> Copy for ColPivQR<T, R, C>
where
DefaultAllocator: Allocator<R, C> + Allocator<DimMinimum<R, C>>,
OMatrix<T, R, C>: Copy,
PermutationSequence<DimMinimum<R, C>>: Copy,
OVector<T, DimMinimum<R, C>>: Copy,
{
}
impl<T: ComplexField, R: DimMin<C>, C: Dim> ColPivQR<T, R, C>
where
DefaultAllocator: Allocator<R, C> + Allocator<R> + Allocator<DimMinimum<R, C>>,
{
pub fn new_with_rtol(mut matrix: OMatrix<T, R, C>, rtol: Option<T::RealField>) -> Self
where
T: ComplexField,
{
let (nrows, ncols) = matrix.shape_generic();
let min_nrows_ncols = nrows.min(ncols);
let mut p = PermutationSequence::identity_generic(min_nrows_ncols);
if min_nrows_ncols.value() == 0 {
return ColPivQR {
col_piv_qr: matrix,
p,
diag: Matrix::zeros_generic(min_nrows_ncols, Const::<1>),
};
}
let mut diag = Matrix::uninit(min_nrows_ncols, Const::<1>);
let mut first_diag_abs = None;
for i in 0..min_nrows_ncols.value() {
let piv = matrix.view_range(i.., i..).icamax_full();
let col_piv = piv.1 + i;
matrix.swap_columns(i, col_piv);
p.append_permutation(i, col_piv);
let diag_value = householder::clear_column_unchecked(&mut matrix, i, 0, None);
let diag_abs = diag_value.clone().modulus();
if i == 0 {
first_diag_abs = Some(diag_abs.clone());
}
if let Some(ref rtol_val) = rtol {
if let Some(ref first_abs) = first_diag_abs {
if diag_abs < rtol_val.clone() * first_abs.clone() {
for j in i..min_nrows_ncols.value() {
diag[j] = MaybeUninit::new(T::zero());
}
break;
}
}
}
diag[i] = MaybeUninit::new(diag_value);
}
let diag = unsafe { diag.assume_init() };
ColPivQR {
col_piv_qr: matrix,
p,
diag,
}
}
#[inline]
#[must_use]
pub fn r(&self) -> OMatrix<T, DimMinimum<R, C>, C>
where
DefaultAllocator: Allocator<DimMinimum<R, C>, C>,
{
let (nrows, ncols) = self.col_piv_qr.shape_generic();
let mut res = self
.col_piv_qr
.rows_generic(0, nrows.min(ncols))
.upper_triangle();
res.set_partial_diagonal(self.diag.iter().map(|e| T::from_real(e.clone().modulus())));
res
}
#[must_use]
pub fn q(&self) -> OMatrix<T, R, DimMinimum<R, C>>
where
DefaultAllocator: Allocator<R, DimMinimum<R, C>>,
{
let (nrows, ncols) = self.col_piv_qr.shape_generic();
let mut res = Matrix::identity_generic(nrows, nrows.min(ncols));
let dim = self.diag.len();
let mut effective_rank = dim;
for i in 0..dim {
if self.diag[i].is_zero() {
effective_rank = i;
break;
}
}
for i in (0..effective_rank).rev() {
let axis = self.col_piv_qr.view_range(i.., i);
let refl = Reflection::new(Unit::new_unchecked(axis), T::zero());
let mut res_rows = res.view_range_mut(i.., i..);
refl.reflect_with_sign(&mut res_rows, self.diag[i].clone().signum());
}
if effective_rank < dim {
for j in effective_rank..dim {
res.column_mut(j).fill(T::zero());
}
}
res
}
#[inline]
#[must_use]
pub const fn p(&self) -> &PermutationSequence<DimMinimum<R, C>> {
&self.p
}
#[must_use]
#[allow(dead_code)] pub(crate) const fn diag_internal(&self) -> &OVector<T, DimMinimum<R, C>> {
&self.diag
}
#[allow(dead_code)] pub fn rank(&self) -> usize {
let dim = self.diag.len();
if dim == 0 {
return 0;
}
let first_diag_abs = self.diag[0].clone().modulus();
if first_diag_abs.is_zero() {
return 0;
}
let mut rank = 0;
for i in 0..dim {
let diag_abs = self.diag[i].clone().modulus();
if diag_abs.is_zero() {
break;
}
rank += 1;
}
rank
}
#[allow(dead_code)] pub fn rank_with_rtol(&self, rtol: T::RealField) -> usize
where
T: ComplexField,
{
let dim = self.diag.len();
if dim == 0 {
return 0;
}
let first_diag_abs = self.diag[0].clone().modulus();
if first_diag_abs.is_zero() {
return 0;
}
let threshold = rtol * first_diag_abs;
let mut rank = 0;
for i in 0..dim {
let diag_abs = self.diag[i].clone().modulus();
if diag_abs < threshold {
break;
}
rank += 1;
}
rank
}
}
#[cfg(test)]
mod tests {
use super::*;
use nalgebra::{DMatrix, Dyn};
fn create_hilbert_matrix(nrows: usize, ncols: usize) -> DMatrix<f64> {
DMatrix::from_fn(nrows, ncols, |i, j| 1.0 / ((i + j + 1) as f64))
}
fn reconstruct_matrix_from_col_piv_qr(
q: &DMatrix<f64>,
r: &DMatrix<f64>,
p: &nalgebra::linalg::PermutationSequence<Dyn>,
) -> DMatrix<f64> {
let qr = q * r;
let mut result = qr.clone();
p.inv_permute_columns(&mut result);
result
}
fn frobenius_norm(matrix: &DMatrix<f64>) -> f64 {
let mut sum = 0.0;
for i in 0..matrix.nrows() {
for j in 0..matrix.ncols() {
let val = matrix[(i, j)];
sum += val * val;
}
}
sum.sqrt()
}
#[test]
fn test_col_piv_qr_hilbert_with_rtol() {
let rtol = 1e-10;
test_hilbert_matrix_with_rtol(20, 20, rtol, "20x20");
test_hilbert_matrix_with_rtol(20, 30, rtol, "20x30");
test_hilbert_matrix_with_rtol(30, 20, rtol, "30x20");
}
fn test_hilbert_matrix_with_rtol(nrows: usize, ncols: usize, rtol: f64, label: &str) {
let h = create_hilbert_matrix(nrows, ncols);
let min_dim = nrows.min(ncols);
println!("\n=== Testing Hilbert {}x{} ({}) ===", nrows, ncols, label);
let qr_with_rtol = ColPivQR::new_with_rtol(h.clone(), Some(rtol));
let qr_without_rtol = ColPivQR::new_with_rtol(h.clone(), None);
let rank_with_rtol = qr_with_rtol.rank_with_rtol(rtol);
let rank_without_rtol = qr_without_rtol.rank();
println!(
"Hilbert {}x{} ({}): rank with rtol={} is {}, without rtol is {}",
nrows, ncols, label, rtol, rank_with_rtol, rank_without_rtol
);
assert!(
rank_with_rtol <= rank_without_rtol,
"Early termination rank {} should be <= full rank {}",
rank_with_rtol,
rank_without_rtol
);
assert!(
rank_with_rtol < min_dim,
"Early termination should reduce rank for ill-conditioned matrix"
);
let diag = qr_with_rtol.diag_internal();
let first_diag_abs = diag[0].clone().modulus();
let threshold = rtol * first_diag_abs;
println!("First diagonal element abs: {}", first_diag_abs);
println!("Threshold (rtol * first_diag_abs): {}", threshold);
for i in 0..rank_with_rtol {
let diag_abs = diag[i].clone().modulus();
assert!(
diag_abs >= threshold,
"Diagonal element [{}] abs={} should be >= threshold {}",
i,
diag_abs,
threshold
);
}
if rank_with_rtol < diag.len() {
let diag_abs_at_rank = diag[rank_with_rtol].clone().modulus();
println!(
"Diagonal element [{}] abs={}",
rank_with_rtol, diag_abs_at_rank
);
if diag_abs_at_rank > 0.0 {
assert!(
diag_abs_at_rank < threshold,
"Diagonal element [{}] abs={} should be < threshold {} (early termination check)",
rank_with_rtol,
diag_abs_at_rank,
threshold
);
}
}
let q = qr_with_rtol.q();
let r = qr_with_rtol.r();
let p = qr_with_rtol.p();
if rank_with_rtol < q.ncols() {
println!(
"Checking Q matrix columns after rank {} (total columns: {})",
rank_with_rtol,
q.ncols()
);
for j in rank_with_rtol..q.ncols() {
let q_col = q.column(j);
let col_norm = q_col.norm();
println!("Q column [{}] norm: {}", j, col_norm);
assert!(
col_norm < 1e-12,
"Q column [{}] should be zero after early termination, but norm is {}",
j,
col_norm
);
}
}
let h_reconstructed = reconstruct_matrix_from_col_piv_qr(&q, &r, p);
let h_norm = frobenius_norm(&h);
let error_matrix = &h - &h_reconstructed;
let error_norm = frobenius_norm(&error_matrix);
let relative_error = error_norm / h_norm;
println!(
"Hilbert {}x{} ({}): relative reconstruction error = {}",
nrows, ncols, label, relative_error
);
assert!(
relative_error < 1e-6,
"Relative reconstruction error {} exceeds 1e-6",
relative_error
);
}
#[test]
fn test_col_piv_qr_identity_matrix() {
let matrix = DMatrix::<f64>::identity(5, 5);
let rtol = 1e-10;
let qr = ColPivQR::new_with_rtol(matrix.clone(), Some(rtol));
let rank = qr.rank_with_rtol(rtol);
assert_eq!(rank, 5, "Identity matrix should have full rank");
let q = qr.q();
let r = qr.r();
let p = qr.p();
let reconstructed = reconstruct_matrix_from_col_piv_qr(&q, &r, p);
let error = frobenius_norm(&(&matrix - &reconstructed));
assert!(
error < 1e-12,
"Reconstruction error {} should be small",
error
);
}
}