Skip to main content

ruxla_core/jnp/
linalg.rs

1//! Linear algebra following `jax.numpy.linalg` (and NumPy's semantics), on
2//! matrices and batches of matrices (see [`lax::linalg`]
3//! for the decompositions). The decompositions and solves (`cholesky`,
4//! `solve`, `inv`, `qr`, `eigh`, `eigvalsh`, `svd`, `svdvals`) take `f32`,
5//! `f64`, `c64`, and `c128`; `det`, `slogdet`, and `norm` take `f32` and
6//! `f64`.
7
8use ruxla_ir::{GatherDims, GatherScatterMode, Shape};
9
10use crate::backend::Backend;
11use crate::jnp;
12use crate::lax;
13use crate::lax::linalg::TriangularSolveOptions;
14use crate::value::{Array, LinalgFloat, LinalgScalar, broadcast_shapes};
15
16/// Checks a batch of square matrices and returns `n`.
17#[track_caller]
18fn square<B: Backend, T: LinalgScalar>(op: &str, a: &Array<B, T>) -> usize {
19    let shape = a.shape();
20    let rank = shape.rank();
21    assert!(
22        rank >= 2 && shape[rank - 1] == shape[rank - 2],
23        "{op} needs a square matrix or a batch of them, got shape [{shape}]"
24    );
25    shape[rank - 1]
26}
27
28/// `shape` with its last `k` dimensions replaced by `tail`.
29fn with_tail(batch: &Shape, tail: &[usize]) -> Shape {
30    let mut d = batch.dims().to_vec();
31    d.extend_from_slice(tail);
32    Shape::from(d)
33}
34
35/// The leading (batch) dimensions of a batch of matrices.
36fn batch_of(shape: &Shape, core: usize) -> Shape {
37    Shape::from(shape.dims()[..shape.rank() - core].to_vec())
38}
39
40/// The rows of each matrix of `x` (`[..., m, k]`) permuted by `perm`
41/// (`i32[..., m]`): row `i` of the result is row `perm[i]` of `x`.
42fn permute_rows<B: Backend, T: LinalgScalar>(x: &Array<B, T>, perm: &Array<B, i32>) -> Array<B, T> {
43    let shape = x.shape();
44    let nb = shape.rank() - 2;
45    let mut index_shape = perm.shape().dims().to_vec();
46    index_shape.push(1);
47    let indices = perm.reshape(index_shape);
48    let batch: Vec<usize> = (0..nb).collect();
49    let dims = GatherDims {
50        offset_dims: vec![nb + 1],
51        collapsed_slice_dims: vec![nb],
52        start_index_map: vec![nb],
53        operand_batching_dims: batch.clone(),
54        start_indices_batching_dims: batch,
55    };
56    let mut sizes = vec![1; nb + 1];
57    sizes.push(shape[nb + 1]);
58    lax::gather(
59        x,
60        &indices,
61        &dims,
62        &sizes,
63        GatherScatterMode::PromiseInBounds,
64    )
65}
66
67/// Solves `a x = b` with the LU factors of `a` (JAX's `_lu_solve_core`
68/// with `trans = 0`), for `b` of shape `[..., n, k]` with `a`'s batch.
69fn lu_solve<B: Backend, T: LinalgScalar>(
70    lu: &Array<B, T>,
71    perm: &Array<B, i32>,
72    b: &Array<B, T>,
73) -> Array<B, T> {
74    let x = permute_rows(b, perm);
75    let x = lax::linalg::triangular_solve(
76        lu,
77        &x,
78        TriangularSolveOptions {
79            left_side: true,
80            lower: true,
81            unit_diagonal: true,
82            ..Default::default()
83        },
84    );
85    lax::linalg::triangular_solve(
86        lu,
87        &x,
88        TriangularSolveOptions {
89            left_side: true,
90            lower: false,
91            ..Default::default()
92        },
93    )
94}
95
96/// The Cholesky factor `L` (lower triangular, `a = L L^T`) of each
97/// symmetric positive definite matrix, as `jnp.linalg.cholesky` (the input
98/// is symmetrized first). Matrices that are not positive definite give
99/// NaNs.
100///
101/// # Panics
102///
103/// Panics if `a` is not a batch of square matrices.
104///
105/// # Examples
106///
107/// ```
108/// use ruxla_core::{Array, Native, jnp};
109///
110/// let a = Array::<Native, f64>::from_vec(vec![4.0, 2.0, 2.0, 5.0], [2, 2]);
111/// assert_eq!(jnp::linalg::cholesky(&a).to_vec(), [2.0, 0.0, 1.0, 2.0]);
112/// ```
113#[track_caller]
114pub fn cholesky<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T> {
115    square("cholesky", a);
116    lax::linalg::cholesky(a, true)
117}
118
119/// Solves `a x = b` for `x`, as `jnp.linalg.solve`: `b` of shape `[n]` is a
120/// vector (the result is `[..., n]`), otherwise a batch of matrices
121/// `[..., n, k]` whose batch dimensions broadcast with `a`'s. The solve
122/// uses the LU factorization of `a`; singular matrices give infinities or
123/// NaNs.
124///
125/// JAX differentiates the solve implicitly (`custom_linear_solve`); ruxla
126/// differentiates through the factorization, which gives the same
127/// derivatives.
128///
129/// # Panics
130///
131/// Panics if `a` is not a batch of square matrices or the shapes do not
132/// match.
133///
134/// # Examples
135///
136/// ```
137/// use ruxla_core::{Array, Native, jnp};
138///
139/// let a = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 1.0, 3.0], [2, 2]);
140/// let b = Array::<Native, f64>::from_vec(vec![3.0, 5.0], [2]);
141/// let x = jnp::linalg::solve(&a, &b).to_vec();
142/// assert!((x[0] - 0.8).abs() < 1e-12 && (x[1] - 1.4).abs() < 1e-12);
143/// ```
144#[track_caller]
145pub fn solve<B: Backend, T: LinalgScalar>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
146    let n = square("solve", a);
147    let a_shape = a.shape();
148    let b_shape = b.shape();
149    let a_batch = batch_of(&a_shape, 2);
150    if b_shape.rank() == 1 {
151        assert_eq!(
152            b_shape[0], n,
153            "solve: shapes [{a_shape}] and [{b_shape}] do not match"
154        );
155        let b = b.reshape([n, 1]).broadcast_to(with_tail(&a_batch, &[n, 1]));
156        let (lu, _, perm) = lax::linalg::lu(a);
157        let x = lu_solve(&lu, &perm, &b);
158        return x.reshape(with_tail(&a_batch, &[n]));
159    }
160    let rank = b_shape.rank();
161    assert!(
162        b_shape[rank - 2] == n,
163        "solve: shapes [{a_shape}] and [{b_shape}] do not match"
164    );
165    let batch = broadcast_shapes(&a_batch, &batch_of(&b_shape, 2));
166    let a = a.broadcast_to(with_tail(&batch, &[n, n]));
167    let b = b.broadcast_to(with_tail(&batch, &[n, b_shape[rank - 1]]));
168    let (lu, _, perm) = lax::linalg::lu(&a);
169    lu_solve(&lu, &perm, &b)
170}
171
172/// The inverse of each square matrix, as `jnp.linalg.inv` (a solve with the
173/// identity).
174///
175/// # Panics
176///
177/// Panics if `a` is not a batch of square matrices.
178#[track_caller]
179pub fn inv<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T> {
180    let n = square("inv", a);
181    let eye =
182        lax::convert_element_type::<B, bool, T>(&lax::iota::<B, i32>([n, n], 0).eq(lax::iota::<
183            B,
184            i32,
185        >(
186            [n, n], 1
187        )));
188    let eye = eye.broadcast_to(a.shape());
189    solve(a, &eye)
190}
191
192/// The diagonals of a batch of square matrices.
193fn diagonal<B: Backend, T: LinalgFloat>(x: &Array<B, T>) -> Array<B, T> {
194    let shape = x.shape();
195    let rank = shape.rank();
196    let n = shape[rank - 1];
197    let eye = lax::iota::<B, i32>([n, n], 0).eq(lax::iota::<B, i32>([n, n], 1));
198    let zero = ruxla_kernels::cast::<f64, T>(0.0);
199    let on = jnp::where_(eye, x, zero);
200    lax::reduce_sum(&on, &[rank - 1])
201}
202
203/// The sign and the natural logarithm of the absolute value of the
204/// determinant of each square matrix, as `jnp.linalg.slogdet` (from the LU
205/// factorization). Singular matrices give a sign of 0 and `-inf`.
206///
207/// # Panics
208///
209/// Panics if `a` is not a batch of square matrices.
210///
211/// # Examples
212///
213/// ```
214/// use ruxla_core::{Array, Native, jnp};
215///
216/// let a = Array::<Native, f64>::from_vec(vec![0.0, 2.0, 3.0, 0.0], [2, 2]);
217/// let (sign, logdet) = jnp::linalg::slogdet(&a);
218/// assert_eq!(sign.to_vec(), [-1.0]);
219/// assert!((logdet.to_vec()[0] - 6f64.ln()).abs() < 1e-12);
220/// ```
221#[track_caller]
222pub fn slogdet<B: Backend, T: LinalgFloat>(a: &Array<B, T>) -> (Array<B, T>, Array<B, T>) {
223    let n = square("slogdet", a);
224    let (lu, pivots, _) = lax::linalg::lu(a);
225    let diag = diagonal(&lu);
226    let last = diag.ndim() - 1;
227    let zero = ruxla_kernels::cast::<f64, T>(0.0);
228    let is_zero = jnp::any(diag.eq(zero), last as i64);
229    let iota = lax::iota::<B, i32>([n], 0).broadcast_to(pivots.shape());
230    let swaps = lax::convert_element_type::<B, bool, i32>(&pivots.ne(&iota));
231    let negative = lax::convert_element_type::<B, bool, i32>(&diag.lt(zero));
232    let parity = jnp::sum(swaps, last as i64) + jnp::sum(negative, last as i64);
233    let odd = lax::convert_element_type::<B, i32, T>(&jnp::fmod(&parity, 2i32));
234    let one = ruxla_kernels::cast::<f64, T>(1.0);
235    let two = ruxla_kernels::cast::<f64, T>(2.0);
236    let sign = jnp::where_(&is_zero, zero, (odd * -two) + one);
237    let neg_inf = ruxla_kernels::cast::<f64, T>(f64::NEG_INFINITY);
238    let logdet = jnp::where_(
239        &is_zero,
240        neg_inf,
241        jnp::sum(jnp::log(jnp::abs(&diag)), last as i64),
242    );
243    (sign, logdet)
244}
245
246/// The determinant of each square matrix, as `jnp.linalg.det`: the sign
247/// times the exponential of the log-determinant from [`slogdet`] (JAX uses
248/// closed forms for 2 x 2 and 3 x 3 matrices, which round differently).
249///
250/// # Panics
251///
252/// Panics if `a` is not a batch of square matrices.
253///
254/// # Examples
255///
256/// ```
257/// use ruxla_core::{Array, Native, jnp};
258///
259/// let a = Array::<Native, f64>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [2, 2]);
260/// assert!((jnp::linalg::det(&a).to_vec()[0] + 2.0).abs() < 1e-12);
261/// ```
262#[track_caller]
263pub fn det<B: Backend, T: LinalgFloat>(a: &Array<B, T>) -> Array<B, T> {
264    let (sign, logdet) = slogdet(a);
265    sign * jnp::exp(logdet)
266}
267
268/// The shape of `q` of [`qr`].
269#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
270pub enum QrMode {
271    /// `q` is `[..., m, k]` and `r` is `[..., k, n]`, for `k = min(m, n)`
272    /// (NumPy's `"reduced"`, the default).
273    #[default]
274    Reduced,
275    /// `q` is `[..., m, m]` and `r` is `[..., m, n]` (`"complete"`).
276    Complete,
277}
278
279/// The QR decomposition of each matrix, as `jnp.linalg.qr` (NumPy's mode
280/// `"r"` is the second result).
281///
282/// # Panics
283///
284/// Panics if `a` is not a batch of matrices.
285#[track_caller]
286pub fn qr<B: Backend, T: LinalgScalar>(
287    a: &Array<B, T>,
288    mode: QrMode,
289) -> (Array<B, T>, Array<B, T>) {
290    lax::linalg::qr(a, mode == QrMode::Complete)
291}
292
293/// The eigenvalues (ascending) and eigenvectors (columns) of each symmetric
294/// matrix, as `jnp.linalg.eigh` (the input is symmetrized first).
295///
296/// # Panics
297///
298/// Panics if `a` is not a batch of square matrices.
299///
300/// # Examples
301///
302/// ```
303/// use ruxla_core::{Array, Native, jnp};
304///
305/// let a = Array::<Native, f64>::from_vec(vec![2.0, 1.0, 1.0, 2.0], [2, 2]);
306/// let (w, v) = jnp::linalg::eigh(&a);
307/// assert!((w.to_vec()[0] - 1.0).abs() < 1e-12 && (w.to_vec()[1] - 3.0).abs() < 1e-12);
308/// assert_eq!(v.shape().dims(), [2, 2]);
309/// ```
310#[track_caller]
311pub fn eigh<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> (Array<B, T::Real>, Array<B, T>) {
312    square("eigh", a);
313    let (v, w) = lax::linalg::eigh(a, true, true, true, None, None);
314    (w, v)
315}
316
317/// The eigenvalues (ascending) of each symmetric matrix, as
318/// `jnp.linalg.eigvalsh`.
319///
320/// # Panics
321///
322/// Panics if `a` is not a batch of square matrices.
323#[track_caller]
324pub fn eigvalsh<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T::Real> {
325    eigh(a).0
326}
327
328/// The singular value decomposition `(u, s, vh)` of each matrix, as
329/// `jnp.linalg.svd` (see [`lax::linalg::svd`]).
330///
331/// # Panics
332///
333/// Panics if `a` is not a batch of matrices.
334#[track_caller]
335pub fn svd<B: Backend, T: LinalgScalar>(
336    a: &Array<B, T>,
337    full_matrices: bool,
338) -> lax::linalg::Svd<B, T> {
339    lax::linalg::svd(a, full_matrices, None, None)
340}
341
342/// The singular values of each matrix in descending order, as
343/// `jnp.linalg.svdvals`.
344///
345/// # Panics
346///
347/// Panics if `a` is not a batch of matrices.
348#[track_caller]
349pub fn svdvals<B: Backend, T: LinalgScalar>(a: &Array<B, T>) -> Array<B, T::Real> {
350    lax::linalg::svd_values(a, None, None)
351}
352
353/// The kind of norm of [`norm`] (NumPy's `ord`).
354#[derive(Clone, Copy, Debug, Default, PartialEq)]
355pub enum NormOrd {
356    /// `ord=None`: the 2-norm of vectors, the Frobenius norm of matrices.
357    #[default]
358    Default,
359    /// `'fro'`: the Frobenius norm (matrices).
360    Fro,
361    /// `'nuc'`: the sum of the singular values (matrices).
362    Nuc,
363    /// `inf`: the largest absolute value (vectors), the largest absolute
364    /// row sum (matrices).
365    Inf,
366    /// `-inf`: the smallest absolute value (vectors), the smallest absolute
367    /// row sum (matrices).
368    NegInf,
369    /// A number: `sum(|x|^p)^(1/p)` for vectors (0 counts the nonzero
370    /// elements); for matrices, 1 and -1 (the largest and smallest absolute
371    /// column sums) and 2 and -2 (the largest and smallest singular values).
372    P(f64),
373}
374
375/// The axes of [`norm`].
376#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
377pub enum NormAxes {
378    /// `axis=None`: all axes (with [`NormOrd::Default`], the 2-norm of the
379    /// flattened array of any rank; otherwise a vector or a matrix).
380    #[default]
381    All,
382    /// One axis: vector norms.
383    Vector(i64),
384    /// Two axes (rows, columns): matrix norms.
385    Matrix(i64, i64),
386}
387
388/// A norm of vectors or matrices, as `jnp.linalg.norm`.
389///
390/// # Panics
391///
392/// Panics if the axes are out of range, or if `ord` is not a norm of the
393/// kind the axes select.
394///
395/// # Examples
396///
397/// ```
398/// use ruxla_core::{Array, Native, jnp};
399/// use ruxla_core::jnp::linalg::{NormAxes, NormOrd};
400///
401/// let x = Array::<Native, f64>::from_vec(vec![3.0, -4.0], [2]);
402/// assert_eq!(jnp::linalg::norm(&x, NormOrd::Default, NormAxes::All, false).to_vec(), [5.0]);
403/// assert_eq!(jnp::linalg::norm(&x, NormOrd::Inf, NormAxes::All, false).to_vec(), [4.0]);
404/// ```
405#[track_caller]
406pub fn norm<B: Backend, T: LinalgFloat>(
407    x: &Array<B, T>,
408    ord: NormOrd,
409    axes: NormAxes,
410    keepdims: bool,
411) -> Array<B, T> {
412    let rank = x.ndim();
413    let shape = x.shape();
414    let axes: Vec<usize> = match axes {
415        NormAxes::All if ord == NormOrd::Default => {
416            let all: Vec<usize> = (0..rank).collect();
417            let y = jnp::sqrt(lax::reduce_sum(&(x * x), &all));
418            return keep(y, &shape, &all, keepdims);
419        }
420        NormAxes::All => (0..rank).collect(),
421        NormAxes::Vector(a) => vec![jnp::normalize_axis(a, rank)],
422        NormAxes::Matrix(r, c) => vec![jnp::normalize_axis(r, rank), jnp::normalize_axis(c, rank)],
423    };
424    let y = match axes.as_slice() {
425        [a] => vector_norm(x, ord, *a),
426        [r, c] => {
427            assert!(r != c, "norm: the two axes must differ");
428            matrix_norm(x, ord, *r, *c)
429        }
430        _ => panic!("norm: pass one axis for a vector norm or two for a matrix norm, got {axes:?}"),
431    };
432    let mut sorted = axes.clone();
433    sorted.sort_unstable();
434    keep(y, &shape, &sorted, keepdims)
435}
436
437/// `y` with the reduced `axes` of `shape` kept as dimensions of size 1.
438fn keep<B: Backend, T: LinalgFloat>(
439    y: Array<B, T>,
440    shape: &Shape,
441    axes: &[usize],
442    keepdims: bool,
443) -> Array<B, T> {
444    if !keepdims {
445        return y;
446    }
447    let dims: Vec<usize> = (0..shape.rank())
448        .map(|d| if axes.contains(&d) { 1 } else { shape[d] })
449        .collect();
450    y.reshape(dims)
451}
452
453fn vector_norm<B: Backend, T: LinalgFloat>(
454    x: &Array<B, T>,
455    ord: NormOrd,
456    axis: usize,
457) -> Array<B, T> {
458    let ax = axis as i64;
459    let zero = ruxla_kernels::cast::<f64, T>(0.0);
460    match ord {
461        NormOrd::Default | NormOrd::P(2.0) => jnp::sqrt(jnp::sum(x * x, ax)),
462        NormOrd::Inf => jnp::maximum(jnp::max(jnp::abs(x), ax), zero),
463        NormOrd::NegInf => jnp::min(jnp::abs(x), ax),
464        NormOrd::P(0.0) => jnp::sum(lax::convert_element_type::<B, bool, T>(&x.ne(zero)), ax),
465        NormOrd::P(1.0) => jnp::sum(jnp::abs(x), ax),
466        NormOrd::P(p) => {
467            let p_t = ruxla_kernels::cast::<f64, T>(p);
468            let inv = ruxla_kernels::cast::<f64, T>(1.0 / p);
469            jnp::power(jnp::sum(jnp::power(jnp::abs(x), p_t), ax), inv)
470        }
471        NormOrd::Fro | NormOrd::Nuc => panic!("norm: {ord:?} is not a vector norm"),
472    }
473}
474
475fn matrix_norm<B: Backend, T: LinalgFloat>(
476    x: &Array<B, T>,
477    ord: NormOrd,
478    row: usize,
479    col: usize,
480) -> Array<B, T> {
481    let zero = ruxla_kernels::cast::<f64, T>(0.0);
482    // The axis left after reducing `first` (which shifts later axes).
483    let after =
484        |first: usize, second: usize| (if second > first { second - 1 } else { second }) as i64;
485    match ord {
486        NormOrd::Default | NormOrd::Fro => {
487            let mut axes = [row, col];
488            axes.sort_unstable();
489            jnp::sqrt(lax::reduce_sum(&(x * x), &axes))
490        }
491        NormOrd::P(1.0) => {
492            let sums = jnp::sum(jnp::abs(x), row as i64);
493            jnp::maximum(jnp::max(sums, after(row, col)), zero)
494        }
495        NormOrd::P(-1.0) => {
496            let sums = jnp::sum(jnp::abs(x), row as i64);
497            jnp::min(sums, after(row, col))
498        }
499        NormOrd::Inf => {
500            let sums = jnp::sum(jnp::abs(x), col as i64);
501            jnp::maximum(jnp::max(sums, after(col, row)), zero)
502        }
503        NormOrd::NegInf => {
504            let sums = jnp::sum(jnp::abs(x), col as i64);
505            jnp::min(sums, after(col, row))
506        }
507        NormOrd::Nuc | NormOrd::P(2.0) | NormOrd::P(-2.0) => {
508            // Move the axes last (`jnp.moveaxis(x, axis, (-2, -1))`).
509            let rank = x.ndim();
510            let mut perm: Vec<usize> = (0..rank).filter(|&d| d != row && d != col).collect();
511            perm.push(row);
512            perm.push(col);
513            let s = lax::linalg::svd_values(&x.transpose(&perm), None, None);
514            let last = (rank - 2) as i64;
515            match ord {
516                NormOrd::P(2.0) => jnp::maximum(jnp::max(&s, last), zero),
517                NormOrd::P(_) => jnp::min(&s, last),
518                _ => jnp::sum(&s, last),
519            }
520        }
521        NormOrd::P(p) => panic!("norm: invalid order {p} for a matrix norm"),
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528    use crate::Native;
529    use crate::lax::linalg::mt;
530    use ruxla_ir::Precision;
531
532    /// The batched matrix product `a @ b` of operands with the same batch
533    /// dimensions.
534    fn batched_matmul<B: Backend, T: LinalgFloat>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
535        let rank = a.ndim();
536        let batch: Vec<usize> = (0..rank - 2).collect();
537        let dims = ruxla_ir::DotDims {
538            lhs_contracting: vec![rank - 1],
539            rhs_contracting: vec![rank - 2],
540            lhs_batch: batch.clone(),
541            rhs_batch: batch,
542        };
543        lax::dot_general_with::<B, T, T>(a, b, &dims, Precision::Highest)
544    }
545
546    fn arr(v: &[f64], shape: &[usize]) -> Array<Native, f64> {
547        Array::from_vec(v.to_vec(), shape)
548    }
549
550    fn close(a: &[f64], b: &[f64]) {
551        assert_eq!(a.len(), b.len());
552        for (x, y) in a.iter().zip(b) {
553            assert!((x - y).abs() < 1e-10, "{a:?} vs {b:?}");
554        }
555    }
556
557    #[test]
558    fn solves_and_inverses() {
559        let a = arr(&[4.0, 1.0, 2.0, 1.0, 3.0, 0.0, 2.0, 0.0, 5.0], &[3, 3]);
560        let x = arr(&[1.0, -2.0, 3.0, 0.5, 1.5, -1.0], &[3, 2]);
561        let b = batched_matmul(&a, &x);
562        close(&solve(&a, &b).to_vec(), &x.to_vec());
563        let ai = inv(&a);
564        let e = batched_matmul(&a, &ai);
565        close(&e.to_vec(), &[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
566        // A batch of `a` with one right-hand side broadcast.
567        let a2 = jnp::stack(&[a.clone(), mt(&a)], 0);
568        let b2 = arr(&[1.0, 2.0, 3.0], &[1, 3, 1]);
569        assert_eq!(solve(&a2, &b2).shape().dims(), [2, 3, 1]);
570        let v = solve(&a2, &arr(&[1.0, 2.0, 3.0], &[3]));
571        assert_eq!(v.shape().dims(), [2, 3]);
572    }
573
574    #[test]
575    fn determinants() {
576        let a = arr(&[4.0, 1.0, 2.0, 1.0, 3.0, 0.0, 2.0, 0.0, 5.0], &[3, 3]);
577        close(&det(&a).to_vec(), &[4.0 * 15.0 - 5.0 - 2.0 * 6.0]);
578        let singular = arr(&[1.0, 2.0, 2.0, 4.0], &[2, 2]);
579        let (sign, logdet) = slogdet(&singular);
580        assert_eq!(sign.to_vec(), [0.0]);
581        assert_eq!(logdet.to_vec(), [f64::NEG_INFINITY]);
582    }
583
584    #[test]
585    fn norms() {
586        let m = arr(&[1.0, -2.0, 3.0, 4.0, 5.0, -6.0], &[2, 3]);
587        let n = |ord, axes| norm(&m, ord, axes, false).to_vec();
588        close(&n(NormOrd::Default, NormAxes::All), &[91f64.sqrt()]);
589        close(&n(NormOrd::P(1.0), NormAxes::All), &[9.0]);
590        close(&n(NormOrd::Inf, NormAxes::All), &[15.0]);
591        close(&n(NormOrd::NegInf, NormAxes::All), &[6.0]);
592        close(&n(NormOrd::P(-1.0), NormAxes::All), &[5.0]);
593        close(&n(NormOrd::P(1.0), NormAxes::Vector(1)), &[6.0, 15.0]);
594        close(&n(NormOrd::P(0.0), NormAxes::Vector(0)), &[2.0, 2.0, 2.0]);
595        close(
596            &n(NormOrd::P(3.0), NormAxes::Vector(-1)),
597            &[36f64.cbrt(), 405f64.cbrt()],
598        );
599        let s = svdvals(&m).to_vec();
600        close(&n(NormOrd::P(2.0), NormAxes::All), &[s[0]]);
601        close(&n(NormOrd::P(-2.0), NormAxes::All), &[s[1]]);
602        close(&n(NormOrd::Nuc, NormAxes::Matrix(1, 0)), &[s[0] + s[1]]);
603        assert_eq!(
604            norm(&m, NormOrd::Fro, NormAxes::Matrix(0, 1), true)
605                .shape()
606                .dims(),
607            [1, 1]
608        );
609    }
610}