use smallvec::SmallVec;
pub(crate) fn matrix_inversion_f(
mut p_src_matrix: &mut [f32],
mut p_dest_matrix: &mut [f32],
mut nb_compo: usize,
) -> bool {
let mut l_permutations = SmallVec::<[u32; 0]>::with_capacity(nb_compo);
let mut src_tmp = SmallVec::<[f32; 0]>::with_capacity(nb_compo);
let mut dest_tmp = SmallVec::<[f32; 0]>::with_capacity(nb_compo);
let mut swap_area = SmallVec::<[f32; 0]>::with_capacity(nb_compo);
l_permutations.resize(nb_compo, 0);
src_tmp.resize(nb_compo, 0.0);
dest_tmp.resize(nb_compo, 0.0);
swap_area.resize(nb_compo, 0.0);
if !lup_decompose(
p_src_matrix,
l_permutations.as_mut_slice(),
swap_area.as_mut_slice(),
nb_compo,
) {
return false;
}
lup_invert(
p_src_matrix,
p_dest_matrix,
nb_compo,
l_permutations.as_slice(),
src_tmp.as_mut_slice(),
dest_tmp.as_mut_slice(),
swap_area.as_mut_slice(),
);
true
}
fn lup_decompose(
matrix: &mut [f32],
permutations: &mut [u32],
p_swap_area: &mut [f32],
nb_compo: usize,
) -> bool {
if nb_compo == 0 {
return false;
}
let l_last_column = nb_compo - 1;
let mut l_tmp_matrix = 0usize;
let mut offset = 1usize;
let mut l_stride = nb_compo - 1;
for (i, perm) in permutations.iter_mut().enumerate().take(nb_compo) {
*perm = i as u32;
}
for k in 0..l_last_column {
let mut l_column_matrix = l_tmp_matrix + k;
let mut p = 0.0f32;
let mut k2 = k;
for _i in k..nb_compo {
let temp = matrix[l_column_matrix].abs();
if temp > p {
p = temp;
k2 = _i;
}
l_column_matrix += nb_compo;
}
if p == 0.0 {
return false;
}
if k2 != k {
permutations.swap(k, k2);
let row_k = l_tmp_matrix;
let row_k2 = l_tmp_matrix + (k2 - k) * nb_compo;
p_swap_area[..nb_compo].copy_from_slice(&matrix[row_k2..row_k2 + nb_compo]);
matrix.copy_within(row_k..row_k + nb_compo, row_k2);
matrix[row_k..row_k + nb_compo].copy_from_slice(&p_swap_area[..nb_compo]);
}
let mut l_dest_matrix = l_tmp_matrix + k;
let mut l_column_matrix = l_dest_matrix + nb_compo;
let temp = matrix[l_dest_matrix];
l_dest_matrix += 1;
for _ in offset..nb_compo {
let p = matrix[l_column_matrix] / temp;
matrix[l_column_matrix] = p;
l_column_matrix += 1;
for _ in offset..nb_compo {
matrix[l_column_matrix] -= p * matrix[l_dest_matrix];
l_column_matrix += 1;
l_dest_matrix += 1;
}
l_dest_matrix -= l_stride;
l_column_matrix += k;
}
offset += 1;
l_stride -= 1;
l_tmp_matrix += nb_compo;
}
true
}
#[allow(clippy::explicit_counter_loop)]
fn lup_solve(
p_result: &mut [f32],
p_matrix: &[f32],
p_vector: &[f32],
p_permutations: &[u32],
nb_compo: usize,
p_intermediate_data: &mut [f32],
) {
debug_assert!(nb_compo > 0);
let mut l_line_matrix = 0usize;
let mut l_intermediate_ptr = 0usize;
let mut l_current_permutation_ptr = 0usize;
for i in 0..nb_compo {
let mut sum = 0.0f32;
let mut l_tmp_matrix = l_line_matrix;
let mut l_current_ptr = 0usize;
for _ in 1..=i {
sum += p_matrix[l_tmp_matrix] * p_intermediate_data[l_current_ptr];
l_tmp_matrix += 1;
l_current_ptr += 1;
}
p_intermediate_data[l_intermediate_ptr] =
p_vector[p_permutations[l_current_permutation_ptr] as usize] - sum;
l_line_matrix += nb_compo;
l_intermediate_ptr += 1;
l_current_permutation_ptr += 1;
}
for (count, k) in (0..nb_compo).rev().enumerate() {
let l_line_matrix = nb_compo * nb_compo - 1 - count * (nb_compo + 1);
let mut l_tmp_matrix = l_line_matrix;
let u = p_matrix[l_tmp_matrix];
l_tmp_matrix += 1;
let mut l_current_ptr = k + 1;
let mut sum = 0.0f32;
for _ in (k + 1)..nb_compo {
sum += p_matrix[l_tmp_matrix] * p_result[l_current_ptr];
l_tmp_matrix += 1;
l_current_ptr += 1;
}
p_result[k] = (p_intermediate_data[k] - sum) / u;
}
}
fn lup_invert(
p_src_matrix: &mut [f32],
p_dest_matrix: &mut [f32],
nb_compo: usize,
p_permutations: &[u32],
p_src_temp: &mut [f32],
p_dest_temp: &mut [f32],
p_swap_area: &mut [f32],
) {
let nb_compo_usize = nb_compo;
for j in 0..nb_compo {
p_src_temp[..nb_compo_usize].fill(0.0);
p_src_temp[j] = 1.0;
lup_solve(
&mut p_dest_temp[..nb_compo_usize],
&p_src_matrix[..nb_compo_usize * nb_compo_usize],
&p_src_temp[..nb_compo_usize],
&p_permutations[..nb_compo_usize],
nb_compo_usize,
&mut p_swap_area[..nb_compo_usize],
);
for i in 0..nb_compo_usize {
p_dest_matrix[j + i * nb_compo_usize] = p_dest_temp[i];
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn invert(mat: &[f32], n: usize) -> Option<Vec<f32>> {
let mut src = mat.to_vec();
let mut dst = vec![0.0f32; n * n];
let mut permutations = vec![0u32; n];
let mut src_temp = vec![0.0f32; n];
let mut dest_temp = vec![0.0f32; n];
let mut swap_area = vec![0.0f32; n];
if lup_decompose(&mut src, &mut permutations, &mut swap_area, n) {
lup_invert(
&mut src,
&mut dst,
n,
&permutations,
&mut src_temp,
&mut dest_temp,
&mut swap_area,
);
Some(dst)
} else {
None
}
}
fn mat_mul(a: &[f32], b: &[f32], n: usize) -> Vec<f32> {
let mut out = vec![0.0f32; n * n];
for i in 0..n {
for j in 0..n {
let mut acc = 0.0f32;
for k in 0..n {
acc += a[i * n + k] * b[k * n + j];
}
out[i * n + j] = acc;
}
}
out
}
fn approx_identity(m: &[f32], n: usize) -> bool {
for i in 0..n {
for j in 0..n {
let want = if i == j { 1.0 } else { 0.0 };
if (m[i * n + j] - want).abs() > 1e-4 {
return false;
}
}
}
true
}
#[test]
fn identity_inversion() {
for n in 1..=4 {
let mut id = vec![0.0f32; n * n];
for i in 0..n {
id[i * n + i] = 1.0;
}
let inv = invert(&id, n).expect("identity is invertible");
assert!(
approx_identity(&inv, n),
"n={}: inverse of I is I, got {:?}",
n,
inv
);
}
}
#[test]
fn known_2x2_inverse() {
let m = [2.0f32, 1.0, 1.0, 3.0];
let inv = invert(&m, 2).expect("invertible");
let expect = [0.6f32, -0.2, -0.2, 0.4];
for (a, b) in inv.iter().zip(expect.iter()) {
assert!((a - b).abs() < 1e-5, "got {:?}, want {:?}", inv, expect);
}
}
#[test]
fn round_trip_is_identity() {
let cases: &[&[f32]] = &[
&[2.0, 1.0, 1.0, 3.0],
&[0.0, 1.0, 1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0],
&[
4.0, 1.0, 2.0, 1.0, 1.0, 3.0, 0.0, 0.0, 2.0, 0.0, 3.0, 1.0, 1.0, 0.0, 1.0, 2.0,
],
&[5.0],
];
for m in cases {
let n = (m.len() as f64).sqrt() as usize;
assert_eq!(n * n, m.len());
let inv = invert(m, n).expect("matrix is invertible");
assert!(
approx_identity(&mat_mul(m, &inv, n), n),
"n={}: M*M^-1 != I for {:?} (inv {:?})",
n,
m,
inv
);
assert!(
approx_identity(&mat_mul(&inv, m, n), n),
"n={}: M^-1*M != I for {:?} (inv {:?})",
n,
m,
inv
);
}
}
#[test]
fn singular_is_rejected() {
let m = [0.0f32, 1.0, 0.0, 2.0];
assert!(invert(&m, 2).is_none());
}
}