use crate::util::checked_inv;
use crate::{Matrix, Vector};
use num_traits::real::Real;
use num_traits::Signed;
use std::iter::{Product, Sum};
use std::ops::{Mul, Neg, Not};
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Parity {
Even,
Odd,
}
impl<T> Mul<T> for Parity
where
T: Neg<Output = T>,
{
type Output = T;
fn mul(self, rhs: T) -> Self::Output {
match self {
Parity::Even => rhs,
Parity::Odd => -rhs,
}
}
}
impl Not for Parity {
type Output = Parity;
fn not(self) -> Self::Output {
match self {
Parity::Even => Parity::Odd,
Parity::Odd => Parity::Even,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct LUDecomposition<T: Copy, const N: usize> {
pub lu: Matrix<T, N, N>,
pub idx: Vector<usize, N>,
pub parity: Parity,
}
impl<T: Copy + Default + Real, const N: usize> LUDecomposition<T, N> {
#[must_use]
pub fn solve<const M: usize>(&self, b: &Matrix<T, N, M>) -> Matrix<T, N, M> {
let b_permuted = b.permute_rows(&self.idx);
Matrix::from_cols(b_permuted.cols().map(|mut x| {
let mut ii = 0usize;
for i in 0..N {
let mut sum = x[i];
if ii != 0 {
for j in (ii - 1)..i {
sum = sum - (self.lu[(i, j)] * x[j]);
}
} else if sum.abs() > T::epsilon() {
ii = i + 1;
}
x[i] = sum;
}
for i in (0..N).rev() {
let mut sum = x[i];
for j in (i + 1)..N {
sum = sum - (self.lu[(i, j)] * x[j]);
}
x[i] = sum / self.lu[(i, i)]
}
x
}))
}
pub fn det(&self) -> T {
self.parity * self.lu.diagonals().fold(T::one(), |l, &r| l * r)
}
#[must_use]
pub fn inv(&self) -> Matrix<T, N, N> {
return self.solve(&Matrix::<T, N, N>::identity());
}
pub fn separate(&self) -> (Matrix<T, N, N>, Matrix<T, N, N>) {
let mut l = Matrix::<T, N, N>::identity();
let mut u = self.lu;
for m in 1..N {
for n in 0..m {
l[(m, n)] = u[(m, n)];
u[(m, n)] = T::zero();
}
}
(l, u)
}
}
pub trait LUDecompose<T: Copy, const N: usize> {
#[must_use]
fn lu(&self) -> Option<LUDecomposition<T, N>>;
#[must_use]
fn inv(&self) -> Option<Matrix<T, N, N>>;
#[must_use]
fn det(&self) -> T;
#[must_use]
fn solve<const M: usize>(&self, b: &Matrix<T, N, M>) -> Option<Matrix<T, N, M>>;
}
impl<T, const N: usize> LUDecompose<T, N> for Matrix<T, N, N>
where
T: Copy + Default + Real + Sum + Product + Signed,
{
fn lu(&self) -> Option<LUDecomposition<T, N>> {
let mut lu = self.clone();
let mut idx: Vector<usize, N> = (0..N).collect();
let mut parity = Parity::Even;
let mut vv: Vector<T, N> = self
.rows()
.map(|row| {
let m = row.elements().cloned().reduce(|acc, x| acc.max(x.abs()))?;
checked_inv(m)
})
.collect::<Option<_>>()?;
for k in 0..N {
let (ipivot, _) = (lu.col(k) * vv)
.abs()
.elements()
.enumerate()
.skip(k) .reduce(|(imax, xmax), (i, x)| match x > xmax {
true => (i, x),
false => (imax, xmax),
})?;
if k != ipivot {
lu.pivot_row(ipivot, k); idx.pivot_row(ipivot, k);
parity = !parity; vv[ipivot] = vv[k] }
let pivot = lu[(k, k)];
if pivot.abs() < T::epsilon() {
return None;
};
for i in (k + 1)..N {
lu[(i, k)] = lu[(i, k)] / pivot;
for j in (k + 1)..N {
lu[(i, j)] = lu[(i, j)] - (lu[(i, k)] * lu[(k, j)]);
}
}
}
return Some(LUDecomposition { lu, idx, parity });
}
fn inv(&self) -> Option<Matrix<T, N, N>> {
match N {
1 => Some(Self::fill(checked_inv(self[0])?)),
2 => {
let mut result = Self::default();
result[(0, 0)] = self[(1, 1)];
result[(1, 1)] = self[(0, 0)];
result[(1, 0)] = -self[(1, 0)];
result[(0, 1)] = -self[(0, 1)];
Some(result * checked_inv(self.det())?)
}
_ => Some(self.lu()?.inv()),
}
}
fn det(&self) -> T {
match N {
1 => self[0],
2 => (self[(0, 0)] * self[(1, 1)]) - (self[(0, 1)] * self[(1, 0)]),
3 => {
(0..N) .map(|i| {
let dn = (0..N)
.map(|j| -> T { self[(j, (j + i) % N)] })
.product::<T>();
let up = (0..N)
.map(|j| -> T { self[(N - j - 1, (j + i) % N)] })
.product::<T>();
dn - up
})
.sum::<T>()
}
_ => {
self.lu().map_or(T::zero(), |lu| lu.det())
}
}
}
fn solve<const M: usize>(&self, b: &Matrix<T, N, M>) -> Option<Matrix<T, N, M>> {
Some(self.lu()?.solve(b))
}
}