librarylibs/Matrix/src/Matrix.xtl

Matrix: matrices -- identity, diagonal, trace, product, determinant, inverse, solving linear systems, orthonormal bases, projection onto a subspace and coordinates in a basis, eigenvalues and eigenvectors of a symmetric matrix, singular values and the best rank-k approximation and principal angles between row spaces. Import it with an alias of your choice: "mx:" u_se< "Matrix". Put libs/Matrix/src on XETAL_PATH ("just path"); the reference is libs/Matrix/docs. Names with l: are exported; those under h: are private to this file.

A matrix is a rank-2 array, rows first. The numerical functions (d_et, i_nverse, s_olve) work in Floats, by Gaussian elimination with partial pivoting; compare their results with Check's ch:n_ear. The transpose is the built-in o_\.

source

Basics

ˡi̲dentity : Num a => Int -> a

function · line 18

i_dentity n: the n by n identity matrix (1 then n zeros, cycled).

ˡi̲dentity ← { n → (n c̲at n) r̲eshape 1 c̲at n r̲eshape 0 }

ˡd̲iag : a -> a

function · line 21

d_iag m: the items on the main diagonal.

ˡd̲iag ← { m →
  k ← 'm̲in r̲/ s̲hape m
  (1 + (o̲ffsets k) × 1 + f̲irst r̲ev s̲hape m) s̲elect r̲avel m
}

ˡt̲race : Num a => a -> a

function · line 27

t_race m: the sum of the diagonal.

ˡt̲race ← { m → '+ r̲/ ˡd̲iag m }

ˡm̲ul : Num a => a -> a -> a

function · line 30

a m_ul b: the matrix product (a matrix and a vector work too).

ˡm̲ul ← { a b → a '+ '× i̲nner b }

Solving

ʰs̲wapping : Int -> Int -> Int -> Int

function (private) · line 35

The permutation of 1..n that swaps i and j.

ʰs̲wapping ← { n i j →
  r ← r̲ange n
  r + ((r = i) × j − i) + (r = j) × i − j
}
Used in: ʰg̲j, ʰd̲etF

ʰp̲ivot : Num a => Int -> a -> Int

function (private) · line 41

The row (k..n) whose item in column k is largest in size.

ʰp̲ivot ← { k m →
  c ← a̲bs (k − 1) d̲rop k s̲elect₂ m
  k + (f̲irst g̲rade n̲eg c) − 1
}
Used in: ʰg̲j, ʰd̲etF

ʰg̲j : Int -> Int -> Float -> Float

function (private) · line 49

Gauss-Jordan on m (Float) for columns k..n of its first n: each column's pivot row moved up, scaled to 1, and the column cleared from every other row.

ʰg̲j ← { n k m →
  k > n ? m
  s ← ((n ʰs̲wapping k) k ʰp̲ivot m) s̲elect m
  r ← r̲ange t̲ally s
  v ← f̲irst k s̲elect k s̲elect₂ s              ⍝ the pivot
  0.000000000001 > a̲bs v ? @ p̲anic< "the matrix is singular: it has no inverse, and its system no unique solution"
  row ← (k s̲elect s) ÷ v
  c ← (k s̲elect₂ s) − f̲loat r = k
  ((n ʰg̲j k + 1) s − c '× t̲able row)
}
p̲anic< expands to
(⎕P̲ANIC ("the matrix is singular: it has no inverse, and its system no unique solution"))
Used in: ʰg̲j, ˡs̲olve

ˡs̲olve : Num a => a -> a -> Float

function · line 63

b s_olve a: x with a m_ul x = b, for a square a; b is a vector or a matrix of right-hand sides (one per column). A singular a stops with error[panic] when a pivot is below 1e-12.

ˡs̲olve ← { b a →
  n ← t̲ally a
  x ← n d̲rop₂ ((n ʰg̲j 1) f̲loat a c̲at₂ b)
  (s̲hape b) r̲eshape x
}

ˡi̲nverse : Num a => a -> Float

function · line 70

i_nverse a: the inverse of a square matrix.

ˡi̲nverse ← { a → (ˡi̲dentity t̲ally a) ˡs̲olve a }

Determinant

ʰd̲etF : Float -> Float

function (private) · line 76

The determinant of a Float matrix m, by elimination: the first pivot times the determinant of what is left, negated for a row swap.

ʰd̲etF ← { m →
  n ← t̲ally m
  n = 1 ? f̲irst r̲avel m
  p ← 1 ʰp̲ivot m
  w ← ((n ʰs̲wapping 1) p) s̲elect m
  v ← f̲irst r̲avel w
  v = 0 ? 0.0
  s ← f̲loat (p = 1) − p ≠ 1
  r ← (1 d̲rop₂ 1 d̲rop w) − ((1 d̲rop f̲irst₂ w) ÷ v) '× t̲able 1 d̲rop f̲irst w
  s × v × ʰd̲etF r
}
Used in: ʰd̲etF, ˡd̲et

ˡd̲et : Num a => a -> Float

function · line 89

d_et a: the determinant of a square matrix.

ˡd̲et ← { a → ʰd̲etF f̲loat a }
Used in: ˡt̲ransform

Subspaces

ʰt̲ol : Any a => a -> Float

function (private) · line 95

The tolerance of a dependent row: a remainder no longer than this fraction of its row's own length is counted as 0.

ʰt̲ol ← { u → 0.0000000001 }
Used in: ʰg̲s

ʰl̲ength : Num a => a -> Float

function (private) · line 98

The length of the vector v.

ʰl̲ength ← { v → s̲qrt '+ r̲/ v × v }
Used in: ʰg̲s

ʰo̲rth : Num a => a -> a -> a

function (private) · line 102

q o_rth v: v less its projection onto the rows of q (orthonormal, possibly none).

ʰo̲rth ← { q v → v − (q '+ '× i̲nner v) '+ '× i̲nner q }
Used in: ʰg̲s

ʰg̲s : Float -> Int -> Float -> Float

function (private) · line 108

Modified Gram-Schmidt from row i of b on, the orthonormal rows so far in q: each row's remainder taken twice (once leaves rounding of the size of the projection; twice is orthogonal to the last digits) and kept, made unit length, unless it is within the tolerance of 0.

ʰg̲s ← { b i q →
  i > t̲ally b ? q
  v ← i s̲elect b
  w ← q ʰo̲rth q ʰo̲rth v
  r ← ʰl̲ength w
  r ≤ (ʰt̲ol @) × ʰl̲ength v ? ((b ʰg̲s i + 1) q)
  ((b ʰg̲s i + 1) q c̲at (1 c̲at t̲ally w) r̲eshape w ÷ r)
}

ˡo̲rthonormal : Num a => a -> Float

function · line 122

o_rthonormal b: an orthonormal basis of the span of b's rows, as rows: modified Gram-Schmidt, twice, in row order, so the first row of the result is the first nonzero row of b made unit length. A row within 1e-10 of its own length of the span of the rows before it is dependent and dropped, so the result has as many rows as b's rank.

ˡo̲rthonormal ← { b →
  f ← f̲loat b
  ((f ʰg̲s 1) (0 c̲at f̲irst r̲ev s̲hape f) r̲eshape 0.0)
}

ˡr̲ank : Num a => a -> Int

function · line 129

r_ank b: the dimension of the span of b's rows, the number of rows of its orthonormal basis (to the same tolerance).

ˡr̲ank ← { b → t̲ally ˡo̲rthonormal b }

ˡp̲roject : (Num a, Num b) => a -> b -> Float

function · line 134

b p_roject m: each row of m (or the vector m) projected onto the span of b's rows: its nearest point there, m Q' Q for Q the orthonormal basis of b's rows. b's rows need not be independent or orthonormal.

ˡp̲roject ← { b m →
  q ← ˡo̲rthonormal b
  ((f̲loat m) '+ '× i̲nner o̲\ q) '+ '× i̲nner q
}

ˡr̲emainder : (Num a, Num b) => a -> b -> Float

function · line 141

b r_emainder m: what is left of m after its projection, m less b p_roject m: orthogonal to every row of b.

ˡr̲emainder ← { b m → (f̲loat m) − b ˡp̲roject m }
Used in: remainder

ˡc̲oordinates : (Num a, Num b) => a -> b -> Float

function · line 149

b c_oordinates m: the coordinates of each row of m (or the vector m) in the rows of b: c with c mx:m_ul b equal to m, for m in the span; for m outside it, the coordinates of its projection. b's rows must be independent (else the coordinates are not unique): solved in b's orthonormal basis Q, as c R = m Q' with R = b Q', so b b' is never inverted.

ˡc̲oordinates ← { b m →
  q ← ˡo̲rthonormal b
  (t̲ally q) < t̲ally b ? @ p̲anic< "the rows of the basis are dependent: coordinates in it are not unique"
  r ← (f̲loat b) '+ '× i̲nner o̲\ q
  a ← (f̲loat m) '+ '× i̲nner o̲\ q
  o̲\ (o̲\ a) ˡs̲olve o̲\ r
}
p̲anic< expands to
(⎕P̲ANIC ("the rows of the basis are dependent: coordinates in it are not unique"))

Symmetric eigenvalues

ʰj̲acobiTol : Any a => a -> Float

function (private) · line 161

Jacobi's stopping point: the off-diagonal part's length (Frobenius) at most this fraction of the whole matrix's.

ʰj̲acobiTol ← { u → 0.000000000000001 }

ʰj̲acobiSweeps : (Any a, Num b) => a -> b

function (private) · line 164

The most sweeps Jacobi makes before it stops with a message.

ʰj̲acobiSweeps ← { u → 30 }

ʰf̲robenius : Num a => a -> Float

function (private) · line 167

The length (Frobenius) of a matrix: every item squared, summed, rooted.

ʰf̲robenius ← { a → s̲qrt '+ r̲/ r̲avel a × a }
Used in: ʰs̲weeps

ʰo̲ff : Float -> Float

function (private) · line 170

The off-diagonal part of the square matrix a, the diagonal zeroed.

ʰo̲ff ← { a → a × f̲loat 0 = ˡi̲dentity t̲ally a }

ʰr̲otation : Float -> Int -> Int -> Float

function (private) · line 177

The rotation that zeroes item (p, q) of the symmetric a, as a full n by n matrix j (j' a j has 0 there): from tau = (a_qq - a_pp) / 2 a_pq, t = sign(tau) / (|tau| + sqrt(1 + tau^2)) (the smaller angle; an overflowing tau^2 makes t 0, no rotation), c = 1 / sqrt(1 + t^2), s = t c (Golub and Van Loan, sym.schur2). An item already 0 is left.

ʰr̲otation ← { a p q →
  n ← t̲ally a
  i ← f̲loat ˡi̲dentity n
  apq ← f̲irst q s̲elect p s̲elect a
  0.0 = apq ? i
  tau ← ((f̲irst q s̲elect q s̲elect a) − f̲irst p s̲elect p s̲elect a) ÷ 2.0 × apq
  t ← (1.0 − 2.0 × f̲loat tau < 0.0) ÷ (a̲bs tau) + s̲qrt 1.0 + tau × tau
  c ← 1.0 ÷ s̲qrt 1.0 + t × t
  ep ← f̲loat (r̲ange n) = p
  eq ← f̲loat (r̲ange n) = q
  i + ((c − 1.0) × (ep '× t̲able ep) + eq '× t̲able eq) + (t × c) × (ep '× t̲able eq) − eq '× t̲able ep
}

ʰs̲weep : (Float, Float) -> (Float, Float)

function (private) · line 192

One cyclic sweep: a rotation for every pair p < q in row order, applied to a (j' a j) and gathered in v (v j); the state (a, v).

ʰs̲weep ← { (a, v) →
  n ← t̲ally a
  k ← (w̲here r̲avel (r̲ange n) '< t̲able r̲ange n) − 1
  ps ← 1 + k d̲iv n
  qs ← 1 + k m̲od n
  r̲ot ← { (i, b, w) →
    j ← ((b ʰr̲otation i s̲elect ps) i s̲elect qs)
    (i + 1, (o̲\ j) ˡm̲ul b ˡm̲ul j, w ˡm̲ul j)
  }
  (_, b, w) ← (t̲ally k) 'r̲ot p̲ower (1, a, v)
  (b, w)
}
Used in: ʰs̲weeps

ʰs̲weeps : Num a => a -> (Float, Float) -> (Float, Float)

function (private) · line 207

Sweeps until the off-diagonal part is within the tolerance of the whole (or stop at the cap with a message); k sweeps made so far.

ʰs̲weeps ← { k (a, v) →
  (ʰf̲robenius ʰo̲ff a) ≤ (ʰj̲acobiTol @) × ʰf̲robenius a ? (a, v)
  k ≥ ʰj̲acobiSweeps @ ? @ p̲anic< "Jacobi did not converge in 30 sweeps"
  (k + 1) ʰs̲weeps ʰs̲weep (a, v)
}
p̲anic< expands to
(⎕P̲ANIC ("Jacobi did not converge in 30 sweeps"))

ʰe̲igen : Num a => a -> (Float, Float)

function (private) · line 217

The eigenvalues of the symmetric s, descending, and its eigenvectors as rows in the same order, each signed so its largest item (the first of equal ones) is positive. s must be square and symmetric (to 1e-12 of its largest item); it is not symmetrized.

ʰe̲igen ← { s →
  a ← f̲loat s
  n ← t̲ally a
  n̲ot (n c̲at n) m̲atch s̲hape a ? @ p̲anic< "the matrix is not square"
  big ← 'm̲ax r̲/ 0.0 c̲at r̲avel a̲bs a
  n̲ot '∧ r̲/ r̲avel (a̲bs a − o̲\ a) ≤ 0.000000000001 × big ? @ p̲anic< "the matrix is not symmetric: eigenvalues here are for symmetric matrices only"
  (d, v) ← 0 ʰs̲weeps (a, f̲loat ˡi̲dentity n)
  o ← g̲rade n̲eg ˡd̲iag d
  w ← o s̲elect o̲\ v
  ones ← n r̲eshape 1.0
  hit ← f̲loat (a̲bs w) = ('m̲ax r̲/₂ a̲bs w) '× t̲able ones
  first ← hit × f̲loat 1.0 = '+ s̲\₂ hit
  sg ← 1.0 − 2.0 × f̲loat 0.0 > '+ r̲/₂ w × first
  (o s̲elect ˡd̲iag d, w × sg '× t̲able ones)
}
p̲anic< expands to
(⎕P̲ANIC ("the matrix is not square"))
p̲anic< expands to
(⎕P̲ANIC ("the matrix is not symmetric: eigenvalues here are for symmetric matrices only"))

ˡe̲igenvalues : Num a => a -> Float

function · line 235

e_igenvalues s: the eigenvalues of the symmetric matrix s, largest first, by cyclic Jacobi.

ˡe̲igenvalues ← { s → (vals, _) ← ʰe̲igen s◆ vals }

ˡe̲igenvectors : Num a => a -> Float

function · line 240

e_igenvectors s: the eigenvectors of the symmetric matrix s, one per row, in the order of e_igenvalues; each of unit length, signed so its largest item is positive: s is (o_\ v) times diag(values) times v.

ˡe̲igenvectors ← { s → (_, vecs) ← ʰe̲igen s◆ vecs }

Singular values

ʰo̲rthogonal? : Truthy a => Float -> a

function (private) · line 246

Whether the rows of a are orthogonal: every pair's dot product at most the tolerance times the product of their lengths.

ʰo̲rthogonal? ← { a →
  g ← a ˡm̲ul o̲\ a
  dg ← ˡd̲iag g
  '∧ r̲/ r̲avel (a̲bs ʰo̲ff g) ≤ (ʰj̲acobiTol @) × s̲qrt dg '× t̲able dg
}
Used in: ʰs̲vdSweeps

ʰs̲vdSweep : (Float, Float) -> (Float, Float)

function (private) · line 255

One sweep of one-sided Jacobi on the rows of a: for every pair p < q, the rotation that makes rows p and q orthogonal (the Jacobi rotation of their Gram matrix, a a'), applied to a and gathered in v.

ʰs̲vdSweep ← { (a, v) →
  n ← t̲ally a
  k ← (w̲here r̲avel (r̲ange n) '< t̲able r̲ange n) − 1
  ps ← 1 + k d̲iv n
  qs ← 1 + k m̲od n
  r̲ot ← { (i, b, w) →
    j ← (((b ˡm̲ul o̲\ b) ʰr̲otation i s̲elect ps) i s̲elect qs)
    (i + 1, (o̲\ j) ˡm̲ul b, (o̲\ j) ˡm̲ul w)
  }
  (_, b, w) ← (t̲ally k) 'r̲ot p̲ower (1, a, v)
  (b, w)
}
Used in: ʰs̲vdSweeps

ʰs̲vdSweeps : Num a => a -> (Float, Float) -> (Float, Float)

function (private) · line 269

Sweeps until the rows are orthogonal (or stop at the cap).

ʰs̲vdSweeps ← { k (a, v) →
  ʰo̲rthogonal? a ? (a, v)
  k ≥ ʰj̲acobiSweeps @ ? @ p̲anic< "Jacobi did not converge in 30 sweeps"
  (k + 1) ʰs̲vdSweeps ʰs̲vdSweep (a, v)
}
p̲anic< expands to
(⎕P̲ANIC ("Jacobi did not converge in 30 sweeps"))

ʰs̲vdTall : Float -> (Float, Float, Float)

function (private) · line 280

The thin SVD of m with at least as many rows as columns: one-sided Jacobi on the rows of m' (m itself is never squared), so the rows end orthogonal, of lengths the singular values, along the left singular vectors; v gathers the rotations, the right ones. Largest first, each v row signed so its largest item is positive.

ʰs̲vdTall ← { m →
  n ← f̲irst r̲ev s̲hape m
  (a, v) ← 0 ʰs̲vdSweeps (o̲\ m, f̲loat ˡi̲dentity n)
  s ← s̲qrt '+ r̲/₂ a × a
  o ← g̲rade n̲eg s
  ones ← n r̲eshape 1.0
  ss ← o s̲elect s
  u ← (o s̲elect a) ÷ (ss + f̲loat ss = 0.0) '× t̲able (t̲ally f̲irst a) r̲eshape 1.0
  w ← o s̲elect v
  hit ← f̲loat (a̲bs w) = ('m̲ax r̲/₂ a̲bs w) '× t̲able ones
  first ← hit × f̲loat 1.0 = '+ s̲\₂ hit
  sg ← 1.0 − 2.0 × f̲loat 0.0 > '+ r̲/₂ w × first
  (u × sg '× t̲able (t̲ally f̲irst u) r̲eshape 1.0, ss, w × sg '× t̲able ones)
}
Used in: ˡs̲vd

ˡs̲vd : Num a => a -> (Float, Float, Float)

function · line 300

s_vd m: the singular value decomposition, (u, s, v) with m equal to (o_\ u) mx:m_ul diag(s) mx:m_ul v: s the singular values, largest first, as many as m's smaller side; u's rows the left singular vectors, v's the right ones (a zero singular value has a zero row in u for tall/square m, in v for wide m). One-sided Jacobi on m or m'.

ˡs̲vd ← { m →
  f ← f̲loat m
  (r, c) ← (f̲irst s̲hape f, f̲irst r̲ev s̲hape f)
  r ≥ c ? ʰs̲vdTall f
  (u, s, v) ← ʰs̲vdTall o̲\ f
  (v, s, u)
}

ˡs̲ingular : Num a => a -> Float

function · line 310

s_ingular m: the singular values of the matrix m, largest first, as many as its smaller side.

ˡs̲ingular ← { m → (_, s, _) ← ˡs̲vd m◆ s }

ˡt̲runcate : Num a => Int -> a -> Float

function · line 316

k t_runcate m: the best approximation of m of rank at most k (Eckart and Young: nearest in both the Frobenius and the spectral norm), its k largest singular values kept and the rest made 0; m itself when k is at least its smaller side.

ˡt̲runcate ← { k m →
  (u, s, v) ← ˡs̲vd m
  j ← k m̲in t̲ally s
  (o̲\ j t̲ake u) ˡm̲ul ((j t̲ake s) '× t̲able (f̲irst r̲ev s̲hape v) r̲eshape 1.0) × j t̲ake v
}
Used in: best

Principal angles

ʰa̲ngleMatrix : Num a => a -> Float

function (private) · line 327

A finite rank-2 matrix for subspace comparison, converted to Float. Scale each nonzero row by its largest magnitude before taking norms.

ʰa̲ngleMatrix ← { a →
  n̲ot 2 = t̲ally s̲hape a ? @ p̲anic< "principal angles require rank-2 matrices"
  f ← f̲loat a
  n̲ot '∧ r̲/ r̲avel (f − f) = 0.0 ? @ p̲anic< "principal angles require finite input"
  columns ← f̲irst r̲ev s̲hape f
  0 = columns ? f
  magnitude ← 'm̲ax r̲/₂ a̲bs f
  divisor ← magnitude + f̲loat magnitude = 0.0
  f ÷ divisor '× t̲able columns r̲eshape 1.0
}
p̲anic< expands to
(⎕P̲ANIC ("principal angles require rank-2 matrices"))
p̲anic< expands to
(⎕P̲ANIC ("principal angles require finite input"))
Used in: ˡa̲ngles

ʰa̲ngles : Float -> Float -> Float

function (private) · line 341

Principal angles for orthonormal rows p,q with dim(p) <= dim(q). The right singular vectors of q p' give principal directions in p, including zero cosine values. Their residuals off q give the sines.

ʰa̲ngles ← { p q →
  (_, cosines, right) ← ˡs̲vd q ˡm̲ul o̲\ p
  directions ← right ˡm̲ul p
  residual ← directions − (directions ˡm̲ul o̲\ q) ˡm̲ul q
  sine ← s̲qrt '+ r̲/₂ residual × residual
  cosine ← 0.0 m̲ax 1.0 m̲in cosines
  ⍝ Nonnegative atan2 by its half-angle form, finite even at c=0.
  angle ← 2.0 × a̲tan sine ÷ (s̲qrt (sine × sine) + cosine × cosine) + cosine
  (g̲rade angle) s̲elect angle
}
Used in: ˡa̲ngles

ˡa̲ngles : (Num a, Num b) => a -> b -> Float

function · line 356

a a_ngles b: ascending principal angles in radians between row spaces, as many as the smaller rank. Orthonormal bases use the 1e-10 relative row-dependence tolerance. Zero-rank inputs give an empty Float vector. SVD cosines plus residual sines preserve small angles without acos(1).

ˡa̲ngles ← { a b →
  x ← ʰa̲ngleMatrix a
  y ← ʰa̲ngleMatrix b
  n̲ot (f̲irst r̲ev s̲hape x) = f̲irst r̲ev s̲hape y ? @ p̲anic< "principal-angle matrices must have the same column count"
  (0 = t̲ally x) ∨ (0 = t̲ally y) ∨ 0 = f̲irst r̲ev s̲hape x ? 0 r̲eshape 0.0
  p ← ˡo̲rthonormal x
  q ← ˡo̲rthonormal y
  (0 = t̲ally p) ∨ 0 = t̲ally q ? 0 r̲eshape 0.0
  (t̲ally p) ≤ t̲ally q ? p ʰa̲ngles q
  q ʰa̲ngles p
}
p̲anic< expands to
(⎕P̲ANIC ("principal-angle matrices must have the same column count"))