1#![allow(clippy::needless_range_loop)]
34
35mod cholesky;
36mod dense;
37mod eig;
38mod eigh;
39mod equations;
40mod error;
41mod factorizations;
42mod generalized;
43mod structured;
44mod logsqrt;
45mod lu;
46mod matfun;
47mod qr;
48mod reflectors;
49mod scalar;
50pub mod sparse;
51mod reorder;
52mod subspaces;
53mod svd;
54
55pub use structured::{ConvolutionMode, DftScale, PascalKind, block_diag, circulant, companion, convolution_matrix, dft, fiedler, hadamard, hankel, hilbert, invhilbert, invpascal, leslie, pascal, solve_banded, solve_circulant, solve_toeplitz, solveh_banded, toeplitz};
56pub use reorder::{EigenSort, OrdQz, OrdQzComplex, RealQzFactors, ordqz, ordqz_complex, qz_real, schur_sorted, schur_sorted_complex};
57pub use generalized::{GeneralizedEigen, QzFactors, eig_generalized, eigh_generalized, qz};
58pub use factorizations::{LdlFactors, QrFactors, QrMode, funm, hessenberg, ldl, polar, qr, rq, schur_real, subspace_angles};
59pub use error::{Diag, LinalgError, Result, UPLO};
60pub use equations::{solve_continuous_are, solve_continuous_lyapunov, solve_discrete_are, solve_discrete_lyapunov, solve_sylvester};
61pub use lu::LuFactorization;
62pub use logsqrt::{fractional_matrix_power, logm, sqrtm};
63pub use matfun::expm;
64pub use subspaces::{Norm, cond, matrix_rank, norm, null_space, orth, pinv};
65pub use scalar::Scalar;
66
67use dense::{Mat, require_square, to_array1, vector};
68use ndarray::{Array1, Array2, ArrayBase, Data, Ix1, Ix2};
69use num_complex::Complex;
70
71pub fn schur_complex<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<ComplexSchur> {
74 let (t, z) = eig::schur_unbalanced(&Mat::from_array(a)?)?;
75 Ok((t.into_array(), z.into_array()))
76}
77
78pub trait Solve<T> {
80 fn solve<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>>;
81 fn solve_into(&self, b: Array1<T>) -> Result<Array1<T>> {
83 self.solve(&b)
84 }
85 fn solve_t<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>>;
87 fn solve_t_into(&self, b: Array1<T>) -> Result<Array1<T>> {
89 self.solve_t(&b)
90 }
91 fn solve_h<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>>;
93 fn solve_h_into(&self, b: Array1<T>) -> Result<Array1<T>> {
95 self.solve_h(&b)
96 }
97}
98
99pub trait Inverse<T> {
101 fn inv(&self) -> Result<Array2<T>>;
102}
103
104pub trait Determinant<T> {
106 fn det(&self) -> Result<T>;
107}
108
109pub trait Factorize<T> {
111 fn factorize(&self) -> Result<LuFactorization<T>>;
112}
113
114pub trait Cholesky<T> {
117 fn cholesky(&self, uplo: UPLO) -> Result<Array2<T>>;
118}
119
120pub trait SolveTriangular<T, Rhs> {
123 type Output;
124 fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &Rhs) -> Result<Self::Output>;
125}
126
127pub trait Eigh<T> {
130 fn eigh(&self, uplo: UPLO) -> Result<(Array1<f64>, Array2<T>)>;
131}
132
133pub trait EigValsh {
135 fn eigvalsh(&self, uplo: UPLO) -> Result<Array1<f64>>;
136}
137
138pub type ComplexSchur = (Array2<Complex<f64>>, Array2<Complex<f64>>);
140
141pub type ComplexEigen = (Array1<Complex<f64>>, Array2<Complex<f64>>);
143
144pub trait Eig {
146 fn eig(&self) -> Result<ComplexEigen>;
147}
148
149pub trait EigVals {
151 fn eigvals(&self) -> Result<Array1<Complex<f64>>>;
152}
153
154#[allow(clippy::upper_case_acronyms)]
157pub trait SVD<T> {
158 #[allow(clippy::type_complexity)]
159 fn svd(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)>;
160}
161
162pub trait SvdJacobi<T> {
166 #[allow(clippy::type_complexity)]
167 fn svd_jacobi(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)>;
168}
169
170#[derive(Debug, Clone)]
172#[non_exhaustive]
173pub struct LeastSquaresResult<T> {
174 pub solution: Array1<T>,
176 pub singular_values: Array1<f64>,
177 pub rank: usize,
179 pub residual_sum_of_squares: Option<f64>,
181}
182
183pub trait LeastSquaresSvd<T> {
190 fn least_squares<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<LeastSquaresResult<T>>;
191}
192
193impl<T: Scalar, S: Data<Elem = T>> Solve<T> for ArrayBase<S, Ix2> {
194 fn solve<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
195 let lu = self.factorize()?;
196 lu.solve(b)
197 }
198 fn solve_t<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
199 self.t().solve(b)
200 }
201 fn solve_h<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
202 self.t().mapv(|v| v.conj()).solve(b)
203 }
204}
205
206impl<T: Scalar> LuFactorization<T> {
207 pub fn solve<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>> {
209 if b.len() != self.dimension() {
210 return Err(LinalgError::Shape(format!("matrix of order {} and vector of length {}", self.dimension(), b.len())));
211 }
212 Ok(to_array1(self.solve_vec(&vector(b)?)))
213 }
214
215 pub fn inv(&self) -> Array2<T> {
217 self.inverse().into_array()
218 }
219}
220
221impl<T: Scalar, S: Data<Elem = T>> Factorize<T> for ArrayBase<S, Ix2> {
222 fn factorize(&self) -> Result<LuFactorization<T>> {
223 LuFactorization::new(Mat::from_array(self)?)
224 }
225}
226
227impl<T: Scalar, S: Data<Elem = T>> Inverse<T> for ArrayBase<S, Ix2> {
228 fn inv(&self) -> Result<Array2<T>> {
229 Ok(self.factorize()?.inv())
230 }
231}
232
233impl<T: Scalar, S: Data<Elem = T>> Determinant<T> for ArrayBase<S, Ix2> {
234 fn det(&self) -> Result<T> {
235 require_square(self.nrows(), self.ncols())?;
236 match self.factorize() {
237 Ok(lu) => Ok(lu.determinant()),
238 Err(LinalgError::Singular(_)) => Ok(T::zero()),
239 Err(e) => Err(e),
240 }
241 }
242}
243
244impl<T: Scalar, S: Data<Elem = T>> Cholesky<T> for ArrayBase<S, Ix2> {
245 fn cholesky(&self, uplo: UPLO) -> Result<Array2<T>> {
246 let l = cholesky::cholesky_lower(&Mat::from_array(self)?, uplo)?;
247 Ok(match uplo {
248 UPLO::Lower => l.into_array(),
249 UPLO::Upper => l.adjoint().into_array(),
250 })
251 }
252}
253
254impl<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>> SolveTriangular<T, ArrayBase<S2, Ix2>> for ArrayBase<S, Ix2> {
255 type Output = Array2<T>;
256 fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &ArrayBase<S2, Ix2>) -> Result<Array2<T>> {
257 Ok(cholesky::solve_triangular(&Mat::from_array(self)?, uplo, diag, &Mat::from_array(b)?)?.into_array())
258 }
259}
260
261impl<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>> SolveTriangular<T, ArrayBase<S2, Ix1>> for ArrayBase<S, Ix2> {
262 type Output = Array1<T>;
263 fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
264 let rhs = Mat { rows: b.len(), cols: 1, data: vector(b)? };
265 Ok(to_array1(cholesky::solve_triangular(&Mat::from_array(self)?, uplo, diag, &rhs)?.data))
266 }
267}
268
269impl<T: Scalar, S: Data<Elem = T>> Eigh<T> for ArrayBase<S, Ix2> {
270 fn eigh(&self, uplo: UPLO) -> Result<(Array1<f64>, Array2<T>)> {
271 let (values, vectors) = eigh::eigh(&Mat::from_array(self)?, uplo)?;
272 Ok((Array1::from_vec(values), vectors.into_array()))
273 }
274}
275
276impl<T: Scalar, S: Data<Elem = T>> EigValsh for ArrayBase<S, Ix2> {
277 fn eigvalsh(&self, uplo: UPLO) -> Result<Array1<f64>> {
278 Ok(Array1::from_vec(eigh::eigvalsh(&Mat::from_array(self)?, uplo)?))
279 }
280}
281
282impl<T: Scalar, S: Data<Elem = T>> Eig for ArrayBase<S, Ix2> {
283 fn eig(&self) -> Result<ComplexEigen> {
284 let (values, vectors) = eig::eig(&Mat::from_array(self)?)?;
285 Ok((Array1::from_vec(values), vectors.into_array()))
286 }
287}
288
289impl<T: Scalar, S: Data<Elem = T>> EigVals for ArrayBase<S, Ix2> {
290 fn eigvals(&self) -> Result<Array1<Complex<f64>>> {
291 Ok(Array1::from_vec(eig::eigvals(&Mat::from_array(self)?)?))
292 }
293}
294
295impl<T: Scalar, S: Data<Elem = T>> SVD<T> for ArrayBase<S, Ix2> {
296 fn svd(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)> {
297 let a = Mat::from_array(self)?;
298 if !calc_u && !calc_vt {
299 return Ok((None, Array1::from_vec(svd::singular_values(&a)?), None));
300 }
301 Ok(full_factors(svd::thin_svd(&a)?, calc_u, calc_vt))
302 }
303}
304
305impl<T: Scalar, S: Data<Elem = T>> SvdJacobi<T> for ArrayBase<S, Ix2> {
306 fn svd_jacobi(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)> {
307 Ok(full_factors(svd::thin_svd_jacobi(&Mat::from_array(self)?)?, calc_u, calc_vt))
308 }
309}
310
311#[allow(clippy::type_complexity)]
313fn full_factors<T: Scalar>(thin: svd::ThinSvd<T>, calc_u: bool, calc_vt: bool) -> (Option<Array2<T>>, Array1<f64>, Option<Array2<T>>) {
314 let u = calc_u.then(|| svd::complete_square(&thin.u).into_array());
315 let vt = calc_vt.then(|| svd::complete_square(&thin.v).adjoint().into_array());
316 (u, Array1::from_vec(thin.sigma), vt)
317}
318
319impl<T: Scalar, S: Data<Elem = T>> LeastSquaresSvd<T> for ArrayBase<S, Ix2> {
320 fn least_squares<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<LeastSquaresResult<T>> {
321 let (m, n) = self.dim();
322 if b.len() != m {
323 return Err(LinalgError::Shape(format!("matrix {m} × {n} and right-hand side of length {}", b.len())));
324 }
325 let a = Mat::from_array(self)?;
326 let rhs = vector(b)?;
327 if m >= n && n > 0 {
329 let qr = qr::householder_pivoted(&a);
330 let mut qtb = rhs.clone();
331 qr.apply_adjoint(&mut qtb);
332 let r00 = qr.r.at(0, 0).abs();
333 let tolerance = r00 * f64::EPSILON * m.max(n) as f64;
334 if r00 > 0.0 && (0..n).all(|i| qr.r.at(i, i).abs() > tolerance * 1e3) {
335 let mut z = qtb[..n].to_vec();
337 for i in (0..n).rev() {
338 let s = (i + 1..n).fold(T::zero(), |s, k| s + qr.r.at(i, k) * z[k]);
339 z[i] = (z[i] - s) / qr.r.at(i, i);
340 }
341 let mut x = vec![T::zero(); n];
342 for (j, &p) in qr.permutation.iter().enumerate() {
343 x[p] = z[j];
344 }
345 let singular_values = Array1::from_vec(svd::singular_values(&qr.upper())?);
348 let residual = (m > n).then(|| qtb[n..].iter().map(|v| v.abs_sqr()).sum::<f64>());
349 return Ok(LeastSquaresResult { solution: to_array1(x), singular_values, rank: n, residual_sum_of_squares: residual });
350 }
351 }
352 let thin = svd::thin_svd(&a)?;
353 let threshold = thin.sigma.first().copied().unwrap_or(0.0) * f64::EPSILON * m.max(n) as f64;
354 let rank = thin.sigma.iter().filter(|&&s| s > threshold).count();
355 let mut x = vec![T::zero(); n];
357 for j in 0..rank {
358 let coefficient = (0..m).fold(T::zero(), |s, i| s + thin.u.at(i, j).conj() * rhs[i]).scale(1.0 / thin.sigma[j]);
359 for (i, xi) in x.iter_mut().enumerate() {
360 *xi += thin.v.at(i, j) * coefficient;
361 }
362 }
363 let residual_sum_of_squares = (m > n && rank == n).then(|| {
364 (0..m).map(|i| (rhs[i] - (0..n).fold(T::zero(), |s, j| s + a.at(i, j) * x[j])).abs_sqr()).sum::<f64>()
365 });
366 Ok(LeastSquaresResult { solution: to_array1(x), singular_values: Array1::from_vec(thin.sigma), rank, residual_sum_of_squares })
367 }
369}
370
371#[cfg(test)]
372mod tests;